diff --git a/core/continuum-academy/src/cognition/eval/default_eval_set.rs b/core/continuum-academy/src/cognition/eval/default_eval_set.rs index 106cc65114..976b25ee85 100644 --- a/core/continuum-academy/src/cognition/eval/default_eval_set.rs +++ b/core/continuum-academy/src/cognition/eval/default_eval_set.rs @@ -153,13 +153,6 @@ where /// step over — the living persona's lane. pub(super) const EVAL_LANE_BASE_PORT: u16 = 58_200; -/// How much of a graded answer to persist in the result. A coder answer (code + reasoning) -/// fits far under this; the generous bound exists ONLY to cap a pathological loop-to-length -/// generation (which is captured up to here, still a diagnosable signal). The old 200-char -/// cap stored only the preamble and blinded every failure diagnosis + correction-corpus mine. -// context-budget-exempt: observability: how much of an answer is CAPTURED into the run ledger for humans, never text sent to a model -pub(super) const ANSWER_CAPTURE_CHARS: usize = 24_000; - /// Per-task detail retained in the DURABLE run ledger row (`append_progress_ledger`). /// The ledger stored only the summary (score/total), so a detached run's per-task /// verdicts were unrecoverable — a webdev pass/fail could not be glass-boxed after the diff --git a/core/continuum-academy/src/cognition/eval/eval_settle.rs b/core/continuum-academy/src/cognition/eval/eval_settle.rs index 8fe8764dbc..3ed362d654 100644 --- a/core/continuum-academy/src/cognition/eval/eval_settle.rs +++ b/core/continuum-academy/src/cognition/eval/eval_settle.rs @@ -105,9 +105,9 @@ pub(super) async fn run_pass_team( // number. Threading the full re-verify+retry into the two-solver loop is a scoped // follow-up. [[proctored-exam-session-dependable-benchmark]] if let Some(cause) = r - .inference_error + .failure .clone() - .or_else(|| w.inference_error.clone()) + .or_else(|| w.failure.clone()) { infra_faults += 1; if infra_reason.is_none() { @@ -116,7 +116,7 @@ pub(super) async fn run_pass_team( results.push(EvalTaskResult { id: t.id.clone(), ok: false, - grade: format!("infra unavailable (lane never recovered): {cause}"), + grade: format!("settlement infrastructure unavailable: {cause}"), acts: 0, answer: String::new(), latency_ms: 0, @@ -180,7 +180,7 @@ pub(super) async fn run_pass_team( ok, grade, acts, - answer: answer.chars().take(ANSWER_CAPTURE_CHARS).collect(), + answer, latency_ms: m.latency_ms, output_tokens: m.output_tokens, tokens_per_second: m.tokens_per_second(), diff --git a/core/continuum-academy/src/cognition/eval/eval_task_result.rs b/core/continuum-academy/src/cognition/eval/eval_task_result.rs index 1996745082..0712c2a636 100644 --- a/core/continuum-academy/src/cognition/eval/eval_task_result.rs +++ b/core/continuum-academy/src/cognition/eval/eval_task_result.rs @@ -15,9 +15,9 @@ pub struct EvalTaskResult { /// the act budget mid-action — an honest "did not finish", never fabricated). For a /// coder exam the answer IS the code, so this must carry the whole thing: a 200-char /// cap stored only the "Sure, I can help..." preamble and made every failure - /// undiagnosable AND un-minable for a correction corpus (2026-07-21). Bounded by - /// ANSWER_CAPTURE_CHARS against a pathological loop-to-length, which is itself a - /// signal worth capturing up to the cap. + /// undiagnosable AND un-minable for a correction corpus (2026-07-21). Retain the + /// complete answer for the grade-time lesson sink; storage policy cannot cut + /// the evidence before that consumer receives it. pub answer: String, /// Wall-clock latency to SETTLE this task: the summed deliberation-generation /// time across every act→observe tick (the model's own measured request time, @@ -67,7 +67,7 @@ pub struct EvalTaskResult { pub struct InfraUnavailable { /// Human cause: which axis broke (not-ready / connect-refused / not-the-served-model /// / compute-error / stream-idle timeout), naming the task it broke on. Display-only - /// — the classification that produced it is [`SettleOutcome::inference_error`], never + /// — the classification that produced it is [`SettleOutcome::failure`], never /// re-parsed from this string. pub reason: String, /// How many tasks were attempted before the run aborted. The exam is INCOMPLETE — a diff --git a/core/continuum-academy/src/cognition/eval/run_pass.rs b/core/continuum-academy/src/cognition/eval/run_pass.rs index 36d1e4082d..b319af78c1 100644 --- a/core/continuum-academy/src/cognition/eval/run_pass.rs +++ b/core/continuum-academy/src/cognition/eval/run_pass.rs @@ -250,7 +250,7 @@ pub(super) async fn run_pass( // Wedge detection is the SERVING layer's job and it is event-based there: the // stream-liveness classifier (phase-aware budgets, 9e2f95820) kills a // zero-token stream at the source and the failure surfaces here as - // `inference_error` — the event path `drive_to_settle` already returns on. + // `failure` — the event path `drive_to_settle` already returns on. // The old flat 600s deadline predated that sensor (#123, 2026-07-17) and was // never demoted once it shipped: it second-guessed the serving layer with a // stopwatch, declared a LIVE multi-minute e2e decode "wedged" (fluid-sim-e2e, @@ -276,7 +276,7 @@ pub(super) async fn run_pass( const PER_TASK_IDLE_BACKSTOP: std::time::Duration = std::time::Duration::from_secs(20 * 60); // BOUNDED INFRA-FAULT RECOVERY (Proctored Exam Session, Slice B). Drive to - // settlement; if the model call itself FAILS (`inference_error`: lane not-ready / + // settlement; if the model call itself FAILS (`failure`: lane not-ready / // connect-refused / "not the active served model" / compute-error / deadline-wedge) // that is an INFRA fault, never a wrong answer. Re-verify the lane and retry the // SAME task — the retried generation is itself the real decode proof — up to @@ -325,9 +325,13 @@ pub(super) async fn run_pass( } } }; - let Some(cause) = settled.inference_error.clone() else { + let Some(cause) = settled.failure.clone() else { break; // reached a verdict (answer OR graded-wrong) on a working lane }; + // Re-verifying an inference lane cannot repair checkpoint custody. + if matches!(cause, crate::cognition::act_observe::SettlementFailure::ReceiptPersistence(_)) { + break; + } infra_attempt += 1; if infra_attempt > INFRA_FAULT_RETRIES { break; @@ -348,7 +352,7 @@ pub(super) async fn run_pass( // INFRA_FAULT_RETRIES re-verify+retry cycles. Record the row for forensics, mark the // run void, and ABORT — every remaining task would only accrue more phantom zeros on // a dead lane. The caller reports InfraUnavailable, NEVER a fake pass_rate. - if let Some(cause) = &settled.inference_error { + if let Some(cause) = &settled.failure { infra_faults += 1; if infra_reason.is_none() { infra_reason = Some(format!("task '{}': {cause}", t.id)); @@ -356,7 +360,7 @@ pub(super) async fn run_pass( results.push(EvalTaskResult { id: t.id.clone(), ok: false, - grade: format!("infra unavailable (lane never recovered): {cause}"), + grade: format!("settlement infrastructure unavailable: {cause}"), acts: 0, answer: String::new(), latency_ms: 0, @@ -372,7 +376,7 @@ pub(super) async fn run_pass( task = %t.id, attempted = results.len(), cause = %cause, - "aborting run as InfraUnavailable — serving lane never recovered; refusing to \ + "aborting run as InfraUnavailable — settlement failed; refusing to \ publish a phantom score over a dead lane" ); break; @@ -444,7 +448,7 @@ pub(super) async fn run_pass( .await { // Take the re-drive only if it produced a real turn (not an infra fault). - if re.inference_error.is_none() { + if re.failure.is_none() { settled = re; } } @@ -512,14 +516,6 @@ pub(super) async fn run_pass( round = redrive_round as u64, "settled on a RED DoD — handing her the verdict with a bounded re-drive" ); - let tail: String = dod_out - .chars() - .rev() - .take(4000) - .collect::>() - .into_iter() - .rev() - .collect(); let red_delivery = crate::cognition::rag_budget::RagDelivery { source_id: "airc".to_string(), items: vec![crate::cognition::rag_budget::RagItem { @@ -527,9 +523,9 @@ pub(super) async fn run_pass( summary: None, pointer: None, content: format!( - "You settled, but the task's definition-of-done currently FAILS. Its output ends: + "You settled, but the task's definition-of-done currently FAILS. Its output is: -{tail} +{dod_out} Fix the workspace and finish — the grade reads the files, and a red build scores zero." ), @@ -559,7 +555,7 @@ Fix the workspace and finish — the grade reads th ) .await { - if re.inference_error.is_none() { + if re.failure.is_none() { settled = re; } } @@ -590,7 +586,7 @@ Fix the workspace and finish — the grade reads th ok: false, grade: format!("infra (DoD could not run, NOT a wrong answer): {reason}"), acts: settled.acts as u32, - answer: answer.chars().take(ANSWER_CAPTURE_CHARS).collect(), + answer, latency_ms: settled.metrics.latency_ms, output_tokens: settled.metrics.output_tokens, tokens_per_second: settled.metrics.tokens_per_second(), @@ -601,9 +597,9 @@ Fix the workspace and finish — the grade reads th }); continue; // no grade, NO lesson — a harness fault teaches nothing } - // `settled.inference_error` is None here — the abort above consumed every infra + // `settled.failure` is None here — the abort above consumed every infra // fault, so this grades a REAL verdict (a working lane produced an answer, right or - // wrong). No `inference_error` arm remains: an infra fault can no longer masquerade + // wrong). No `failure` arm remains: an infra fault can no longer masquerade // as a graded miss. let (ok, grade) = if !t.ui_checks.is_empty() { // FUNCTIONAL WEB-DEV: grade what her UI ACTUALLY RENDERED. Observe `target` through @@ -713,7 +709,7 @@ Fix the workspace and finish — the grade reads th ok, grade, acts: total_acts, - answer: answer.chars().take(ANSWER_CAPTURE_CHARS).collect(), + answer, latency_ms: m.latency_ms, output_tokens: m.output_tokens, tokens_per_second: m.tokens_per_second(), diff --git a/core/continuum-academy/src/cognition/eval/warm_gate.rs b/core/continuum-academy/src/cognition/eval/warm_gate.rs index 7995ea34fc..57ea034f72 100644 --- a/core/continuum-academy/src/cognition/eval/warm_gate.rs +++ b/core/continuum-academy/src/cognition/eval/warm_gate.rs @@ -37,10 +37,13 @@ pub(super) async fn warm_gate(cycle: &crate::cognition::workspace::WorkspaceCycl crate::cognition::workspace::TurnFraming::directed(), ) .await; - if probe.inference_error.is_none() { + if probe.failure.is_none() { warm = true; break; } + if matches!(probe.failure, Some(crate::cognition::act_observe::SettlementFailure::ReceiptPersistence(_))) { + break; + } tokio::time::sleep(std::time::Duration::from_secs(4)).await; } // Reset the volatile scratch the probe touched so task #1 starts from the same diff --git a/core/continuum-academy/src/cognition/experience.rs b/core/continuum-academy/src/cognition/experience.rs index 6e674a4afd..f20a348212 100644 --- a/core/continuum-academy/src/cognition/experience.rs +++ b/core/continuum-academy/src/cognition/experience.rs @@ -225,7 +225,7 @@ impl ExperienceRecord { /// the honest, end-to-end-instrumented lived verdict is whether she *converged* /// — reached a real settle-verdict (`Speak`/`Pass`/`RaiseUnprompted`) without /// an inference/serving fault. Two magic-number-free failure signals make a - /// lived turn salient: an infra fault (`inference_error`), and NON-CONVERGENCE + /// lived turn salient: an infra fault (`failure`), and NON-CONVERGENCE /// — the settle loop ran out its action budget mid-`Act` and never reached a /// verdict (`SettleOutcome.decision` is still `Act`, the "did not finish" the /// eval grader already recognizes). Both are structural facts of the outcome, @@ -240,7 +240,7 @@ impl ExperienceRecord { // eval's "did not finish", and an honest capability signal with no threshold. let converged = !matches!(settled.decision, Decision::Act { .. }); let clean = - converged && settled.inference_error.is_none() && settled.capacity_refusal.is_none(); + converged && settled.failure.is_none() && settled.capacity_refusal.is_none(); Self { // The stimulus IS the task for a lived turn: the message she answered, // posed as the prompt. No `test`/`expect` — nothing objective to grade @@ -253,11 +253,16 @@ impl ExperienceRecord { // correctness claim — a lived turn has no grader (see doc above). ok: clean, grade: match ( - &settled.inference_error, + &settled.failure, &settled.capacity_refusal, converged, ) { - (Some(cause), _, _) => format!("lived turn: inference fault — {cause}"), + (Some(crate::cognition::act_observe::SettlementFailure::Inference(cause)), _, _) => { + format!("lived turn: inference fault — {cause}") + } + (Some(crate::cognition::act_observe::SettlementFailure::ReceiptPersistence(cause)), _, _) => { + format!("lived turn: receipt persistence fault — {cause}") + } (None, Some(error), _) => format!("lived turn: prompt capacity refused — {error}"), (None, None, false) => { "lived turn: did not converge (action budget exhausted mid-act)".to_string() diff --git a/core/continuum-academy/src/cognition/experience/tests.rs b/core/continuum-academy/src/cognition/experience/tests.rs index 81870c2d3b..7d700c4fbb 100644 --- a/core/continuum-academy/src/cognition/experience/tests.rs +++ b/core/continuum-academy/src/cognition/experience/tests.rs @@ -16,7 +16,7 @@ world_state: world_state.to_string(), room_updates: Default::default(), metrics: TurnMetrics::default(), - inference_error: None, + failure: None, deferred_before_dispatch: false, capacity_refusal: None, touched_paths: Vec::new(), @@ -233,6 +233,14 @@ lived_fault.grade.contains("inference fault"), "the fault cause is named in the grade" ); + let mut persistence_failed = faulted; + persistence_failed.failure = Some(crate::cognition::act_observe::SettlementFailure::ReceiptPersistence( + std::sync::Arc::new(crate::cognition::persona_workspace::TaskSinkError::OwnerGone(peer.as_uuid())), + )); + let lived_persistence = ExperienceRecord::from_lived_turn("ping", &persistence_failed); + assert!(!lived_persistence.ok, "checkpoint failure is not accepted experience"); + assert!(lived_persistence.grade.contains("receipt persistence fault")); + assert!(!lived_persistence.grade.contains("inference fault")); // NON-CONVERGENCE: the drive-loop ran out its action budget mid-Act and never // reached a verdict — the lived analog of the eval's "did not finish". A @@ -248,7 +256,7 @@ world_state: "budget exhausted after 8 acts".into(), room_updates: Default::default(), metrics: TurnMetrics::default(), - inference_error: None, + failure: None, deferred_before_dispatch: false, capacity_refusal: None, touched_paths: Vec::new(), @@ -464,7 +472,7 @@ world_state: String::new(), room_updates: Default::default(), metrics: TurnMetrics::default(), - inference_error: None, + failure: None, deferred_before_dispatch: false, capacity_refusal: None, touched_paths: Vec::new(), diff --git a/core/continuum-cognition/src/cognition/act_observe/apply.rs b/core/continuum-cognition/src/cognition/act_observe/apply.rs index de57d37edb..5476f10dc8 100644 --- a/core/continuum-cognition/src/cognition/act_observe/apply.rs +++ b/core/continuum-cognition/src/cognition/act_observe/apply.rs @@ -215,7 +215,7 @@ pub async fn apply_act( for call in calls { let cmd = call.name.replace('_', "/"); if is_long_running(&cmd) { - let handle = exec.dispatch_background( + let accepted = exec.dispatch_background( cmd.clone(), call.input.clone(), // In THESE hands: a long-running command a card turn dispatches runs in @@ -229,7 +229,14 @@ pub async fn apply_act( None => identity, } }), - ); + ).await; + let handle = match accepted { + Ok(handle) => handle, + Err(error) => { + bg_notes.push(format!("[not run] {cmd}: {}", error.message)); + continue; + } + }; dispatched_calls.push(call.clone()); body.working_memory.record_dispatch_event( handle, diff --git a/core/continuum-cognition/src/cognition/act_observe/mod.rs b/core/continuum-cognition/src/cognition/act_observe/mod.rs index eb2963833d..ff345aebe3 100644 --- a/core/continuum-cognition/src/cognition/act_observe/mod.rs +++ b/core/continuum-cognition/src/cognition/act_observe/mod.rs @@ -37,7 +37,7 @@ pub(crate) use observation::call_args; pub use observation::{extract_paths, ActOutcome, ActStatus, Observation, ToolOutput, ToolVerb}; mod types; -pub use types::{SettleOutcome, SettleStep}; +pub use types::{SettleOutcome, SettleStep, SettlementFailure}; mod apply; /// Marks committed before an effect reaches the world (stop-drain S2, card 68811445). diff --git a/core/continuum-cognition/src/cognition/act_observe/settle.rs b/core/continuum-cognition/src/cognition/act_observe/settle.rs index 842f62d105..2e8cd7a7c2 100644 --- a/core/continuum-cognition/src/cognition/act_observe/settle.rs +++ b/core/continuum-cognition/src/cognition/act_observe/settle.rs @@ -15,7 +15,7 @@ use crate::cognition::workspace::{Burst, Decision, Situation, TurnFraming, TurnM use super::apply::apply_act; use super::perception::{any_real_receipt, batch_evidence, claimed_file_without_act, collect_touched_paths, mutated_workspace, ConcernPhase, wrote_without_observation}; -use super::types::{SettleOutcome, SettleStep}; +use super::types::{SettleOutcome, SettleStep, SettlementFailure}; use crate::inference::turn_bound::TICK_DEADLINE; mod tick_deadline; diff --git a/core/continuum-cognition/src/cognition/act_observe/settle/settle_step.rs b/core/continuum-cognition/src/cognition/act_observe/settle/settle_step.rs index 5d5fb59b36..640ea0facb 100644 --- a/core/continuum-cognition/src/cognition/act_observe/settle/settle_step.rs +++ b/core/continuum-cognition/src/cognition/act_observe/settle/settle_step.rs @@ -67,7 +67,7 @@ pub async fn settle_step( // One Instant and one probe; no signature change, and the caller's arithmetic // is unchanged. let cycle_started = std::time::Instant::now(); - let ws = cycle.run_situated(burst, framing, situation).await; + let mut ws = cycle.run_situated(burst, framing, situation).await; let cycle_ms = cycle_started.elapsed().as_millis() as u64; // The cost of THIS tick's deliberation generation — latency + tokens of the // model call behind the verdict. Carried out alongside the step so the caller @@ -100,6 +100,11 @@ pub async fn settle_step( if let Some(m) = metrics.as_ref() { cycle.note_generation(m); } + if let Err(error) = cycle.persist_render_receipts(std::mem::take(&mut ws.render_receipts)).await { + continuum_base::probe!(class = "settle.receipt_persistence_failed", room = %room_id, + error = %error, "served generation retained; checkpoint failed before applying final speech or action"); + return (SettleStep::ReceiptPersistenceFailed { error: Arc::new(error) }, metrics, step_receipts); + } // A FAILED model call is not a verdict and not a silence — surface it LOUD so no // failure ever masquerades as a chosen `Pass` ([[fallbacks-are-illegal-fail-loud]]). // Checked BEFORE the decision so a fault can never collapse into `Passed` (the @@ -123,7 +128,7 @@ pub async fn settle_step( continuum_base::probe!( class = "settle.inference_failed", room = %room_id, - error = &error.to_string()[..error.to_string().len().min(160)], + error = %error, "deliberation generation FAILED — surfacing before the step returns" ); return ( diff --git a/core/continuum-cognition/src/cognition/act_observe/settle/settle_to_outcome.rs b/core/continuum-cognition/src/cognition/act_observe/settle/settle_to_outcome.rs index c9f9e99a25..c62561c8ec 100644 --- a/core/continuum-cognition/src/cognition/act_observe/settle/settle_to_outcome.rs +++ b/core/continuum-cognition/src/cognition/act_observe/settle/settle_to_outcome.rs @@ -115,7 +115,7 @@ pub(super) async fn settle_to_outcome<'c>( // faulted thought is retried in place, bounded, before the turn is // surrendered — the flicker costs one re-generation, not the turn. Only a // SUSTAINED fault (budget spent across the turn) ends the turn with - // inference_error, exactly as before — 4+ faults in one turn IS a wedge worth + // failure, exactly as before — 4+ faults in one turn IS a wedge worth // surrendering to, not a flicker. Whole-turn budget, not per-tick. const DELIBERATION_RETRY_BUDGET: u32 = 3; let mut delib_retries: u32 = 0; @@ -147,7 +147,7 @@ pub(super) async fn settle_to_outcome<'c>( room_updates: Arc::clone(&burst.room_updates), metrics, generation_receipts: generation_receipts.clone(), - inference_error: None, + failure: None, deferred_before_dispatch: false, capacity_refusal: None, touched_paths: touched, @@ -248,7 +248,7 @@ pub(super) async fn settle_to_outcome<'c>( room_updates: Arc::clone(&burst.room_updates), metrics, generation_receipts: generation_receipts.clone(), - inference_error: Some(error), + failure: Some(SettlementFailure::Inference(error)), deferred_before_dispatch: false, capacity_refusal: None, touched_paths: touched, @@ -480,7 +480,7 @@ pub(super) async fn settle_to_outcome<'c>( ), capacity_refusal: Some(error.clone()), generation_receipts, - inference_error: None, + failure: None, touched_paths: touched, turn_acts, }; @@ -604,7 +604,7 @@ pub(super) async fn settle_to_outcome<'c>( room_updates: Arc::clone(&burst.room_updates), metrics, generation_receipts: generation_receipts.clone(), - inference_error: None, + failure: None, deferred_before_dispatch: false, capacity_refusal: None, touched_paths: touched, @@ -714,7 +714,7 @@ pub(super) async fn settle_to_outcome<'c>( room_updates: Arc::clone(&burst.room_updates), metrics, generation_receipts: generation_receipts.clone(), - inference_error: None, + failure: None, deferred_before_dispatch: false, capacity_refusal: None, touched_paths: touched, @@ -731,7 +731,7 @@ pub(super) async fn settle_to_outcome<'c>( room_updates: Arc::clone(&burst.room_updates), metrics, generation_receipts: generation_receipts.clone(), - inference_error: None, + failure: None, deferred_before_dispatch: false, capacity_refusal: None, touched_paths: touched, @@ -749,6 +749,16 @@ pub(super) async fn settle_to_outcome<'c>( SettleStep::DeferredBeforeDispatch => { unreachable!("deferral is a driven-turn disposition, not an individual step"); } + SettleStep::ReceiptPersistenceFailed { error } => { + return SettleOutcome { + room: room_id, decision: Decision::pass(), spoken: None, acts, + world_state: burst.rendered.clone(), room_updates: Arc::clone(&burst.room_updates), + metrics, generation_receipts, + failure: Some(SettlementFailure::ReceiptPersistence(error)), + deferred_before_dispatch: false, capacity_refusal: None, + touched_paths: touched, turn_acts, + }; + } SettleStep::InferenceFailed { error } => { // A STARVED MIND KEEPS HER BUDGET. This arm's retry budget is for a // TRANSIENT MODEL FAULT — a generation that reached the lane and came @@ -782,7 +792,7 @@ pub(super) async fn settle_to_outcome<'c>( metrics, generation_receipts: generation_receipts.clone(), // Not an inference fault: no inference was ever dispatched. - inference_error: None, + failure: None, deferred_before_dispatch: can_defer_input(generation_receipts.len(), acts, turn_acts.len(), delib_retries), capacity_refusal: None, touched_paths: touched, @@ -795,7 +805,7 @@ pub(super) async fn settle_to_outcome<'c>( // in place, bounded, and ALWAYS probe so the wedge signal stays // visible to the concurrency investigation (the retry recovers the // turn; it must never HIDE the fault). Only a SUSTAINED fault - // (budget spent) surrenders the turn with inference_error, exactly + // (budget spent) surrenders the turn with failure, exactly // as before. // A generation the act deadline dropped in flight is no transient fault: its // retry waits out another whole bound on the same engine (up to three, so one @@ -823,7 +833,7 @@ pub(super) async fn settle_to_outcome<'c>( room_updates: Arc::clone(&burst.room_updates), metrics, generation_receipts: generation_receipts.clone(), - inference_error: Some(error), + failure: Some(SettlementFailure::Inference(error)), deferred_before_dispatch: false, capacity_refusal: None, touched_paths: touched, diff --git a/core/continuum-cognition/src/cognition/act_observe/settle/tests.rs b/core/continuum-cognition/src/cognition/act_observe/settle/tests.rs index 17ef06bb10..01bf7690a2 100644 --- a/core/continuum-cognition/src/cognition/act_observe/settle/tests.rs +++ b/core/continuum-cognition/src/cognition/act_observe/settle/tests.rs @@ -255,7 +255,7 @@ &mut conversation, ) .await; - assert!(settled.inference_error.is_some(), "a failed act"); + assert!(settled.failure.is_some(), "a failed act"); assert!(!settled.deferred_before_dispatch, "never a lane wait"); assert!(settled.generation_receipts.is_empty(), "no completion"); assert_eq!(start.elapsed(), crate::inference::turn_bound::TICK_DEADLINE, "one bound, no in-place retry"); diff --git a/core/continuum-cognition/src/cognition/act_observe/tests/credit.rs b/core/continuum-cognition/src/cognition/act_observe/tests/credit.rs index 145842b41e..d9326ed5d3 100644 --- a/core/continuum-cognition/src/cognition/act_observe/tests/credit.rs +++ b/core/continuum-cognition/src/cognition/act_observe/tests/credit.rs @@ -154,9 +154,9 @@ async fn live_room_input_reaches_next_action_without_replacing_task_or_room() { let outcome = drive_to_settle_with_input(&cycle, burst, 8, framing, &mut conversation).await; assert!( - outcome.inference_error.is_none(), + outcome.failure.is_none(), "{:?}", - outcome.inference_error + outcome.failure ); assert_eq!(outcome.acts, 2); assert_eq!(outcome.room, room); diff --git a/core/continuum-cognition/src/cognition/act_observe/tests/drive.rs b/core/continuum-cognition/src/cognition/act_observe/tests/drive.rs index 23a3f44e65..f7d0fa761c 100644 --- a/core/continuum-cognition/src/cognition/act_observe/tests/drive.rs +++ b/core/continuum-cognition/src/cognition/act_observe/tests/drive.rs @@ -126,7 +126,7 @@ async fn acted_then_capacity_refused_retains_work_without_replay() { assert_eq!(outcome.metrics.output_tokens, 40); assert_eq!(outcome.metrics.latency_ms, 1200); assert!(!outcome.deferred_before_dispatch); - assert!(outcome.inference_error.is_none()); + assert!(outcome.failure.is_none()); assert!(matches!( SettleStep::from_settled(outcome).0, SettleStep::CapacityRefused { @@ -164,7 +164,7 @@ async fn capacity_refusal_leaves_the_driver_once_with_typed_custody() { let outcome = drive_to_settle(&cycle, "keep the complete input", 8, TurnFraming::ambient()).await; assert_eq!(faculty.0.load(std::sync::atomic::Ordering::SeqCst), 1); - assert!(outcome.inference_error.is_none()); + assert!(outcome.failure.is_none()); assert!(outcome.deferred_before_dispatch); assert_eq!(outcome.acts, 0); assert!(outcome.generation_receipts.is_empty()); @@ -575,3 +575,52 @@ async fn settle_step_defers_the_act_without_executing_when_may_act_is_false() { "a permitted act DOES reach the executor" ); } + +#[tokio::test] +async fn receipt_custody_failure_stops_settlement_without_retrying_inference() { + use crate::ai::provenance::{GenerationOutcome, GenerationReceipt}; + use crate::cognition::act_observe::SettlementFailure; + use crate::cognition::persona_workspace::{PersonaWorkspaceRegistry, TaskSinkError}; + use std::sync::atomic::{AtomicUsize, Ordering}; + struct Served { + contribution: Contribution, + calls: AtomicUsize, + } + #[async_trait] + impl Faculty for Served { + fn id(&self) -> FacultyId { FacultyId::Deliberation } + fn reacts_to_broadcast(&self) -> bool { true } + async fn contribute(&self, _: &Workspace) -> Option { + self.calls.fetch_add(1, Ordering::SeqCst); + Some(self.contribution.clone()) + } + } + let owner = Uuid::new_v4(); + let incarnation = Uuid::new_v4(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); + let mut contribution = Contribution::verdict(Decision::Speak { text: "must not be emitted".into() }, 1.0, "served"); + contribution.receipts.push(GenerationReceipt { + submitted_request_id: "served-before-owner-loss".into(), + outcome: GenerationOutcome::Served { model: "fixture".into(), provider: "fixture".into(), provider_request_id: None }, + capture: None, genes: Vec::new(), gene_scales: Vec::new(), allocation: None, + }); + contribution.render_receipts.push(crate::cognition::render_receipt::RenderReceipt { + owner, incarnation, request: "served-before-owner-loss".into(), + view: continuum_context::view::Receipt { epoch: 1, items: Vec::new() }, + }); + let faculty = Arc::new(Served { contribution, calls: AtomicUsize::new(0) }); + let cycle = WorkspaceCycle::new(vec![faculty.clone()], Arc::new(SalienceArbiter)) + .with_render_custody(®istry, owner, incarnation); + drop(registry); + let outcome = drive_to_settle(&cycle, "observe the task".to_owned(), 2, TurnFraming::directed()).await; + assert_eq!(faculty.calls.load(Ordering::SeqCst), 1, "persistence must not spend an inference retry"); + assert!(outcome.spoken.is_none()); + assert_eq!(outcome.acts, 0); + assert!(!outcome.deferred_before_dispatch, "the generation really was served"); + assert!(matches!(&outcome.failure, Some(SettlementFailure::ReceiptPersistence(error)) + if matches!(error.as_ref(), TaskSinkError::OwnerGone(id) if *id == owner))); + assert_eq!(outcome.generation_receipts.len(), 1); + let (step, _, receipts) = SettleStep::from_settled(outcome); + assert!(matches!(step, SettleStep::ReceiptPersistenceFailed { .. })); + assert!(matches!(receipts[0].outcome, GenerationOutcome::Served { .. })); +} diff --git a/core/continuum-cognition/src/cognition/act_observe/types.rs b/core/continuum-cognition/src/cognition/act_observe/types.rs index ac450dae1d..717ca7ebfc 100644 --- a/core/continuum-cognition/src/cognition/act_observe/types.rs +++ b/core/continuum-cognition/src/cognition/act_observe/types.rs @@ -8,6 +8,14 @@ use crate::ai::types::ToolCall; use crate::cognition::workspace::{Decision, TurnMetrics}; +#[derive(Clone, Debug, thiserror::Error)] +pub enum SettlementFailure { + #[error("inference failed: {0}")] + Inference(String), + #[error("render receipt persistence failed: {0}")] + ReceiptPersistence(std::sync::Arc), +} + /// The result of driving a mind to settlement. pub struct SettleOutcome { /// EVERY act this turn made, in order: (the intent she stated, the exact calls). The @@ -39,13 +47,10 @@ pub struct SettleOutcome { /// to the accuracy grade — the same number a live turn could surface for the /// serving governor. pub metrics: TurnMetrics, - /// `Some(cause)` when the settle loop stopped because the deliberation model - /// call FAILED (timeout, 5xx, a serving lane refusing a model it isn't hosting) - /// rather than settling on a verdict. The grader MUST treat this as an - /// infrastructure failure — NOT a wrong answer — so an inference hiccup never - /// corrupts the accuracy metric ([[self-improvement-is-a-control-loop]]: the - /// reward is only as trustworthy as the metric). `None` on every settled turn. - pub inference_error: Option, + /// Infrastructure prevented settlement. The variant distinguishes a failed + /// generation from a served generation whose render receipt could not be + /// persisted. Neither is a graded wrong answer or an accepted learning turn. + pub failure: Option, /// The entire turn stopped at admission before any generation or action. /// Callers retain its inbound delivery obligation; this is not a chosen Pass. pub deferred_before_dispatch: bool, @@ -86,7 +91,7 @@ pub struct SettleOutcome { impl SettleOutcome { /// An infra-failure outcome: no verdict was reached because the deliberation /// call failed OR was aborted by a watchdog (e.g. a per-task deadline in the - /// eval loop). The grader keys on `inference_error.is_some()` to score this a + /// eval loop). The grader keys on `failure.is_some()` to score this a /// NAMED infrastructure failure — never a wrong answer — so a serving wedge /// never masquerades as a capability miss ([[self-improvement-is-a-control-loop]]). /// Zeroed metrics/acts because none accrued meaningfully. `TurnMetrics: Default`. @@ -99,7 +104,7 @@ impl SettleOutcome { world_state: String::new(), room_updates: Default::default(), metrics: TurnMetrics::default(), - inference_error: Some(cause.into()), + failure: Some(SettlementFailure::Inference(cause.into())), deferred_before_dispatch: false, capacity_refusal: None, touched_paths: Vec::new(), @@ -162,6 +167,10 @@ pub enum SettleStep { /// tick, the eval grades it an infra failure — never a serene no-op that hides a /// broken lane. `error` names the cause verbatim from the adapter. InferenceFailed { error: String }, + /// The generation was served, but its observed task ends could not be + /// checkpointed. This step did not apply its command or final speech decision. + /// Generation-time streaming may already have exposed provisional tokens. + ReceiptPersistenceFailed { error: std::sync::Arc }, } impl SettleStep { @@ -171,8 +180,7 @@ impl SettleStep { /// result through the one existing turn handler, no parallel match. /// /// The mapping is total and lossless for the live handler's purposes: - /// • `inference_error` present → `InferenceFailed` (a failed model is never a - /// chosen silence — [[fallbacks-are-illegal-fail-loud]]); + /// • `failure` present → the matching typed failure step; /// • `Speak`/`RaiseUnprompted` → `Spoke` (the prose reaches the room); /// • `Act` → `Acted` — the drive spent its whole act budget without settling on /// speech; the results are already in memory, so the live handler `continue`s @@ -207,11 +215,14 @@ impl SettleStep { generation_receipts, ); } - if let Some(error) = outcome.inference_error { + if let Some(error) = outcome.failure { // The fault path keeps them too: a turn whose deliberation failed still // dispatched generations, and that is precisely when provenance matters. return ( - SettleStep::InferenceFailed { error }, + match error { + SettlementFailure::Inference(error) => SettleStep::InferenceFailed { error }, + SettlementFailure::ReceiptPersistence(error) => SettleStep::ReceiptPersistenceFailed { error }, + }, metrics, generation_receipts, ); @@ -262,7 +273,7 @@ mod tests { } } - fn outcome_with(decision: Decision, inference_error: Option) -> SettleOutcome { + fn outcome_with(decision: Decision, failure: Option) -> SettleOutcome { SettleOutcome { spoken: match &decision { Decision::Speak { text } | Decision::RaiseUnprompted { text } => Some(text.clone()), @@ -273,7 +284,7 @@ mod tests { world_state: String::new(), room_updates: Default::default(), metrics: TurnMetrics::default(), - inference_error, + failure: failure.map(SettlementFailure::Inference), deferred_before_dispatch: false, capacity_refusal: None, touched_paths: Vec::new(), @@ -335,7 +346,7 @@ mod tests { matches!(step, SettleStep::Passed { reason: Some(r) } if r == "done — patch ready") ); - // inference_error present → InferenceFailed, REGARDLESS of decision — a + // failure present → InferenceFailed, REGARDLESS of decision — a // failed model is never a chosen silence. let (step, _, _) = SettleStep::from_settled(outcome_with( Decision::pass(), diff --git a/core/continuum-cognition/src/cognition/context_streams/tasks.rs b/core/continuum-cognition/src/cognition/context_streams/tasks.rs index 0b94ff9ea5..fd22ea4e3b 100644 --- a/core/continuum-cognition/src/cognition/context_streams/tasks.rs +++ b/core/continuum-cognition/src/cognition/context_streams/tasks.rs @@ -9,10 +9,18 @@ use continuum_context::source::{Item, Source}; use super::{element, priority, ContextMessage, Producer}; use crate::cognition::working_memory::{DispatchStatus, WorkingMemory}; +use continuum_kernel::runtime::tasks::TaskEndState; + +/// A durable end is a different occurrence from a streaming dispatch update. +/// Bind the complete immutable result fingerprint, not just its status label. +pub(crate) fn terminal_element(persona: uuid::Uuid, task: uuid::Uuid, fingerprint: &[u8; 32]) -> ElementId { + element(persona, Producer::Task, &[task.as_bytes().as_slice(), fingerprint.as_slice()].concat()) +} /// The one mapping from a task's state to the occurrence her view renders and a render receipt /// names: a task's terminal state is its own occurrence, so acknowledging an end never matches the -/// running line that came before it. The task ledger (#5585) calls this to read a receipt. +/// running line that came before it. Durable ledger ends use terminal_element instead, +/// which binds their complete immutable fingerprint. pub(crate) fn task_element(persona: uuid::Uuid, task: uuid::Uuid, status: &DispatchStatus) -> ElementId { let state = match status { DispatchStatus::Running => 0u8, @@ -27,6 +35,14 @@ pub(crate) struct Tasks<'a> { pub persona: uuid::Uuid, } +fn task_line(task: uuid::Uuid, word: &str, label: Option<&str>) -> String { + let line = format!("{word} task {}", airc_core::shown_id::shown_form(task)); + match label { + Some(label) if !label.is_empty() => format!("{line} {label}"), + _ => line, + } +} + impl Source for Tasks<'_> { fn name(&self) -> &str { "tasks" @@ -37,8 +53,14 @@ impl Source for Tasks<'_> { } fn items(&self) -> Vec> { - let tasks = self.memory.dispatched_snapshot(); - if tasks.is_empty() { + let terminals = self.memory.task_terminals(); + let terminal_ids: std::collections::BTreeSet<_> = terminals.iter().map(|end| end.task).collect(); + let dispatched = self.memory.dispatched_snapshot(); + let labels: std::collections::BTreeMap<_, _> = dispatched.iter() + .map(|(task, label, ..)| (*task, label.clone())).collect(); + let tasks: Vec<_> = dispatched.into_iter() + .filter(|(task, ..)| !terminal_ids.contains(task)).collect(); + if tasks.is_empty() && !terminals.iter().any(|end| end.wake_pending) { return Vec::new(); } let banner = super::standing( @@ -54,13 +76,28 @@ impl Source for Tasks<'_> { DispatchStatus::Done => "ok", DispatchStatus::Failed => "failed", }; - let line = format!("{word} task {} {label}", airc_core::shown_id::shown_form(task)); + let line = task_line(task, word, Some(&label)); let whole = if output.is_empty() { line.clone() } else { format!("{line}\n{output}") }; let summary = summarize(&output, Shape::Output).map(|level| ContextMessage::user(format!("{line}\n{level}"))); Item::whole(task_element(self.persona, task, &status), Cause::Root(Origin::ActivityStart), task.to_string(), ContextMessage::user(whole)) .with_summary(summary) .with_pointer(ContextMessage::user(line)) })); + items.extend(terminals.into_iter().filter(|end| end.wake_pending).map(|end| { + let status = match end.state { + TaskEndState::Done => "ok", + TaskEndState::Failed => "failed", + TaskEndState::TimedOut => "timed_out", + TaskEndState::Stopped => "stopped", + TaskEndState::Lost => "lost", + }; + // This item is the terminal notification, not a projection claiming + // to contain the ledger's output. Its identity binds that exact end. + let line = ContextMessage::user(task_line(end.task, status, labels.get(&end.task).map(String::as_str))); + Item::whole(terminal_element(self.persona, end.task, &end.fingerprint), + Cause::Root(Origin::ActivityStart), end.task.to_string(), line.clone()) + .with_pointer(line) + })); items } } @@ -70,6 +107,38 @@ mod tests { use super::*; use continuum_context::epoch::Block; + #[test] + fn terminal_replaces_dispatch_in_the_same_shape_and_keeps_known_label() { + use continuum_kernel::runtime::tasks::{TaskEnd, TaskOutput}; + let memory = WorkingMemory::new(8); + let persona = uuid::Uuid::new_v4(); + let task = uuid::Uuid::new_v4(); + memory.record_dispatch_event(task, "compile core", "working", DispatchStatus::Running); + memory.stage_task_end(task, TaskEnd::Done(TaskOutput::Json(serde_json::json!({"ok": true})))).expect("fixture terminal"); + memory.publish_task_checkpoint(memory.snapshot().task_results.publication()); + let items = Tasks { memory: &memory, persona }.items(); + let expected = format!("ok task {} compile core", airc_core::shown_id::shown_form(task)); + assert_eq!(items.iter().filter(|item| item.full().text == expected).count(), 1); + assert!(items.iter().all(|item| !item.full().text.contains("running task"))); + let restored = WorkingMemory::new(8); + restored.restore(memory.snapshot()); + let expected = format!("ok task {}", airc_core::shown_id::shown_form(task)); + assert!(Tasks { memory: &restored, persona }.items().iter().any(|item| item.full().text == expected)); + } + + #[test] + fn dispatch_has_one_source_even_when_thoughts_are_present() { + let memory = WorkingMemory::new(8); + let persona = uuid::Uuid::new_v4(); + let task = uuid::Uuid::new_v4(); + memory.record("I will examine the completed work."); + memory.record_dispatch_event(task, "unique-dispatch-label", "finished", DispatchStatus::Done); + let thoughts = super::super::thoughts::Thoughts { memory: &memory, persona }.items(); + assert!(thoughts.iter().all(|item| !item.full().text.contains("unique-dispatch-label"))); + let tasks = Tasks { memory: &memory, persona }.items(); + assert_eq!(tasks.iter().filter(|item| item.full().text.contains("unique-dispatch-label")).count(), 1); + } + // what this catches: a task's end that a receipt cannot name (the terminal state sharing the // running line's occurrence), or a level that drops how the task ended (Codex on #5639: the // ledger acknowledges from the first receipt listing the terminal element at any level). diff --git a/core/continuum-cognition/src/cognition/context_streams/tests.rs b/core/continuum-cognition/src/cognition/context_streams/tests.rs index c64b56f6a4..57720c7062 100644 --- a/core/continuum-cognition/src/cognition/context_streams/tests.rs +++ b/core/continuum-cognition/src/cognition/context_streams/tests.rs @@ -78,6 +78,9 @@ fn a_view_from_an_older_build_is_dropped_and_authoritative_state_survives() { use crate::cognition::working_memory::VolatileSnapshot; let memory = WorkingMemory::new(8); + let task = uuid::Uuid::new_v4(); + memory.stage_task_ends(vec![(task, continuum_kernel::runtime::tasks::TaskEnd::Stopped)]) + .expect("stage authoritative terminal"); memory.record_receipt("I ran code/list Result: 4 files"); memory.record_settlement("listed the four files", None); let actions = Actions { memory: &memory, persona: uuid::Uuid::nil() }; @@ -85,6 +88,7 @@ fn a_view_from_an_older_build_is_dropped_and_authoritative_state_survives() { let (view, _) = View::start(Vec::new(), &[&actions as &dyn Source<_>], whole).unwrap(); memory.keep_view(Some(view)); // Text, never `serde_json::Value`: the view's element ids are u128, which a Value cannot hold. + let terminals = serde_json::to_string(&memory.snapshot().task_results).expect("terminal references"); let good = serde_json::to_string(&memory.snapshot()).expect("encode"); // The older build's shape: the same real view, its `level` pairs removed and nothing else. @@ -105,6 +109,8 @@ fn a_view_from_an_older_build_is_dropped_and_authoritative_state_survives() { restored.restore(snap); assert!(restored.take_view().is_none(), "the stale view is dropped: her next act opens a new epoch"); assert!(restored.has_receipt(), "her newest result survives"); + assert_eq!(restored.pending_task_wakes(), vec![task], "discarding a view must not acknowledge an end"); + assert_eq!(serde_json::to_string(&restored.snapshot().task_results).expect("terminal references"), terminals); let settled = |m: &WorkingMemory| m.recent_entries().iter().any(|entry| entry.text.contains("listed the four files")); assert!(settled(&restored), "her settlement survives"); @@ -118,7 +124,10 @@ fn a_view_from_an_older_build_is_dropped_and_authoritative_state_survives() { let saved = serde_json::to_string(&restored.snapshot()).expect("encode"); assert!(!saved.contains("\"context_view\"")); let again = WorkingMemory::new(8); + assert_eq!(serde_json::to_string(&restored.snapshot().task_results).expect("terminal references"), terminals, + "terminal identity and fingerprint survive the next save"); again.restore(serde_json::from_str(&saved).expect("the repaired save decodes")); + assert_eq!(again.pending_task_wakes(), vec![task]); assert!(again.has_receipt() && settled(&again), "authoritative state survives the repaired save"); // A corrupt authoritative field is still refused: only the derived view is forgiven. diff --git a/core/continuum-cognition/src/cognition/deferred_faculty.rs b/core/continuum-cognition/src/cognition/deferred_faculty.rs index 92317c809b..819f3ea1ec 100644 --- a/core/continuum-cognition/src/cognition/deferred_faculty.rs +++ b/core/continuum-cognition/src/cognition/deferred_faculty.rs @@ -40,7 +40,7 @@ use std::sync::Arc; use async_trait::async_trait; use continuum_kernel::runtime::stage::{ - Cost, ExecutionCost, InputRevision, MindId, Provenance, Ran, ResidencyCost, RunOutcome, Stage, + Cost, ExecutionCost, InputRevision, MindId, Ran, ResidencyCost, RunOutcome, Stage, StageContext, StageId, StageIncarnation, StageRunner, TopicName, Triggers, }; use uuid::Uuid; @@ -97,9 +97,9 @@ impl Stage for FacultyStage { async fn run( &self, - ctx: &StageContext, + _ctx: &StageContext, ws: &Workspace, - revisions: &[InputRevision], + _revisions: &[InputRevision], ) -> RunOutcome> { let finding = self.inner.contribute(ws).await.map(|mut c| { // Stamp with the cycle it reasoned against AND the room it reasoned about: the late @@ -112,13 +112,7 @@ impl Stage for FacultyStage { contribution: c, } }); - RunOutcome::Produced(vec![( - finding, - Provenance { - by: ctx.run, - from: revisions.to_vec(), - }, - )]) + RunOutcome::Produced(vec![finding]) } } diff --git a/core/continuum-cognition/src/cognition/generate_response.rs b/core/continuum-cognition/src/cognition/generate_response.rs index 17d7d75a39..2337a70b8f 100644 --- a/core/continuum-cognition/src/cognition/generate_response.rs +++ b/core/continuum-cognition/src/cognition/generate_response.rs @@ -1,6 +1,6 @@ //! Rust-owned response-generation prompt assembly and admission. //! -//! Rust owns response admission, the response-generation contract, +//! The shared inference gateway owns admission. This module owns the contract, //! prompt assembly, and the identity-reminder template. Host runtimes //! may be native Rust, game/live loops, AIRC daemons, or wrappers around //! those hosts; none of them own cognition slot coordination for this @@ -39,14 +39,10 @@ use crate::ai::adapter::InferenceDevice; use crate::ai::types::ResponseFormat; use crate::ai::{ChatMessage, MessageContent, TextGenerationRequest, TextGenerationResponse}; -use crate::resources::throughput_class::{ResourceClass, TargetSilicon}; -use crate::inference::resource_admission::{ResourceAdmissionError, ResourceAdmissionGate, ResourceAdmissionGuard, ResourceAdmissionPolicy, ResourceAdmissionRequest}; use crate::cognition::should_respond::AIDecisionContext; -use crate::resources::throughput_lease::ThroughputLeaseRevocationPolicy; use crate::ai::adapter::global_registry; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; -use std::sync::LazyLock; use std::time::Duration; use ts_rs::TS; @@ -83,28 +79,6 @@ const DEFAULT_GENERATE_TEMPERATURE: f32 = 0.7; /// ceiling before `tokio::time::timeout` returns Err. const DEFAULT_GENERATE_TIMEOUT_MS: u64 = 180_000; -/// Conservative default for local response generation while the -/// substrate-governor bridge becomes the source of these numbers. -const DEFAULT_GENERATE_MAX_CONCURRENCY: usize = 4; - -/// Cost-unit budget paired with [`DEFAULT_GENERATE_MAX_CONCURRENCY`]. -const DEFAULT_GENERATE_MAX_COST_UNITS: u32 = 4; - -/// One response generation claims one local-generation cost unit unless -/// the caller provides a stricter policy. -const DEFAULT_GENERATE_COST_UNITS: u32 = 1; - -/// Lease TTL must outlive the generation timeout so slow-but-valid work -/// is not marked reclaimable before `tokio::time::timeout` fires. -const DEFAULT_GENERATE_LEASE_TTL_PAD_MS: u64 = 5_000; - -static GENERATE_RESPONSE_ADMISSION: LazyLock = - LazyLock::new(ResourceAdmissionGate::new); - -#[cfg(test)] -static GENERATE_RESPONSE_TEST_LOCK: LazyLock> = - LazyLock::new(|| std::sync::Mutex::new(())); - // ─── IPC request + response shapes ──────────────────────────────────── /// IPC request: ask the cognition service to assemble a response-prompt @@ -139,55 +113,6 @@ pub struct GenerateResponseRequest { #[ts(optional)] #[ts(optional, type = "number")] pub timeout_ms: Option, - /// Rust-owned admission policy for this generation. When omitted, - /// `evaluate_response` applies the local-generation defaults above. - /// Hosts that know tighter resource limits should pass them here; - /// they should not coordinate slots outside Rust. - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub admission: Option, -} - -/// Per-call local-generation admission policy. This is the contract a -/// host uses to ask Rust for response-generation capacity instead of -/// owning slots itself. -#[derive(Debug, Clone, Serialize, Deserialize, TS, PartialEq, schemars::JsonSchema)] -#[serde(rename_all = "camelCase")] -#[ts( - export, - export_to = "../../../protocol/typescript/cognition/GenerateResponseAdmissionPolicy.ts" -)] -pub struct GenerateResponseAdmissionPolicy { - pub target_silicon: TargetSilicon, - pub max_concurrency: usize, - pub max_cost_units: u32, - pub cost_units: u32, - #[ts(type = "number")] - pub lease_ttl_ms: u64, -} - -impl GenerateResponseAdmissionPolicy { - fn with_timeout(timeout_ms: u64) -> Self { - Self { - target_silicon: TargetSilicon::UnifiedMemory, - max_concurrency: DEFAULT_GENERATE_MAX_CONCURRENCY, - max_cost_units: DEFAULT_GENERATE_MAX_COST_UNITS, - cost_units: DEFAULT_GENERATE_COST_UNITS, - lease_ttl_ms: timeout_ms.saturating_add(DEFAULT_GENERATE_LEASE_TTL_PAD_MS), - } - } - - fn into_resource_policy(self) -> ResourceAdmissionPolicy { - ResourceAdmissionPolicy { - resource_class: ResourceClass::LocalGeneration, - target_silicon: self.target_silicon, - max_concurrency: self.max_concurrency, - max_cost_units: self.max_cost_units, - cost_units: self.cost_units, - lease_ttl_ms: self.lease_ttl_ms, - revocation_policy: ThroughputLeaseRevocationPolicy::Graceful, - } - } } /// IPC response: generated text plus timing + token telemetry. @@ -228,16 +153,6 @@ pub struct TokenUsage { /// the Rust caller decides policy explicitly. #[derive(Debug, thiserror::Error)] pub enum GenerateResponseError { - /// Rust admission denied this response before inference began. - /// Hosts ask Rust, receive a typed denial, and retry/replan explicitly. - #[error( - "response generation admission denied for persona={persona_id:?} room={room_id:?}: {reason}" - )] - AdmissionDenied { - persona_id: String, - room_id: String, - reason: String, - }, /// The provider registry had no adapter capable of serving this /// model + provider tuple. No alternate runtime is attempted. #[error("no AI adapter available for provider={provider:?} model={model:?}")] @@ -279,7 +194,7 @@ pub async fn evaluate_response( ) -> Result { let start_ms = continuum_base::time::EpochMs::now().millis(); let timeout_ms = request.timeout_ms.unwrap_or(DEFAULT_GENERATE_TIMEOUT_MS); - let _lease = acquire_generate_response_lease(&request, start_ms, timeout_ms)?; + // The llama-server adapter owns admission through the shared turn gateway. // Bind this turn to the persona's ESTABLISHED inference handle (reused across // turns, re-homed if lost — self-healing), bound to the model the engine actually @@ -352,53 +267,6 @@ pub async fn evaluate_response( Ok(result_from_response(response, model, start_ms, end_ms)) } -fn acquire_generate_response_lease( - request: &GenerateResponseRequest, - now_ms: u64, - timeout_ms: u64, -) -> Result { - let policy = request - .admission - .clone() - .unwrap_or_else(|| GenerateResponseAdmissionPolicy::with_timeout(timeout_ms)); - - GENERATE_RESPONSE_ADMISSION - .acquire(ResourceAdmissionRequest { - lease_id: generate_response_lease_id(&request.context, now_ms), - artifact_key: generate_response_artifact_key(&request.context), - holder_id: request.context.persona_id.clone(), - policy: policy.into_resource_policy(), - now_ms, - }) - .map_err(|err| GenerateResponseError::AdmissionDenied { - persona_id: request.context.persona_id.clone(), - room_id: request.context.room_id.clone(), - reason: format_resource_admission_error(err), - }) -} - -fn generate_response_lease_id(context: &AIDecisionContext, now_ms: u64) -> String { - format!( - "cognition/generate-response:{}:{}:{}", - context.room_id, context.persona_id, now_ms - ) -} - -fn generate_response_artifact_key(context: &AIDecisionContext) -> String { - format!( - "cognition/generate-response:{}:{}:{}", - context.room_id, context.persona_id, context.trigger_message.id - ) -} - -fn format_resource_admission_error(err: ResourceAdmissionError) -> String { - match err { - ResourceAdmissionError::InvalidPolicy { reason } - | ResourceAdmissionError::Denied { reason } - | ResourceAdmissionError::Lease { reason } => reason, - } -} - /// Build the `TextGenerationRequest` the adapter consumes. /// Pure: caller passes `request`, `model`, and the start-timestamp so /// tests can assert the request shape without time interference. diff --git a/core/continuum-cognition/src/cognition/generate_response/tests.rs b/core/continuum-cognition/src/cognition/generate_response/tests.rs index e0c2c681c1..446e7c8342 100644 --- a/core/continuum-cognition/src/cognition/generate_response/tests.rs +++ b/core/continuum-cognition/src/cognition/generate_response/tests.rs @@ -418,134 +418,11 @@ fn request_with_overrides( temperature: temp, max_tokens: max, timeout_ms: timeout, - admission: None, } } -fn request_with_admission( - context: AIDecisionContext, - admission: GenerateResponseAdmissionPolicy, -) -> GenerateResponseRequest { - GenerateResponseRequest { - context, - model: None, - temperature: None, - max_tokens: None, - timeout_ms: Some(100), - admission: Some(admission), - } -} - -fn admission( - max_concurrency: usize, - max_cost_units: u32, - cost_units: u32, -) -> GenerateResponseAdmissionPolicy { - GenerateResponseAdmissionPolicy { - target_silicon: TargetSilicon::UnifiedMemory, - max_concurrency, - max_cost_units, - cost_units, - lease_ttl_ms: 1_000, - } -} - -fn reset_generate_response_leases_for_test() { - GENERATE_RESPONSE_ADMISSION.reset_for_test(); -} - -fn lock_generate_response_tests() -> std::sync::MutexGuard<'static, ()> { - GENERATE_RESPONSE_TEST_LOCK - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) -} - -fn active_generate_response_leases_for_test(now_ms: u64) -> usize { - GENERATE_RESPONSE_ADMISSION.active_count_for_test(now_ms) -} - -/// What this catches: response admission is Rust-owned. A successful -/// acquire claims a local-generation lease, and dropping the RAII -/// guard releases it. The same drop path is what runs when -/// `evaluate_response` exits via success, provider error, missing -/// adapter, or timeout. -#[test] -fn rust_admission_guard_releases_local_generation_lease_on_exit() { - let _test_lock = lock_generate_response_tests(); - reset_generate_response_leases_for_test(); - let request = - request_with_admission(ctx(Some("You are Alice."), vec![]), admission(4, 4, 1)); - - { - let _guard = acquire_generate_response_lease(&request, 1_000, 100) - .expect("valid request should acquire a Rust lease"); - assert_eq!(active_generate_response_leases_for_test(1_001), 1); - } - - assert_eq!( - active_generate_response_leases_for_test(1_002), - 0, - "dropping the guard must release the local-generation lease" - ); -} - -/// What this catches: Rust denies over-capacity response generation -/// before any provider call. This is the hard boundary that keeps -/// host wrappers from owning cognition slots. -#[test] -fn rust_admission_denies_concurrency_and_cost_pressure() { - let _test_lock = lock_generate_response_tests(); - reset_generate_response_leases_for_test(); - let first = request_with_admission(ctx(Some("You are Alice."), vec![]), admission(1, 4, 1)); - let second = - request_with_admission(ctx(Some("You are Alice."), vec![]), admission(1, 4, 1)); - let _held = acquire_generate_response_lease(&first, 2_000, 100) - .expect("first request should fit the policy"); - - let err = acquire_generate_response_lease(&second, 2_001, 100) - .expect_err("second request must be denied by Rust concurrency policy"); - assert!(matches!( - err, - GenerateResponseError::AdmissionDenied { reason, .. } - if reason.contains("max_concurrency=1") - )); - - reset_generate_response_leases_for_test(); - let expensive = - request_with_admission(ctx(Some("You are Alice."), vec![]), admission(4, 2, 3)); - let err = acquire_generate_response_lease(&expensive, 3_000, 100) - .expect_err("request whose cost exceeds policy must be denied"); - assert!(matches!( - err, - GenerateResponseError::AdmissionDenied { reason, .. } - if reason.contains("cost_units=3 exceeds max_cost_units=2") - )); -} - -/// What this catches: expired leases are reaped during Rust -/// admission, so a dead holder does not permanently block the -/// local-generation lane. -#[test] -fn rust_admission_reaps_expired_generation_leases() { - let _test_lock = lock_generate_response_tests(); - reset_generate_response_leases_for_test(); - let request = - request_with_admission(ctx(Some("You are Alice."), vec![]), admission(1, 1, 1)); - let guard = acquire_generate_response_lease(&request, 4_000, 100) - .expect("first request should fit the policy"); - std::mem::forget(guard); - - assert_eq!(active_generate_response_leases_for_test(4_001), 1); - let replacement = acquire_generate_response_lease(&request, 5_001, 100) - .expect("expired forgotten lease should be reaped before admission"); - replacement - .release() - .expect("explicit release should return the replacement lease"); - assert_eq!(active_generate_response_leases_for_test(5_002), 0); -} - /// What this catches: defaults — no overrides — produces a -/// TextGenerationRequest with provider="local", model=Qwen-default, +/// TextGenerationRequest routed to the llama-server gateway with an explicit model, /// temperature=0.7, max_tokens=None (the model owns its length), /// response_format=Text, purpose="cognition/generate-response", and /// persona/room attribution carried from the context. Pins the wire diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs index 9d6a932a44..8a61ff8088 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs @@ -560,15 +560,17 @@ impl Faculty for LlmDeliberationFaculty { async fn contribute(&self, ws: &Workspace) -> Option { let mut receipts = Vec::new(); - let contribution = self.contribute_with_receipts(ws, &mut receipts).await; + let mut rendered = Vec::new(); + let contribution = self.contribute_with_receipts(ws, &mut receipts, &mut rendered).await; let mut contribution = match contribution { Some(contribution) => contribution, - None if receipts.is_empty() => return None, + None if receipts.is_empty() && rendered.is_empty() => return None, // A corrective retry may yield before dispatch. Keep its earlier // attempt's evidence without inventing a decision or another call. None => Contribution::context(FacultyId::Deliberation, "", 0.0, ""), }; contribution.receipts = receipts; + contribution.render_receipts = rendered; Some(contribution) } } diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/request.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/request.rs index 48b841ab5b..e018ba053b 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/request.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/request.rs @@ -135,6 +135,7 @@ impl LlmDeliberationFaculty { // The allocation her prompt was fitted under: the receipt carries it with the capture. allocation: Option, receipts: &mut Vec, + rendered: &mut Vec, ) -> Option> { // Identity belongs to the submitted adapter request. Provider response IDs // remain separate, and one workspace can issue several calls. @@ -290,6 +291,10 @@ impl LlmDeliberationFaculty { .and_then(|r| r.timing.as_ref()) .map(|t| (t.cached_tokens, t.prefill_tokens)), ); + // The render receipt: taken on every outcome, so a failed request's prompt is never + // receipted, and delivered only where the request was served. + let submitted = self.context_view.lock().as_mut().and_then(continuum_context::view::View::take_submitted); + let receipted_request = request_id.clone(); let receipt = match &gen_result { Ok(response) => crate::ai::provenance::GenerationReceipt::from_response(request_id, response), Err(error) => crate::ai::provenance::GenerationReceipt::faulted(request_id, error.to_string()), @@ -298,6 +303,17 @@ impl LlmDeliberationFaculty { // window reads: in the window it was served in, whether or not her turn settles soon. if matches!(receipt.outcome, crate::ai::provenance::GenerationOutcome::Served { .. }) { crate::cognition::resident_service::note_generation(self.persona_id); + // A measurement fork's prompts are not hers: they never acknowledge what she was shown. + if let (Some(view), false, Some(memory)) = + (submitted, self.forked, self.working_memory.as_ref()) + { + rendered.push(crate::cognition::render_receipt::RenderReceipt { + owner: self.persona_id, + incarnation: memory.incarnation(), + request: receipted_request, + view, + }); + } } receipts.push( receipt diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/window_feedback.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/window_feedback.rs index 480078dab8..4eb4c1c3d1 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/window_feedback.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/window_feedback.rs @@ -311,6 +311,15 @@ async fn provider_context_feedback_refits_and_captures_each_attempt() { < LlmDeliberationFaculty::messages_cost(&pair[0].messages)); } assert_eq!(outcome.receipts.len(), seen.len()); + let served: Vec<_> = outcome.receipts.iter().filter(|receipt| { + matches!(receipt.outcome, crate::ai::provenance::GenerationOutcome::Served { .. }) + }).collect(); + assert_eq!(outcome.render_receipts.len(), served.len()); + for (rendered, generation) in outcome.render_receipts.iter().zip(served) { + assert_eq!(rendered.owner, persona); + assert_eq!(rendered.incarnation, wm.incarnation()); + assert_eq!(rendered.request, generation.submitted_request_id); + } for (receipt, request) in outcome.receipts.iter().zip(seen.iter()) { assert_eq!( Some(&receipt.submitted_request_id), @@ -428,6 +437,7 @@ async fn provider_context_feedback_faults_when_required_input_cannot_fit() { let outcome = faculty.contribute(&ws).await.expect("fault contribution"); assert!(outcome.fault.is_none()); assert!(outcome.capacity_refusal.is_some()); + assert!(outcome.render_receipts.is_empty(), "a refused prompt cannot retire task ends"); assert_eq!( outcome.receipts.len(), 1, diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs index 479434f63c..7b700477b4 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs @@ -5,6 +5,7 @@ impl LlmDeliberationFaculty { &self, ws: &Workspace, receipts: &mut Vec, + rendered: &mut Vec, ) -> Option { // ONE atomic snapshot of the model binding for the whole turn — the // adapter we generate through, the model we request, and the served window @@ -307,7 +308,7 @@ impl LlmDeliberationFaculty { // previous value is also what keeps the initializer honest). sent_allowance = request.max_tokens.or(sent_allowance); let result = self - .generate_for_workspace(ws, &binding, fit_window, request, view.allocation.clone(), receipts) + .generate_for_workspace(ws, &binding, fit_window, request, view.allocation.clone(), receipts, rendered) .await?; gen_await_ms = gen_await_ms.saturating_add(started.elapsed().as_millis() as u64); match result { @@ -744,12 +745,10 @@ impl LlmDeliberationFaculty { }; return Some(self.act_verdict(vec![call], &resp, ws.activity_room_id)); } - // Its ends at the codec's Output level (head and tail, never a head cut), else whole. - use continuum_context::levels::{summarize, Shape}; - let cut = summarize(&resp.text, Shape::Output).unwrap_or_else(|| resp.text.clone()); // unwrap_or_else: no smaller level means the text is its own summary return Some(Contribution::deliberation_fault(format!( - "the model hit the output limit mid-thought with no committed action (finish_reason Length, {} chars) — a cut thought is not an answer. It read: {cut}", - resp.text.len() + "the model hit the output limit mid-thought with no committed action \ + (finish_reason Length, {} bytes, response {}) — a cut thought is not an answer", + resp.text.len(), resp.request_id ))); } diff --git a/core/continuum-cognition/src/cognition/mod.rs b/core/continuum-cognition/src/cognition/mod.rs index c571c85fc8..a4cedbe143 100644 --- a/core/continuum-cognition/src/cognition/mod.rs +++ b/core/continuum-cognition/src/cognition/mod.rs @@ -65,6 +65,7 @@ pub use continuum_capture::prompt_capture; pub mod rag_source_faculty; pub mod rate_proposals; pub mod recall_faculty; +pub mod render_receipt; pub mod recent_message; pub use continuum_prompt::audience; pub use continuum_engram::recall_ranker; diff --git a/core/continuum-cognition/src/cognition/persona_workspace.rs b/core/continuum-cognition/src/cognition/persona_workspace.rs index ef1bc389fb..277f381224 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace.rs @@ -29,19 +29,20 @@ use uuid::Uuid; use crate::identity::{PeerId, PersonaRef}; use super::deferred_faculty::DeferredFaculty; -use crate::ai::embedding::{CachingEmbeddingProvider, EmbeddingProvider, LexicalEmbedder}; use super::llm_deliberation_faculty::LlmDeliberationFaculty; use super::rag_source_faculty::{RagSourceFaculty, SaliencePolicy}; use super::recall_faculty::RecallFaculty; use super::working_memory::WorkingMemory; use super::workspace::{ActingBody, Faculty, SituationFocusArbiter, WorkspaceCycle}; use crate::ai::adapter::AIProviderAdapter; +use crate::ai::embedding::{CachingEmbeddingProvider, EmbeddingProvider, LexicalEmbedder}; use crate::cognition::admission_state::AdmissionState; use crate::cognition::rag_budget::RagSource; /// Explicit offline adoption of a selected legacy checkpoint; shares this /// owner's schema, native path, and cross-process checkpoint exclusion. pub mod checkpoint_adoption; +mod checkpoint_storage; mod act_output; mod rehome; @@ -58,7 +59,12 @@ mod acting_hands; pub use acting_hands::*; mod root_acting_workspace; pub use root_acting_workspace::*; +mod owner_checkpoint; +pub use owner_checkpoint::OwnerCheckpointError; +mod task_consumption; +pub use task_consumption::{ResidentTaskSink, TaskConsumptionError, TaskSinkError}; mod own_speech_persisted; +pub use own_speech_persisted::VolatileReceipt; mod mind_results_reporter; pub use mind_results_reporter::MindResultsReporter; pub(crate) use own_speech_persisted::*; diff --git a/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_adoption.rs b/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_adoption.rs index cccb5ab3ba..2af0047c0d 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_adoption.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_adoption.rs @@ -5,11 +5,11 @@ //! caller's offline check, and never claims the selected snapshot was flushed //! at shutdown or authenticated to a process lifetime. -use std::fs::{self, File, OpenOptions}; -use std::io::{self, Read, Write}; +use super::checkpoint_storage::resolved_path; +use std::fs::{self, File}; +use std::io::{self, Read}; use std::path::{Path, PathBuf}; -use fs2::FileExt; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use uuid::Uuid; @@ -188,27 +188,6 @@ fn optional_selection(path: &Path) -> Result, Adopti } } -fn resolved_path(path: &Path) -> Result { - match fs::symlink_metadata(path) { - Ok(metadata) => { - if metadata.file_type().is_symlink() { - return Err(invalid( - "symbolic checkpoint/evidence paths are not accepted", - )); - } - Ok(fs::canonicalize(path)?) - } - Err(error) if error.kind() == io::ErrorKind::NotFound => { - let parent = path.parent().ok_or_else(|| invalid("path has no parent"))?; - let name = path - .file_name() - .ok_or_else(|| invalid("path has no filename"))?; - Ok(resolved_path(parent)?.join(name)) - } - Err(error) => Err(error.into()), - } -} - fn source_path(path: &Path, persona: Uuid) -> Result { if persona.is_nil() { return Err(invalid("an explicit non-nil persona UUID is required")); @@ -263,90 +242,49 @@ fn exists(path: &Path) -> io::Result { /// Same file lock used by save, load and adoption. Callers keep the returned /// handle alive until their complete file operation ends. Readers wait rather /// than interpreting another owner's work as an absent checkpoint. -pub(super) fn lock_checkpoint(path: &Path, wait: bool) -> io::Result { - let parent = path - .parent() - .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "checkpoint has no parent"))?; - fs::create_dir_all(parent)?; - let lock_path = parent.join(".volatile.lock"); - match fs::symlink_metadata(&lock_path) { - Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_file() => { - return Err(io::Error::new( - io::ErrorKind::InvalidInput, - "checkpoint lock is not a regular file", - )); - } - Ok(_) => {} - Err(error) if error.kind() == io::ErrorKind::NotFound => {} - Err(error) => return Err(error), - } - let file = OpenOptions::new() - .read(true) - .write(true) - .create(true) - .truncate(false) - .open(lock_path)?; - if wait { - FileExt::lock_exclusive(&file)?; - } else { - FileExt::try_lock_exclusive(&file)?; - } - Ok(file) +pub(super) fn lock_checkpoint( + path: &Path, + wait: bool, +) -> io::Result { + super::checkpoint_storage::for_path(path)?.lock(Path::new(".volatile.lock"), wait) } -pub(super) fn sync_parent(path: &Path) -> io::Result<()> { - // POSIX directory durability. Windows file contents are flushed below; - // this receipt does not promise power-loss directory-journal guarantees. - #[cfg(unix)] - File::open( - path.parent() - .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "no parent"))?, - )? - .sync_all()?; - #[cfg(not(unix))] - let _ = path; - Ok(()) +fn relative<'a>( + writer: &continuum_kernel::system_resources::disk_reporters::ClassWriter, + path: &'a Path, +) -> io::Result { + let checkpoint = resolved_path(&writer.path(Path::new("volatile.json"))?)?; + let parent = checkpoint + .parent() + .ok_or_else(|| io::Error::other("checkpoint has no parent"))?; + resolved_path(path)? + .strip_prefix(parent) + .map(Path::to_path_buf) + .map_err(|_| { + io::Error::new( + io::ErrorKind::InvalidInput, + "adoption evidence is outside owner class", + ) + }) } -fn preserve(path: &Path, bytes: &[u8]) -> Result<(), AdoptionError> { - if exists(path)? { - return if read_bounded(path)? == bytes { - // A previous publication may have reached its final name before - // parent sync failed; equality alone does not complete that step. - sync_parent(path)?; - Ok(()) - } else { - Err(AdoptionError::EvidenceConflict(path.display().to_string())) - }; - } - let parent = path - .parent() - .ok_or_else(|| invalid("evidence has no parent"))?; - let temporary = parent.join(format!(".preserve-{}.tmp", Uuid::new_v4())); - let mut file = OpenOptions::new() - .write(true) - .create_new(true) - .open(&temporary)?; - file.write_all(bytes)?; - file.sync_all()?; - drop(file); - // Publish a complete inode without overwriting existing evidence. Unlike a - // direct create+write, an interrupted write never occupies the final name. - // Both paths are on the same filesystem. Unsupported hard links are an IO - // refusal, not a fallback to a partially visible or destructive write. - let published = fs::hard_link(&temporary, path); - match published { - Ok(()) => {} +fn preserve( + writer: &continuum_kernel::system_resources::disk_reporters::ClassWriter, + path: &Path, + bytes: &[u8], +) -> Result<(), AdoptionError> { + let name = relative(writer, path)?; + match writer.publish_new(&name, bytes) { + Ok(()) => Ok(()), Err(error) if error.kind() == io::ErrorKind::AlreadyExists => { if read_bounded(path)? != bytes { return Err(AdoptionError::EvidenceConflict(path.display().to_string())); } + writer.fence_existing(&name)?; + Ok(()) } - Err(error) => return Err(error.into()), + Err(error) => Err(error.into()), } - fs::remove_file(&temporary)?; - sync_parent(path)?; - Ok(()) } /// Adopt the selected bytes under the checkpoint owner's exclusion. The @@ -371,7 +309,8 @@ pub fn adopt( "plan paths no longer match declared identity and native destination", )); } - let _lock = lock_checkpoint(&destination, false)?; + let writer = super::checkpoint_storage::for_path(&destination)?; + let _lock = writer.lock(Path::new(".volatile.lock"), false)?; ensure_offline()?; let encoded_plan = serde_json::to_vec(plan).map_err(|error| invalid(error.to_string()))?; let parent = destination @@ -425,10 +364,10 @@ pub fn adopt( { // Complete a previous rename's directory durability step before // acknowledging recovery, even if its first attempt failed here. - sync_parent(&destination)?; + writer.fence_existing(Path::new("volatile.json"))?; let encoded_receipt = serde_json::to_vec(&receipt).map_err(|error| invalid(error.to_string()))?; - preserve(&receipt_path, &encoded_receipt)?; + preserve(&writer, &receipt_path, &encoded_receipt)?; receipt.already_applied = true; return Ok(receipt); } @@ -439,24 +378,23 @@ pub fn adopt( if current_destination != plan.prior_destination { return Err(AdoptionError::DestinationChanged); } - fs::create_dir_all(&evidence)?; // Archives before intent: a visible plan always has complete preserved // inputs. Partial files are a refusal on retry, never silently overwritten. - preserve(&archive, &source_bytes)?; + preserve(&writer, &archive, &source_bytes)?; if let Some(expected) = &plan.prior_destination { let (current, bytes) = selection(&destination)?; if ¤t != expected { return Err(AdoptionError::DestinationChanged); } - preserve(&prior, &bytes)?; + preserve(&writer, &prior, &bytes)?; } - preserve(&intent, &encoded_plan)?; + preserve(&writer, &intent, &encoded_plan)?; // Separate inode from immutable evidence, so future in-place writes to the // live file cannot alter the source archive. // One staged payload per explicit plan: repeated offline/precondition // refusals reuse its verified bytes instead of accumulating full copies. let staged = evidence.join("staged.json"); - preserve(&staged, &source_bytes)?; + preserve(&writer, &staged, &source_bytes)?; ensure_offline()?; if selection(&plan.source.path)?.0 != plan.source { return Err(AdoptionError::SourceChanged); @@ -464,8 +402,7 @@ pub fn adopt( if optional_selection(&destination)? != plan.prior_destination { return Err(AdoptionError::DestinationChanged); } - fs::rename(&staged, &destination)?; - sync_parent(&destination)?; + writer.replace(Path::new("volatile.json"), &source_bytes)?; let published = optional_selection(&destination)?; if published .as_ref() @@ -477,6 +414,6 @@ pub fn adopt( } let encoded_receipt = serde_json::to_vec(&receipt).map_err(|error| invalid(error.to_string()))?; - preserve(&receipt_path, &encoded_receipt)?; + preserve(&writer, &receipt_path, &encoded_receipt)?; Ok(receipt) } diff --git a/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_storage.rs b/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_storage.rs new file mode 100644 index 0000000000..89585c625b --- /dev/null +++ b/core/continuum-cognition/src/cognition/persona_workspace/checkpoint_storage.rs @@ -0,0 +1,80 @@ +//! Checkpoint paths, locks and writes share the personas disk-class owner. +use continuum_kernel::system_resources::disk_reporters::ClassWriter; +use std::{ + io, + path::{Path, PathBuf}, +}; +use uuid::Uuid; + +pub(super) fn writer(owner: Uuid) -> io::Result { + #[cfg(not(any(test, feature = "test-fixtures")))] + let class = ClassWriter::of("personas")?; + // Explicit test layout, from the same class catalog as boot. Resolve on this + // thread so NativeHomeOverride and blocking-worker fixture custody agree. + #[cfg(any(test, feature = "test-fixtures"))] + let class = { + let native = crate::paths::home_dir() + .ok_or_else(|| io::Error::other("fixture has no native home"))?; + let home = crate::paths::continuum_home().map_err(io::Error::other)?; + continuum_kernel::system_resources::disk_reporters::standard_tracked_dirs(&native, &home) + .into_iter() + .find(|class| class.class() == "personas") + .ok_or_else(|| io::Error::other("fixture catalog has no personas class"))? + .writer() + }; + Ok(class.owned_by(owner)) +} + +pub(super) fn path(owner: Uuid) -> io::Result { + writer(owner)?.path(Path::new("volatile.json")) +} + +pub(super) fn for_path(path: &Path) -> io::Result { + let owner = path + .parent() + .and_then(Path::file_name) + .and_then(|s| s.to_str()) + .and_then(|s| Uuid::parse_str(s).ok()) + .ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidInput, "checkpoint has no typed owner") + })?; + let writer = writer(owner)?; + if resolved_path(&std::path::absolute(path)?)? + != resolved_path(&std::path::absolute( + writer.path(Path::new("volatile.json"))?, + )?)? + { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "checkpoint is outside its owner class", + )); + } + Ok(writer) +} + +/// Resolve existing ancestors before comparing class custody. Temporary homes on +/// macOS may use /var while canonical paths use /private/var. The ClassWriter +/// still owns confinement and the actual held-directory write. +pub(super) fn resolved_path(path: &Path) -> io::Result { + match std::fs::symlink_metadata(path) { + Ok(metadata) => { + if metadata.file_type().is_symlink() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "symbolic checkpoint/evidence paths are not accepted", + )); + } + std::fs::canonicalize(path) + } + Err(error) if error.kind() == io::ErrorKind::NotFound => { + let parent = path + .parent() + .ok_or_else(|| io::Error::other("path has no parent"))?; + let name = path + .file_name() + .ok_or_else(|| io::Error::other("path has no filename"))?; + Ok(resolved_path(parent)?.join(name)) + } + Err(error) => Err(error), + } +} diff --git a/core/continuum-cognition/src/cognition/persona_workspace/own_speech_persisted.rs b/core/continuum-cognition/src/cognition/persona_workspace/own_speech_persisted.rs index 0c404298d0..c8dd19b0dd 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/own_speech_persisted.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/own_speech_persisted.rs @@ -28,16 +28,32 @@ impl OwnSpeechPersisted { } pub(super) fn volatile_path(persona_id: Uuid) -> std::io::Result { - let home = crate::paths::home_dir().ok_or_else(|| { - std::io::Error::new( - std::io::ErrorKind::NotFound, - "cannot resolve persistent home directory", - ) - })?; - Ok(home - .join(".continuum/personas") - .join(persona_id.to_string()) - .join("volatile.json")) + checkpoint_storage::path(persona_id) +} + +/// Proof returned only after the exact snapshot is synced and renamed. The registry +/// must match the incarnation against its current resident before using these IDs. +#[derive(Debug)] +pub struct VolatileReceipt { + owner: Uuid, + incarnation: Uuid, + consumed_tasks: Vec, + perceived_tasks: std::collections::BTreeSet, +} + +impl VolatileReceipt { + pub fn owner(&self) -> Uuid { + self.owner + } + pub fn incarnation(&self) -> Uuid { + self.incarnation + } + pub fn consumed_tasks(&self) -> &[Uuid] { + &self.consumed_tasks + } + pub fn perceived_tasks(&self) -> &std::collections::BTreeSet { + &self.perceived_tasks + } } /// Persist the volatile tier — atomic tmp+rename so a crash mid-write never @@ -48,9 +64,9 @@ pub(super) fn save_volatile( reason: SaveReason, staged_deadline: Option, wm: &super::super::working_memory::WorkingMemory, -) -> std::io::Result<()> { - let path = volatile_path(persona_id)?; - let _checkpoint_lock = checkpoint_adoption::lock_checkpoint(&path, true)?; +) -> std::io::Result { + let writer = checkpoint_storage::writer(persona_id)?; + let _checkpoint_lock = writer.lock(std::path::Path::new(".volatile.lock"), true)?; let mut snapshot = wm.snapshot(); // THE HANDOFF (card 49b5e806): composed from what her turns already stamped (rooting, // work/note, the seam walk) plus the two things only the seam knows — what tears this @@ -75,23 +91,27 @@ pub(super) fn save_volatile( snapshot.acting_card = wm .peek_restored_acting_card() .or_else(|| acting_card_of(persona_id)); + let receipt = VolatileReceipt { + owner: persona_id, + incarnation: wm.incarnation(), + consumed_tasks: snapshot.task_results.consumed_ids(), + perceived_tasks: snapshot.task_results.perceived_ids(), + }; + let task_publication = snapshot.task_results.publication(); let persisted = PersistedVolatile { wm: snapshot, - own_speech: OwnSpeechPersisted::ByRoom(super::super::deliberation_budget::own_speech_by_room( - crate::identity::PeerId::from_uuid(persona_id), - )), + own_speech: OwnSpeechPersisted::ByRoom( + super::super::deliberation_budget::own_speech_by_room( + crate::identity::PeerId::from_uuid(persona_id), + ), + ), }; - if let Some(dir) = path.parent() { - std::fs::create_dir_all(dir)?; - } - let tmp = path.with_extension("json.tmp"); - use std::io::Write; - let mut file = std::fs::File::create(&tmp)?; - file.write_all(&serde_json::to_vec(&persisted)?)?; - file.sync_all()?; - drop(file); - std::fs::rename(&tmp, &path)?; - checkpoint_adoption::sync_parent(&path) + writer.replace( + std::path::Path::new("volatile.json"), + &serde_json::to_vec(&persisted)?, + )?; + wm.publish_task_checkpoint(task_publication); + Ok(receipt) } /// Load the previous life's volatile tier under the same owner lock as saves @@ -108,14 +128,19 @@ pub(super) fn save_volatile( pub(crate) fn persisted_result_handles( persona_id: Uuid, ) -> std::io::Result>> { - result_handles_at(&volatile_path(persona_id)?) + let path = volatile_path(persona_id)?; + let _lock = checkpoint_adoption::lock_checkpoint(&path, true)?; + result_handles_at(&path) } /// [`persisted_result_handles`] for the checkpoint at `path` (the filesystem seam). pub(super) fn result_handles_at( path: &std::path::Path, ) -> std::io::Result>> { - type Cached = (std::time::SystemTime, std::sync::Arc>); + type Cached = ( + std::time::SystemTime, + std::sync::Arc>, + ); static CACHE: std::sync::OnceLock< parking_lot::Mutex>, > = std::sync::OnceLock::new(); @@ -137,16 +162,33 @@ pub(super) fn result_handles_at( .map(|persisted| persisted.wm.reachable_handles()) .unwrap_or_default(), ); - cache.lock().insert(path.to_path_buf(), (modified, std::sync::Arc::clone(&handles))); + cache.lock().insert( + path.to_path_buf(), + (modified, std::sync::Arc::clone(&handles)), + ); Ok(handles) } pub(super) fn load_volatile(persona_id: Uuid) -> std::io::Result> { - load_volatile_at(&volatile_path(persona_id)?) + let path = volatile_path(persona_id)?; + let _lock = checkpoint_adoption::lock_checkpoint(&path, true)?; + if !path.try_exists()? { + let native = crate::paths::home_dir() + .ok_or_else(|| std::io::Error::other("cannot inspect prior checkpoint location"))?; + let previous = native + .join(".continuum/personas") + .join(persona_id.to_string()) + .join("volatile.json"); + if previous != path && previous.try_exists()? { + return Err(std::io::Error::other(format!("checkpoint exists at {}; explicit offline checkpoint adoption is required before using {}", previous.display(), path.display()))); + } + } + load_volatile_at(&path) } -pub(super) fn load_volatile_at(path: &std::path::Path) -> std::io::Result> { - let _lock = checkpoint_adoption::lock_checkpoint(path, true)?; +pub(super) fn load_volatile_at( + path: &std::path::Path, +) -> std::io::Result> { let bytes = match std::fs::read(path) { Ok(bytes) => bytes, Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), diff --git a/core/continuum-cognition/src/cognition/persona_workspace/owner_checkpoint.rs b/core/continuum-cognition/src/cognition/persona_workspace/owner_checkpoint.rs new file mode 100644 index 0000000000..a5b225fc3b --- /dev/null +++ b/core/continuum-cognition/src/cognition/persona_workspace/owner_checkpoint.rs @@ -0,0 +1,46 @@ +//! One resident-state commit boundary, shared by task delivery and perception. +//! The payload owner stages typed state; this owner supplies admission, replacement +//! exclusion, the existing checkpoint writer and publication after persistence. +use super::*; + +#[derive(Debug, thiserror::Error)] +pub enum OwnerCheckpointError { + #[error("resident checkpoint admission is closed")] + Stopped, + #[error("owner {0} is not a registered resident")] + Absent(Uuid), + #[error("owner checkpoint failed: {0}")] + Checkpoint(#[from] std::io::Error), +} + +impl PersonaWorkspaceRegistry { + /// Commit through the registered resident's existing snapshot and writer. + /// A stage must validate its complete input before mutation. An IO failure may + /// leave staged memory, so replay must be idempotent and must checkpoint again. + /// Staging alone never authorizes an acknowledgement or publishes a wake. + /// + /// Payloads, source cursors and wake obligations must all be part of this same + /// saved snapshot. This boundary cannot make an external/in-memory queue durable. + /// Incarnation-sensitive callers validate their expected incarnation in `stage`, + /// while replacement is excluded. Do not call registry operations from `stage`. + pub fn commit_owner_state>( + &self, + owner: Uuid, + stage: impl FnOnce(&WorkingMemory) -> Result<(), E>, + ) -> Result { + let stopped = self.checkpoint_stopped.lock(); + if *stopped { + return Err(OwnerCheckpointError::Stopped.into()); + } + let _assembly = self.assembly.lock(); + let memory = self + .cycles + .lock() + .get(&owner) + .map(|resident| Arc::clone(&resident.working_memory)) + .ok_or_else(|| E::from(OwnerCheckpointError::Absent(owner)))?; + stage(&memory)?; + save_volatile(owner, SaveReason::Periodic, None, &memory) + .map_err(|error| E::from(OwnerCheckpointError::Checkpoint(error))) + } +} diff --git a/core/continuum-cognition/src/cognition/persona_workspace/root_acting_workspace.rs b/core/continuum-cognition/src/cognition/persona_workspace/root_acting_workspace.rs index a08a874fdd..de2398b66a 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/root_acting_workspace.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/root_acting_workspace.rs @@ -267,7 +267,7 @@ impl PersonaWorkspaceRegistry { } let mut listed: Vec = roster .iter() - .map(|(id, name)| format!("{name} ({})", &id.to_string()[..8])) + .map(|(id, name)| format!("{name} ({id})")) .collect(); listed.sort(); format!("Online now: {}.", listed.join(", ")) @@ -282,7 +282,7 @@ impl PersonaWorkspaceRegistry { /// Checkpoint lock/read/schema failures refuse this registration and leave /// an existing resident unchanged. Call from a blocking worker during boot. pub fn register_from_cfg( - &self, + self: &Arc, cfg: PersonaBrainConfig, ) -> std::io::Result> { let _assembly = self.assembly.lock(); @@ -297,7 +297,7 @@ impl PersonaWorkspaceRegistry { .tool_head() .attach(crate::cognition::tool_head::entity::ToolHeadStore::new(Arc::clone(store), persona_id)); } - let cycle = Arc::new(cycle); + let cycle = Arc::new(cycle.with_render_custody(self, persona_id, working_memory.incarnation())); // cycles THEN templates (the one canonical lock order). let mut cycles = self.cycles.lock(); self.templates.lock().insert(persona_id, template); @@ -315,7 +315,7 @@ impl PersonaWorkspaceRegistry { /// Lazy-init so a persona's cycle is assembled once and reused across every /// room it services (the "one soul" invariant). Also retains the fork-template /// (same as [`register_from_cfg`](Self::register_from_cfg)). - pub fn get_or_build(&self, cfg: PersonaBrainConfig) -> std::io::Result> { + pub fn get_or_build(self: &Arc, cfg: PersonaBrainConfig) -> std::io::Result> { let persona_id = cfg.persona_id; if let Some(existing) = self.get(&persona_id) { return Ok(existing); @@ -333,7 +333,7 @@ impl PersonaWorkspaceRegistry { .tool_head() .attach(crate::cognition::tool_head::entity::ToolHeadStore::new(Arc::clone(store), persona_id)); } - let cycle = Arc::new(cycle); + let cycle = Arc::new(cycle.with_render_custody(self, persona_id, working_memory.incarnation())); // cycles THEN templates (the one canonical lock order). let mut cycles = self.cycles.lock(); self.templates.lock().insert(persona_id, template); @@ -349,7 +349,7 @@ impl PersonaWorkspaceRegistry { /// Periodic crash checkpoint. A busy writer coalesces this tick; no queue /// of blocking jobs accumulates behind slow storage. - pub fn checkpoint_volatile_all(&self) -> Vec<(Uuid, std::io::Result<()>)> { + pub fn checkpoint_volatile_all(&self) -> Vec<(Uuid, std::io::Result)> { let Some(stopped) = self.checkpoint_stopped.try_lock() else { return Vec::new(); }; @@ -360,7 +360,7 @@ impl PersonaWorkspaceRegistry { } /// Explicit save is repeatable and leaves periodic persistence running. - pub fn flush_volatile_all(&self) -> Vec<(Uuid, std::io::Result<()>)> { + pub fn flush_volatile_all(&self) -> Vec<(Uuid, std::io::Result)> { let _checkpoint = self.checkpoint_stopped.lock(); self.write_volatile_all(SaveReason::Seam) } @@ -369,7 +369,7 @@ impl PersonaWorkspaceRegistry { /// then snapshot CURRENT residents. The caller must quiesce mutation first. /// Blocking work can outlive an async timeout; callers must receipt that as /// uncertain, never successful. No later periodic write can overtake this one. - pub fn stop_volatile_checkpoints(&self) -> Vec<(Uuid, std::io::Result<()>)> { + pub fn stop_volatile_checkpoints(&self) -> Vec<(Uuid, std::io::Result)> { let mut stopped = self.checkpoint_stopped.lock(); *stopped = true; self.write_volatile_all(SaveReason::Seam) @@ -377,7 +377,7 @@ impl PersonaWorkspaceRegistry { // Only called under checkpoint_stopped. The cycle lookup lock is released // before snapshot/serialization/IO, keeping room turns and roster reads free. - pub(super) fn write_volatile_all(&self, reason: SaveReason) -> Vec<(Uuid, std::io::Result<()>)> { + pub(super) fn write_volatile_all(&self, reason: SaveReason) -> Vec<(Uuid, std::io::Result)> { // ONE staged-read budget for the whole seam, shared by every resident, so the save // phase is bounded by the phase and not by resident count; a periodic write has none. let staged_deadline = matches!(reason, SaveReason::Seam) @@ -438,7 +438,9 @@ impl PersonaWorkspaceRegistry { let test_home = crate::paths::NativeHomeOverride::current(); #[cfg(test)] let test_home = &test_home; - let results: Vec<(Uuid, std::io::Result<()>)> = std::thread::scope(|scope| { + #[cfg(test)] + let fence_fault = continuum_host::durable::fault_injection::FenceFault::capture(); + let results: Vec<(Uuid, std::io::Result)> = std::thread::scope(|scope| { let handles: Vec<_> = residents .into_iter() .map(|(id, memory)| { @@ -447,7 +449,10 @@ impl PersonaWorkspaceRegistry { let _home = test_home .as_deref() .map(crate::paths::NativeHomeOverride::install); - save_one(id, memory) + #[cfg(test)] + { fence_fault.run(|| save_one(id, memory)) } + #[cfg(not(test))] + { save_one(id, memory) } }); (id, handle) }) diff --git a/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs new file mode 100644 index 0000000000..8e5048a72e --- /dev/null +++ b/core/continuum-cognition/src/cognition/persona_workspace/task_consumption.rs @@ -0,0 +1,179 @@ +//! Durable task consumption uses the registered resident and its existing checkpoint +//! owner. No constructor-owned writer or remembered dispatch handle participates. +use super::*; +use continuum_kernel::runtime::tasks::TaskEnd; + +#[derive(Debug, thiserror::Error)] +pub enum TaskConsumptionError { + #[error(transparent)] + Owner(#[from] OwnerCheckpointError), + #[error("task read receipt belongs to a replaced memory incarnation for {0}")] + Replaced(Uuid), + #[error(transparent)] + Receipt(#[from] super::super::working_memory::TaskReceiptError), +} + +impl PersonaWorkspaceRegistry { + /// Only a submitted terminal occurrence can retire a wake. Fold blocks and + /// retired entries are not evidence that this end was shown. The checkpoint + /// below rechecks incarnation under admission, so replacement during matching + /// cannot acknowledge the next resident's memory. + pub fn record_rendered_tasks( + &self, + receipt: &crate::cognition::render_receipt::RenderReceipt, + ) -> Result, TaskConsumptionError> { + use continuum_context::level::Level; + let memory = self + .cycles + .lock() + .get(&receipt.owner) + .map(|resident| Arc::clone(&resident.working_memory)) + .ok_or(OwnerCheckpointError::Absent(receipt.owner))?; + if memory.incarnation() != receipt.incarnation { + return Err(TaskConsumptionError::Replaced(receipt.owner)); + } + let shown: std::collections::BTreeSet<_> = receipt + .view + .items + .iter() + .filter(|item| { + !item.retired && matches!(item.level, Level::Full | Level::Summary | Level::Pointer) + }) + .filter_map(|item| item.element) + .collect(); + let tasks: Vec<_> = memory + .task_terminals() + .into_iter() + .filter(|end| end.wake_pending) + .filter(|end| { + shown.contains(&crate::cognition::context_streams::tasks::terminal_element( + receipt.owner, + end.task, + &end.fingerprint, + )) + }) + .map(|end| end.task) + .collect(); + if tasks.is_empty() { + return Ok(None); + } + self.record_task_reads(receipt.owner, receipt.incarnation, &tasks) + .map(Some) + } + + /// Success receipts exactly the snapshot containing this end and its wake + /// obligation. A replay also checkpoints: a prior insertion may have failed IO. + /// Registration/replacement is excluded until the snapshot is committed; the + /// next incarnation restores it through the existing registration path. + pub fn consume_task_ends( + &self, + owner: Uuid, + ends: Vec<(Uuid, TaskEnd)>, + ) -> Result { + self.commit_owner_state(owner, |memory| { + memory.stage_task_ends(ends)?; + Ok(()) + }) + } + + /// Commit only reads reported by this registered memory incarnation. A repeated + /// receipt still saves: an earlier staging may have survived a failed write. + pub fn record_task_reads( + &self, + owner: Uuid, + incarnation: Uuid, + tasks: &[Uuid], + ) -> Result { + self.commit_owner_state(owner, |memory| { + if memory.incarnation() != incarnation { + return Err(TaskConsumptionError::Replaced(owner)); + } + memory.stage_task_reads(tasks)?; + Ok(()) + }) + } +} + +/// Async adapter for the registered owner. Filesystem work runs on a blocking +/// worker and is awaited; a worker failure cannot be acknowledged as consumption. +pub struct ResidentTaskSink(Arc); + +impl ResidentTaskSink { + pub fn new(registry: Arc) -> Self { + Self(registry) + } + + /// Await the same checkpoint owner used for incoming ends. The caller keeps + /// this persistence result separate from the generation that produced the + /// receipt: failure here cannot turn a served generation into an inference fault. + pub async fn record_rendered( + &self, + receipt: crate::cognition::render_receipt::RenderReceipt, + ) -> Result, TaskSinkError> { + self.commit(move |registry| registry.record_rendered_tasks(&receipt)) + .await + } + + async fn commit( + &self, + operation: impl FnOnce(&PersonaWorkspaceRegistry) -> Result + + Send + + 'static, + ) -> Result { + let registry = Arc::clone(&self.0); + // Carry the existing test filesystem scope onto the blocking worker. + #[cfg(test)] + let test_home = crate::paths::NativeHomeOverride::current(); + #[cfg(test)] + let fence_fault = continuum_host::durable::fault_injection::FenceFault::capture(); + Ok(tokio::task::spawn_blocking(move || { + #[cfg(test)] + let _native = test_home + .as_deref() + .map(crate::paths::NativeHomeOverride::install); + #[cfg(test)] + { + fence_fault.run(|| operation(®istry)) + } + #[cfg(not(test))] + { + operation(®istry) + } + }) + .await??) + } +} + +#[derive(Debug, thiserror::Error)] +pub enum TaskSinkError { + #[error("receipt checkpoint owner {0} no longer exists")] + OwnerGone(Uuid), + #[error("render receipt does not belong to cycle {owner} incarnation {incarnation}")] + CustodyMismatch { owner: Uuid, incarnation: Uuid }, + #[error(transparent)] + Consumption(#[from] TaskConsumptionError), + #[error("resident task checkpoint worker failed: {0}")] + Worker(#[from] tokio::task::JoinError), +} + +#[async_trait::async_trait] +impl continuum_kernel::runtime::tasks::TaskOwnerSink for ResidentTaskSink { + type Error = TaskSinkError; + + async fn consume( + &self, + owner: Uuid, + ends: &[(Uuid, TaskEnd)], + ) -> Result, Self::Error> { + let offered: std::collections::BTreeSet<_> = ends.iter().map(|(task, _)| *task).collect(); + let ends = ends.to_vec(); + let receipt = self + .commit(move |registry| registry.consume_task_ends(owner, ends)) + .await?; + Ok(receipt + .perceived_tasks() + .intersection(&offered) + .copied() + .collect()) + } +} diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests.rs index 2219479f21..9b99e2df33 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests.rs @@ -20,3 +20,5 @@ mod final_checkpoint_drains_admitted_periodic_writer_before_ack; use final_checkpoint_drains_admitted_periodic_writer_before_ack::*; mod gated_grounding; use gated_grounding::*; + +mod task_consumption; diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/final_checkpoint_drains_admitted_periodic_writer_before_ack.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/final_checkpoint_drains_admitted_periodic_writer_before_ack.rs index 59670f2fa5..fa08d1ce13 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/final_checkpoint_drains_admitted_periodic_writer_before_ack.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/final_checkpoint_drains_admitted_periodic_writer_before_ack.rs @@ -176,7 +176,7 @@ use super::*; // this is exactly what fed a dead reference to a doomed 10s eval. #[test] pub(super) fn resolve_persona_takes_uuid_short_id_or_name_and_fails_loud() { - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); let asha = Uuid::new_v4(); let atlas = Uuid::new_v4(); let mut asha_cfg = cfg_for(asha); @@ -233,7 +233,7 @@ use super::*; // room it services (the "one soul, many rooms" / anti-Severance invariant). #[tokio::test] pub(super) async fn registry_keeps_one_mind_per_persona() { - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); let persona = Uuid::new_v4(); let first = registry .get_or_build(cfg_for(persona)) @@ -260,7 +260,7 @@ use super::*; // discarded the fresh config — the bug this guards.) #[tokio::test] pub(super) async fn register_overwrites_on_respawn() { - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); let persona = Uuid::new_v4(); // register_from_cfg IS the production overwrite path (supervisor.rs spawn); // it builds + caches and returns the fresh Arc. @@ -288,7 +288,7 @@ use super::*; pub(super) async fn failed_checkpoint_load_preserves_the_registered_resident() { let home = tempfile::tempdir().unwrap(); let _native = crate::paths::NativeHomeOverride::install(home.path()); - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); let persona = Uuid::new_v4(); assert!(load_volatile(persona).unwrap().is_none()); let current = registry.register_from_cfg(cfg_for(persona)).unwrap(); @@ -319,7 +319,7 @@ use super::*; pub(super) async fn resident_registration_refuses_checkpoint_and_lock_errors() { let home = tempfile::tempdir().unwrap(); let _native = crate::paths::NativeHomeOverride::install(home.path()); - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); for fault in ["schema", "read", "lock"] { let persona = Uuid::new_v4(); let path = volatile_path(persona).unwrap(); @@ -547,7 +547,7 @@ use super::*; #[tokio::test] pub(super) async fn eval_fork_drops_hands_describing_grounding_when_tools_stripped() { const HANDS_MARKER: &str = "drill in with code/list and code/tree"; - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); let persona = Uuid::new_v4(); // SlowGrounding's fixed roster line stands in for capability-NEUTRAL // grounding; the hands-describing source is its own tiny stub. @@ -629,7 +629,7 @@ use super::*; #[tokio::test] pub(super) async fn suppress_recall_omits_the_recall_faculty_from_the_eval_fork() { use crate::cognition::workspace::FacultyId; - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); let persona = Uuid::new_v4(); registry .register_from_cfg(cfg_for(persona)) diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs index ec36aff556..5e6f0d1649 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs @@ -533,7 +533,7 @@ use super::*; pub(super) async fn every_resident_at_a_seam_measures_her_own_tree_including_untracked_files() { let home = tempfile::tempdir().unwrap(); let _native = crate::paths::NativeHomeOverride::install(home.path()); - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); let mut residents = Vec::new(); for i in 0..3 { let persona = Uuid::new_v4(); @@ -588,7 +588,7 @@ use super::*; pub(super) async fn her_mind_room_runs_on_its_own_cycle_never_checkpointed() { let home = tempfile::tempdir().unwrap(); let _native = crate::paths::NativeHomeOverride::install(home.path()); - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); let her = Uuid::new_v4(); let live = registry.register_from_cfg(cfg_for(her)).expect("live cycle"); let mind_room = crate::cognition::mind_room::mind_room_id(her); @@ -609,7 +609,7 @@ use super::*; pub(super) async fn resident_checkpoint_excludes_replaced_cycles_and_eval_forks() { let home = tempfile::tempdir().unwrap(); let _native = crate::paths::NativeHomeOverride::install(home.path()); - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); let persona = Uuid::new_v4(); let old_cycle = registry .register_from_cfg(cfg_for(persona)) @@ -710,7 +710,7 @@ use super::*; pub(super) async fn resident_checkpoint_reports_io_failure_and_saves_other_residents() { let home = tempfile::tempdir().unwrap(); let _native = crate::paths::NativeHomeOverride::install(home.path()); - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); let failed = Uuid::new_v4(); let healthy = Uuid::new_v4(); for id in [failed, healthy] { @@ -725,7 +725,7 @@ use super::*; std::fs::create_dir_all(path.parent().unwrap()).unwrap(); // Deterministic on Unix and Windows: a directory cannot be overwritten // by the temporary checkpoint file, regardless of user permissions. - std::fs::create_dir(path.with_extension("json.tmp")).unwrap(); + std::fs::create_dir(&path).expect("test: obstruct only the failed resident checkpoint"); let outcomes = registry.flush_volatile_all(); assert_eq!(outcomes.len(), 2); assert!(outcomes diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs new file mode 100644 index 0000000000..f79cf578f4 --- /dev/null +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/task_consumption.rs @@ -0,0 +1,477 @@ +#![cfg(test)] +use super::*; +use continuum_kernel::runtime::tasks::TaskEnd; + +#[tokio::test] +async fn durable_terminal_source_receipts_retire_only_the_exact_published_end( +) -> Result<(), Box> { + use continuum_context::source::Source; + use continuum_context::view::View; + let home = tempfile::tempdir()?; + let _native = crate::paths::NativeHomeOverride::install(home.path()); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); + let sink = ResidentTaskSink::new(Arc::clone(®istry)); + let owner = Uuid::new_v4(); + registry.register_from_cfg(cfg_for(owner))?; + let task = Uuid::new_v4(); + registry.consume_task_ends(owner, vec![(task, TaskEnd::TimedOut)])?; + let cycle = registry.register_from_cfg(cfg_for(owner))?; + let memory = Arc::clone(®istry.cycles.lock()[&owner].working_memory); + let source = crate::cognition::context_streams::tasks::Tasks { + memory: &memory, + persona: owner, + }; + let (view, _) = View::::start( + Vec::new(), + &[&source as &dyn Source<_>], + |claims| claims.iter().map(|claim| claim.full_chars).collect(), + )?; + assert!(view + .render() + .any(|message| message.text.contains("timed_out task"))); + let mut receipt = crate::cognition::render_receipt::RenderReceipt { + owner, + incarnation: memory.incarnation(), + request: "submitted-request".to_owned(), + view: view.receipt(), + }; + let exact = receipt.clone(); + let isolated = registry.mind_cycle(&owner).ok_or("private cycle absent")?; + isolated + .persist_render_receipts(vec![exact.clone()]) + .await?; + assert_eq!( + memory.pending_task_wakes(), + vec![task], + "private cycles have no live checkpoint authority" + ); + let mut foreign = exact.clone(); + foreign.incarnation = Uuid::new_v4(); + assert!(matches!( + cycle + .persist_render_receipts(vec![exact.clone(), foreign]) + .await, + Err(TaskSinkError::CustodyMismatch { .. }) + )); + assert_eq!( + memory.pending_task_wakes(), + vec![task], + "validate the whole batch before retirement" + ); + for item in &mut receipt.view.items { + item.element = None; + } + assert!(sink.record_rendered(receipt).await?.is_none()); + receipt = exact.clone(); + for item in &mut receipt.view.items { + item.level = continuum_context::level::Level::Folded; + } + assert!(sink.record_rendered(receipt).await?.is_none()); + receipt = exact.clone(); + for item in &mut receipt.view.items { + let of = item.element.ok_or("terminal receipt lacks element")?; + item.level = continuum_context::level::Level::Repeat { of }; + } + assert!(sink.record_rendered(receipt).await?.is_none()); + assert_eq!( + memory.pending_task_wakes(), + vec![task], + "repeat is not a newly perceived terminal end" + ); + receipt = exact.clone(); + for item in &mut receipt.view.items { + item.retired = true; + } + assert!(sink.record_rendered(receipt).await?.is_none()); + assert_eq!(memory.pending_task_wakes(), vec![task]); + let fence_fault = continuum_host::durable::fault_injection::FailedFenceScope::enter(); + assert!(matches!( + sink.record_rendered(exact.clone()).await, + Err(TaskSinkError::Consumption(TaskConsumptionError::Owner( + OwnerCheckpointError::Checkpoint(_) + ))) + )); + assert_eq!(memory.pending_task_wakes(), vec![task]); + let before_retry = WorkingMemory::new(8); + before_retry.restore(load_volatile(owner)?.ok_or("checkpoint absent")?.wm); + assert_eq!(before_retry.pending_task_wakes(), vec![task]); + drop(fence_fault); + cycle.persist_render_receipts(vec![exact.clone()]).await?; + assert!(memory.pending_task_wakes().is_empty()); + let checkpoint = std::fs::read(volatile_path(owner)?)?; + assert!(sink.record_rendered(exact.clone()).await?.is_none()); + assert_eq!(std::fs::read(volatile_path(owner)?)?, checkpoint); + assert!( + source.items().is_empty(), + "a consumed end must not leave a standing task banner" + ); + let restored = WorkingMemory::new(8); + restored.restore(load_volatile(owner)?.ok_or("checkpoint absent")?.wm); + assert!(restored.pending_task_wakes().is_empty()); + registry.register_from_cfg(cfg_for(owner))?; + assert!( + matches!(cycle.persist_render_receipts(vec![exact.clone()]).await, + Err(TaskSinkError::Consumption(TaskConsumptionError::Replaced(id))) if id == owner) + ); + // Retaining a cycle must not retain its registry through a reference cycle. + let weak = Arc::downgrade(®istry); + drop(sink); + drop(registry); + assert!(weak.upgrade().is_none()); + assert!(matches!(cycle.persist_render_receipts(vec![exact]).await, + Err(TaskSinkError::OwnerGone(id)) if id == owner)); + Ok(()) +} + +#[tokio::test] +async fn forgotten_end_is_committed_before_receipt_and_restored_with_wake( +) -> Result<(), Box> { + let home = tempfile::tempdir()?; + let _native = crate::paths::NativeHomeOverride::install(home.path()); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); + let owner = Uuid::new_v4(); + let task = Uuid::new_v4(); + registry.register_from_cfg(cfg_for(owner))?; + let receipt = registry.consume_task_ends(owner, vec![(task, TaskEnd::Stopped)])?; + assert_eq!(receipt.owner(), owner); + assert_eq!(receipt.consumed_tasks(), &[task]); + let old_incarnation = receipt.incarnation(); + let on_disk = load_volatile(owner)?.ok_or("checkpoint absent")?; + let restored = WorkingMemory::new(8); + restored.restore(on_disk.wm); + assert_eq!(restored.snapshot().task_results.consumed_ids(), vec![task]); + assert_eq!(restored.pending_task_wakes(), vec![task]); + registry.register_from_cfg(cfg_for(owner))?; + let memory = Arc::clone(®istry.cycles.lock()[&owner].working_memory); + assert_ne!(memory.incarnation(), old_incarnation); + assert_eq!(memory.pending_task_wakes(), vec![task]); + assert!(memory.stage_task_reads(&[task])?); + let replay = registry.consume_task_ends(owner, vec![(task, TaskEnd::Stopped)])?; + assert_eq!(replay.incarnation(), memory.incarnation()); + let next = WorkingMemory::new(8); + next.restore(load_volatile(owner)?.ok_or("checkpoint absent")?.wm); + assert!(next.pending_task_wakes().is_empty()); + assert_eq!(next.snapshot().task_results.consumed_ids(), vec![task]); + Ok(()) +} + +#[tokio::test] +async fn absent_conflicting_and_shutdown_consumption_are_explicit_refusals( +) -> Result<(), Box> { + let home = tempfile::tempdir()?; + let _native = crate::paths::NativeHomeOverride::install(home.path()); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); + let owner = Uuid::new_v4(); + let task = Uuid::new_v4(); + assert!( + matches!(registry.consume_task_ends(owner, vec![(task, TaskEnd::Lost)]), Err(TaskConsumptionError::Owner(OwnerCheckpointError::Absent(id))) if id == owner) + ); + registry.register_from_cfg(cfg_for(owner))?; + registry.consume_task_ends(owner, vec![(task, TaskEnd::Lost)])?; + let path = volatile_path(owner)?; + let before = std::fs::read(&path)?; + assert!(matches!( + registry.consume_task_ends(owner, vec![(task, TaskEnd::Stopped)]), + Err(TaskConsumptionError::Receipt(_)) + )); + assert_eq!(std::fs::read(&path)?, before); + for (_, result) in registry.stop_volatile_checkpoints() { + result?; + } + let before = std::fs::read(&path)?; + assert!(matches!( + registry.consume_task_ends(owner, vec![(Uuid::new_v4(), TaskEnd::Lost)]), + Err(TaskConsumptionError::Owner(OwnerCheckpointError::Stopped)) + )); + assert_eq!(std::fs::read(&path)?, before); + Ok(()) +} + +#[tokio::test] +async fn failed_checkpoint_returns_no_receipt_and_replay_commits_staged_end( +) -> Result<(), Box> { + let home = tempfile::tempdir()?; + let _native = crate::paths::NativeHomeOverride::install(home.path()); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); + let owner = Uuid::new_v4(); + let task = Uuid::new_v4(); + registry.register_from_cfg(cfg_for(owner))?; + for (_, result) in registry.flush_volatile_all() { + result?; + } + let path = volatile_path(owner)?; + let before = std::fs::read(&path)?; + // The shared durability fault refuses placement before replacing the checkpoint. + // The existing committed checkpoint is never removed or replaced by the test. + let fence_fault = continuum_host::durable::fault_injection::FailedFenceScope::enter(); + assert!(matches!( + registry.consume_task_ends(owner, vec![(task, TaskEnd::Lost)]), + Err(TaskConsumptionError::Owner( + OwnerCheckpointError::Checkpoint(_) + )) + )); + assert_eq!(std::fs::read(&path)?, before); + let memory = Arc::clone(®istry.cycles.lock()[&owner].working_memory); + assert!(memory.pending_task_wakes().is_empty()); + assert!(memory.stage_task_reads(&[task]).is_err()); + drop(fence_fault); + // The ordinary checkpoint owner also publishes a staged end after IO recovers. + for (_, result) in registry.flush_volatile_all() { + result?; + } + assert_eq!(memory.pending_task_wakes(), vec![task]); + let receipt = registry.consume_task_ends(owner, vec![(task, TaskEnd::Lost)])?; + assert_eq!(receipt.consumed_tasks(), &[task]); + let restored = WorkingMemory::new(8); + restored.restore(load_volatile(owner)?.ok_or("checkpoint absent")?.wm); + assert_eq!(restored.snapshot().task_results.consumed_ids(), vec![task]); + assert_eq!(restored.pending_task_wakes(), vec![task]); + Ok(()) +} + +#[tokio::test] +async fn ledger_ack_requires_perception_and_restart_replays_unread_ends( +) -> Result<(), Box> { + use continuum_kernel::runtime::tasks::{TaskExecution, TaskLedger, TaskOutput}; + let home = tempfile::tempdir()?; + let _native = crate::paths::NativeHomeOverride::install(home.path()); + let (adapter, _database) = continuum_kernel::orm::store::fresh_adapter().await; + let ledger = TaskLedger::new(adapter.clone()).await?; + let registry = Arc::new(PersonaWorkspaceRegistry::new()); + let sink = ResidentTaskSink::new(Arc::clone(®istry)); + let owner = Uuid::new_v4(); + let task = ledger + .accept( + owner, + "test/result".into(), + TaskExecution::new_command_executor(), + ) + .await?; + let end = TaskEnd::Done(TaskOutput::Json( + serde_json::json!({"result":"useful result"}), + )); + ledger + .finish( + task, + owner, + ledger.execution(task, owner).await?, + end.clone(), + ) + .await?; + let limit = std::num::NonZeroUsize::new(32).ok_or("invalid fixture page")?; + assert!(ledger + .deliver_page(owner, None, limit, &sink) + .await + .is_err()); + assert_eq!(ledger.pending(task, owner).await?, Some(end.clone())); + registry.register_from_cfg(cfg_for(owner))?; + let checkpoint = volatile_path(owner)?; + std::fs::create_dir_all(checkpoint.parent().ok_or("checkpoint parent absent")?)?; + let fence_fault = continuum_host::durable::fault_injection::FailedFenceScope::enter(); + assert!(ledger + .deliver_page(owner, None, limit, &sink) + .await + .is_err()); + assert_eq!(ledger.pending(task, owner).await?, Some(end.clone())); + drop(fence_fault); + assert_eq!( + ledger + .deliver_page(owner, None, limit, &sink) + .await? + .acknowledged, + 0 + ); + assert_eq!(ledger.pending(task, owner).await?, Some(end.clone())); + let reopened = TaskLedger::new(adapter).await?; + let restored = WorkingMemory::new(8); + restored.restore(load_volatile(owner)?.ok_or("checkpoint absent")?.wm); + assert_eq!(restored.pending_task_wakes(), vec![task]); + assert_eq!(reopened.terminal(task, owner).await?, Some(end.clone())); + registry.register_from_cfg(cfg_for(owner))?; + assert_eq!( + reopened + .deliver_page(owner, None, limit, &sink) + .await? + .acknowledged, + 0 + ); + assert_eq!(restored.pending_task_wakes(), vec![task]); + assert_eq!(reopened.pending(task, owner).await?, Some(end.clone())); + let memory = Arc::clone(®istry.cycles.lock()[&owner].working_memory); + use continuum_context::{source::Source, view::View}; + let source = crate::cognition::context_streams::tasks::Tasks { + memory: &memory, + persona: owner, + }; + let (view, _) = View::::start( + Vec::new(), + &[&source as &dyn Source<_>], + |claims| claims.iter().map(|claim| claim.full_chars).collect(), + )?; + let receipt = crate::cognition::render_receipt::RenderReceipt { + owner, + incarnation: memory.incarnation(), + request: "served-task-result".into(), + view: view.receipt(), + }; + let fence_fault = continuum_host::durable::fault_injection::FailedFenceScope::enter(); + assert!(sink.record_rendered(receipt.clone()).await.is_err()); + assert!(reopened + .deliver_page(owner, None, limit, &sink) + .await + .is_err()); + assert_eq!(reopened.pending(task, owner).await?, Some(end.clone())); + drop(fence_fault); + sink.record_rendered(receipt).await?; + // Crash after the perception checkpoint but before ACK: replay uses the + // restored exact receipt, without prompting her again or remembering a handle. + registry.register_from_cfg(cfg_for(owner))?; + assert_eq!( + reopened + .deliver_page(owner, None, limit, &sink) + .await? + .acknowledged, + 1 + ); + assert_eq!(reopened.pending(task, owner).await?, None); + registry.register_from_cfg(cfg_for(owner))?; + assert_eq!( + reopened + .deliver_page(owner, None, limit, &sink) + .await? + .acknowledged, + 0 + ); + assert!(registry.cycles.lock()[&owner] + .working_memory + .pending_task_wakes() + .is_empty()); + assert_eq!(reopened.terminal(task, owner).await?, Some(end)); + Ok(()) +} + +#[tokio::test] +async fn failed_read_checkpoint_keeps_wake_pending_until_retry( +) -> Result<(), Box> { + let home = tempfile::tempdir()?; + let _native = crate::paths::NativeHomeOverride::install(home.path()); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); + let owner = Uuid::new_v4(); + let task = Uuid::new_v4(); + registry.register_from_cfg(cfg_for(owner))?; + registry.consume_task_ends(owner, vec![(task, TaskEnd::Stopped)])?; + let memory = Arc::clone(®istry.cycles.lock()[&owner].working_memory); + assert!(memory.stage_task_reads(&[task])?); + let fence_fault = continuum_host::durable::fault_injection::FailedFenceScope::enter(); + let failed = registry.flush_volatile_all(); + assert_eq!(failed.len(), 1); + assert!(failed[0].1.is_err()); + assert_eq!(memory.pending_task_wakes(), vec![task]); + let restarted = WorkingMemory::new(8); + restarted.restore(load_volatile(owner)?.ok_or("checkpoint absent")?.wm); + assert_eq!(restarted.pending_task_wakes(), vec![task]); + assert!( + !memory.stage_task_reads(&[task])?, + "already staged is not durable success" + ); + drop(fence_fault); + for (_, result) in registry.flush_volatile_all() { + result?; + } + assert!(memory.pending_task_wakes().is_empty()); + let restarted = WorkingMemory::new(8); + restarted.restore(load_volatile(owner)?.ok_or("checkpoint absent")?.wm); + assert!(restarted.pending_task_wakes().is_empty()); + Ok(()) +} + +#[tokio::test] +async fn task_read_receipt_rejects_replaced_memory_and_retries_failed_commit( +) -> Result<(), Box> { + let home = tempfile::tempdir()?; + let _native = crate::paths::NativeHomeOverride::install(home.path()); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); + let owner = Uuid::new_v4(); + let task = Uuid::new_v4(); + registry.register_from_cfg(cfg_for(owner))?; + let accepted = registry.consume_task_ends(owner, vec![(task, TaskEnd::Stopped)])?; + registry.register_from_cfg(cfg_for(owner))?; + let current = Arc::clone(®istry.cycles.lock()[&owner].working_memory); + assert!( + matches!(registry.record_task_reads(owner, accepted.incarnation(), &[task]), Err(TaskConsumptionError::Replaced(id)) if id == owner) + ); + assert_eq!(current.pending_task_wakes(), vec![task]); + let fence_fault = continuum_host::durable::fault_injection::FailedFenceScope::enter(); + assert!(matches!( + registry.record_task_reads(owner, current.incarnation(), &[task]), + Err(TaskConsumptionError::Owner( + OwnerCheckpointError::Checkpoint(_) + )) + )); + assert_eq!(current.pending_task_wakes(), vec![task]); + drop(fence_fault); + registry.record_task_reads(owner, current.incarnation(), &[task])?; + assert!(current.pending_task_wakes().is_empty()); + let restored = WorkingMemory::new(8); + restored.restore(load_volatile(owner)?.ok_or("checkpoint absent")?.wm); + assert!(restored.pending_task_wakes().is_empty()); + Ok(()) +} + +#[tokio::test] +async fn rejected_read_batch_cannot_partially_retire_a_durable_wake( +) -> Result<(), Box> { + let home = tempfile::tempdir()?; + let _native = crate::paths::NativeHomeOverride::install(home.path()); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); + let owner = Uuid::new_v4(); + let task = Uuid::new_v4(); + registry.register_from_cfg(cfg_for(owner))?; + registry.consume_task_ends(owner, vec![(task, TaskEnd::Stopped)])?; + let memory = Arc::clone(®istry.cycles.lock()[&owner].working_memory); + let path = volatile_path(owner)?; + let before = std::fs::read(&path)?; + assert!(matches!( + registry.record_task_reads(owner, memory.incarnation(), &[task, Uuid::new_v4()]), + Err(TaskConsumptionError::Receipt(_)) + )); + assert_eq!(std::fs::read(&path)?, before); + // An unrelated later checkpoint must not publish a partial staging from the + // refused batch. Checking only the immediate wake would miss that failure. + for (_, result) in registry.flush_volatile_all() { + result?; + } + let restored = WorkingMemory::new(8); + restored.restore(load_volatile(owner)?.ok_or("checkpoint absent")?.wm); + assert_eq!(memory.pending_task_wakes(), vec![task]); + assert_eq!(restored.pending_task_wakes(), vec![task]); + Ok(()) +} + +#[tokio::test] +async fn served_read_arriving_after_shutdown_preserves_restart_delivery( +) -> Result<(), Box> { + let home = tempfile::tempdir()?; + let _native = crate::paths::NativeHomeOverride::install(home.path()); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); + let owner = Uuid::new_v4(); + let task = Uuid::new_v4(); + registry.register_from_cfg(cfg_for(owner))?; + registry.consume_task_ends(owner, vec![(task, TaskEnd::Lost)])?; + let memory = Arc::clone(®istry.cycles.lock()[&owner].working_memory); + for (_, result) in registry.stop_volatile_checkpoints() { + result?; + } + let path = volatile_path(owner)?; + let before = std::fs::read(&path)?; + assert!(matches!( + registry.record_task_reads(owner, memory.incarnation(), &[task]), + Err(TaskConsumptionError::Owner(OwnerCheckpointError::Stopped)) + )); + assert_eq!(std::fs::read(&path)?, before); + let restored = WorkingMemory::new(8); + restored.restore(load_volatile(owner)?.ok_or("checkpoint absent")?.wm); + assert_eq!(memory.pending_task_wakes(), vec![task]); + assert_eq!(restored.pending_task_wakes(), vec![task]); + Ok(()) +} diff --git a/core/continuum-cognition/src/cognition/rag_source_faculty/tests.rs b/core/continuum-cognition/src/cognition/rag_source_faculty/tests.rs index c5cf0706fe..910afbec82 100644 --- a/core/continuum-cognition/src/cognition/rag_source_faculty/tests.rs +++ b/core/continuum-cognition/src/cognition/rag_source_faculty/tests.rs @@ -635,4 +635,3 @@ retrieved bid out-saliences it — else the persona forgets the room's rules" ); } - diff --git a/core/continuum-cognition/src/cognition/render_receipt.rs b/core/continuum-cognition/src/cognition/render_receipt.rs new file mode 100644 index 0000000000..4688f77a80 --- /dev/null +++ b/core/continuum-cognition/src/cognition/render_receipt.rs @@ -0,0 +1,20 @@ +//! The render receipt: what one submitted prompt showed her, bound to whose mind it was and +//! which request carried it (HER-TOOLS, "The render receipt"). The view takes its half when the +//! prompt is sent (`View::sent`); the deliberation faculty returns it with its contribution +//! where the request was served, so a prompt the engine never accepted is never receipted. +//! The task ledger (#5585) is the sink: it acknowledges a task's end from the first receipt that +//! shows that task's item, and writes nothing else. The memory incarnation joins the binding +//! with that ledger's `WorkingMemory::incarnation`. + +use uuid::Uuid; + +/// One submitted, served prompt: whose, which request, and what it showed her in order. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RenderReceipt { + pub owner: Uuid, + /// The memory that supplied the prompt, never the registry's current instance + /// looked up after generation. A replaced resident cannot consume this receipt. + pub incarnation: Uuid, + pub request: String, + pub view: continuum_context::view::Receipt, +} diff --git a/core/continuum-cognition/src/cognition/resident_service.rs b/core/continuum-cognition/src/cognition/resident_service.rs index e6f89ad59a..30c31e3d3a 100644 --- a/core/continuum-cognition/src/cognition/resident_service.rs +++ b/core/continuum-cognition/src/cognition/resident_service.rs @@ -25,7 +25,10 @@ static LEDGERS: LazyLock> = LazyLock::new(DashMap: pub fn note_settled(persona: Uuid, settled: &SettleOutcome, wall_ms: u64) { let turn = turn_of( settled.capacity_refusal.as_ref(), - settled.inference_error.is_some(), + settled.failure.as_ref().map(|failure| match failure { + crate::cognition::act_observe::SettlementFailure::Inference(_) => Refusal::InferenceFailed, + crate::cognition::act_observe::SettlementFailure::ReceiptPersistence(_) => Refusal::ReceiptPersistenceFailed, + }), settled.deferred_before_dispatch, &settled.generation_receipts, &settled.metrics, @@ -73,7 +76,7 @@ pub fn close_windows(span: Window) -> Vec<(Uuid, ResidentWindow)> { /// beside that, so a mind that worked and then parked is both. fn turn_of( capacity: Option<&CapacityRefusal>, - inference_failed: bool, + failure: Option, deferred_before_dispatch: bool, receipts: &[GenerationReceipt], metrics: &TurnMetrics, @@ -102,7 +105,7 @@ fn turn_of( budget_tokens: saturating_u32(refusal.budget_tokens), context_window: refusal.readiness.as_ref().map(|r| r.observed_window()), }), - None if inference_failed => Some(Refusal::InferenceFailed), + None if failure.is_some() => failure, None if deferred_before_dispatch => Some(Refusal::LaneStarved), None => None, }; @@ -136,18 +139,18 @@ mod tests { fn a_refusal_before_inference_is_demand_with_no_completion_and_keeps_its_numbers() { let kimi = CapacityRefusal::from(PromptCapacityError { required_tokens: 26_101, budget_tokens: 17_829 }); let metrics = TurnMetrics::default(); - let turn = turn_of(Some(&kimi), false, true, &[], &metrics, 0, 2_000); + let turn = turn_of(Some(&kimi), None, true, &[], &metrics, 0, 2_000); assert_eq!(turn.completion, None); assert_eq!( turn.refusal, Some(Refusal::PromptCapacity { required_tokens: 26_101, budget_tokens: 17_829, context_window: None }) ); - let worked = turn_of(Some(&kimi), false, false, &[served("qwen3.6-35b-a3b")], &metrics, 2, 90_000); + let worked = turn_of(Some(&kimi), None, false, &[served("qwen3.6-35b-a3b")], &metrics, 2, 90_000); assert_eq!(worked.completion.map(|c| (c.acts, c.model)), Some((2, "qwen3.6-35b-a3b".to_string()))); assert!(worked.refusal.is_some()); - let starved = turn_of(None, false, true, &[], &metrics, 0, 600_000); + let starved = turn_of(None, None, true, &[], &metrics, 0, 600_000); assert_eq!((starved.completion, starved.refusal), (None, Some(Refusal::LaneStarved))); } } diff --git a/core/continuum-cognition/src/cognition/working_memory.rs b/core/continuum-cognition/src/cognition/working_memory.rs index 85b59b4730..a18acea9e2 100644 --- a/core/continuum-cognition/src/cognition/working_memory.rs +++ b/core/continuum-cognition/src/cognition/working_memory.rs @@ -298,6 +298,8 @@ pub struct WorkingMemory { /// has read: her cursors, kept here because the history that carried each page is the /// first thing a tight window's fit drops ([`super::open_views`]). open_views: Mutex, + task_results: Mutex, + incarnation: Uuid, /// Her learned tool head: every call she makes is noted here, and the deliberation faculty /// reads and adopts the head at each epoch turnover ([`super::tool_head`]). tool_head: Arc, @@ -440,6 +442,8 @@ pub struct VolatileSnapshot { /// written before this field. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub open_views: Vec, + /// Consumed terminal references and outstanding wake obligations, checkpointed together. + pub(crate) task_results: task_results::TaskResults, } impl VolatileSnapshot { @@ -603,6 +607,8 @@ pub struct WmEntry { mod derived; mod action_log; mod continuity; +mod task_results; +pub use task_results::{TaskReceiptConflict, TaskReceiptError}; mod ledger; mod perception; mod residency; diff --git a/core/continuum-cognition/src/cognition/working_memory/continuity.rs b/core/continuum-cognition/src/cognition/working_memory/continuity.rs index 4c747de704..7a8ffa9d07 100644 --- a/core/continuum-cognition/src/cognition/working_memory/continuity.rs +++ b/core/continuum-cognition/src/cognition/working_memory/continuity.rs @@ -212,6 +212,7 @@ impl WorkingMemory { context_view: self.view.lock().clone(), receipt_children: self.receipt_children.lock().clone(), open_views: self.open_views.lock().saved(), + task_results: self.task_results.lock().clone(), } } @@ -240,6 +241,11 @@ impl WorkingMemory { } pub fn restore(&self, mut snap: VolatileSnapshot) { + { + let mut results = snap.task_results.clone(); + results.publish_restored(); + *self.task_results.lock() = results; + } // Read before any field moves out of the snapshot below. let records = snap.action_records(); // A restored mind keeps only the newest concern evidence its existing diff --git a/core/continuum-cognition/src/cognition/working_memory/ledger.rs b/core/continuum-cognition/src/cognition/working_memory/ledger.rs index d86ec55d0f..b4cdd2d39c 100644 --- a/core/continuum-cognition/src/cognition/working_memory/ledger.rs +++ b/core/continuum-cognition/src/cognition/working_memory/ledger.rs @@ -67,6 +67,8 @@ impl WorkingMemory { receipt_children: Mutex::new(BTreeMap::new()), active_from_seq: AtomicU64::new(0), open_views: Mutex::new(Default::default()), + task_results: Mutex::new(Default::default()), + incarnation: Uuid::new_v4(), tool_head: Default::default(), } } diff --git a/core/continuum-cognition/src/cognition/working_memory/task_results.rs b/core/continuum-cognition/src/cognition/working_memory/task_results.rs new file mode 100644 index 0000000000..fcfbd3fe61 --- /dev/null +++ b/core/continuum-cognition/src/cognition/working_memory/task_results.rs @@ -0,0 +1,285 @@ +//! Owner consumption state. Notification delivery is not wake admission, and +//! neither an in-memory insertion nor this snapshot alone acknowledges the ledger. +use super::WorkingMemory; +use continuum_kernel::runtime::tasks::{TaskEnd, TaskEndState}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; +use uuid::Uuid; + +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +pub(crate) struct TaskResults { + entries: BTreeMap, + // Runtime publication fence; durable restoration publishes its saved entries. + #[serde(skip)] + published: BTreeMap, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +struct ConsumedEnd { + fingerprint: [u8; 32], + state: TaskEndState, + wake_pending: bool, +} + +/// A published terminal fact. The fingerprint identifies the immutable ledger +/// result, including its body; it is not merely the coarse Done/Failed status. +pub(crate) struct TaskTerminal { + pub task: Uuid, + pub fingerprint: [u8; 32], + pub state: TaskEndState, + pub wake_pending: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +#[error("task {task} was already consumed with a different terminal result")] +pub struct TaskReceiptConflict { + pub task: Uuid, +} + +#[derive(Debug, thiserror::Error)] +pub enum TaskReceiptError { + #[error("task {0} has no published consumption receipt")] + Unpublished(Uuid), + #[error(transparent)] + Conflict(#[from] TaskReceiptConflict), + #[error("terminal fingerprint encoding failed: {0}")] + Encoding(#[from] serde_json::Error), +} + +impl WorkingMemory { + /// Identity of this live memory instance; restoration creates a new incarnation. + pub fn incarnation(&self) -> Uuid { + self.incarnation + } + + /// Stage a terminal reference and its wake obligation atomically. Whole output + /// remains in TaskLedger; the fingerprint detects conflicting replay without + /// duplicating binary/JSON bodies in every resident checkpoint. The registry must + /// checkpoint this exact state before publishing the wake. Only a later + /// checkpointed perception receipt can authorize ledger acknowledgement. + /// A replay is inert, including after its wake has already been admitted. + pub fn stage_task_end(&self, task: Uuid, end: TaskEnd) -> Result { + self.stage_task_ends(vec![(task, end)]) + } + + /// Validate a complete owner page before changing any consumption state. + pub fn stage_task_ends(&self, ends: Vec<(Uuid, TaskEnd)>) -> Result { + let mut incoming = BTreeMap::new(); + for (task, end) in ends { + let fingerprint: [u8; 32] = Sha256::digest(serde_json::to_vec(&end)?).into(); // Disk boundary: persist integrity fingerprints, not duplicate ledger output. + if let Some((previous, _)) = incoming.insert(task, (fingerprint, end.state())) { + if previous != fingerprint { + return Err(TaskReceiptConflict { task }.into()); + } + } + } + let mut results = self.task_results.lock(); + for (task, (fingerprint, _)) in &incoming { + if let Some(previous) = results.entries.get(task) { + if previous.fingerprint != *fingerprint { + return Err(TaskReceiptConflict { task: *task }.into()); + } + } + } + let mut changed = false; + for (task, (fingerprint, state)) in incoming { + if let std::collections::btree_map::Entry::Vacant(entry) = results.entries.entry(task) { + entry.insert(ConsumedEnd { + fingerprint, + state, + wake_pending: true, + }); + changed = true; + } + } + Ok(changed) + } + + /// The shared checkpoint writer calls this only after syncing its exact snapshot. + pub(crate) fn publish_task_checkpoint(&self, saved: TaskPublication) { + let mut results = self.task_results.lock(); + for (task, pending) in saved.0 { + if results.entries.contains_key(&task) { + results.published.insert(task, pending); + } + } + } + + pub fn pending_task_wakes(&self) -> Vec { + let results = self.task_results.lock(); + results + .published + .iter() + .filter_map(|(task, pending)| pending.then_some(*task)) + .collect() + } + + pub(crate) fn task_terminals(&self) -> Vec { + let results = self.task_results.lock(); + results.entries.iter().filter_map(|(task, end)| { + results.published.get(task).map(|pending| TaskTerminal { + task: *task, + fingerprint: end.fingerprint, + state: end.state, + wake_pending: *pending, + }) + }).collect() + } + + /// Stage retirement only after a successful rendered-context read receipt. + /// The wake remains published until the checkpoint containing retirement commits. + /// Notification delivery and entering the service loop are not perception. + /// Returns whether staging changed. False does not prove persistence: an earlier + /// stage may still need a checkpoint retry. Unknown tasks cannot create receipts. + pub fn stage_task_reads(&self, tasks: &[Uuid]) -> Result { + let mut results = self.task_results.lock(); + for task in tasks { + if !results.published.contains_key(task) || !results.entries.contains_key(task) { + return Err(TaskReceiptError::Unpublished(*task)); + } + } + let mut changed = false; + for task in tasks { + if let Some(entry) = results.entries.get_mut(task) { + changed |= entry.wake_pending; + entry.wake_pending = false; + } + } + Ok(changed) + } +} + +/// Exact wake projection of one serialized snapshot. Constructed only by its owner. +pub(crate) struct TaskPublication(BTreeMap); + +impl TaskResults { + pub(crate) fn publication(&self) -> TaskPublication { + TaskPublication( + self.entries + .iter() + .map(|(id, end)| (*id, end.wake_pending)) + .collect(), + ) + } + + pub(crate) fn publish_restored(&mut self) { + self.published = self.publication().0; + } + + /// A checkpoint receipt must use IDs from its serialized snapshot, not from + /// a second read of mutable working memory after IO completes. + pub(crate) fn consumed_ids(&self) -> Vec { + self.entries.keys().copied().collect() + } + + /// Perception in this exact serialized snapshot; filing alone never qualifies. + pub(crate) fn perceived_ids(&self) -> std::collections::BTreeSet { + self.entries.iter().filter_map(|(task, end)| (!end.wake_pending).then_some(*task)).collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn forgotten_task_survives_snapshot_and_replay_does_not_rearm_admitted_wake() { + let memory = WorkingMemory::new(8); + let task = Uuid::new_v4(); + assert!(memory + .stage_task_end(task, TaskEnd::Stopped) + .expect("initial end")); + let snapshot = memory.snapshot(); + let encoded = serde_json::to_vec(&snapshot).expect("encode checkpoint"); + let restored = WorkingMemory::new(8); + restored.restore(serde_json::from_slice(&encoded).expect("decode checkpoint")); + assert_eq!(restored.snapshot().task_results.consumed_ids(), vec![task]); + assert_eq!(restored.pending_task_wakes(), vec![task]); + assert!(!restored + .stage_task_end(task, TaskEnd::Stopped) + .expect("identical replay")); + assert!(restored.stage_task_reads(&[task]).expect("published task")); + assert!(!restored + .stage_task_end(task, TaskEnd::Stopped) + .expect("replay after admission")); + assert_eq!( + restored.pending_task_wakes(), + vec![task], + "staged retirement is not a committed read receipt" + ); + restored.publish_task_checkpoint(restored.snapshot().task_results.publication()); + assert!(restored.pending_task_wakes().is_empty()); + let next_life = WorkingMemory::new(8); + next_life.restore(restored.snapshot()); + assert!(next_life.pending_task_wakes().is_empty()); + assert_eq!(next_life.snapshot().task_results.consumed_ids(), vec![task]); + } + + #[test] + fn read_batch_refuses_unknown_task_without_partial_retirement() { + let memory = WorkingMemory::new(8); + let task = Uuid::new_v4(); + memory.stage_task_end(task, TaskEnd::Stopped).expect("stage"); + memory.publish_task_checkpoint(memory.snapshot().task_results.publication()); + assert!(memory.stage_task_reads(&[task, Uuid::new_v4()]).is_err()); + memory.publish_task_checkpoint(memory.snapshot().task_results.publication()); + assert_eq!(memory.pending_task_wakes(), vec![task]); + } + + #[test] + fn older_checkpoint_cannot_publish_a_later_read() { + let memory = WorkingMemory::new(8); + let task = Uuid::new_v4(); + memory + .stage_task_end(task, TaskEnd::Stopped) + .expect("stage end"); + memory.publish_task_checkpoint(memory.snapshot().task_results.publication()); + let earlier = memory.snapshot().task_results.publication(); + assert!(memory.stage_task_reads(&[task]).expect("published task")); + memory.publish_task_checkpoint(earlier); + assert_eq!(memory.pending_task_wakes(), vec![task]); + memory.publish_task_checkpoint(memory.snapshot().task_results.publication()); + assert!(memory.pending_task_wakes().is_empty()); + } + + #[test] + fn conflicting_batch_stages_nothing() { + let memory = WorkingMemory::new(8); + let existing = Uuid::new_v4(); + let new = Uuid::new_v4(); + memory + .stage_task_end(existing, TaskEnd::Lost) + .expect("existing"); + assert!(memory + .stage_task_ends(vec![(new, TaskEnd::Stopped), (existing, TaskEnd::Stopped)]) + .is_err()); + assert_eq!( + memory.snapshot().task_results.consumed_ids(), + vec![existing] + ); + } + + #[test] + fn conflicting_end_is_refused_and_later_arrival_is_not_in_prior_snapshot() { + let memory = WorkingMemory::new(8); + let first = Uuid::new_v4(); + let later = Uuid::new_v4(); + memory + .stage_task_end(first, TaskEnd::Lost) + .expect("first end"); + let snapshot = memory.snapshot(); + memory + .stage_task_end(later, TaskEnd::Stopped) + .expect("later end"); + assert_eq!(snapshot.task_results.consumed_ids(), vec![first]); + assert!(matches!(memory.stage_task_end(first, TaskEnd::Stopped), + Err(TaskReceiptError::Conflict(TaskReceiptConflict { task })) if task == first)); + assert!(memory.pending_task_wakes().is_empty()); + assert!(memory.stage_task_reads(&[first]).is_err()); + memory.publish_task_checkpoint(snapshot.task_results.publication()); + assert_eq!(memory.pending_task_wakes(), vec![first]); + assert!(memory.stage_task_reads(&[later]).is_err()); + assert!(memory.stage_task_reads(&[Uuid::new_v4()]).is_err()); + } +} diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs b/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs index 8866b75972..42fdf29e17 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/actions.rs @@ -161,7 +161,21 @@ async fn dispatched_commands_stream_back_by_handle() { assert_eq!(c.3, DispatchStatus::Done); assert_eq!(c.2, "0 errors, 0 warnings"); - // Her view renders each as its own item (context_streams::tasks), tested there. + use continuum_context::source::Source; + let rendered = crate::cognition::context_streams::tasks::Tasks { memory: &wm, persona: Uuid::nil() } + .items().into_iter().map(|item| item.full().text.clone()).collect::>().join("\n"); + assert!( + rendered.contains("[tasks]"), + "the mind sees its sentinels" + ); + assert!( + rendered.contains("compile core\n0 errors"), + "finished result shown" + ); + assert!( + rendered.contains("running task") && rendered.contains("research task"), + "in-flight shown" + ); } // what this catches: a finished background handle dropped before a submitted prompt showed her diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs b/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs index ca60a60915..87576b5807 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs @@ -271,47 +271,15 @@ fn her_acts_survive_ring_churn_and_roundtrip_the_snapshot() { } #[test] -fn an_old_snapshot_without_acts_restores_without_panic() { - // A hand-authored legacy snapshot: entries have NO `acts` key at all. - let legacy_json = r#"{ - "entries": [ - { "kind": "Thought", "text": "thinking about the tokenizer" }, - { "kind": { "Receipt": { "n": 1 } }, "text": "[action #1] code/list → ok" } - ], - "last_action": [1, "code/list → ok"], - "action_fps": ["code/list|{}"], - "next_action_seq": 2 - }"#; - let snap: VolatileSnapshot = - serde_json::from_str(legacy_json).expect("legacy snapshot deserializes"); - let fresh = WorkingMemory::new(8); - fresh.restore(snap); - // Both legacy entries survive the round-trip (asserted by content, not a raw - // count — restore ALSO appends a `[resumed]` wake-orientation fact by design, - // #147/#165: a restore IS an interruption, so she wakes oriented, never blank). - let texts = fresh.recent(); - assert!( - texts - .iter() - .any(|t| t.contains("thinking about the tokenizer")), - "the legacy thought restored" - ); - assert!( - texts.iter().any(|t| t.contains("[action #1] code/list")), - "the legacy receipt restored" - ); - assert!( - fresh.pinned_facts().iter().any(|t| t.starts_with("[resumed]")), - "restore pins the wake-orientation notice" - ); - assert!( - fresh.recent_acts().is_empty(), - "a legacy receipt has no typed acts — defaulted empty, never a panic" - ); - assert!( - fresh.has_receipt(), - "the receipt kind still survives the trip" - ); +fn snapshot_without_task_consumption_is_refused() -> Result<(), Box> { + let memory = WorkingMemory::new(8); + memory.record_receipt("code/list completed"); + let mut encoded = serde_json::to_value(memory.snapshot())?; + encoded.as_object_mut().ok_or("snapshot must be an object")?.remove("task_results"); + let error = serde_json::from_value::(encoded) + .expect_err("missing durable task state must not silently become an empty mailbox"); + assert!(error.to_string().contains("task_results")); + Ok(()) } #[test] diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs b/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs index 3f20024dc9..ea8fcbcbc2 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs @@ -274,6 +274,7 @@ fn volatile_snapshot_round_trips_and_renders_the_interruption() { context_view: None, receipt_children: Default::default(), open_views: Vec::new(), + task_results: Default::default(), }); assert!(quiet.recent().is_empty(), "an empty snapshot restores an empty window"); let q = quiet.pinned_facts(); diff --git a/core/continuum-cognition/src/cognition/workspace.rs b/core/continuum-cognition/src/cognition/workspace.rs index 2182943092..fe3a535467 100644 --- a/core/continuum-cognition/src/cognition/workspace.rs +++ b/core/continuum-cognition/src/cognition/workspace.rs @@ -43,6 +43,7 @@ mod arbiter; pub use arbiter::*; mod workspace_cycle; mod workspace_cycle_2; +mod render_custody; #[cfg(test)] mod tests; diff --git a/core/continuum-cognition/src/cognition/workspace/arbiter.rs b/core/continuum-cognition/src/cognition/workspace/arbiter.rs index c43f9c231b..5b8d68f9ce 100644 --- a/core/continuum-cognition/src/cognition/workspace/arbiter.rs +++ b/core/continuum-cognition/src/cognition/workspace/arbiter.rs @@ -207,6 +207,7 @@ pub struct ActingBody { /// integrates the bids into the bounded workspace, the workspace broadcasts. /// The participation [`Decision`] is then read from the broadcast. pub struct WorkspaceCycle { + pub(super) render_custody: super::render_custody::RenderCustody, pub(super) faculties: Vec>, pub(super) arbiter: Arc, /// Replay/logging seam — every tick is recorded here. Default `Noop` diff --git a/core/continuum-cognition/src/cognition/workspace/cause.rs b/core/continuum-cognition/src/cognition/workspace/cause.rs index 5fba59edb3..a830ffb569 100644 --- a/core/continuum-cognition/src/cognition/workspace/cause.rs +++ b/core/continuum-cognition/src/cognition/workspace/cause.rs @@ -388,6 +388,9 @@ pub struct Workspace { /// earned a place in the prompt is a judgement about relevance. Populated from /// the same `all_bids` full-competition set the capture sink records. pub receipts: Vec, + /// Submitted render facts from all bids, including bids omitted by attention. + /// The resident owner must persist consumption before retiring a task wake. + pub render_receipts: Vec, /// Is this a SELF-INITIATED turn — the never-stop heartbeat pursuing the /// persona's own thread with no inbound message — versus a turn driven by an /// arriving message or an examiner's question? Drives the `[Your own time]` @@ -465,6 +468,7 @@ impl Workspace { broadcast: Vec::new(), attention: TurnAttention::Ambient, receipts: Vec::new(), + render_receipts: Vec::new(), self_initiated: false, workspace_deliverable: false, initiative: false, diff --git a/core/continuum-cognition/src/cognition/workspace/edit.rs b/core/continuum-cognition/src/cognition/workspace/edit.rs index ea2990c3eb..9143631e58 100644 --- a/core/continuum-cognition/src/cognition/workspace/edit.rs +++ b/core/continuum-cognition/src/cognition/workspace/edit.rs @@ -308,6 +308,9 @@ pub struct Contribution { /// Neither field can be derived from the other and neither should be removed for /// the other's sake. pub receipts: Vec, + /// Submitted render facts return through the same owned faculty result. + /// They are evidence for the resident checkpoint owner, never an acknowledgement. + pub render_receipts: Vec, /// The model's **verbatim generation** for this verdict — the raw response text /// EXACTLY as the model emitted it, BEFORE the tool-call/PASS parser lifted a /// [`Decision`] from it. Set ONLY by the deliberation faculty on its verdict @@ -411,6 +414,7 @@ impl Contribution { fault: None, capacity_refusal: None, receipts: Vec::new(), + render_receipts: Vec::new(), raw_generation: None, trailing: false, } @@ -486,6 +490,7 @@ impl Contribution { fault: None, capacity_refusal: None, receipts: Vec::new(), + render_receipts: Vec::new(), raw_generation: None, trailing: false, } @@ -535,6 +540,7 @@ impl Contribution { fault: Some(error), capacity_refusal: None, receipts: Vec::new(), + render_receipts: Vec::new(), raw_generation: None, trailing: false, } diff --git a/core/continuum-cognition/src/cognition/workspace/render_custody.rs b/core/continuum-cognition/src/cognition/workspace/render_custody.rs new file mode 100644 index 0000000000..8bc531bf37 --- /dev/null +++ b/core/continuum-cognition/src/cognition/workspace/render_custody.rs @@ -0,0 +1,48 @@ +//! A cycle's receipt custody is fixed at assembly. Private and measurement +//! cycles cannot borrow the live resident's checkpoint authority. +use super::WorkspaceCycle; +use crate::cognition::persona_workspace::{PersonaWorkspaceRegistry, ResidentTaskSink, TaskSinkError}; +use crate::cognition::render_receipt::RenderReceipt; +use std::sync::{Arc, Weak}; +use uuid::Uuid; + +pub(super) enum RenderCustody { + Isolated, + Resident { + registry: Weak, + owner: Uuid, + incarnation: Uuid, + }, +} + +impl WorkspaceCycle { + pub(crate) fn with_render_custody( + mut self, + registry: &Arc, + owner: Uuid, + incarnation: Uuid, + ) -> Self { + self.render_custody = RenderCustody::Resident { + registry: Arc::downgrade(registry), owner, incarnation, + }; + self + } + + /// Persist the observations of this resident's served generations. Isolated + /// cycles have no durable task acknowledgement authority. Registry teardown + /// and receipt disagreement are explicit failures, never an owner substitution. + pub async fn persist_render_receipts(&self, receipts: Vec) -> Result<(), TaskSinkError> { + let RenderCustody::Resident { registry, owner, incarnation } = &self.render_custody else { + return Ok(()); + }; + if receipts.is_empty() { return Ok(()); } + // Validate the complete batch before any receipt can mutate the ledger. + if receipts.iter().any(|receipt| receipt.owner != *owner || receipt.incarnation != *incarnation) { + return Err(TaskSinkError::CustodyMismatch { owner: *owner, incarnation: *incarnation }); + } + let registry = registry.upgrade().ok_or(TaskSinkError::OwnerGone(*owner))?; + let sink = ResidentTaskSink::new(registry); + for receipt in receipts { sink.record_rendered(receipt).await?; } + Ok(()) + } +} diff --git a/core/continuum-cognition/src/cognition/workspace/tests.rs b/core/continuum-cognition/src/cognition/workspace/tests.rs index c6ac3969e6..314566edf6 100644 --- a/core/continuum-cognition/src/cognition/workspace/tests.rs +++ b/core/continuum-cognition/src/cognition/workspace/tests.rs @@ -1,23 +1,25 @@ #![cfg(test)] - // what this catches: PROVENANCE BEING FILTERED BY ATTENTION. Card 0d51573a. - // `ws.broadcast` is the FOCUSED set, so deriving receipts from it would drop the - // generations of any faculty attention dropped (the arbiter cut by a count until card - // c537d687; it forwards every bid now, and receipts must still not depend on it). Astra found that in my first implementation, - // which flat_mapped broadcast; my previous test could not catch it because it - // hand-assembled `ws.broadcast` and never ran the arbiter at all. - // - // THIS TEST DRIVES THE REAL CYCLE so the truncation actually happens. A fault - // receipt from a losing faculty is precisely the record worth keeping — a failed - // call that got truncated away is invisible exactly when someone needs it. + // Every faculty's generation and render evidence returns through the real + // cycle. The arbiter now forwards every bid, so this test does not exercise + // dropped-bid behavior; collection still reads all_bids, not the broadcast. #[tokio::test] - async fn a_losing_faculty_keeps_its_receipt_even_though_attention_dropped_its_bid() { + async fn the_cycle_returns_every_facultys_generation_and_render_receipts() { use crate::ai::provenance::GenerationReceipt; let mut loud = Contribution::context(FacultyId::Recall, "loud", 0.9, "wins attention"); loud.receipts = vec![GenerationReceipt::faulted("req-loud", "served after retry")]; let mut quiet = Contribution::context(FacultyId::WorldModel, "quiet", 0.1, "loses attention"); quiet.receipts = vec![GenerationReceipt::faulted("req-quiet", "lane refused the model")]; + // A previous successful attempt can have rendered before this faculty's + // later attempt faulted. Neither fact may disappear with its losing bid. + let rendered = crate::cognition::render_receipt::RenderReceipt { + owner: uuid::Uuid::new_v4(), + incarnation: uuid::Uuid::new_v4(), + request: "req-quiet-earlier-served".to_owned(), + view: continuum_context::view::Receipt { epoch: 1, items: Vec::new() }, + }; + quiet.render_receipts.push(rendered.clone()); let faculties: Vec> = vec![ Arc::new(FixedFaculty(loud)), @@ -25,6 +27,7 @@ ]; let ws = cycle(faculties).run("burst").await; assert_eq!(ws.broadcast.len(), 2, "attention forwards every bid"); + assert_eq!(ws.render_receipts, vec![rendered]); let ids: Vec<&str> = ws .generation_receipts() diff --git a/core/continuum-cognition/src/cognition/workspace/workspace_cycle.rs b/core/continuum-cognition/src/cognition/workspace/workspace_cycle.rs index 88efb143b2..c74fed72d1 100644 --- a/core/continuum-cognition/src/cognition/workspace/workspace_cycle.rs +++ b/core/continuum-cognition/src/cognition/workspace/workspace_cycle.rs @@ -3,6 +3,7 @@ use super::*; impl WorkspaceCycle { pub fn new(faculties: Vec>, arbiter: Arc) -> Self { Self { + render_custody: super::render_custody::RenderCustody::Isolated, faculties, arbiter, capture: Arc::new(NoopWorkspaceCaptureSink), diff --git a/core/continuum-cognition/src/cognition/workspace/workspace_cycle_2.rs b/core/continuum-cognition/src/cognition/workspace/workspace_cycle_2.rs index e90724718e..f7c68b5d3a 100644 --- a/core/continuum-cognition/src/cognition/workspace/workspace_cycle_2.rs +++ b/core/continuum-cognition/src/cognition/workspace/workspace_cycle_2.rs @@ -237,6 +237,10 @@ impl WorkspaceCycle { .iter() .flat_map(|c| c.receipts.iter().cloned()) .collect(); + ws.render_receipts = all_bids + .iter() + .flat_map(|c| c.render_receipts.iter().cloned()) + .collect(); // WHERE THIS TICK'S LATENCY WENT, on the always-on probe stream. // // `timings` already holds per-faculty wall-clock for every faculty across diff --git a/core/continuum-cognition/src/cognition/workspace_capture.rs b/core/continuum-cognition/src/cognition/workspace_capture.rs index 7b80f70ad9..1c614c1159 100644 --- a/core/continuum-cognition/src/cognition/workspace_capture.rs +++ b/core/continuum-cognition/src/cognition/workspace_capture.rs @@ -257,6 +257,7 @@ mod tests { fault: None, capacity_refusal: None, receipts: Vec::new(), + render_receipts: Vec::new(), raw_generation: None, trailing: false, parts: Vec::new(), @@ -279,6 +280,7 @@ mod tests { fault: None, capacity_refusal: None, receipts: Vec::new(), + render_receipts: Vec::new(), // #210: the verbatim generation carries a leading-char fumble the parser // tolerated — the capture must preserve it so model-vs-harness is decidable. raw_generation: Some(" Result) -> Result<(), crate::sdk_codegen::CommandError> { validate_target(¶ms.target, current)?; + if receipt.is_some_and(|receipt| !receipt.tasks.is_quiet()) { + return Err(crate::sdk_codegen::CommandError::Invalid( + "shutdown withheld while background custody is unresolved; no process exit was committed".into(), + )); + } if receipt.map(shutdown_receipt_digest).transpose()?.as_deref() != Some(params.receipt_sha256.as_str()) { return Err(crate::sdk_codegen::CommandError::Invalid( "shutdown commit requires the completed save receipt from this process".into(), @@ -228,7 +233,7 @@ mod tests { #[test] fn commit_requires_same_instance_and_completed_received_receipt() { let current = ShutdownTarget { pid: 42, instance: "first".into() }; - let receipt = ShutdownReceipt { modules: vec![], total_ms: 19 }; + let receipt = ShutdownReceipt { tasks: crate::runtime::DrainOutcome::Drained, modules: vec![], total_ms: 19 }; let mut params = ShutdownCommitParams { target: current.clone(), receipt_sha256: shutdown_receipt_digest(&receipt).unwrap() }; assert!(validate_commit(¶ms, ¤t, None).is_err()); assert!(validate_commit(¶ms, ¤t, Some(&receipt)).is_ok()); @@ -242,6 +247,23 @@ mod tests { assert!(validate_commit(¶ms, ¤t, Some(&receipt)).is_err()); } + #[test] + fn matching_receipt_hash_cannot_authorize_exit_with_unresolved_custody() -> Result<(), crate::sdk_codegen::CommandError> { + let current = ShutdownTarget { pid: 42, instance: "withheld".into() }; + for tasks in [ + crate::runtime::DrainOutcome::Incomplete { in_flight: 1 }, + crate::runtime::DrainOutcome::Unknown { reason: "terminal persistence failed".into() }, + ] { + let receipt = ShutdownReceipt { tasks, modules: Vec::new(), total_ms: 1 }; + let params = ShutdownCommitParams { + target: current.clone(), + receipt_sha256: shutdown_receipt_digest(&receipt)?, + }; + assert!(validate_commit(¶ms, ¤t, Some(&receipt)).is_err()); + } + Ok(()) + } + // Exercise the real exit in an isolated test child, never the serving core. // The child must obtain the retained receipt before commit can end it. #[tokio::test] diff --git a/core/continuum-core/src/main.rs b/core/continuum-core/src/main.rs index 6d7dacee6b..0669a6d0f8 100644 --- a/core/continuum-core/src/main.rs +++ b/core/continuum-core/src/main.rs @@ -75,16 +75,20 @@ fn install_shutdown_handlers() { if let Ok(mut sig) = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) { - sig.recv().await; - eprintln!("[continuum-core] SIGTERM — save-and-join broadcast, then exit"); - // The CBAR stop (2026-09-02): every module saves and joins in - // parallel under a bound — replacing a flat 2s sleep during - // which NOTHING saved. Sentinels last (they are children, not - // modules), then the fast _exit that skips llama.cpp's - // double-free-prone static destructors (note above). - continuum_core::runtime::run_signal_shutdown().await; - continuum_sentinel::shutdown_all_sentinels(); - unsafe { libc::_exit(0) }; + while sig.recv().await.is_some() { + eprintln!("[continuum-core] SIGTERM — save-and-join broadcast, then exit"); + // The CBAR stop (2026-09-02): every module saves and joins in + // parallel under a bound — replacing a flat 2s sleep during + // which NOTHING saved. Sentinels last (they are children, not + // modules), then the fast _exit that skips llama.cpp's + // double-free-prone static destructors (note above). + if let Err(reason) = continuum_core::runtime::run_signal_shutdown().await { + eprintln!("[continuum-core] {reason}; awaiting another shutdown request"); + continue; + } + continuum_sentinel::shutdown_all_sentinels(); + unsafe { libc::_exit(0) }; + } } }); @@ -93,11 +97,15 @@ fn install_shutdown_handlers() { if let Ok(mut sig) = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::interrupt()) { - sig.recv().await; - eprintln!("[continuum-core] SIGINT — save-and-join broadcast, then exit"); - continuum_core::runtime::run_signal_shutdown().await; - continuum_sentinel::shutdown_all_sentinels(); - unsafe { libc::_exit(0) }; + while sig.recv().await.is_some() { + eprintln!("[continuum-core] SIGINT — save-and-join broadcast, then exit"); + if let Err(reason) = continuum_core::runtime::run_signal_shutdown().await { + eprintln!("[continuum-core] {reason}; awaiting another shutdown request"); + continue; + } + continuum_sentinel::shutdown_all_sentinels(); + unsafe { libc::_exit(0) }; + } } }); } @@ -118,43 +126,48 @@ fn install_shutdown_handlers() { let mut ctrl_close = tokio::signal::windows::ctrl_close().ok(); let mut ctrl_shutdown = tokio::signal::windows::ctrl_shutdown().ok(); - let close_fut = async { - match ctrl_close.as_mut() { - Some(s) => { - s.recv().await; + loop { + let close_fut = async { + match ctrl_close.as_mut() { + Some(s) => s.recv().await, + None => std::future::pending::>().await, } - None => std::future::pending::<()>().await, - } - }; - let shutdown_fut = async { - match ctrl_shutdown.as_mut() { - Some(s) => { - s.recv().await; + }; + let shutdown_fut = async { + match ctrl_shutdown.as_mut() { + Some(s) => s.recv().await, + None => std::future::pending::>().await, } - None => std::future::pending::<()>().await, + }; + + let signal = tokio::select! { + signal = ctrl_c.recv() => signal, + signal = close_fut => signal, + signal = shutdown_fut => signal, + }; + if signal.is_none() { + eprintln!("[continuum-core] shutdown signal stream closed; listener stopped"); + return; } - }; - - tokio::select! { - _ = ctrl_c.recv() => {} - _ = close_fut => {} - _ = shutdown_fut => {} + eprintln!("[continuum-core] shutdown signal — save-and-join broadcast, then exit"); + // THE SAME BROADCAST THE UNIX ARMS RUN. This arm killed sentinels, slept a + // flat 2 seconds, and `_exit`ed — which is precisely the behaviour the SIGTERM + // arm's own comment says was replaced on 2026-09-02 ("a flat 2s sleep during + // which NOTHING saved"). The unix half was fixed and this half was not, so on + // Windows no module has ever saved on a signal stop: not the citizens' + // workspaces, not the log queue, nothing. The node that runs the citizens is a + // Windows node. + // + // Ordering matches unix deliberately: modules drain and save FIRST, sentinels + // are killed after (they are children, not modules), then the fast `_exit` + // that skips llama.cpp's double-free-prone static destructors. + if let Err(reason) = continuum_core::runtime::run_signal_shutdown().await { + eprintln!("[continuum-core] {reason}; awaiting another shutdown request"); + continue; + } + continuum_sentinel::shutdown_all_sentinels(); + unsafe { libc::_exit(0) }; } - eprintln!("[continuum-core] shutdown signal — save-and-join broadcast, then exit"); - // THE SAME BROADCAST THE UNIX ARMS RUN. This arm killed sentinels, slept a - // flat 2 seconds, and `_exit`ed — which is precisely the behaviour the SIGTERM - // arm's own comment says was replaced on 2026-09-02 ("a flat 2s sleep during - // which NOTHING saved"). The unix half was fixed and this half was not, so on - // Windows no module has ever saved on a signal stop: not the citizens' - // workspaces, not the log queue, nothing. The node that runs the citizens is a - // Windows node. - // - // Ordering matches unix deliberately: modules drain and save FIRST, sentinels - // are killed after (they are children, not modules), then the fast `_exit` - // that skips llama.cpp's double-free-prone static destructors. - continuum_core::runtime::run_signal_shutdown().await; - continuum_sentinel::shutdown_all_sentinels(); - unsafe { libc::_exit(0) }; }); } } diff --git a/core/continuum-core/src/modules/citizen_health/resident_service.rs b/core/continuum-core/src/modules/citizen_health/resident_service.rs index 17e57fdf90..99aa7927f6 100644 --- a/core/continuum-core/src/modules/citizen_health/resident_service.rs +++ b/core/continuum-core/src/modules/citizen_health/resident_service.rs @@ -110,6 +110,7 @@ fn probe(alarm: &ResidentAlarm) { let refusal = match alarm.refusal { Some(resident::Refusal::PromptCapacity { .. }) => "prompt_capacity", Some(resident::Refusal::InferenceFailed) => "inference_failed", + Some(resident::Refusal::ReceiptPersistenceFailed) => "receipt_persistence_failed", Some(resident::Refusal::LaneStarved) => "lane_starved", None => "none", }; diff --git a/core/continuum-core/src/test_env/loose_id_guard.rs b/core/continuum-core/src/test_env/loose_id_guard.rs index affa5b739e..ae3ef7777b 100644 --- a/core/continuum-core/src/test_env/loose_id_guard.rs +++ b/core/continuum-core/src/test_env/loose_id_guard.rs @@ -57,8 +57,6 @@ const LOOSE_IDS: &[LooseId] = &[ LooseId { file: "cognition/eval/eval_task_result.rs", field: "persona_id", why: "pending: ours, but nothing on this path RESOLVES yet. Typing it as an identity today would assert something the code does not do — #164/#396" }, LooseId { file: "cognition/eval/fork_eval_cycle_waiting.rs", field: "persona_id", why: "pending: ours, but nothing on this path RESOLVES yet. Typing it as an identity today would assert something the code does not do — #164/#396" }, LooseId { file: "cognition/eval/format_exam_lesson.rs", field: "persona_id", why: "pending: ours, but nothing on this path RESOLVES yet. Typing it as an identity today would assert something the code does not do — #164/#396" }, - LooseId { file: "cognition/generate_response.rs", field: "persona_id", why: "pending: ours, but nothing on this path RESOLVES yet. Typing it as an identity today would assert something the code does not do — #164/#396" }, - LooseId { file: "cognition/generate_response.rs", field: "room_id", why: "pending: ours, but nothing on this path RESOLVES yet. Typing it as an identity today would assert something the code does not do — #164/#396" }, LooseId { file: "cognition/replay.rs", field: "room_id", why: "pending: ours, but nothing on this path RESOLVES yet. Typing it as an identity today would assert something the code does not do — #164/#396" }, LooseId { file: "cognition/should_respond.rs", field: "persona_id", why: "pending: ours, but nothing on this path RESOLVES yet. Typing it as an identity today would assert something the code does not do — #164/#396" }, LooseId { file: "cognition/should_respond.rs", field: "room_id", why: "pending: ours, but nothing on this path RESOLVES yet. Typing it as an identity today would assert something the code does not do — #164/#396" }, diff --git a/core/continuum-core/src/test_env/mind_integration/hands_isolation.rs b/core/continuum-core/src/test_env/mind_integration/hands_isolation.rs index 06b67aaa04..dc90385150 100644 --- a/core/continuum-core/src/test_env/mind_integration/hands_isolation.rs +++ b/core/continuum-core/src/test_env/mind_integration/hands_isolation.rs @@ -95,7 +95,7 @@ async fn listing(hands: &ActingHands) -> String { // CALL's own hands are bound to (Astra on #5026), never her current focus: a turn // moving her focus to another claim before the task's first poll cannot move it. #[tokio::test] -async fn command_work_stays_with_its_card_across_background_dispatch() { +async fn command_work_stays_with_its_card_across_background_dispatch() -> Result<(), String> { use crate::persona::cognition_pulse::work_idle_ms; let home = tempfile::TempDir::new().unwrap(); std::fs::write(home.path().join("work.txt"), "work").unwrap(); @@ -113,13 +113,15 @@ async fn command_work_stays_with_its_card_across_background_dispatch() { assert!(work_idle_ms(persona, Some(card_a), EpochMs::now().millis()).is_some()); let exec = hands.executor.command_executor().unwrap(); + let (adapter, _task_directory) = crate::orm::store::fresh_adapter().await; + exec.set_task_ledger(Arc::new(continuum_kernel::runtime::tasks::TaskLedger::new(adapter).await?))?; let mut rx = exec.message_bus().unwrap().receiver(); let handle = exec.dispatch_background( "code/list", serde_json::json!({"path": "."}), Some(CallerIdentity::local_persona(crate::identity::PeerId::from_uuid(persona)).in_hands(claim_a)), - ); - // Current-thread test: the spawned task has not been polled yet. Her focus moves on. + ).await.map_err(|e| e.message)?; + // Acceptance finished before spawning: her focus moves before the task's first poll. let claim_b = crate::identity::hands_context::HandsContext::for_claim(persona, card_b, Uuid::new_v4()); note_acting_root_in(persona, Some(claim_b), Some(home.path().to_path_buf())); note_acting_card_in(persona, Some(claim_b), card_b); @@ -143,6 +145,7 @@ async fn command_work_stays_with_its_card_across_background_dispatch() { set_focus(persona, None); note_acting_root_in(persona, Some(claim_a), None); note_acting_root_in(persona, Some(claim_b), None); + Ok(()) } // what this catches (Astra on #5026): admission living in helpers, so a command that diff --git a/core/continuum-core/src/test_env/mind_integration/remote_lane.rs b/core/continuum-core/src/test_env/mind_integration/remote_lane.rs index 791db51f43..8a7eea28db 100644 --- a/core/continuum-core/src/test_env/mind_integration/remote_lane.rs +++ b/core/continuum-core/src/test_env/mind_integration/remote_lane.rs @@ -56,7 +56,7 @@ async fn rehome_requires_a_readable_local_assignment() { crate::persona::cognition_extensions::install(); // her remote binding is persona's to read let root = tempfile::tempdir().expect("root"); let _native = crate::paths::NativeHomeOverride::install(root.path()); - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); let id = Uuid::new_v4(); let cycle = registry.register_from_cfg(cfg_for(id, "Ivar")).expect("resident"); let (original, original_model) = cycle.current_model_route().expect("binding"); @@ -91,7 +91,7 @@ async fn a_resident_bound_at_the_provisional_window_is_rehomed_to_the_served_win crate::persona::cognition_extensions::install(); let root = tempfile::tempdir().expect("root"); let _native = crate::paths::NativeHomeOverride::install(root.path()); - let registry = PersonaWorkspaceRegistry::new(); + let registry = Arc::new(PersonaWorkspaceRegistry::new()); let local = registry.register_from_cfg(cfg_for(Uuid::new_v4(), "Aiko")).expect("local resident"); let remote = registry.register_from_cfg(cfg_for(Uuid::new_v4(), "Kira")).expect("remote resident"); let airc = crate::identity::citizen_path::citizen_home_path(root.path(), crate::identity::IdentityKind::Persona, None, "Kira"); diff --git a/core/continuum-engine/src/ai/heuristic_adapter.rs b/core/continuum-engine/src/ai/heuristic_adapter.rs index e4b0bfdbd6..ccc7dab638 100644 --- a/core/continuum-engine/src/ai/heuristic_adapter.rs +++ b/core/continuum-engine/src/ai/heuristic_adapter.rs @@ -26,7 +26,7 @@ //! //! ### What the response looks like //! -//! `[heuristic:<8-char-hash>] ack: ""` +//! `[heuristic:] ack: ""` //! //! Enough to prove (a) the inference command surface is wired, //! (b) the prompt actually reached the adapter, (c) the response is @@ -69,11 +69,6 @@ pub const HEURISTIC_PROVIDER_ID: &str = "heuristic"; /// adapter handled the request. pub const HEURISTIC_DEFAULT_MODEL: &str = "heuristic-echo-v1"; -/// Echo length cap — last N chars of the most recent user message -/// surfaces in the response. -// context-budget-exempt: a TEST-ONLY canned adapter's echo width (gated behind test-fixtures); never a live bound -const ECHO_CHARS: usize = 200; - /// The adapter struct itself. No mutable state, no clock access, no /// external resources — instances are cheap and interchangeable. /// @@ -226,7 +221,7 @@ impl HeuristicInferenceAdapter { String::new() } - /// Compute a deterministic 8-char hex prefix tying the response + /// Compute a deterministic SHA-256 fingerprint tying the response /// to its inputs. Same canonical inputs → same hash → same /// response text. This is the replay contract. fn determinism_prefix(req: &TextGenerationRequest) -> String { @@ -267,8 +262,7 @@ impl HeuristicInferenceAdapter { } } let digest = hasher.finalize(); - let hex: String = digest.iter().take(4).map(|b| format!("{b:02x}")).collect(); - hex + format!("{digest:x}") } /// Build the response text from the request. Pure function — @@ -287,15 +281,7 @@ impl HeuristicInferenceAdapter { /// algorithms." pub fn build_response_text(req: &TextGenerationRequest) -> String { let prefix = Self::determinism_prefix(req); - let last = Self::last_user_text(&req.messages); - let echoed: String = last - .chars() - .rev() - .take(ECHO_CHARS) - .collect::() - .chars() - .rev() - .collect(); + let echoed = Self::last_user_text(&req.messages); let plain = if echoed.is_empty() { format!("[heuristic:{prefix}] ack: (no user text in prompt)") } else { @@ -622,18 +608,19 @@ mod tests { #[tokio::test] async fn response_echoes_last_user_message_with_heuristic_prefix() { + let latest = format!("keep the beginning {} and the end", "wide unicode 界".repeat(40)); let adapter = HeuristicInferenceAdapter::new(); let resp = adapter .generate_text(req_with(vec![ system_msg("you are nice"), user_msg("first question"), assistant_msg("first answer"), - user_msg("second question — please answer this"), + user_msg(&latest), ])) .await .unwrap(); assert!( - resp.text.contains("second question — please answer this"), + resp.text.contains(&latest), "must echo the LATEST user message, got: {}", resp.text ); diff --git a/core/continuum-engine/src/inference/resource_admission.rs b/core/continuum-engine/src/inference/resource_admission.rs index 888f737714..4e9a5afe31 100644 --- a/core/continuum-engine/src/inference/resource_admission.rs +++ b/core/continuum-engine/src/inference/resource_admission.rs @@ -1,18 +1,10 @@ -//! Shared Rust resource admission, and the serving lanes' admission and ledger. -//! -//! This is the small lease gate that every expensive subsystem can use -//! while the substrate governor becomes the process-wide allocator: -//! inference, training, rendering, audio, TTS, STT, classifiers, RAG, -//! and background work. Callers submit typed resource policy; the gate -//! admits or denies before work starts and returns an RAII guard that -//! releases the lease on every exit path. +//! Serving lanes' admission and ledger. //! //! The serving lanes, their permits and the model-call ledger (in-flight gauges, //! prompt samples, measured waits) are serving facts, so they live with the engine; //! the mind's own turn bookkeeping is `cognition::turn_ledger`, which calls down here. -mod gate; mod lanes; mod metrics; mod progress; @@ -20,7 +12,6 @@ mod serving_lane_permit; #[cfg(test)] mod tests; -pub use gate::*; pub use lanes::*; pub use metrics::*; pub use progress::{LaneWait, LaneProgress}; diff --git a/core/continuum-engine/src/inference/resource_admission/gate.rs b/core/continuum-engine/src/inference/resource_admission/gate.rs deleted file mode 100644 index f0675c88e5..0000000000 --- a/core/continuum-engine/src/inference/resource_admission/gate.rs +++ /dev/null @@ -1,212 +0,0 @@ -//! The hard resource-admission gate and its lease-backed guard. - -use crate::resources::throughput_class::{ResourceClass, TargetSilicon}; -use crate::resources::throughput_lease::{ - ThroughputLease, ThroughputLeaseError, ThroughputLeaseRegistry, ThroughputLeaseRevocationPolicy, -}; -use serde::{Deserialize, Serialize}; -use std::sync::{Mutex, MutexGuard}; -use ts_rs::TS; - -#[derive(Debug, Clone, Serialize, Deserialize, TS, PartialEq)] -#[serde(rename_all = "camelCase")] -#[ts( - export, - export_to = "../../../protocol/typescript/cognition/ResourceAdmissionPolicy.ts" -)] -pub struct ResourceAdmissionPolicy { - pub resource_class: ResourceClass, - pub target_silicon: TargetSilicon, - pub max_concurrency: usize, - pub max_cost_units: u32, - pub cost_units: u32, - #[ts(type = "number")] - pub lease_ttl_ms: u64, - pub revocation_policy: ThroughputLeaseRevocationPolicy, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct ResourceAdmissionRequest { - pub lease_id: String, - pub artifact_key: String, - pub holder_id: String, - pub policy: ResourceAdmissionPolicy, - pub now_ms: u64, -} - -#[derive(Debug, Clone, Eq, PartialEq, thiserror::Error)] -pub enum ResourceAdmissionError { - #[error("invalid resource admission policy: {reason}")] - InvalidPolicy { reason: String }, - #[error("resource admission denied: {reason}")] - Denied { reason: String }, - #[error("resource lease error: {reason}")] - Lease { reason: String }, -} - -#[derive(Debug, Default)] -pub struct ResourceAdmissionGate { - registry: Mutex, -} - -impl ResourceAdmissionGate { - pub fn new() -> Self { - Self::default() - } - - pub fn acquire( - &'static self, - request: ResourceAdmissionRequest, - ) -> Result { - validate_policy(&request.policy)?; - - let lease = ThroughputLease { - lease_id: request.lease_id.clone(), - artifact_key: request.artifact_key, - resource_class: request.policy.resource_class, - target_silicon: request.policy.target_silicon, - holder_id: request.holder_id, - cost_units: request.policy.cost_units, - acquired_at_ms: request.now_ms, - expires_at_ms: request.now_ms.saturating_add(request.policy.lease_ttl_ms), - revocation_policy: request.policy.revocation_policy, - }; - - let mut registry = self.lock_registry(); - registry.expire(request.now_ms); - let snapshot = registry.snapshot(request.now_ms); - let active_count = snapshot - .active - .iter() - .filter(|lease| lease.target_silicon == request.policy.target_silicon) - .count(); - let active_cost = snapshot - .cost_by_target_silicon - .get(&request.policy.target_silicon) - .copied() - .unwrap_or(0); - - if active_count >= request.policy.max_concurrency { - return Err(ResourceAdmissionError::Denied { - reason: format!( - "resource_class={:?} target_silicon={:?} active_count={} max_concurrency={}", - request.policy.resource_class, - request.policy.target_silicon, - active_count, - request.policy.max_concurrency - ), - }); - } - if active_cost.saturating_add(request.policy.cost_units) > request.policy.max_cost_units { - return Err(ResourceAdmissionError::Denied { - reason: format!( - "resource_class={:?} target_silicon={:?} active_cost={} requested_cost={} max_cost_units={}", - request.policy.resource_class, - request.policy.target_silicon, - active_cost, - request.policy.cost_units, - request.policy.max_cost_units - ), - }); - } - - registry - .acquire(lease, request.now_ms) - .map_err(|err| ResourceAdmissionError::Lease { - reason: format_lease_error(err), - })?; - - Ok(ResourceAdmissionGuard { - gate: self, - lease_id: Some(request.lease_id), - }) - } - - pub(super) fn release(&self, lease_id: &str) -> Result { - self.lock_registry().release(lease_id) - } - - pub(super) fn lock_registry(&self) -> MutexGuard<'_, ThroughputLeaseRegistry> { - self.registry - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) - } - - #[cfg(any(test, feature = "test-fixtures"))] - pub fn reset_for_test(&self) { - *self.lock_registry() = ThroughputLeaseRegistry::new(); - } - - #[cfg(any(test, feature = "test-fixtures"))] - pub fn active_count_for_test(&self, now_ms: u64) -> usize { - self.lock_registry().snapshot(now_ms).active.len() - } -} - -#[derive(Debug)] -pub struct ResourceAdmissionGuard { - gate: &'static ResourceAdmissionGate, - lease_id: Option, -} - -impl ResourceAdmissionGuard { - #[cfg(any(test, feature = "test-fixtures"))] - pub fn release(mut self) -> Result { - let lease_id = self - .lease_id - .take() - .expect("resource admission guard must contain a lease id before release"); - self.gate.release(&lease_id) - } -} - -impl Drop for ResourceAdmissionGuard { - fn drop(&mut self) { - let Some(lease_id) = self.lease_id.take() else { - return; - }; - let _ = self.gate.release(&lease_id); - } -} - -pub(super) fn validate_policy(policy: &ResourceAdmissionPolicy) -> Result<(), ResourceAdmissionError> { - if policy.max_concurrency == 0 { - return Err(invalid_policy("max_concurrency must be greater than zero")); - } - if policy.cost_units == 0 { - return Err(invalid_policy("cost_units must be greater than zero")); - } - if policy.max_cost_units == 0 { - return Err(invalid_policy("max_cost_units must be greater than zero")); - } - if policy.cost_units > policy.max_cost_units { - return Err(invalid_policy(format!( - "cost_units={} exceeds max_cost_units={}", - policy.cost_units, policy.max_cost_units - ))); - } - if policy.lease_ttl_ms == 0 { - return Err(invalid_policy("lease_ttl_ms must be greater than zero")); - } - Ok(()) -} - -pub(super) fn invalid_policy(reason: impl Into) -> ResourceAdmissionError { - ResourceAdmissionError::InvalidPolicy { - reason: reason.into(), - } -} - -pub(super) fn format_lease_error(err: ThroughputLeaseError) -> String { - match err { - ThroughputLeaseError::DuplicateLease { lease_id } => { - format!("duplicate lease_id={lease_id}") - } - ThroughputLeaseError::MissingLease { lease_id } => { - format!("missing lease_id={lease_id}") - } - ThroughputLeaseError::ExpiredLease { lease_id } => { - format!("expired lease_id={lease_id}") - } - } -} diff --git a/core/continuum-host/src/durable/fault_injection.rs b/core/continuum-host/src/durable/fault_injection.rs index e36e17b34e..8e1ab3f5d2 100644 --- a/core/continuum-host/src/durable/fault_injection.rs +++ b/core/continuum-host/src/durable/fault_injection.rs @@ -1,6 +1,4 @@ -//! Injected faults for tests of code that fences through [`super::fence`]. -//! Compiled only for tests and the `test-fixtures` feature, never into a release binary. - +//! Test-only durability faults, explicitly carried across blocking-worker boundaries. use std::cell::Cell; thread_local! { @@ -11,15 +9,81 @@ pub(super) fn fence_fails() -> bool { FAIL_FENCE.with(Cell::get) } -/// Runs `f` with every durability fence on this thread failing, then restores. -pub fn with_failed_fence(f: impl FnOnce()) { - struct Reset; - impl Drop for Reset { - fn drop(&mut self) { - FAIL_FENCE.with(|fail| fail.set(false)); +/// Thread-bound fault scope; an async fixture must stay on its current-thread runtime. +pub struct FailedFenceScope { + previous: bool, + thread_bound: std::marker::PhantomData>, +} + +impl FailedFenceScope { + pub fn enter() -> Self { + Self { + previous: FAIL_FENCE.with(|fault| fault.replace(true)), + thread_bound: std::marker::PhantomData, } } - FAIL_FENCE.with(|fail| fail.set(true)); - let _reset = Reset; - f(); +} + +impl Drop for FailedFenceScope { + fn drop(&mut self) { + FAIL_FENCE.with(|fault| fault.set(self.previous)); + } +} + +/// Captured fixture state. Capturing alone does not affect another thread. +#[derive(Clone, Copy)] +pub struct FenceFault(bool); + +impl FenceFault { + pub fn capture() -> Self { + Self(fence_fails()) + } + + /// Install this fixture only for the operation and restore the previous state, + /// including on unwind. Nested fixture scopes cannot clear an outer fault. + pub fn run(self, operation: impl FnOnce() -> R) -> R { + struct Reset(bool); + impl Drop for Reset { + fn drop(&mut self) { + FAIL_FENCE.with(|fault| fault.set(self.0)); + } + } + let previous = FAIL_FENCE.with(|fault| fault.replace(self.0)); + let _reset = Reset(previous); + operation() + } +} + +pub fn with_failed_fence(operation: impl FnOnce() -> R) -> R { + FenceFault(true).run(operation) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn nested_scope_restores_the_outer_fault() { + assert!(!fence_fails()); + with_failed_fence(|| { + with_failed_fence(|| assert!(fence_fails())); + assert!(fence_fails()); + }); + assert!(!fence_fails()); + } + + #[test] + fn captured_fault_is_explicit_and_scoped_on_worker() -> Result<(), String> { + let captured = with_failed_fence(FenceFault::capture); + let worker = std::thread::spawn(move || { + assert!(!fence_fails()); + captured.run(|| assert!(fence_fails())); + assert!(!fence_fails()); + }); + worker + .join() + .map_err(|_| "fault fixture worker panicked".to_string())?; + assert!(!fence_fails()); + Ok(()) + } } diff --git a/core/continuum-host/src/durable/staging.rs b/core/continuum-host/src/durable/staging.rs index 4dcd0a6dd0..a212893c82 100644 --- a/core/continuum-host/src/durable/staging.rs +++ b/core/continuum-host/src/durable/staging.rs @@ -38,7 +38,11 @@ impl Staging { pub fn new(dir: &Dir) -> io::Result { let dir = dir.try_clone()?; loop { - let name = format!(".{}-{}.staging", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed)); + let name = format!( + ".{}-{}.staging", + std::process::id(), + SEQ.fetch_add(1, Ordering::Relaxed) + ); match dir.open_with(&name, OpenOptions::new().write(true).create_new(true)) { Ok(file) => return Ok(Staging { dir, name, file }), Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue, @@ -64,6 +68,10 @@ impl Staging { /// Sync and move over `name` in the same directory, replacing what is there. pub fn replace(self, name: &Path) -> io::Result<()> { + #[cfg(any(test, feature = "test-fixtures"))] + if super::fault_injection::fence_fails() { + return Err(io::Error::other("injected durability fence failure")); + } self.file.sync_all()?; self.dir.rename(&self.name, &self.dir, name)?; super::os::sync_placed(&self.dir, name) @@ -72,6 +80,10 @@ impl Staging { /// Sync and publish at `name` in the same directory: `AlreadyExists` if it is taken (a racing /// identical publisher calls [`fence_existing`] on it), never an overwrite. pub fn publish_new(self, name: &Path) -> io::Result<()> { + #[cfg(any(test, feature = "test-fixtures"))] + if super::fault_injection::fence_fails() { + return Err(io::Error::other("injected durability fence failure")); + } self.file.sync_all()?; self.dir.hard_link(&self.name, &self.dir, name)?; super::os::sync_placed(&self.dir, name) @@ -91,7 +103,8 @@ impl Drop for Staging { /// Complete the durability fence of `name` in `dir`, a name another publisher created and may not /// have synced yet, so a reader never trusts an unfenced name. pub fn fence_existing(dir: &Dir, name: &Path) -> io::Result<()> { - dir.open_with(name, OpenOptions::new().read(true).write(true))?.sync_all()?; + dir.open_with(name, OpenOptions::new().read(true).write(true))? + .sync_all()?; super::os::sync_placed(dir, name) } @@ -104,9 +117,19 @@ pub struct Lock { /// Lock `name` in `dir` exclusively, waiting for a holder when `wait`, else refusing with /// `WouldBlock`. pub fn lock(dir: &Dir, name: &Path, wait: bool) -> io::Result { - let file = dir.open_with(name, OpenOptions::new().read(true).write(true).create(true).truncate(false))?; + let file = dir.open_with( + name, + OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false), + )?; if !file.metadata()?.is_file() { - return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("lock {} is not a regular file", name.display()))); + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("lock {} is not a regular file", name.display()), + )); } let file = file.into_std(); if wait { @@ -114,7 +137,9 @@ pub fn lock(dir: &Dir, name: &Path, wait: bool) -> io::Result { } else { match file.try_lock() { Ok(()) => {} - Err(TryLockError::WouldBlock) => return Err(io::Error::from(io::ErrorKind::WouldBlock)), + Err(TryLockError::WouldBlock) => { + return Err(io::Error::from(io::ErrorKind::WouldBlock)) + } Err(TryLockError::Error(error)) => return Err(error), } } @@ -124,12 +149,26 @@ pub fn lock(dir: &Dir, name: &Path, wait: bool) -> io::Result { /// Lock the file at `path` (its directory opened and held). pub fn lock_path(path: &Path, wait: bool) -> io::Result { let (dir, name) = split(path)?; - lock(&Dir::open_ambient_dir(dir, cap_std::ambient_authority())?, Path::new(name), wait) + lock( + &Dir::open_ambient_dir(dir, cap_std::ambient_authority())?, + Path::new(name), + wait, + ) } fn split(path: &Path) -> io::Result<(&Path, &std::ffi::OsStr)> { match (path.parent(), path.file_name()) { - (Some(dir), Some(name)) => Ok((if dir.as_os_str().is_empty() { Path::new(".") } else { dir }, name)), - _ => Err(io::Error::new(io::ErrorKind::InvalidInput, format!("{} names no file in a directory", path.display()))), + (Some(dir), Some(name)) => Ok(( + if dir.as_os_str().is_empty() { + Path::new(".") + } else { + dir + }, + name, + )), + _ => Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("{} names no file in a directory", path.display()), + )), } } diff --git a/core/continuum-host/src/durable/tests.rs b/core/continuum-host/src/durable/tests.rs index e0b63a19b2..c2f1c0825c 100644 --- a/core/continuum-host/src/durable/tests.rs +++ b/core/continuum-host/src/durable/tests.rs @@ -92,3 +92,22 @@ fn a_held_lock_refuses_a_second_holder() { // between fork and exec (O_CLOEXEC releases it at exec), so "free" is "free once that ends". lock_path(&path, true).expect("free again"); } + +// The managed class path uses Staging, not the legacy path-based fence helper. +#[test] +fn staged_replacement_fault_preserves_old_bytes_and_retry_succeeds() -> io::Result<()> { + let root = tempfile::tempdir()?; + let path = root.path().join("state"); + std::fs::write(&path, b"old")?; + let replace = || -> io::Result<()> { + let mut stage = Staging::new_in(root.path())?; + stage.write_all(b"new")?; + stage.replace(Path::new("state")) + }; + assert!(fault_injection::with_failed_fence(replace).is_err()); + assert_eq!(std::fs::read(&path)?, b"old"); + assert_eq!(std::fs::read_dir(root.path())?.count(), 1); + replace()?; + assert_eq!(std::fs::read(path)?, b"new"); + Ok(()) +} diff --git a/core/continuum-kernel/src/orm/gated_adapter.rs b/core/continuum-kernel/src/orm/gated_adapter.rs index b408f2a8f7..fc622754bb 100644 --- a/core/continuum-kernel/src/orm/gated_adapter.rs +++ b/core/continuum-kernel/src/orm/gated_adapter.rs @@ -32,11 +32,26 @@ pub(crate) struct PausedWrite { pub(crate) struct GatedAdapter { inner: Arc, next: Mutex>, + unwind_next: std::sync::atomic::AtomicBool, + fail_after_create: std::sync::atomic::AtomicBool, + fail_query: std::sync::atomic::AtomicBool, } impl GatedAdapter { pub(crate) fn new(inner: Arc) -> Self { - Self { inner, next: Mutex::new(None) } + Self { inner, next: Mutex::new(None), unwind_next: std::sync::atomic::AtomicBool::new(false), fail_after_create: std::sync::atomic::AtomicBool::new(false), fail_query: std::sync::atomic::AtomicBool::new(false) } + } + + pub(crate) fn unwind_next_write(&self) { + self.unwind_next.store(true, std::sync::atomic::Ordering::SeqCst); + } + + pub(crate) fn fail_after_next_create(&self) { + self.fail_after_create.store(true, std::sync::atomic::Ordering::SeqCst); + } + + pub(crate) fn fail_next_query(&self) { + self.fail_query.store(true, std::sync::atomic::Ordering::SeqCst); } /// Hold the next write at a gate. Only that one write is held. @@ -55,6 +70,9 @@ impl GatedAdapter { &self, write: impl FnOnce(Arc) -> BoxFuture<'static, R> + Send + 'static, ) -> R { + if self.unwind_next.swap(false, std::sync::atomic::Ordering::SeqCst) { + std::panic::resume_unwind(Box::new("injected storage unwind")); + } let gate = self.next.lock().expect("gate lock").take(); // test fixture: a poisoned gate means an earlier test thread panicked let inner = Arc::clone(&self.inner); tokio::spawn(async move { @@ -88,12 +106,21 @@ impl StorageAdapter for GatedAdapter { Err("the gated fixture does not own its adapter".to_string()) } async fn create(&self, record: DataRecord) -> StorageResult { - self.write(move |a| Box::pin(async move { a.create(record).await })).await + let fail = self.fail_after_create.swap(false, std::sync::atomic::Ordering::SeqCst); + let result = self.write(move |a| Box::pin(async move { a.create(record).await })).await; + if fail && result.success { + StorageResult::err("injected loss of write acknowledgement after commit") + } else { + result + } } async fn read(&self, collection: &str, id: &UUID) -> StorageResult { self.inner.read(collection, id).await } async fn query(&self, query: StorageQuery) -> StorageResult> { + if self.fail_query.swap(false, std::sync::atomic::Ordering::SeqCst) { + return StorageResult::err("injected query failure"); + } self.inner.query(query).await } async fn query_with_join(&self, query: StorageQuery) -> StorageResult> { diff --git a/core/continuum-kernel/src/runtime/admission_gate.rs b/core/continuum-kernel/src/runtime/admission_gate.rs index aaa326404b..cb036e4b80 100644 --- a/core/continuum-kernel/src/runtime/admission_gate.rs +++ b/core/continuum-kernel/src/runtime/admission_gate.rs @@ -20,6 +20,8 @@ //! not fail when the production copy regressed. use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use tokio::sync::Notify; /// High bit. Leaves 63 bits of count, which is not a limit anyone reaches: the count is /// concurrent units of work, bounded by citizens or queue capacity. @@ -28,14 +30,26 @@ const CLOSED: u64 = 1 << 63; /// Admission state for one resource: open/closed plus the in-flight count, in one word. pub struct AdmissionGate { word: AtomicU64, + idle: Notify, +} + +tokio::task_local! { + // Execution context, not a second owner: the RAII permit still owns the count. + static EXECUTING_GATES: Vec>; } impl AdmissionGate { + pub(crate) fn held_by_current_task(&self) -> bool { + EXECUTING_GATES + .try_with(|gates| gates.iter().any(|gate| std::ptr::eq(gate.as_ref(), self))) + .is_ok_and(|held| held) + } /// A new, OPEN gate with nothing in flight. `const` so it can be a `static` without /// a lazy initialiser. pub const fn new() -> Self { Self { word: AtomicU64::new(0), + idle: Notify::const_new(), } } @@ -66,6 +80,32 @@ impl AdmissionGate { self.admit_hooked(|| {}) } + /// Transfer admission into an owned task without releasing it at the spawn. + pub fn admit_owned(self: &Arc) -> Option { + let permit = self.admit()?; + let gate = Arc::clone(self); + // Transfer the single counted admission to the owned RAII permit. + std::mem::forget(permit); + Some(OwnedPermit { gate }) + } + + /// Close admission and await all existing permits. Cancelling a waiter never + /// reopens the gate or releases another task's custody; another waiter can resume. + pub async fn close_and_wait(&self) { + self.close(); + loop { + let idle = self.idle.notified(); + tokio::pin!(idle); + // Register before checking the count so the final release cannot + // occur between observing work and subscribing to its completion. + idle.as_mut().enable(); + if self.in_flight() == 0 { + return; + } + idle.await; + } + } + /// `admit`, with a hook run between the LOAD and the compare-exchange. /// /// The hook exists so a test can make the CAS genuinely fail. A test that simply @@ -109,16 +149,16 @@ impl AdmissionGate { /// an entry still sitting in the channel, and a drain would then call the module quiet /// while the writer still had work. /// - /// So the contract for this method is narrow and must stay narrow: **it is only - /// correct when a permit was `mem::forget`ed at a hand-off, and it must be called - /// exactly once for each one.** Anywhere both ends are in the same scope, use the + /// The contract is narrow: release exactly one counted admission, either from + /// a permit's Drop or after a permit was forgotten at the log-thread hand-off. + /// Anywhere both ends are in the same scope, use the /// permit and let it drop — a manual decrement has to be repeated at every exit path /// and will be missed at the next one added. /// /// Saturating, so a double release cannot wrap the count into the closed bit and /// reopen a shut gate. A double release is still a bug; this only bounds the damage. pub fn release_one(&self) { - let _ = self + let released = self .word .fetch_update(Ordering::AcqRel, Ordering::Acquire, |cur| { let count = cur & !CLOSED; @@ -130,6 +170,9 @@ impl AdmissionGate { Some((cur & CLOSED) | (count - 1)) } }); + if matches!(released, Ok(previous) if previous & !CLOSED == 1) { + self.idle.notify_waiters(); + } } /// Shut the gate. Returns whether THIS call closed it, so a second caller — a signal @@ -157,9 +200,34 @@ pub struct Permit<'a> { impl Drop for Permit<'_> { fn drop(&mut self) { - // Subtracting 1 from the whole word decrements the low-bit count and cannot reach - // the closed bit, because a permit only exists when the count was at least 1. - self.gate.word.fetch_sub(1, Ordering::AcqRel); + self.gate.release_one(); + } +} + +/// An admitted task's custody, retained through persistence and execution. +#[must_use = "retain the permit until the admitted work and its persistence finish"] +pub struct OwnedPermit { + gate: Arc, +} + +impl OwnedPermit { + /// Carry custody through the future and mark its causal scope, so it cannot + /// synchronously shut down the runtime that must wait for this same future. + pub(crate) async fn scope(self, work: F) -> F::Output { + let mut gates = match EXECUTING_GATES.try_with(Clone::clone) { + Ok(gates) => gates, + Err(_) => Vec::new(), // No enclosing admitted execution on this task. + }; + gates.push(Arc::clone(&self.gate)); + let result = EXECUTING_GATES.scope(gates, work).await; + drop(self); + result + } +} + +impl Drop for OwnedPermit { + fn drop(&mut self) { + self.gate.release_one(); } } @@ -167,6 +235,42 @@ impl Drop for Permit<'_> { mod tests { use super::*; + #[tokio::test] + async fn cancelling_drain_keeps_admission_closed_and_custody_owned() -> Result<(), String> { + let gate = Arc::new(AdmissionGate::new()); + let permit = gate.admit_owned().ok_or("open gate refused admission")?; + { + let drain = gate.close_and_wait(); + tokio::pin!(drain); + assert!(futures::poll!(drain.as_mut()).is_pending()); + } + assert!(!gate.is_open()); + assert_eq!(gate.in_flight(), 1); + assert!(gate.admit_owned().is_none()); + let successor = gate.close_and_wait(); + let peer = gate.close_and_wait(); + tokio::pin!(successor, peer); + assert!(futures::poll!(successor.as_mut()).is_pending()); + assert!(futures::poll!(peer.as_mut()).is_pending()); + drop(permit); + assert!(futures::poll!(successor.as_mut()).is_ready()); + assert!(futures::poll!(peer.as_mut()).is_ready()); + assert_eq!(gate.in_flight(), 0); + Ok(()) + } + + #[tokio::test] + async fn release_before_drain_subscription_is_observed() -> Result<(), String> { + let gate = Arc::new(AdmissionGate::new()); + let permit = gate.admit_owned().ok_or("open gate refused admission")?; + gate.close(); + drop(permit); + let drain = gate.close_and_wait(); + tokio::pin!(drain); + assert!(futures::poll!(drain.as_mut()).is_ready()); + Ok(()) + } + // what this catches: THE RACE, driven through the REAL admit/close rather than a // reimplementation of them. With an open flag and a count as separate atomics this // order was reachable: admit reads OPEN, close lands, drain reads 0 and saves, admit @@ -201,8 +305,15 @@ mod tests { ); assert!(gate.admit().is_none()); drop(permit); - assert_eq!(gate.in_flight(), 0, "the drain's wait ends when the work does"); - assert!(!gate.is_open(), "releasing the last permit must not reopen the gate"); + assert_eq!( + gate.in_flight(), + 0, + "the drain's wait ends when the work does" + ); + assert!( + !gate.is_open(), + "releasing the last permit must not reopen the gate" + ); } // what this catches: the closed bit and the count disturbing each other. They share @@ -217,7 +328,11 @@ mod tests { assert_eq!(gate.in_flight(), 3); drop(b); // one finishes BEFORE the close gate.close(); - assert_eq!(gate.in_flight(), 2, "the close carries what was still running"); + assert_eq!( + gate.in_flight(), + 2, + "the close carries what was still running" + ); drop(a); drop(c); // and the rest finish after it, out of admission order assert_eq!(gate.in_flight(), 0); @@ -232,7 +347,10 @@ mod tests { let gate = AdmissionGate::new(); let _held = gate.admit().expect("open"); assert!(gate.close(), "first close closed it"); - assert!(!gate.close(), "second close must report it was already shut"); + assert!( + !gate.close(), + "second close must report it was already shut" + ); assert_eq!(gate.in_flight(), 1, "and must not disturb the count"); } @@ -320,7 +438,11 @@ mod tests { let gate = AdmissionGate::new(); let permit = gate.admit().expect("open"); std::mem::forget(permit); // handed to another thread - assert_eq!(gate.in_flight(), 1, "the work is still in flight after the hand-off"); + assert_eq!( + gate.in_flight(), + 1, + "the work is still in flight after the hand-off" + ); gate.release_one(); // the holder finished it assert_eq!(gate.in_flight(), 0); } diff --git a/core/continuum-kernel/src/runtime/command_executor.rs b/core/continuum-kernel/src/runtime/command_executor.rs index cd9a5d1b72..bdcaa59ce0 100644 --- a/core/continuum-kernel/src/runtime/command_executor.rs +++ b/core/continuum-kernel/src/runtime/command_executor.rs @@ -81,11 +81,17 @@ pub struct DispatchFailure { impl DispatchFailure { pub(crate) fn not_committed(message: String) -> Self { - Self { outcome: DispatchOutcome::NotCommitted, message } + Self { + outcome: DispatchOutcome::NotCommitted, + message, + } } fn uncertain(message: String) -> Self { - Self { outcome: DispatchOutcome::Uncertain, message } + Self { + outcome: DispatchOutcome::Uncertain, + message, + } } } @@ -167,6 +173,8 @@ pub struct CommandExecutor { /// them inline against the owned `registry` + `interceptors` + /// TS bridge. remote_transport: Arc, + task_ledger: tokio::sync::OnceCell>, + task_execution: super::tasks::TaskExecution, } impl CommandExecutor { @@ -177,13 +185,18 @@ impl CommandExecutor { bus: None, policy: Arc::new(crate::routing::AllowAllPolicy), remote_transport: Arc::new(crate::routing::NotImplementedRemoteTransport), + task_ledger: tokio::sync::OnceCell::new(), + task_execution: super::tasks::TaskExecution::new_command_executor(), } } /// The trust this executor's policy resolves for `caller`: the same policy its gate uses /// ([`AuthPolicy::caller_trust`](crate::routing::AuthPolicy::caller_trust)). `None` when the /// policy cannot resolve it, which an owner-only handler treats as a refusal. - pub fn caller_trust(&self, caller: Option<&crate::routing::CallerIdentity>) -> Option { + pub fn caller_trust( + &self, + caller: Option<&crate::routing::CallerIdentity>, + ) -> Option { self.policy.caller_trust(caller) } @@ -351,37 +364,6 @@ impl CommandExecutor { outcome } - /// Fire a command in the BACKGROUND: return a handle (UUID) immediately, run the - /// dispatch on a spawned task, and on completion emit `command:completed` carrying the - /// handle AND the result. A subscriber — e.g. a persona that sent a sentinel, a - /// compile, or a debugger away — matches the completion by handle and folds the outcome - /// in when it lands, never blocking the turn. This is the fire-and-poll shape (#86): the - /// caller does not await the work. The handle is reusable in a follow-up command - /// (cancel/query/attach), which is why it's a plain UUID ([[commands-are-agency-algs-are-pathways]]). - pub fn dispatch_background( - self: &std::sync::Arc, - command: impl Into, - params: Value, - caller: Option, - ) -> uuid::Uuid { - let handle = uuid::Uuid::new_v4(); - let command: CommandUri = command.into(); - let this = std::sync::Arc::clone(self); - tokio::spawn(async move { - let start = std::time::Instant::now(); - // The caller's hands are bound and admitted inside dispatch, for this task's whole - // life: a release that began before its first poll refuses it by name. - let outcome = this.dispatch(&command, params, caller.as_ref()).await; - this.emit_command_completed( - command.path(), - &outcome, - start.elapsed().as_millis() as u64, - Some(handle), - ); - }); - handle - } - /// Routing decision on a [`CommandUri`]. Local URIs go through the /// existing chain; non-Local URIs return a typed /// not-yet-implemented error pending the transport selector. @@ -423,7 +405,8 @@ impl CommandExecutor { // Around-dispatch concerns (a caller's hands admission, the cognition pulse's work // accounting) are installed by their owners at boot (`dispatch_hook`); one refusal // ends the dispatch with nothing committed. - let scopes = super::dispatch_hook::enter_all(caller).map_err(DispatchFailure::not_committed)?; + let scopes = + super::dispatch_hook::enter_all(caller).map_err(DispatchFailure::not_committed)?; let in_command = scopes.clone(); let decision = route(command); // Local in-process dispatches pass `None` — substrate's own @@ -447,7 +430,9 @@ impl CommandExecutor { // proceeds to transport selection. match verdict { Verdict::Forbidden { reason } => { - return Err(DispatchFailure::not_committed(format!("forbidden: {reason}"))); + return Err(DispatchFailure::not_committed(format!( + "forbidden: {reason}" + ))); } Verdict::Deferred { reason, @@ -622,7 +607,10 @@ impl CommandExecutor { command_name: command.to_string(), duration_ms, success: outcome.is_ok(), - error: outcome.as_ref().err().map(|failure| failure.message.clone()), + error: outcome + .as_ref() + .err() + .map(|failure| failure.message.clone()), handle, result, }; @@ -805,5 +793,7 @@ impl CommandExecutor { // // Pure dependency injection. No global. No panic-if-uninitialized. +mod background; + #[cfg(test)] mod tests; diff --git a/core/continuum-kernel/src/runtime/command_executor/background.rs b/core/continuum-kernel/src/runtime/command_executor/background.rs new file mode 100644 index 0000000000..f2fc777d12 --- /dev/null +++ b/core/continuum-kernel/src/runtime/command_executor/background.rs @@ -0,0 +1,335 @@ +//! Persist acceptance before execution and the terminal result before notification. +use super::{CommandExecutor, DispatchFailure}; +use crate::routing::{CallerIdentity, CommandUri}; +use crate::runtime::tasks::{TaskEnd, TaskLedger, TaskOutput}; +use futures::FutureExt; +use serde_json::Value; +use std::sync::Arc; +use uuid::Uuid; + +// Custody is unresolved until a terminal is durable. A storage error alone +// cannot certify that acceptance did not commit. +// An unexpected unwind/drop in storage must not turn a released permit into a +// successful shutdown. Handler unwinds still produce their ordinary terminal. +struct PersistenceCustody<'a> { + unresolved: &'a std::sync::atomic::AtomicBool, + settled: bool, +} + +impl Drop for PersistenceCustody<'_> { + fn drop(&mut self) { + if !self.settled { + self.unresolved + .store(true, std::sync::atomic::Ordering::Release); + } + } +} + +impl CommandExecutor { + /// Explicit storage injection for an embedded executor or an isolated fixture. + pub fn set_task_ledger(&self, ledger: Arc) -> Result<(), String> { + self.task_ledger + .set(ledger) + .map_err(|_| "task ledger already initialized".into()) + } + + /// Resolve the same node store used by modules; never create a private database. + pub async fn task_ledger(&self) -> Result<&Arc, String> { + self.task_ledger + .get_or_try_init(|| async { + let data = self + .registry + .get_by_name("data") + .ok_or("background tasks require the data module")?; + let storage = data + .as_storage() + .ok_or("background tasks require the data storage provider")?; + let adapter = storage.adapter("main").await?; + TaskLedger::new(adapter).await.map(Arc::new) + }) + .await + } + + /// Await durable acceptance only, not execution. A refusal has no command effects. + /// The caller identity owns the receipt; command parameters cannot choose its owner. + pub async fn dispatch_background( + self: &Arc, + command: impl Into, + params: Value, + caller: Option, + ) -> Result { + let caller = caller.ok_or_else(|| { + DispatchFailure::not_committed("background tasks require an authenticated owner".into()) + })?; + let owner = caller.peer_id.as_uuid(); + let command: CommandUri = command.into(); + // Admission precedes the first storage await. A close either refuses + // this request without effects or sees custody throughout acceptance. + let custody = self.registry.task_admission.admit_owned().ok_or_else(|| { + DispatchFailure::not_committed("runtime is draining background tasks".into()) + })?; + let ledger = Arc::clone( + self.task_ledger() + .await + .map_err(DispatchFailure::not_committed)?, + ); + // The execution task owns persistence too. Dropping the caller while an + // insert is in flight must not strand a committed acceptance without work. + let (accepted, receipt) = tokio::sync::oneshot::channel(); + let this = Arc::clone(self); + tokio::spawn(custody.scope(async move { + let mut persistence = PersistenceCustody { + unresolved: &this.registry.task_persistence_failed, + settled: false, + }; + let handle = match ledger.accept(owner, command.to_string(), this.task_execution).await { + Ok(handle) => handle, + Err(error) => { + let _ = accepted.send(Err(DispatchFailure::uncertain(error))); + return; + } + }; + // A forgotten receipt does not cancel accepted work; its durable + // terminal remains available to the authenticated owner's replay. + let _ = accepted.send(Ok(handle)); + let start = std::time::Instant::now(); + // Keep the existing policy and hands admission scopes inside dispatch. + // Catch an unwinding handler without detaching a second execution task. + let outcome = + match std::panic::AssertUnwindSafe(this.dispatch(&command, params, Some(&caller))) + .catch_unwind() + .await + { + Ok(outcome) => outcome, + Err(_) => Err(DispatchFailure::uncertain( + "background command panicked".into(), + )), + }; + let outcome = outcome.and_then(|result| { + TaskOutput::try_from(result).map_err(DispatchFailure::uncertain) + }); + let end = match outcome { + Ok(output) => TaskEnd::Done(output), + Err(error) => TaskEnd::Failed { + message: error.message, + outcome: error.outcome, + }, + }; + let winner = match ledger.finish(handle, owner, this.task_execution, end).await { + Ok(winner) => winner, + Err(error) => { + tracing::error!(%handle, %owner, %error, "task ended but terminal persistence failed; acceptance remains unresolved"); + return; + } + }; + persistence.settled = true; + // A competing supervisor may have persisted a different terminal first. + // Every delivery must project that durable winner, never this writer's loser. + let outcome = completion(winner); + this.emit_command_completed( + command.path(), + &outcome, + start.elapsed().as_millis() as u64, + Some(handle), + ); + })); + receipt.await.map_err(|_| { + DispatchFailure::uncertain( + "background acceptance owner stopped before reporting".into(), + ) + })? + } +} + +fn completion(end: TaskEnd) -> Result { + match end { + TaskEnd::Done(output) => Ok(output.into()), + TaskEnd::Failed { message, outcome } => Err(DispatchFailure { message, outcome }), + TaskEnd::TimedOut => Err(DispatchFailure::uncertain("task timed out".into())), + TaskEnd::Stopped => Err(DispatchFailure::uncertain("task stopped".into())), + TaskEnd::Lost => Err(DispatchFailure::uncertain("task execution lost".into())), + } +} + +#[cfg(test)] +mod tests { + use super::super::DispatchOutcome; + use super::*; + use crate::runtime::{ + CommandInterceptor, CommandResult, InterceptorOutcome, MessageBus, ModuleRegistry, + }; + + #[tokio::test] + async fn closed_runtime_refuses_before_resolving_storage() -> Result<(), String> { + let registry = Arc::new(ModuleRegistry::new()); + registry.task_admission.close(); + // No data module or injected ledger: a request that gets past admission + // would fail at storage resolution with a different error. + let executor = Arc::new(CommandExecutor::new(registry.clone())); + let caller = + CallerIdentity::local_persona(crate::identity::PeerId::from_uuid(Uuid::new_v4())); + let result = executor + .dispatch_background("test/result", Value::Null, Some(caller)) + .await; + let Err(error) = result else { + return Err("closed runtime admitted background work".into()); + }; + assert_eq!(error.message, "runtime is draining background tasks"); + assert_eq!(error.outcome, DispatchOutcome::NotCommitted); + assert_eq!(registry.task_admission.in_flight(), 0); + Ok(()) + } + + struct GatedResult { + entered: tokio::sync::Notify, + release: tokio::sync::Notify, + unwind: bool, + } + + #[async_trait::async_trait] + impl CommandInterceptor for GatedResult { + fn name(&self) -> &'static str { + "gated-test-result" + } + async fn try_route( + &self, + _: &str, + _: &Value, + _: Option<&CallerIdentity>, + ) -> Result { + self.entered.notify_one(); + self.release.notified().await; + if self.unwind { + // Fault injection: exercise the real supervisor's unwind boundary + // without relying on a process-global panic hook or aborting process. + std::panic::resume_unwind(Box::new("injected handler unwind")); + } + Ok(InterceptorOutcome::Handled(CommandResult::Json( + Value::Null, + ))) + } + } + + #[tokio::test] + async fn dropping_acceptance_waiter_does_not_orphan_execution() -> Result<(), String> { + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let ledger = Arc::new(TaskLedger::new(adapter).await?); + let gate = Arc::new(GatedResult { + entered: tokio::sync::Notify::new(), + release: tokio::sync::Notify::new(), + unwind: false, + }); + let bus = Arc::new(MessageBus::new()); + let mut events = bus.receiver(); + let executor = Arc::new( + CommandExecutor::new(Arc::new(ModuleRegistry::new())) + .with_message_bus(bus) + .with_interceptor(gate.clone()), + ); + executor.set_task_ledger(ledger.clone())?; + let owner = Uuid::new_v4(); + let caller = CallerIdentity::local_persona(crate::identity::PeerId::from_uuid(owner)); + { + let waiting = executor.dispatch_background("test/result", Value::Null, Some(caller)); + tokio::pin!(waiting); + // On this current-thread runtime the new execution task cannot run + // during poll: abandon its receipt before it starts acceptance. + assert!(futures::poll!(waiting.as_mut()).is_pending()); + } + tokio::time::timeout(std::time::Duration::from_secs(5), gate.entered.notified()) + .await + .map_err(|error| error.to_string())?; + assert_eq!(executor.registry.task_admission.in_flight(), 1); + let drain = executor.registry.task_admission.close_and_wait(); + tokio::pin!(drain); + assert!(futures::poll!(drain.as_mut()).is_pending()); + gate.release.notify_one(); + let event = tokio::time::timeout(std::time::Duration::from_secs(5), events.recv()) + .await + .map_err(|error| error.to_string())? + .map_err(|error| error.to_string())?; + let handle = event.payload["handle"] + .as_str() + .ok_or("completion has no task handle")?; + let handle = Uuid::parse_str(handle).map_err(|error| error.to_string())?; + assert!(matches!( + ledger.pending(handle, owner).await?, + Some(TaskEnd::Done(_)) + )); + tokio::time::timeout(std::time::Duration::from_secs(5), drain) + .await + .map_err(|error| error.to_string())?; + assert_eq!(executor.registry.task_admission.in_flight(), 0); + Ok(()) + } + + #[tokio::test] + async fn terminal_delivery_handles_competing_writers_and_unwinding_handlers( + ) -> Result<(), String> { + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let ledger = Arc::new(TaskLedger::new(adapter).await?); + for unwind in [false, true] { + let gate = Arc::new(GatedResult { + entered: tokio::sync::Notify::new(), + release: tokio::sync::Notify::new(), + unwind, + }); + let bus = Arc::new(MessageBus::new()); + let mut events = bus.receiver(); + let executor = Arc::new( + CommandExecutor::new(Arc::new(ModuleRegistry::new())) + .with_message_bus(bus) + .with_interceptor(gate.clone()), + ); + executor.set_task_ledger(ledger.clone())?; + let owner = Uuid::new_v4(); + let caller = CallerIdentity::local_persona(crate::identity::PeerId::from_uuid(owner)); + let task = executor + .dispatch_background("test/result", Value::Null, Some(caller)) + .await + .map_err(|error| error.message)?; + tokio::time::timeout(std::time::Duration::from_secs(5), gate.entered.notified()) + .await + .map_err(|error| error.to_string())?; + // Inject another writer's committed terminal; this tests arbitration, + // not permission to declare a running command stopped. + let winner = TaskEnd::Failed { + message: if unwind { + "background command panicked" + } else { + "previous terminal" + } + .into(), + outcome: DispatchOutcome::Uncertain, + }; + if !unwind { + ledger + .finish( + task, + owner, + ledger.execution(task, owner).await?, + winner.clone(), + ) + .await?; + } + gate.release.notify_one(); + let event = tokio::time::timeout(std::time::Duration::from_secs(5), events.recv()) + .await + .map_err(|error| error.to_string())? + .map_err(|error| error.to_string())?; + assert_eq!(event.name, "command:completed"); + assert_eq!(event.payload["handle"], task.to_string()); + assert_eq!(event.payload["success"], false); + assert_eq!( + event.payload["error"], + if unwind { + "background command panicked" + } else { + "previous terminal" + } + ); + assert_eq!(ledger.pending(task, owner).await?, Some(winner)); + } + Ok(()) + } +} diff --git a/core/continuum-kernel/src/runtime/command_executor/tests.rs b/core/continuum-kernel/src/runtime/command_executor/tests.rs index e71a5b2bed..31cc8b30f0 100644 --- a/core/continuum-kernel/src/runtime/command_executor/tests.rs +++ b/core/continuum-kernel/src/runtime/command_executor/tests.rs @@ -268,21 +268,27 @@ ); } - // what this catches: dispatch_background returns a handle IMMEDIATELY (fire-and-poll) + // what this catches: dispatch_background returns after durable acceptance, before execution, // and its completion event carries BOTH the handle and the result — so a subscriber // (a persona that sent a sentinel away) matches the completion to its dispatch and // folds the outcome in without a second call. This is the producer for the WM async // recency channel. #[tokio::test] - async fn dispatch_background_completion_carries_handle_and_result() { + async fn dispatch_background_completion_carries_handle_and_result() -> Result<(), String> { let registry = Arc::new(ModuleRegistry::new()); registry.register(Arc::new(CannedModule::answering(Ok(serde_json::json!({ "built": true, "warnings": 0 }))))); let bus = Arc::new(MessageBus::new()); let mut rx = bus.receiver(); let executor = Arc::new(CommandExecutor::new(registry).with_message_bus(bus)); - // Fire in the background — returns a handle immediately, does not await the work. - let handle = executor.dispatch_background("canned/ping", serde_json::json!({}), None); + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let ledger = Arc::new(crate::runtime::tasks::TaskLedger::new(adapter).await?); + executor.set_task_ledger(ledger.clone())?; + let owner = uuid::Uuid::new_v4(); + let caller = crate::routing::CallerIdentity::local_persona(crate::identity::PeerId::from_uuid(owner)); + // Await durable acceptance, not the command's execution. + let handle = executor.dispatch_background("canned/ping", serde_json::json!({}), Some(caller)) + .await.map_err(|e| e.message)?; let event = next_command_completed(&mut rx).await; assert_eq!(event.command_name, "canned/ping"); @@ -297,6 +303,58 @@ Some(serde_json::json!({ "built": true, "warnings": 0 })), "completion carries the result — no second call needed" ); + assert!(matches!(ledger.pending(handle, owner).await?, Some(crate::runtime::tasks::TaskEnd::Done(_))), + "terminal receipt must be durable before the completion event"); + Ok(()) + } + + #[tokio::test] + async fn background_acceptance_refusal_never_reaches_dispatch() { + let seen = Arc::new(AtomicUsize::new(0)); + let executor = Arc::new(CommandExecutor::new(Arc::new(ModuleRegistry::new())) + .with_interceptor(Arc::new(RecordingDecliner { name: "effect", seen: seen.clone(), mark: 1 }))); + let anonymous = executor.dispatch_background("effect/run", serde_json::json!({}), None).await; + assert!(matches!(anonymous, Err(DispatchFailure { outcome: DispatchOutcome::NotCommitted, .. }))); + let caller = crate::routing::CallerIdentity::local_persona(crate::identity::PeerId::from_uuid(uuid::Uuid::new_v4())); + // Identity alone is insufficient: no storage provider means no durable acceptance. + let no_store = executor.dispatch_background("effect/run", serde_json::json!({}), Some(caller)).await; + assert!(matches!(no_store, Err(DispatchFailure { outcome: DispatchOutcome::NotCommitted, .. }))); + tokio::task::yield_now().await; + assert_eq!(seen.load(Ordering::SeqCst), 0); + } + + #[tokio::test] + async fn background_failure_retains_effect_classification_after_reopen() -> Result<(), String> { + use crate::runtime::tasks::{TaskEnd, TaskLedger}; + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let ledger = Arc::new(TaskLedger::new(adapter.clone()).await?); + let registry = Arc::new(ModuleRegistry::new()); + registry.register(Arc::new(CannedModule::answering(Err("handler failed after possible effect".into())))); + let bus = Arc::new(MessageBus::new()); + let mut rx = bus.receiver(); + let executor = Arc::new(CommandExecutor::new(registry).with_message_bus(bus)); + executor.set_task_ledger(ledger)?; + let owner = uuid::Uuid::new_v4(); + for (command, expected) in [ + ("canned/boom", DispatchOutcome::Uncertain), + ("absent/command", DispatchOutcome::NotCommitted), + ] { + let caller = crate::routing::CallerIdentity::local_persona(crate::identity::PeerId::from_uuid(owner)); + let handle = executor.dispatch_background(command, serde_json::json!({}), Some(caller)) + .await.map_err(|error| error.message)?; + let event = next_command_completed(&mut rx).await; + assert_eq!(event.handle, Some(handle)); + assert!(!event.success); + let reopened = TaskLedger::new(adapter.clone()).await?; + match reopened.pending(handle, owner).await? { + Some(TaskEnd::Failed { message, outcome }) => { + assert_eq!(outcome, expected); + assert_eq!(Some(message), event.error); + } + other => return Err(format!("expected durable failure, got {other:?}")), + } + } + Ok(()) } #[tokio::test] diff --git a/core/continuum-kernel/src/runtime/mod.rs b/core/continuum-kernel/src/runtime/mod.rs index 8507874122..14d0699b4e 100644 --- a/core/continuum-kernel/src/runtime/mod.rs +++ b/core/continuum-kernel/src/runtime/mod.rs @@ -43,6 +43,7 @@ pub mod control; pub mod event_classes; pub mod event_graph; pub mod tracked_checkout; +pub mod tasks; pub mod daemon; pub mod governor_bus; pub mod handle; diff --git a/core/continuum-kernel/src/runtime/registry.rs b/core/continuum-kernel/src/runtime/registry.rs index cb8ba9e18b..625a27ffac 100644 --- a/core/continuum-kernel/src/runtime/registry.rs +++ b/core/continuum-kernel/src/runtime/registry.rs @@ -15,6 +15,10 @@ use std::any::TypeId; use std::sync::Arc; pub struct ModuleRegistry { + /// Background acceptance, execution and terminal persistence share custody + /// with this runtime's module registry, including across executor instances. + pub(crate) task_admission: Arc, + pub(crate) task_persistence_failed: std::sync::atomic::AtomicBool, /// Modules by name: "voice" -> Arc modules: DashMap<&'static str, Arc>, @@ -57,6 +61,8 @@ impl Default for ModuleRegistry { impl ModuleRegistry { pub fn new() -> Self { let registry = Self { + task_admission: Arc::new(super::admission_gate::AdmissionGate::new()), + task_persistence_failed: std::sync::atomic::AtomicBool::new(false), modules: DashMap::new(), configs: DashMap::new(), metrics: DashMap::new(), @@ -400,7 +406,8 @@ mod tests { struct StubSpec; impl crate::sdk_codegen::CommandSpec for StubSpec { const NAME: &'static str = "test/stub-descriptor"; - const ACCESS_LEVEL: crate::sdk_codegen::AccessLevel = crate::sdk_codegen::AccessLevel::AiSafe; + const ACCESS_LEVEL: crate::sdk_codegen::AccessLevel = + crate::sdk_codegen::AccessLevel::AiSafe; const WIRE: crate::sdk_codegen::WireShape = crate::sdk_codegen::WireShape::Bare; type Params = StubParams; type Result = StubResult; @@ -547,5 +554,4 @@ mod tests { let found = registry.module_of_type::(); assert!(found.is_some()); } - } diff --git a/core/continuum-kernel/src/runtime/runtime/runtime.rs b/core/continuum-kernel/src/runtime/runtime/runtime.rs index 870e7894f9..efa92dc1eb 100644 --- a/core/continuum-kernel/src/runtime/runtime/runtime.rs +++ b/core/continuum-kernel/src/runtime/runtime/runtime.rs @@ -1,7 +1,10 @@ use super::*; -impl Runtime { +#[cfg(test)] +#[path = "runtime_tests.rs"] +mod tests; +impl Runtime { /// `shutdown`, with the per-phase bound passed IN. /// /// A parameter rather than a constant because the TIMEOUT arms could not otherwise be @@ -9,13 +12,44 @@ impl Runtime { /// were only ever constructed as literals and asserted on. Deleting the timeout /// handling here would have left every one of those tests green — the outcomes were /// described by the suite and never produced by it. Found by IntelMac. + pub(super) fn self_shutdown_refusal(&self) -> Option { + self.registry.task_admission.held_by_current_task().then(|| ShutdownReceipt { + tasks: DrainOutcome::Unknown { + reason: "an admitted task cannot shut down its own runtime; request shutdown outside its execution scope".into(), + }, + modules: Vec::new(), + total_ms: 0, + }) + } + pub(super) async fn shutdown_within(&self, per_phase: std::time::Duration) -> ShutdownReceipt { + if let Some(receipt) = self.self_shutdown_refusal() { + return receipt; + } + let started = std::time::Instant::now(); + // The same registry is held by every executor. Close before waiting so + // acceptance cannot race past a zero count. Cancellation leaves it closed. + let tasks = match tokio::time::timeout(per_phase, self.registry.task_admission.close_and_wait()).await { + Err(_) => DrainOutcome::Unknown { + reason: format!("background task custody did not settle within {}ms; modules remain running", per_phase.as_millis()), + }, + Ok(()) if self.registry.task_persistence_failed.load(std::sync::atomic::Ordering::Acquire) => DrainOutcome::Unknown { + reason: "background task persistence did not settle; durable acceptances require reconciliation".into(), + }, + Ok(()) => DrainOutcome::Drained, + }; + if !tasks.is_quiet() { + return ShutdownReceipt { + tasks, + modules: Vec::new(), + total_ms: started.elapsed().as_millis() as u64, + }; + } let modules = self.registry.list_modules(); info!( "Stopping {} modules (drain → save → join, parallel, 2s bound per phase)...", modules.len() ); - let started = std::time::Instant::now(); let futs = modules.iter().filter_map(|name| { self.registry.get_by_name(name).map(|module| { // Deref, not clone: `list_modules` yields `Vec<&'static str>`, so `name` @@ -72,6 +106,7 @@ impl Runtime { }) }); let receipt = ShutdownReceipt { + tasks, modules: futures::future::join_all(futs).await, total_ms: started.elapsed().as_millis() as u64, }; @@ -153,7 +188,6 @@ impl Runtime { ); Ok(()) } - } /// Quarantine threshold for the per-module tick loop. After this many @@ -450,7 +484,11 @@ pub struct ModuleSpec { } impl ModuleSpec { - pub(super) const fn new(name: &'static str, group: ServiceGroup, category: ModuleCategory) -> Self { + pub(super) const fn new( + name: &'static str, + group: ServiceGroup, + category: ModuleCategory, + ) -> Self { Self { name, group, diff --git a/core/continuum-kernel/src/runtime/runtime/runtime_tests.rs b/core/continuum-kernel/src/runtime/runtime/runtime_tests.rs new file mode 100644 index 0000000000..ba4343e2b9 --- /dev/null +++ b/core/continuum-kernel/src/runtime/runtime/runtime_tests.rs @@ -0,0 +1,172 @@ +#[path = "self_shutdown_tests.rs"] +mod self_shutdown_tests; + +use super::*; +use crate::runtime::runtime::piece_2_pr3_dispatch_tests::RecordingModule; +use std::sync::atomic::Ordering; + +#[tokio::test] +async fn shutdown_waits_for_acceptance_and_terminal_storage_after_receipt_is_forgotten( +) -> Result<(), String> { + use crate::orm::gated_adapter::GatedAdapter; + use crate::runtime::tasks::TaskLedger; + use crate::runtime::CommandExecutor; + let runtime = Runtime::new(); + let (module, _) = RecordingModule::new("storage-boundary", Vec::new()); + runtime.register(module.clone()); + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let adapter = Arc::new(GatedAdapter::new(adapter)); + let ledger = Arc::new(TaskLedger::new(adapter.clone()).await?); + let executor = Arc::new( + CommandExecutor::new(runtime.registry.clone()).with_message_bus(runtime.bus.clone()), + ); + executor.set_task_ledger(ledger.clone())?; + let mut events = runtime.bus.receiver(); + let owner = uuid::Uuid::new_v4(); + let caller = + crate::routing::CallerIdentity::local_persona(crate::identity::PeerId::from_uuid(owner)); + let acceptance = adapter.pause_next_write(); + { + let receipt = + executor.dispatch_background("test/unhandled", serde_json::Value::Null, Some(caller)); + tokio::pin!(receipt); + assert!(futures::poll!(receipt.as_mut()).is_pending()); + acceptance.entered.notified().await; + // Drop the actual caller while its durable acceptance write is paused. + } + let shutdown = runtime.shutdown_within(std::time::Duration::from_secs(30)); + tokio::pin!(shutdown); + assert!(futures::poll!(shutdown.as_mut()).is_pending()); + assert_eq!(module.saves.load(Ordering::SeqCst), 0); + let terminal = adapter.pause_next_write(); + acceptance.release.notify_one(); + terminal.entered.notified().await; + assert!(futures::poll!(shutdown.as_mut()).is_pending()); + assert_eq!(module.saves.load(Ordering::SeqCst), 0); + terminal.release.notify_one(); + let receipt = shutdown.await; + assert!(receipt.state_is_durable()); + assert_eq!(module.saves.load(Ordering::SeqCst), 1); + let completion = events.recv().await.map_err(|error| error.to_string())?; + let task = completion.payload["handle"] + .as_str() + .ok_or("missing completion handle")?; + let task = uuid::Uuid::parse_str(task).map_err(|error| error.to_string())?; + // The command was unhandled, but its failure is durable and deliverable; + // module shutdown cannot overtake either storage boundary. + assert!(matches!( + ledger.pending(task, owner).await?, + Some(crate::runtime::tasks::TaskEnd::Failed { .. }) + )); + Ok(()) +} + +#[tokio::test(start_paused = true)] +async fn shutdown_owner_retries_withheld_custody_without_repeating_module_stop( +) -> Result<(), String> { + let runtime = Arc::new(Runtime::new()); + let (module, _) = RecordingModule::new("retry-custody-store", Vec::new()); + runtime.register(module.clone()); + let custody = runtime + .registry + .task_admission + .admit_owned() + .ok_or("admission refused")?; + let operation = ShutdownOperation::new(); + let mut first = operation.begin(Some(runtime.clone()), std::time::Duration::ZERO); + first.changed().await.map_err(|error| error.to_string())?; + let receipt = first + .borrow_and_update() + .clone() + .ok_or("missing withheld receipt")?; + assert!(!receipt.tasks.is_quiet()); + assert_eq!(module.saves.load(Ordering::SeqCst), 0); + drop(first); + drop(custody); + let mut retry = operation.begin(Some(runtime.clone()), std::time::Duration::ZERO); + assert!(retry.borrow().is_none()); + retry.changed().await.map_err(|error| error.to_string())?; + let receipt = retry + .borrow_and_update() + .clone() + .ok_or("missing completed receipt")?; + assert!(receipt.state_is_durable()); + let again = operation.begin(Some(runtime), std::time::Duration::ZERO); + assert_eq!(again.borrow().as_ref(), Some(&receipt)); + assert_eq!(module.saves.load(Ordering::SeqCst), 1); + Ok(()) +} + +#[tokio::test(start_paused = true)] +async fn unfinished_custody_withholds_module_stop_and_a_later_drain_can_finish( +) -> Result<(), String> { + let runtime = Runtime::new(); + let (module, _) = RecordingModule::new("custody-store", Vec::new()); + runtime.register(module.clone()); + let custody = runtime + .registry + .task_admission + .admit_owned() + .ok_or("admission refused")?; + let receipt = runtime + .shutdown_within(std::time::Duration::from_millis(10)) + .await; + assert!(!receipt.state_is_durable()); + assert!(!receipt.tasks.is_quiet()); + assert!(receipt.modules.is_empty()); + assert_eq!(module.saves.load(Ordering::SeqCst), 0); + assert!(runtime.registry.task_admission.admit_owned().is_none()); + drop(custody); + let receipt = runtime + .shutdown_within(std::time::Duration::from_millis(10)) + .await; + assert!(receipt.state_is_durable()); + assert_eq!(module.saves.load(Ordering::SeqCst), 1); + Ok(()) +} + +#[tokio::test] +async fn cancelling_shutdown_wait_does_not_release_task_custody() -> Result<(), String> { + let runtime = Runtime::new(); + let (module, _) = RecordingModule::new("cancel-custody-store", Vec::new()); + runtime.register(module.clone()); + let custody = runtime + .registry + .task_admission + .admit_owned() + .ok_or("admission refused")?; + { + let stop = runtime.shutdown_within(std::time::Duration::from_secs(1)); + tokio::pin!(stop); + assert!(futures::poll!(stop.as_mut()).is_pending()); + } + assert_eq!(module.saves.load(Ordering::SeqCst), 0); + assert_eq!(runtime.registry.task_admission.in_flight(), 1); + assert!(runtime.registry.task_admission.admit_owned().is_none()); + drop(custody); + assert!(runtime + .shutdown_within(std::time::Duration::from_secs(1)) + .await + .state_is_durable()); + Ok(()) +} + +#[tokio::test] +async fn failed_terminal_persistence_is_not_a_quiet_runtime() { + let runtime = Runtime::new(); + let (module, _) = RecordingModule::new("failed-custody-store", Vec::new()); + runtime.register(module.clone()); + // Inject the execution owner's terminal-write failure fact; this tests + // shutdown's consumption of it, not the storage adapter's fault handling. + runtime + .registry + .task_persistence_failed + .store(true, Ordering::Release); + let receipt = runtime + .shutdown_within(std::time::Duration::from_secs(1)) + .await; + assert!(!receipt.state_is_durable()); + assert_eq!(module.saves.load(Ordering::SeqCst), 0); + assert!(matches!(receipt.tasks, DrainOutcome::Unknown { .. })); + assert!(receipt.modules.is_empty()); +} diff --git a/core/continuum-kernel/src/runtime/runtime/self_shutdown_tests.rs b/core/continuum-kernel/src/runtime/runtime/self_shutdown_tests.rs new file mode 100644 index 0000000000..7de2e2c3d6 --- /dev/null +++ b/core/continuum-kernel/src/runtime/runtime/self_shutdown_tests.rs @@ -0,0 +1,256 @@ +use super::*; +use crate::runtime::runtime::piece_2_pr3_dispatch_tests::RecordingModule; +use crate::runtime::{CommandExecutor, CommandInterceptor, InterceptorOutcome}; +use std::sync::atomic::Ordering; + +struct RequestOwnShutdown { + runtime: Arc, + operation: Arc, +} + +#[async_trait::async_trait] +impl CommandInterceptor for RequestOwnShutdown { + fn name(&self) -> &'static str { + "request-own-shutdown" + } + + async fn try_route( + &self, + _: &str, + _: &serde_json::Value, + _: Option<&crate::routing::CallerIdentity>, + ) -> Result { + let direct = self.runtime.shutdown().await; + assert!(!direct.tasks.is_quiet()); + assert!(direct.modules.is_empty()); + let observer = self + .operation + .begin(Some(self.runtime.clone()), Duration::ZERO); + let receipt = observer + .borrow() + .clone() + .ok_or("self-shutdown was not refused immediately")?; + assert!(!receipt.tasks.is_quiet()); + assert!(self.runtime.registry.task_admission.is_open()); + Ok(InterceptorOutcome::Handled(CommandResult::Json( + serde_json::Value::Null, + ))) + } +} + +#[tokio::test] +async fn actual_background_self_shutdown_refuses_before_closing_and_can_finish( +) -> Result<(), String> { + let runtime = Arc::new(Runtime::new()); + let (module, _) = RecordingModule::new("self-shutdown-store", Vec::new()); + runtime.register(module.clone()); + let operation = Arc::new(ShutdownOperation::new()); + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let ledger = Arc::new(crate::runtime::tasks::TaskLedger::new(adapter).await?); + let mut events = runtime.bus.receiver(); + let executor = Arc::new( + CommandExecutor::new(runtime.registry.clone()) + .with_message_bus(runtime.bus.clone()) + .with_interceptor(Arc::new(RequestOwnShutdown { + runtime: runtime.clone(), + operation: operation.clone(), + })), + ); + executor.set_task_ledger(ledger.clone())?; + let owner = uuid::Uuid::new_v4(); + let caller = + crate::routing::CallerIdentity::local_persona(crate::identity::PeerId::from_uuid(owner)); + let handle = executor + .dispatch_background("test/shutdown", serde_json::Value::Null, Some(caller)) + .await + .map_err(|e| e.message)?; + tokio::time::timeout(Duration::from_secs(5), events.recv()) + .await + .map_err(|e| e.to_string())? + .map_err(|e| e.to_string())?; + assert!(matches!( + ledger.pending(handle, owner).await?, + Some(crate::runtime::tasks::TaskEnd::Done(_)) + )); + assert_eq!(module.saves.load(Ordering::SeqCst), 0); + assert!(runtime.registry.task_admission.is_open()); + // The refused request did not poison the retained process operation. + let observer = operation.begin(Some(runtime.clone()), Duration::ZERO); + let receipt = await_shutdown(observer, Duration::from_secs(5)) + .await + .ok_or("external shutdown did not finish")?; + assert!(receipt.state_is_durable()); + assert_eq!(module.saves.load(Ordering::SeqCst), 1); + Ok(()) +} + +#[tokio::test] +async fn storage_unwind_cannot_release_custody_as_a_clean_shutdown() -> Result<(), String> { + let runtime = Arc::new(Runtime::new()); + let (module, _) = RecordingModule::new("storage-unwind", Vec::new()); + runtime.register(module.clone()); + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let adapter = Arc::new(crate::orm::gated_adapter::GatedAdapter::new(adapter)); + let ledger = Arc::new(crate::runtime::tasks::TaskLedger::new(adapter.clone()).await?); + let executor = Arc::new(CommandExecutor::new(runtime.registry.clone())); + executor.set_task_ledger(ledger)?; + adapter.unwind_next_write(); + let caller = crate::routing::CallerIdentity::local_persona(crate::identity::PeerId::from_uuid( + uuid::Uuid::new_v4(), + )); + let result = executor + .dispatch_background("test/result", serde_json::Value::Null, Some(caller)) + .await; + assert!(result.is_err()); + assert_eq!(runtime.registry.task_admission.in_flight(), 0); + let receipt = runtime.shutdown().await; + assert!(!receipt.tasks.is_quiet()); + assert!(receipt.modules.is_empty()); + assert_eq!(module.saves.load(Ordering::SeqCst), 0); + Ok(()) +} + +struct FailTerminalWrite(Arc); + +#[tokio::test] +async fn verified_acceptance_readback_recovers_lost_acknowledgement() -> Result<(), String> { + use crate::orm::adapter::StorageAdapter; + let runtime = Arc::new(Runtime::new()); + let (module, _) = RecordingModule::new("acceptance-ack-loss", Vec::new()); + runtime.register(module.clone()); + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let adapter = Arc::new(crate::orm::gated_adapter::GatedAdapter::new(adapter)); + let ledger = Arc::new(crate::runtime::tasks::TaskLedger::new(adapter.clone()).await?); + let executor = Arc::new(CommandExecutor::new(runtime.registry.clone())); + executor.set_task_ledger(ledger.clone())?; + adapter.fail_after_next_create(); + let owner = uuid::Uuid::new_v4(); + let caller = + crate::routing::CallerIdentity::local_persona(crate::identity::PeerId::from_uuid(owner)); + let handle = executor + .dispatch_background("test/result", serde_json::Value::Null, Some(caller)) + .await + .map_err(|error| error.message)?; + let receipt = runtime.shutdown().await; + assert!(receipt.state_is_durable()); + assert_eq!(module.saves.load(Ordering::SeqCst), 1); + assert!(matches!( + ledger.pending(handle, owner).await?, + Some(crate::runtime::tasks::TaskEnd::Failed { .. }) + )); + // The adapter really committed the acceptance before losing its reply. + let count = adapter + .count(crate::orm::query::QueryBuilder::new("kernel_task_facts").build()) + .await; + assert!(count.success); + assert_eq!(count.data, Some(2)); + Ok(()) +} + +#[tokio::test] +async fn unreadable_committed_acceptance_retains_custody_without_execution() -> Result<(), String> { + use crate::orm::adapter::StorageAdapter; + let runtime = Arc::new(Runtime::new()); + let (module, _) = RecordingModule::new("acceptance-readback-failure", Vec::new()); + runtime.register(module.clone()); + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let adapter = Arc::new(crate::orm::gated_adapter::GatedAdapter::new(adapter)); + let ledger = Arc::new(crate::runtime::tasks::TaskLedger::new(adapter.clone()).await?); + let mut events = runtime.bus.receiver(); + let executor = Arc::new( + CommandExecutor::new(runtime.registry.clone()).with_message_bus(runtime.bus.clone()), + ); + executor.set_task_ledger(ledger)?; + adapter.fail_after_next_create(); + adapter.fail_next_query(); + let caller = crate::routing::CallerIdentity::local_persona(crate::identity::PeerId::from_uuid( + uuid::Uuid::new_v4(), + )); + let error = executor + .dispatch_background("test/result", serde_json::Value::Null, Some(caller)) + .await + .err() + .ok_or("unverified acceptance incorrectly authorized execution")?; + assert_eq!( + error.outcome, + crate::runtime::command_executor::DispatchOutcome::Uncertain + ); + let receipt = runtime.shutdown().await; + assert!(matches!(receipt.tasks, DrainOutcome::Unknown { .. })); + assert!(receipt.modules.is_empty()); + assert_eq!(module.saves.load(Ordering::SeqCst), 0); + // The failed acknowledgement and failed read must not erase the committed + // acceptance, authorize a second insert, or publish a false completion. + let count = adapter + .count(crate::orm::query::QueryBuilder::new("kernel_task_facts").build()) + .await; + assert!(count.success); + assert_eq!(count.data, Some(1)); + assert!(matches!( + events.try_recv(), + Err(tokio::sync::broadcast::error::TryRecvError::Empty) + )); + Ok(()) +} + +#[async_trait::async_trait] +impl CommandInterceptor for FailTerminalWrite { + fn name(&self) -> &'static str { + "fail-terminal-write" + } + + async fn try_route( + &self, + _: &str, + _: &serde_json::Value, + _: Option<&crate::routing::CallerIdentity>, + ) -> Result { + // Acceptance has already committed. Fail only the terminal write after + // a successful handler result, outside the handler unwind boundary. + self.0.unwind_next_write(); + Ok(InterceptorOutcome::Handled(CommandResult::Json( + serde_json::Value::Null, + ))) + } +} + +#[tokio::test] +async fn terminal_storage_unwind_neither_announces_completion_nor_allows_shutdown( +) -> Result<(), String> { + let runtime = Arc::new(Runtime::new()); + let (module, _) = RecordingModule::new("terminal-unwind", Vec::new()); + runtime.register(module.clone()); + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let adapter = Arc::new(crate::orm::gated_adapter::GatedAdapter::new(adapter)); + let ledger = Arc::new(crate::runtime::tasks::TaskLedger::new(adapter.clone()).await?); + let mut events = runtime.bus.receiver(); + let executor = Arc::new( + CommandExecutor::new(runtime.registry.clone()) + .with_message_bus(runtime.bus.clone()) + .with_interceptor(Arc::new(FailTerminalWrite(adapter))), + ); + executor.set_task_ledger(ledger.clone())?; + let owner = uuid::Uuid::new_v4(); + let caller = + crate::routing::CallerIdentity::local_persona(crate::identity::PeerId::from_uuid(owner)); + let handle = executor + .dispatch_background("test/result", serde_json::Value::Null, Some(caller)) + .await + .map_err(|error| error.message)?; + tokio::time::timeout( + Duration::from_secs(5), + runtime.registry.task_admission.close_and_wait(), + ) + .await + .map_err(|error| error.to_string())?; + assert_eq!(ledger.pending(handle, owner).await?, None); + assert!(matches!( + events.try_recv(), + Err(tokio::sync::broadcast::error::TryRecvError::Empty) + )); + let receipt = runtime.shutdown().await; + assert!(matches!(receipt.tasks, DrainOutcome::Unknown { .. })); + assert!(receipt.modules.is_empty()); + assert_eq!(module.saves.load(Ordering::SeqCst), 0); + Ok(()) +} diff --git a/core/continuum-kernel/src/runtime/runtime/service_profile.rs b/core/continuum-kernel/src/runtime/runtime/service_profile.rs index bacdaa94a3..f6abede559 100644 --- a/core/continuum-kernel/src/runtime/runtime/service_profile.rs +++ b/core/continuum-kernel/src/runtime/runtime/service_profile.rs @@ -159,6 +159,8 @@ impl ModuleStop { export_to = "../../../protocol/typescript/system/ShutdownReceipt.ts" )] pub struct ShutdownReceipt { + /// Background acceptance and terminal persistence must settle before modules stop. + pub tasks: DrainOutcome, pub modules: Vec, #[ts(type = "number")] pub total_ms: u64, @@ -176,11 +178,17 @@ impl ShutdownReceipt { /// Every module drained, saved, and completed its final shutdown flush. pub fn state_is_durable(&self) -> bool { - self.unsaved().is_empty() + self.tasks.is_quiet() && self.unsaved().is_empty() } /// One line a human can act on, without reading the process's log after it exited. pub fn summary(&self) -> String { + if !self.tasks.is_quiet() { + return format!( + "module shutdown withheld: background task custody {:?}", + self.tasks + ); + } let unsaved = self.unsaved(); if unsaved.is_empty() { return format!( @@ -216,14 +224,14 @@ impl ShutdownReceipt { /// tests drift into testing something adjacent. pub(super) struct ShutdownOperation { pub(super) result: tokio::sync::watch::Sender>, - pub(super) started: std::sync::atomic::AtomicBool, + pub(super) started: Arc>, } impl ShutdownOperation { pub(super) fn new() -> Self { Self { result: tokio::sync::watch::channel(None).0, - started: std::sync::atomic::AtomicBool::new(false), + started: Arc::new(parking_lot::Mutex::new(false)), } } @@ -231,6 +239,8 @@ impl ShutdownOperation { /// result. Idempotent: a second caller — a signal racing the stop verb, a retried /// request — joins the first broadcast rather than running `save_state` twice over /// the same state. + /// A custody refusal stops no modules and permits an explicit new attempt; + /// once module shutdown starts its receipt remains the single retained result. /// /// `settle` is how long the citizens' turns may still finish before the modules drain /// (card 32fa22ba): the turns' measured remaining time, never more than this. ZERO = @@ -241,10 +251,21 @@ impl ShutdownOperation { rt: Option>, settle: std::time::Duration, ) -> tokio::sync::watch::Receiver> { - if !self.started.swap(true, std::sync::atomic::Ordering::AcqRel) { + // Check before spawning: a spawned shutdown owner no longer carries the + // requesting command's execution scope. Refusal must precede turn settle. + if let Some(receipt) = rt.as_ref().and_then(|rt| rt.self_shutdown_refusal()) { + return tokio::sync::watch::channel(Some(receipt)).1; + } + let mut running = self.started.lock(); + if !*running { + *running = true; + // A retry is permitted only after custody withheld every module stop. + // Do not hand its caller the previous attempt's terminal receipt. + self.result.send_replace(None); match rt { Some(rt) => { let tx = self.result.clone(); + let started = Arc::clone(&self.started); // Detached ON PURPOSE: this is the task whose whole point is that no // connection owns it. A socket handler is cancelled when its client // goes away, and a shutdown cancelled after ingress closed leaves the @@ -263,7 +284,15 @@ impl ShutdownOperation { // receipt in precisely the case this design exists for. A later // subscriber would then wait forever on a `None` that never // changes. + // Serialize publication with a new begin: a caller that + // observes the withheld receipt can immediately retry, + // without racing an old publisher over its new attempt. + let mut running = started.lock(); + let withheld = !receipt.tasks.is_quiet(); let _ = tx.send_replace(Some(receipt)); + if withheld { + *running = false; + } }); } None => { @@ -271,6 +300,7 @@ impl ShutdownOperation { // Publishing an empty receipt says exactly that, rather than leaving // every observer waiting on a broadcast that will never run. let _ = self.result.send_replace(Some(ShutdownReceipt { + tasks: DrainOutcome::Drained, modules: Vec::new(), total_ms: 0, })); @@ -298,7 +328,9 @@ pub(super) fn process_shutdown() -> &'static ShutdownOperation { /// /// Delegates to the process's single [`ShutdownOperation`]. See that type for why the /// operation is owned rather than free-standing. -pub fn begin_shutdown(settle: std::time::Duration) -> tokio::sync::watch::Receiver> { +pub fn begin_shutdown( + settle: std::time::Duration, +) -> tokio::sync::watch::Receiver> { process_shutdown().begin(signal_runtime(), settle) } @@ -347,7 +379,7 @@ pub fn signal_runtime() -> Option> { SIGNAL_RUNTIME.get().cloned() } -pub async fn run_signal_shutdown() { +pub async fn run_signal_shutdown() -> Result<(), String> { // Through the SAME idempotent operation the `system/shutdown` verb triggers, so a // signal arriving while the verb is running joins that broadcast instead of starting // a second one over the same state. The bound is deliberately larger than one phase: @@ -357,22 +389,59 @@ pub async fn run_signal_shutdown() { // No settle: a signal's deadline is the supervisor's (launchd's ExitTimeOut, a // console close), not ours to spend waiting on turns. let rx = begin_shutdown(std::time::Duration::ZERO); + await_signal_shutdown(rx).await +} + +async fn await_signal_shutdown( + rx: tokio::sync::watch::Receiver>, +) -> Result<(), String> { match await_shutdown(rx, std::time::Duration::from_secs(8)).await { Some(receipt) => { - // A signal handler cannot return an exit code to anyone, so the receipt's only - // readers are the log and the probe ledger — which is exactly why it is - // written here rather than dropped. `_exit` follows immediately. + // Withheld custody forbids process exit. Keep the signal listener alive + // so a later explicit request can retry the same shutdown owner. + if !receipt.tasks.is_quiet() { + return Err(receipt.summary()); + } if !receipt.state_is_durable() { eprintln!( "[continuum-core] STOPPED WITH UNSAVED STATE: {}", receipt.summary() ); } + Ok(()) } - None => { - eprintln!( - "[continuum-core] shutdown did not finish within 8s — state durability is UNKNOWN" - ); + None => Err("shutdown did not finish within 8s; process exit withheld".into()), + } +} + +#[cfg(test)] +mod signal_custody_tests { + use super::*; + + #[tokio::test(start_paused = true)] + async fn signal_timeout_preserves_owner_and_requires_a_quiet_receipt() { + let (owner, observer) = tokio::sync::watch::channel(None); + assert!(await_signal_shutdown(observer).await.is_err()); + // The timed-out observer must not authorize exit or destroy the retained + // operation. A later signal reads its actual receipt. + for tasks in [ + DrainOutcome::Incomplete { in_flight: 1 }, + DrainOutcome::Unknown { + reason: "terminal persistence failed".into(), + }, + ] { + owner.send_replace(Some(ShutdownReceipt { + tasks, + modules: vec![], + total_ms: 0, + })); + assert!(await_signal_shutdown(owner.subscribe()).await.is_err()); } + owner.send_replace(Some(ShutdownReceipt { + tasks: DrainOutcome::Drained, + modules: vec![], + total_ms: 0, + })); + assert!(await_signal_shutdown(owner.subscribe()).await.is_ok()); } } diff --git a/core/continuum-kernel/src/runtime/runtime/the_receipt_survives_every_observer_going_away.rs b/core/continuum-kernel/src/runtime/runtime/the_receipt_survives_every_observer_going_away.rs index 53cdc67862..103272840d 100644 --- a/core/continuum-kernel/src/runtime/runtime/the_receipt_survives_every_observer_going_away.rs +++ b/core/continuum-kernel/src/runtime/runtime/the_receipt_survives_every_observer_going_away.rs @@ -131,6 +131,7 @@ pub(super) mod conditional_modules_tests { "giving up watching must not end the shutdown" ); let receipt = ShutdownReceipt { + tasks: DrainOutcome::Drained, modules: Vec::new(), total_ms: 3, }; @@ -429,6 +430,7 @@ pub(super) mod conditional_modules_tests { #[test] fn the_summary_names_the_modules_that_did_not_save() { let receipt = ShutdownReceipt { + tasks: DrainOutcome::Drained, modules: vec![ stop("logger", ModuleStopOutcome::Clean), stop("cognition", ModuleStopOutcome::SaveTimedOut), @@ -452,6 +454,7 @@ pub(super) mod conditional_modules_tests { #[test] fn an_empty_receipt_reports_the_count_it_actually_stopped() { let receipt = ShutdownReceipt { + tasks: DrainOutcome::Drained, modules: Vec::new(), total_ms: 0, }; @@ -548,7 +551,6 @@ pub(super) mod conditional_modules_tests { "{err}" ); } - } /// The mesh states the census reads, as the kernel sees them: through `MeshPresence` /// alone (airc's `AircDiscovery` is the real implementor, above the kernel). @@ -567,11 +569,17 @@ pub(super) mod conditional_modules_tests { } fn healthy() -> Mesh { - Mesh { can_host: true, kind: "healthy" } + Mesh { + can_host: true, + kind: "healthy", + } } fn degraded() -> Mesh { - Mesh { can_host: false, kind: "degraded" } + Mesh { + can_host: false, + kind: "degraded", + } } /// FullCitizen + Healthy → must include persona hosting. diff --git a/core/continuum-kernel/src/runtime/stage/runner.rs b/core/continuum-kernel/src/runtime/stage/runner.rs index 68a67a03d5..751269e784 100644 --- a/core/continuum-kernel/src/runtime/stage/runner.rs +++ b/core/continuum-kernel/src/runtime/stage/runner.rs @@ -120,7 +120,7 @@ impl Shared { Ok(outcome) => { self.panics.store(0, Ordering::Release); match outcome { - RunOutcome::Produced(outputs) => self.publish(outputs), + RunOutcome::Produced(outputs) => self.publish(outputs, run, revisions), RunOutcome::Idle => Ran::Idle, RunOutcome::Stopped(receipt) => Ran::Stopped(receipt), RunOutcome::Dispatched => { @@ -140,9 +140,18 @@ impl Shared { } /// Publish each output under the compare-and-set, atomically with making it visible. - fn publish(&self, outputs: Vec<(S::Output, Provenance)>) -> Ran { + fn publish( + &self, + outputs: Vec, + run: RunId, + revisions: &[InputRevision], + ) -> Ran { let (mut accepted, mut refused) = (Vec::new(), 0); - for (output, provenance) in outputs { + for output in outputs { + let provenance = Provenance { + by: run, + from: revisions.to_vec(), + }; self.published.send_if_modified(|state| { let fresh = state.publication.try_publish(&provenance.from) == Published::Accepted; if fresh { diff --git a/core/continuum-kernel/src/runtime/stage/stage.rs b/core/continuum-kernel/src/runtime/stage/stage.rs index 0a50ec936e..72f3576eb4 100644 --- a/core/continuum-kernel/src/runtime/stage/stage.rs +++ b/core/continuum-kernel/src/runtime/stage/stage.rs @@ -5,7 +5,7 @@ use async_trait::async_trait; use super::control::{ControlRequest, StopReceipt}; use super::cost::Cost; use super::identity::{RunId, StageId}; -use super::topic::{InputRevision, Provenance}; +use super::topic::InputRevision; use super::triggers::Triggers; /// What the substrate hands a run: its identity and the control requests it checks at its yield @@ -26,8 +26,9 @@ impl StageContext { /// What one run produced. #[derive(Debug)] pub enum RunOutcome { - /// Outputs to publish under the publication rule, each with its provenance. - Produced(Vec<(O, Provenance)>), + /// Outputs to publish. The runner stamps the actual run and submitted inputs; + /// a stage cannot substitute provenance. + Produced(Vec), /// Work handed to the task owner; its completion re-triggers the stage. Dispatched, /// Nothing to do for these inputs. diff --git a/core/continuum-kernel/src/runtime/stage/tests.rs b/core/continuum-kernel/src/runtime/stage/tests.rs index 3452c3cd01..bbfd1c1e6d 100644 --- a/core/continuum-kernel/src/runtime/stage/tests.rs +++ b/core/continuum-kernel/src/runtime/stage/tests.rs @@ -139,13 +139,7 @@ impl Stage for Counting { } } } - RunOutcome::Produced(vec![( - input.len() as u64, - Provenance { - by: ctx.run, - from: input.to_vec(), - }, - )]) + RunOutcome::Produced(vec![input.len() as u64]) } } @@ -162,13 +156,7 @@ async fn a_stage_honours_control_with_the_receipt_that_proves_it() { let (tx, rx) = tokio::sync::watch::channel(ControlRequest::Continue); let ctx = StageContext { run, control: rx }; match Counting.run(&ctx, &(), &input).await { - RunOutcome::Produced(out) => assert_eq!( - out[0].1, - Provenance { - by: run, - from: input.to_vec() - } - ), + RunOutcome::Produced(out) => assert_eq!(out, vec![1]), other => panic!("left alone it completes: {other:?}"), // test: the assertion failing loudly } tx.send(ControlRequest::Yield) @@ -214,18 +202,12 @@ impl Stage for Echo { } async fn run( &self, - ctx: &StageContext, + _ctx: &StageContext, input: &i64, - revisions: &[InputRevision], + _revisions: &[InputRevision], ) -> RunOutcome { assert!(*input >= 0, "test: a negative input panics the run"); // test: the deliberate panic under test - RunOutcome::Produced(vec![( - *input, - Provenance { - by: ctx.run, - from: revisions.to_vec(), - }, - )]) + RunOutcome::Produced(vec![*input]) } } @@ -300,7 +282,19 @@ async fn an_inline_run_publishes_under_the_same_rule() { refused: 0 } ); - assert_eq!(runner.latest().map(|o| o.output), Some(4)); + let inline_output = runner.latest().expect("test: inline output was published"); + assert_eq!(inline_output.output, 4); + assert_eq!( + inline_output.provenance, + Provenance { + by: RunId { + incarnation: incarnation(1), + seq: 1 + }, + from: vec![rev("numbers", 4)], + }, + "the runner stamps its own run and inputs even when the stage ignores them" + ); assert_eq!( runner.run_inline(&2, &[rev("numbers", 2)]).await, Ran::Produced { diff --git a/core/continuum-kernel/src/runtime/tasks.rs b/core/continuum-kernel/src/runtime/tasks.rs new file mode 100644 index 0000000000..357a928547 --- /dev/null +++ b/core/continuum-kernel/src/runtime/tasks.rs @@ -0,0 +1,734 @@ +//! Durable task facts. Acceptance precedes execution; the first terminal insert wins. +//! A terminal fact is also the outbox: it remains pending until its owner acknowledges it. +//! Execution supervision and the owner sink are separate from this persistence contract. + +use crate::orm::query::{QueryBuilder, QueryOperator}; +use crate::orm::types::{CollectionSchema, FieldType, SchemaField}; +use crate::orm::{adapter::StorageAdapter, entity::OrmEntity, store::OrmStore}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::num::NonZeroUsize; +use std::sync::Arc; +use uuid::Uuid; + +mod output; +pub use output::TaskOutput; +mod execution; +pub use execution::{FinishError, TaskExecution}; +mod delivery; +pub use delivery::{DeliveryError, DeliveryPage, TaskOwnerSink}; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub enum TaskEnd { + Done(TaskOutput), + Failed { + message: String, + outcome: super::command_executor::DispatchOutcome, + }, + TimedOut, + Stopped, + Lost, +} + +/// The terminal fact without its ledger-owned output. Consumers may project this +/// status but must not equate it with having read the result body. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum TaskEndState { + Done, + Failed, + TimedOut, + Stopped, + Lost, +} + +impl TaskEnd { + pub fn state(&self) -> TaskEndState { + match self { + Self::Done(_) => TaskEndState::Done, + Self::Failed { .. } => TaskEndState::Failed, + Self::TimedOut => TaskEndState::TimedOut, + Self::Stopped => TaskEndState::Stopped, + Self::Lost => TaskEndState::Lost, + } + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +enum Fact { + Accepted { + command: String, + execution: TaskExecution, + }, + Ended(TaskEnd), + Delivered, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +struct TaskFact { + task: Uuid, + owner: Uuid, + fact: Fact, +} + +impl OrmEntity for TaskFact { + const COLLECTION: &'static str = "kernel_task_facts"; + + fn collection_schema() -> CollectionSchema { + let mut fields = crate::orm::entity::base_entity_fields(); + for (name, field_type) in [ + ("task", FieldType::Uuid), + ("owner", FieldType::Uuid), + ("fact", FieldType::Json), + ] { + fields.push(SchemaField { + name: name.into(), + field_type, + indexed: false, + unique: false, + nullable: false, + max_length: None, + foreign_key: None, + }); + } + CollectionSchema { + collection: Self::COLLECTION.into(), + fields, + indexes: vec![], + } + } +} + +/// One ledger may be reopened or shared by multiple supervisors. INSERT, rather than a +/// process-local lock or equal-version monotonic upsert, arbitrates terminal races. +pub struct TaskLedger { + facts: OrmStore, +} + +/// A bounded reconciliation page. Advance even when `ends` is empty: acknowledged +/// rows still consume scan space. A new reconciliation starts with no cursor. +pub struct PendingPage { + pub ends: Vec<(Uuid, TaskEnd)>, + pub after: Option, + pub exhausted: bool, +} + +impl TaskLedger { + pub async fn new(adapter: Arc) -> Result { + Ok(Self { + facts: OrmStore::new(adapter).await.map_err(|e| e.to_string())?, + }) + } + + pub async fn accept( + &self, + owner: Uuid, + command: String, + execution: TaskExecution, + ) -> Result { + let task = Uuid::new_v4(); + let acceptance = TaskFact { + task, + owner, + fact: Fact::Accepted { command, execution }, + }; + match self.facts.save(task, &acceptance).await { + Ok(()) => Ok(task), + Err(write_error) => { + // A failed acknowledgement does not prove the write failed. + // Resolve this exact attempted acceptance, without a second + // insert or execution owner. Only an identical durable fact + // authorizes execution; absence or read failure stays uncertain. + match self.facts.find_by_id(task).await { + Ok(Some(stored)) if stored == acceptance => Ok(task), + Ok(_) => Err(write_error.to_string()), + Err(read_error) => Err(format!( + "acceptance write failed: {write_error}; readback failed: {read_error}" + )), + } + } + } + } + + /// Recover the exact execution owner without guessing from a forgotten handle + /// or a process snapshot. Only the recipient may inspect this registration. + pub async fn execution(&self, task: Uuid, owner: Uuid) -> Result { + match self + .facts + .find_by_id(task) + .await + .map_err(|e| FinishError::Persistence(e.to_string()))? + { + Some(TaskFact { + task: stored_task, + owner: stored, + fact: Fact::Accepted { execution, .. }, + }) if stored == owner && stored_task == task => Ok(execution), + _ => Err(FinishError::Authorization( + "task is absent or belongs to another owner".into(), + )), + } + } + + async fn authorize(&self, task: Uuid, owner: Uuid) -> Result<(), String> { + self.execution(task, owner) + .await + .map(|_| ()) + .map_err(String::from) + } + + /// Only a supervisor that has observed execution ending calls this. A cancellation + /// request alone is not an end. Competing endings return the durable winner. + pub async fn finish( + &self, + task: Uuid, + owner: Uuid, + execution: TaskExecution, + end: TaskEnd, + ) -> Result { + let accepted = self.execution(task, owner).await?; + if accepted != execution { + return Err(FinishError::ExecutionMismatch { + task, + accepted, + offered: execution, + }); + } + let id = Uuid::new_v5(&task, b"terminal"); + let row = TaskFact { + task, + owner, + fact: Fact::Ended(end.clone()), + }; + match self.facts.save(id, &row).await { + Ok(()) => Ok(end), + Err(write_error) => match self + .facts + .find_by_id(id) + .await + .map_err(|e| FinishError::Persistence(e.to_string()))? + { + Some(TaskFact { + task: stored_task, + owner: stored_owner, + fact: Fact::Ended(winner), + }) if stored_task == task && stored_owner == owner => Ok(winner), + // Never reinterpret an arbitrary store failure as a successful completion. + _ => Err(FinishError::Persistence(write_error.to_string())), + }, + } + } + + pub async fn pending(&self, task: Uuid, owner: Uuid) -> Result, String> { + self.authorize(task, owner).await?; + let delivered = self + .facts + .find_by_id(Uuid::new_v5(&task, b"delivered")) + .await + .map_err(|e| e.to_string())?; + match delivered { + Some(TaskFact { + task: stored_task, + owner: stored_owner, + fact: Fact::Delivered, + }) if stored_task == task && stored_owner == owner => return Ok(None), + Some(_) => return Err("task delivery fact has an invalid identity or shape".into()), + None => {} + } + self.read_terminal(task, owner).await + } + + /// Resolve the durable terminal even after delivery acknowledgement. Resident + /// checkpoints carry references; the ledger remains the one output owner. + pub async fn terminal(&self, task: Uuid, owner: Uuid) -> Result, String> { + self.authorize(task, owner).await?; + self.read_terminal(task, owner).await + } + + async fn read_terminal(&self, task: Uuid, owner: Uuid) -> Result, String> { + match self + .facts + .find_by_id(Uuid::new_v5(&task, b"terminal")) + .await + .map_err(|e| e.to_string())? + { + Some(TaskFact { + task: stored_task, + owner: stored_owner, + fact: Fact::Ended(end), + }) if stored_task == task && stored_owner == owner => Ok(Some(end)), + None => Ok(None), + _ => Err("task terminal fact has an invalid identity or shape".into()), + } + } + + /// Called only after the sink durably consumes the terminal fact. A repeated delivery + /// uses the same task id; the sink must deduplicate before acknowledging here. + pub async fn acknowledge(&self, task: Uuid, owner: Uuid) -> Result<(), String> { + self.authorize(task, owner).await?; + let terminal = self + .facts + .find_by_id(Uuid::new_v5(&task, b"terminal")) + .await + .map_err(|e| e.to_string())?; + if !matches!( + terminal, + Some(TaskFact { + task: stored_task, owner: stored_owner, fact: Fact::Ended(_), + }) if stored_task == task && stored_owner == owner + ) { + return Err("cannot acknowledge a task without a terminal fact".into()); + } + let id = Uuid::new_v5(&task, b"delivered"); + let row = TaskFact { + task, + owner, + fact: Fact::Delivered, + }; + match self.facts.save(id, &row).await { + Ok(()) => Ok(()), + Err(error) => match self.facts.find_by_id(id).await.map_err(|e| e.to_string())? { + Some(stored) if stored == row => Ok(()), + _ => Err(error.to_string()), + }, + } + } + + /// Reconstruct delivery from durable ownership, never from remembered handles. + /// This scan is not a live subscription: concurrent inserts are picked up by the + /// next sweep. Notification triggers and boot recovery both start a fresh sweep. + pub async fn pending_page( + &self, + owner: Uuid, + after: Option, + limit: NonZeroUsize, + ) -> Result { + let mut query = QueryBuilder::new(TaskFact::COLLECTION) + .filter_eq("owner", owner.to_string()) + .sort_asc("id") + .limit(limit.get()); + if let Some(cursor) = after { + query = query.filter("id", QueryOperator::Gt(Value::String(cursor.to_string()))); + } + let rows = self + .facts + .find_matching(query.build()) + .await + .map_err(|e| e.to_string())?; + let exhausted = rows.len() < limit.get(); + let next = rows.last().map(|(id, _)| *id); + let mut ends = Vec::new(); + for (id, row) in rows { + if row.owner != owner { + return Err("task owner query returned another owner".into()); + } + if matches!(row.fact, Fact::Accepted { .. }) { + if id != row.task { + return Err("task acceptance has an invalid identity".into()); + } + if let Some(end) = self.pending(row.task, owner).await? { + ends.push((row.task, end)); + } + } + } + Ok(PendingPage { + ends, + after: next, + exhausted, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn accepted_execution_survives_reopen_and_is_not_replaced_by_new_executor( + ) -> Result<(), String> { + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let ledger = TaskLedger::new(adapter.clone()).await?; + let owner = Uuid::new_v4(); + let execution = TaskExecution::new_command_executor(); + let task = ledger.accept(owner, "code/shell".into(), execution).await?; + drop(ledger); + let replacement = TaskExecution::new_command_executor(); + assert_ne!(execution, replacement); + let reopened = TaskLedger::new(adapter).await?; + assert_eq!(reopened.execution(task, owner).await?, execution); + assert!(reopened.execution(task, Uuid::new_v4()).await.is_err()); + assert_eq!(reopened.pending(task, owner).await?, None); + // An old incarnation is unresolved, not automatically Lost at reopen. + assert_eq!(reopened.terminal(task, owner).await?, None); + assert_eq!( + reopened + .finish(task, owner, replacement, TaskEnd::Lost) + .await, + Err(FinishError::ExecutionMismatch { + task, + accepted: execution, + offered: replacement + }) + ); + assert_eq!(reopened.terminal(task, owner).await?, None); + // Late evidence from the accepted incarnation remains valid after reopen. + assert_eq!( + reopened + .finish(task, owner, execution, TaskEnd::Stopped) + .await?, + TaskEnd::Stopped + ); + // Even after a terminal exists, a replacement cannot claim its completion. + assert_eq!( + reopened + .finish(task, owner, replacement, TaskEnd::Lost) + .await, + Err(FinishError::ExecutionMismatch { + task, + accepted: execution, + offered: replacement + }) + ); + assert_eq!( + reopened.terminal(task, owner).await?, + Some(TaskEnd::Stopped) + ); + Ok(()) + } + + #[tokio::test] + async fn concurrent_ends_survive_reopen_and_delivery_retry() -> Result<(), String> { + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let first = TaskLedger::new(adapter.clone()).await?; + let second = TaskLedger::new(adapter.clone()).await?; + let owner = Uuid::new_v4(); + let task = first + .accept( + owner, + "code/shell".into(), + TaskExecution::new_command_executor(), + ) + .await?; + assert!(first.acknowledge(task, owner).await.is_err()); + let (a, b) = tokio::join!( + first.finish( + task, + owner, + first.execution(task, owner).await?, + TaskEnd::Done(TaskOutput::Json(Value::Null)) + ), + second.finish( + task, + owner, + second.execution(task, owner).await?, + TaskEnd::Stopped + ), + ); + let winner = a?; + assert_eq!(winner, b?); + drop(first); + drop(second); + let reopened = TaskLedger::new(adapter).await?; + assert_eq!(reopened.pending(task, owner).await?, Some(winner.clone())); + let page = reopened + .pending_page(owner, None, NonZeroUsize::new(10).ok_or("test page size")?) + .await?; + assert_eq!(page.ends, vec![(task, winner.clone())]); + assert_eq!( + reopened + .finish( + task, + owner, + reopened.execution(task, owner).await?, + TaskEnd::Lost + ) + .await?, + winner + ); + assert!(reopened.pending(task, Uuid::new_v4()).await.is_err()); + reopened.acknowledge(task, owner).await?; + reopened.acknowledge(task, owner).await?; + assert_eq!(reopened.pending(task, owner).await?, None); + Ok(()) + } + + #[tokio::test] + async fn corrupt_delivery_cannot_hide_an_unconsumed_end() -> Result<(), String> { + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let ledger = TaskLedger::new(adapter).await?; + let owner = Uuid::new_v4(); + let task = ledger + .accept( + owner, + "code/shell".into(), + TaskExecution::new_command_executor(), + ) + .await?; + ledger + .finish( + task, + owner, + ledger.execution(task, owner).await?, + TaskEnd::Stopped, + ) + .await?; + ledger + .facts + .save( + Uuid::new_v5(&task, b"delivered"), + &TaskFact { + task, + owner: Uuid::new_v4(), + fact: Fact::Delivered, + }, + ) + .await + .map_err(|e| e.to_string())?; + assert!(ledger.pending(task, owner).await.is_err()); + assert!(ledger.acknowledge(task, owner).await.is_err()); + Ok(()) + } + + #[tokio::test] + async fn replay_pages_cross_empty_pages_without_leaking_other_owners() -> Result<(), String> { + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let ledger = TaskLedger::new(adapter).await?; + let owner = Uuid::new_v4(); + let foreign = Uuid::new_v4(); + let consumed = ledger + .accept( + owner, + "consumed".into(), + TaskExecution::new_command_executor(), + ) + .await?; + ledger + .finish( + consumed, + owner, + ledger.execution(consumed, owner).await?, + TaskEnd::Stopped, + ) + .await?; + ledger.acknowledge(consumed, owner).await?; + let pending = ledger + .accept( + owner, + "pending".into(), + TaskExecution::new_command_executor(), + ) + .await?; + ledger + .finish( + pending, + owner, + ledger.execution(pending, owner).await?, + TaskEnd::Done(TaskOutput::Json(Value::Null)), + ) + .await?; + let other = ledger + .accept( + foreign, + "other".into(), + TaskExecution::new_command_executor(), + ) + .await?; + ledger + .finish( + other, + foreign, + ledger.execution(other, foreign).await?, + TaskEnd::Stopped, + ) + .await?; + let mut after = None; + let mut found = Vec::new(); + let mut exhausted = false; + // Five facts for this owner, plus the empty last page. This bound also + // catches a cursor that fails to advance on an empty-result page. + for _ in 0..7 { + let page = ledger.pending_page(owner, after, NonZeroUsize::MIN).await?; + found.extend(page.ends); + if page.exhausted { + exhausted = true; + break; + } + assert_ne!(page.after, after); + after = page.after; + } + assert!(exhausted); + assert_eq!( + found, + vec![(pending, TaskEnd::Done(TaskOutput::Json(Value::Null)))] + ); + Ok(()) + } + use crate::orm::gated_adapter::GatedAdapter; + + #[tokio::test] + async fn unreadable_acceptance_is_not_an_authorization_refusal() -> Result<(), String> { + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let gated = Arc::new(GatedAdapter::new(adapter)); + let ledger = TaskLedger::new(gated.clone()).await?; + let owner = Uuid::new_v4(); + let execution = TaskExecution::new_command_executor(); + let task = ledger.accept(owner, "code/shell".into(), execution).await?; + gated.fail_next_query(); + assert!(matches!( + ledger + .finish(task, owner, execution, TaskEnd::Stopped) + .await, + Err(FinishError::Persistence(_)) + )); + assert_eq!(ledger.terminal(task, owner).await?, None); + assert!(matches!( + ledger + .finish(task, Uuid::new_v4(), execution, TaskEnd::Stopped) + .await, + Err(FinishError::Authorization(_)) + )); + assert_eq!( + ledger + .finish(task, owner, execution, TaskEnd::Stopped) + .await?, + TaskEnd::Stopped + ); + Ok(()) + } + + #[tokio::test] + async fn lost_terminal_and_delivery_replies_survive_reopen_without_duplicate_facts( + ) -> Result<(), String> { + use crate::orm::adapter::StorageAdapter; + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let adapter = Arc::new(GatedAdapter::new(adapter)); + let ledger = TaskLedger::new(adapter.clone()).await?; + let owner = Uuid::new_v4(); + let task = ledger + .accept( + owner, + "test/reply-loss".into(), + TaskExecution::new_command_executor(), + ) + .await?; + adapter.fail_after_next_create(); + assert_eq!( + ledger + .finish( + task, + owner, + ledger.execution(task, owner).await?, + TaskEnd::Stopped + ) + .await?, + TaskEnd::Stopped + ); + drop(ledger); + let reopened = TaskLedger::new(adapter.clone()).await?; + assert_eq!(reopened.pending(task, owner).await?, Some(TaskEnd::Stopped)); + adapter.fail_after_next_create(); + reopened.acknowledge(task, owner).await?; + drop(reopened); + let reopened = TaskLedger::new(adapter.clone()).await?; + assert_eq!(reopened.pending(task, owner).await?, None); + assert_eq!( + reopened + .finish( + task, + owner, + reopened.execution(task, owner).await?, + TaskEnd::Lost + ) + .await?, + TaskEnd::Stopped + ); + reopened.acknowledge(task, owner).await?; + assert_eq!(reopened.pending(task, owner).await?, None); + let count = adapter + .count(QueryBuilder::new(TaskFact::COLLECTION).build()) + .await; + assert!(count.success); + assert_eq!( + count.data, + Some(3), + "one acceptance, one end, one delivery fact" + ); + Ok(()) + } + + async fn notified(signal: &tokio::sync::Notify) -> Result<(), String> { + tokio::time::timeout(std::time::Duration::from_secs(5), signal.notified()) + .await + .map_err(|error| error.to_string()) + } + + #[tokio::test] + async fn cancelled_terminal_write_cannot_replace_winner_or_resurrect_delivery( + ) -> Result<(), String> { + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let gated = Arc::new(GatedAdapter::new(adapter.clone())); + let delayed = Arc::new(TaskLedger::new(gated.clone()).await?); + let current = TaskLedger::new(adapter.clone()).await?; + let owner = Uuid::new_v4(); + let task = current + .accept( + owner, + "code/shell".into(), + TaskExecution::new_command_executor(), + ) + .await?; + let pause = gated.pause_next_write(); + let writer = tokio::spawn(async move { + delayed + .finish( + task, + owner, + delayed.execution(task, owner).await?, + TaskEnd::Lost, + ) + .await + }); + notified(&pause.entered).await?; + writer.abort(); + assert!(matches!(writer.await, Err(error) if error.is_cancelled())); + + // The competing supervisor observed the actual execution ending. Its result + // reaches the sink while the abandoned storage operation is still pending. + let winner = TaskEnd::Done(TaskOutput::Json(serde_json::json!({"saved": true}))); + assert_eq!( + current + .finish( + task, + owner, + current.execution(task, owner).await?, + winner.clone() + ) + .await?, + winner + ); + assert_eq!(current.pending(task, owner).await?, Some(winner.clone())); + current.acknowledge(task, owner).await?; + pause.release.notify_one(); + notified(&pause.done).await?; + drop(current); + + let reopened = TaskLedger::new(adapter).await?; + assert_eq!( + reopened + .finish( + task, + owner, + reopened.execution(task, owner).await?, + TaskEnd::Lost + ) + .await?, + winner + ); + assert_eq!(reopened.pending(task, owner).await?, None); + assert!(reopened + .pending_page(owner, None, NonZeroUsize::new(10).ok_or("test page size")?) + .await? + .ends + .is_empty()); + Ok(()) + } +} diff --git a/core/continuum-kernel/src/runtime/tasks/delivery.rs b/core/continuum-kernel/src/runtime/tasks/delivery.rs new file mode 100644 index 0000000000..79d04c0c78 --- /dev/null +++ b/core/continuum-kernel/src/runtime/tasks/delivery.rs @@ -0,0 +1,104 @@ +//! The shared owner-delivery seam from HER-TASKS T2. Notifications only request a +//! reconciliation; durable ownership supplies the results and consumption precedes ACK. +use super::{TaskEnd, TaskLedger}; +use std::collections::BTreeSet; +use std::num::NonZeroUsize; +use uuid::Uuid; + +/// Implemented by the owner of the recipient's durable state, never by a transient +/// workspace or a notification channel. Success means the exact terminal result and +/// its outstanding wake obligation are durable. Returned IDs attest checkpointed +/// perception, not filing, and must belong to this page. Replays deduplicate by ID. +/// Consume the owner page in one commit; per-result checkpoints amplify storage work. +#[async_trait::async_trait] +pub trait TaskOwnerSink: Send + Sync { + type Error: std::error::Error + Send + Sync + 'static; + + async fn consume(&self, owner: Uuid, ends: &[(Uuid, TaskEnd)]) -> Result, Self::Error>; +} + +/// Failure retains its boundary: a sink refusal cannot masquerade as an ACK failure, +/// and a failed ACK can be replayed after consumption without repeating its effects. +#[derive(Debug)] +pub enum DeliveryError { + Read(String), + Consume { owner: Uuid, source: E }, + InvalidReceipt { task: Uuid }, + Acknowledge { task: Uuid, message: String }, +} + +impl std::fmt::Display for DeliveryError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Read(message) => write!(f, "task replay read failed: {message}"), + Self::Consume { owner, source } => { + write!(f, "owner {owner} consumption failed: {source}") + } + Self::Acknowledge { task, message } => { + write!(f, "task {task} acknowledgement failed: {message}") + } + Self::InvalidReceipt { task } => write!(f, "perception receipt for task {task} is outside the delivered page"), + } + } +} + +impl std::error::Error for DeliveryError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Consume { source, .. } => Some(source), + Self::Read(_) | Self::Acknowledge { .. } | Self::InvalidReceipt { .. } => None, + } + } +} + +pub struct DeliveryPage { + pub acknowledged: usize, + pub after: Option, + pub exhausted: bool, +} + +impl TaskLedger { + /// Deliver one bounded storage page. The existing lifecycle/scheduler owns when to + /// continue or restart a sweep; this seam creates no timer, listener or executor. + /// On failure restart the sweep: previously acknowledged tasks are excluded, while + /// an unacknowledged consumption is replayed into the sink's durable deduplication. + pub async fn deliver_page( + &self, + owner: Uuid, + after: Option, + limit: NonZeroUsize, + sink: &S, + ) -> Result> { + let page = self + .pending_page(owner, after, limit) + .await + .map_err(DeliveryError::Read)?; + let perceived = if page.ends.is_empty() { + BTreeSet::new() + } else { + sink.consume(owner, &page.ends) + .await + .map_err(|source| DeliveryError::Consume { owner, source })? + }; + let offered: BTreeSet<_> = page.ends.iter().map(|(task, _)| *task).collect(); + // Validate the entire receipt before acknowledging any row. + if let Some(task) = perceived.difference(&offered).next() { + return Err(DeliveryError::InvalidReceipt { task: *task }); + } + let mut acknowledged = 0; + for task in perceived { + self.acknowledge(task, owner) + .await + .map_err(|message| DeliveryError::Acknowledge { task, message })?; + acknowledged += 1; + } + Ok(DeliveryPage { + acknowledged, + after: page.after, + exhausted: page.exhausted, + }) + } +} + +#[cfg(test)] +mod tests; diff --git a/core/continuum-kernel/src/runtime/tasks/delivery/tests.rs b/core/continuum-kernel/src/runtime/tasks/delivery/tests.rs new file mode 100644 index 0000000000..d7b4197fbc --- /dev/null +++ b/core/continuum-kernel/src/runtime/tasks/delivery/tests.rs @@ -0,0 +1,287 @@ +//! The delivery boundary cannot acknowledge an unconsumed terminal result. +#![cfg(test)] +use super::*; +use crate::runtime::tasks::TaskExecution; +use std::sync::{ + atomic::{AtomicBool, AtomicUsize, Ordering}, + Arc, +}; + +struct PerceptionSink(parking_lot::Mutex>); + +#[async_trait::async_trait] +impl TaskOwnerSink for PerceptionSink { + type Error = std::io::Error; + + async fn consume(&self, _: Uuid, _: &[(Uuid, TaskEnd)]) -> Result, Self::Error> { + Ok(self.0.lock().clone()) + } +} + +#[tokio::test] +async fn only_page_scoped_perception_can_ack_and_invalid_batch_has_no_partial_effects( +) -> Result<(), Box> { + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let ledger = TaskLedger::new(adapter).await?; + let owner = Uuid::new_v4(); + let first = ledger + .accept(owner, "first".into(), TaskExecution::new_command_executor()) + .await?; + let second = ledger + .accept( + owner, + "second".into(), + TaskExecution::new_command_executor(), + ) + .await?; + ledger + .finish( + first, + owner, + ledger.execution(first, owner).await?, + TaskEnd::Stopped, + ) + .await?; + ledger + .finish( + second, + owner, + ledger.execution(second, owner).await?, + TaskEnd::Lost, + ) + .await?; + let sink = PerceptionSink(Default::default()); + let limit = NonZeroUsize::new(32).ok_or("invalid fixture page")?; + assert_eq!( + ledger + .deliver_page(owner, None, limit, &sink) + .await? + .acknowledged, + 0 + ); + let foreign = Uuid::new_v4(); + sink.0.lock().extend([first, foreign]); + assert!( + matches!(ledger.deliver_page(owner, None, limit, &sink).await, + Err(DeliveryError::InvalidReceipt { task }) if task == foreign) + ); + assert_eq!(ledger.pending(first, owner).await?, Some(TaskEnd::Stopped)); + sink.0.lock().remove(&foreign); + assert_eq!( + ledger + .deliver_page(owner, None, limit, &sink) + .await? + .acknowledged, + 1 + ); + assert_eq!(ledger.pending(first, owner).await?, None); + assert_eq!(ledger.pending(second, owner).await?, Some(TaskEnd::Lost)); + Ok(()) +} + +struct Sink { + ledger: Arc, + refuse: AtomicBool, + commits: AtomicUsize, + seen: parking_lot::Mutex>, +} + +#[async_trait::async_trait] +impl TaskOwnerSink for Sink { + type Error = std::io::Error; + + async fn consume( + &self, + owner: Uuid, + ends: &[(Uuid, TaskEnd)], + ) -> Result, Self::Error> { + for (task, end) in ends { + let pending = self + .ledger + .pending(*task, owner) + .await + .map_err(std::io::Error::other)?; + assert_eq!(pending.as_ref(), Some(end), "consumption must precede ACK"); + } + if self.refuse.load(Ordering::SeqCst) { + return Err(std::io::Error::other("injected persistence refusal")); + } + self.commits.fetch_add(1, Ordering::SeqCst); + self.seen + .lock() + .extend(ends.iter().map(|(task, end)| (owner, *task, end.clone()))); + Ok(ends.iter().map(|(task, _)| *task).collect()) + } +} + +#[tokio::test] +async fn refused_consumption_remains_pending_and_replay_needs_no_registered_handle( +) -> Result<(), Box> { + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let ledger = Arc::new(TaskLedger::new(adapter.clone()).await?); + let owner = Uuid::new_v4(); + let task = ledger + .accept(owner, "build".into(), TaskExecution::new_command_executor()) + .await?; + ledger + .finish( + task, + owner, + ledger.execution(task, owner).await?, + TaskEnd::Stopped, + ) + .await?; + let sink = Sink { + ledger: ledger.clone(), + refuse: AtomicBool::new(true), + seen: Default::default(), + commits: AtomicUsize::new(0), + }; + let limit = NonZeroUsize::new(32).expect("test: nonzero page"); + assert!( + matches!(ledger.deliver_page(owner, None, limit, &sink).await, Err(DeliveryError::Consume { owner: failed, .. }) if failed == owner) + ); + assert_eq!(ledger.pending(task, owner).await?, Some(TaskEnd::Stopped)); + assert!(sink.seen.lock().is_empty()); + + let reopened = TaskLedger::new(adapter).await?; + sink.refuse.store(false, Ordering::SeqCst); + assert_eq!( + reopened + .deliver_page(owner, None, limit, &sink) + .await? + .acknowledged, + 1 + ); + assert_eq!(*sink.seen.lock(), vec![(owner, task, TaskEnd::Stopped)]); + assert_eq!( + reopened + .deliver_page(owner, None, limit, &sink) + .await? + .acknowledged, + 0 + ); + assert_eq!(sink.seen.lock().len(), 1); + Ok(()) +} + +#[tokio::test] +async fn page_delivery_keeps_owner_isolation_and_crosses_empty_pages( +) -> Result<(), Box> { + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let ledger = Arc::new(TaskLedger::new(adapter).await?); + let owner = Uuid::new_v4(); + let foreign = Uuid::new_v4(); + let mine = ledger + .accept(owner, "mine".into(), TaskExecution::new_command_executor()) + .await?; + let theirs = ledger + .accept( + foreign, + "theirs".into(), + TaskExecution::new_command_executor(), + ) + .await?; + ledger + .finish( + mine, + owner, + ledger.execution(mine, owner).await?, + TaskEnd::Lost, + ) + .await?; + ledger + .finish( + theirs, + foreign, + ledger.execution(theirs, foreign).await?, + TaskEnd::Stopped, + ) + .await?; + let sink = Sink { + ledger: ledger.clone(), + refuse: AtomicBool::new(false), + seen: Default::default(), + commits: AtomicUsize::new(0), + }; + let mut after = None; + let mut exhausted = false; + // Acceptance, terminal and optional ACK rows plus a final empty page. + for _ in 0..4 { + let page = ledger + .deliver_page( + owner, + after, + NonZeroUsize::new(1).expect("test: nonzero"), + &sink, + ) + .await?; + if page.exhausted { + exhausted = true; + break; + } + assert_ne!(page.after, after); + after = page.after; + } + assert!(exhausted); + assert_eq!(*sink.seen.lock(), vec![(owner, mine, TaskEnd::Lost)]); + assert_eq!( + ledger.pending(theirs, foreign).await?, + Some(TaskEnd::Stopped) + ); + Ok(()) +} + +#[tokio::test] +async fn one_owner_page_is_consumed_once_before_its_acknowledgements( +) -> Result<(), Box> { + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let ledger = Arc::new(TaskLedger::new(adapter).await?); + let owner = Uuid::new_v4(); + let first = ledger + .accept(owner, "first".into(), TaskExecution::new_command_executor()) + .await?; + let second = ledger + .accept( + owner, + "second".into(), + TaskExecution::new_command_executor(), + ) + .await?; + ledger + .finish( + first, + owner, + ledger.execution(first, owner).await?, + TaskEnd::Stopped, + ) + .await?; + ledger + .finish( + second, + owner, + ledger.execution(second, owner).await?, + TaskEnd::Lost, + ) + .await?; + let sink = Sink { + ledger: ledger.clone(), + refuse: AtomicBool::new(false), + commits: AtomicUsize::new(0), + seen: Default::default(), + }; + let page = ledger + .deliver_page( + owner, + None, + NonZeroUsize::new(32).ok_or("invalid test page")?, + &sink, + ) + .await?; + assert_eq!(page.acknowledged, 2); + assert_eq!(sink.commits.load(Ordering::SeqCst), 1); + assert_eq!(sink.seen.lock().len(), 2); + assert_eq!(ledger.pending(first, owner).await?, None); + assert_eq!(ledger.pending(second, owner).await?, None); + Ok(()) +} diff --git a/core/continuum-kernel/src/runtime/tasks/execution.rs b/core/continuum-kernel/src/runtime/tasks/execution.rs new file mode 100644 index 0000000000..aec960e0c1 --- /dev/null +++ b/core/continuum-kernel/src/runtime/tasks/execution.rs @@ -0,0 +1,44 @@ +//! Durable identity of the execution owner, distinct from the result recipient. +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +/// A command executor instance owns its in-process dispatch until quiescence. +/// This is not a PID: a replacement executor gets a new incarnation even in the +/// same process. Absence from a process snapshot does not prove this owner ended. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum TaskExecution { + CommandExecutor { incarnation: Uuid }, +} + +impl TaskExecution { + pub fn new_command_executor() -> Self { + Self::CommandExecutor { + incarnation: Uuid::new_v4(), + } + } +} + +/// A refused terminal publication, distinct from a completed task's outcome. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum FinishError { + #[error("task completion authorization failed: {0}")] + Authorization(String), + #[error( + "task {task} completion execution mismatch: accepted {accepted:?}, offered {offered:?}" + )] + ExecutionMismatch { + task: Uuid, + accepted: TaskExecution, + offered: TaskExecution, + }, + #[error("task terminal persistence failed: {0}")] + Persistence(String), +} + +// Command/test boundaries that expose textual errors can render the typed refusal; +// reconciliation inside the task owner matches FinishError directly. +impl From for String { + fn from(error: FinishError) -> Self { + error.to_string() + } +} diff --git a/core/continuum-kernel/src/runtime/tasks/output.rs b/core/continuum-kernel/src/runtime/tasks/output.rs new file mode 100644 index 0000000000..066d31f3bb --- /dev/null +++ b/core/continuum-kernel/src/runtime/tasks/output.rs @@ -0,0 +1,108 @@ +//! Lossless durable command results. This is storage, not prompt material: consumers +//! budget a reference to the result rather than copying binary bytes into context. + +use crate::runtime::{cell_shapes::HandleRef, CommandResult}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "shape", content = "payload", rename_all = "snake_case")] +pub enum TaskOutput { + Json(Value), + Binary { metadata: Value, data: Vec }, + Handle(HandleRef), +} + +impl TryFrom for TaskOutput { + type Error = String; + + fn try_from(result: CommandResult) -> Result { + match result { + CommandResult::Json(value) => Ok(Self::Json(value)), + CommandResult::Binary { metadata, data } => Ok(Self::Binary { metadata, data }), + CommandResult::Handle(handle) => Ok(Self::Handle(handle)), + CommandResult::Stream(_) => Err(CommandResult::stream_protocol_error()), + CommandResult::Lambda(_) => Err(CommandResult::lambda_protocol_error()), + } + } +} + +impl From for CommandResult { + fn from(output: TaskOutput) -> Self { + match output { + TaskOutput::Json(value) => Self::Json(value), + TaskOutput::Binary { metadata, data } => Self::Binary { metadata, data }, + TaskOutput::Handle(handle) => Self::Handle(handle), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::runtime::tasks::{TaskEnd, TaskExecution, TaskLedger}; + use uuid::Uuid; + + #[tokio::test] + async fn binary_and_handle_survive_ledger_reopen() -> Result<(), String> { + let (adapter, _directory) = crate::orm::store::fresh_adapter().await; + let ledger = TaskLedger::new(adapter.clone()).await?; + let owner = Uuid::new_v4(); + let bytes: Vec = (0..=255).collect(); + let binary = TaskOutput::try_from(CommandResult::Binary { + metadata: serde_json::json!({"format": "arbitrary-bytes"}), + data: bytes.clone(), + })?; + assert!(matches!(&binary, TaskOutput::Binary { data, .. } if data == &bytes)); + let handle = TaskOutput::try_from(CommandResult::handle( + "producer", + Uuid::new_v4(), + "producer::Result", + ))?; + assert!(matches!(&handle, TaskOutput::Handle(_))); + let binary_task = ledger + .accept( + owner, + "producer/binary".into(), + TaskExecution::new_command_executor(), + ) + .await?; + let handle_task = ledger + .accept( + owner, + "producer/handle".into(), + TaskExecution::new_command_executor(), + ) + .await?; + ledger + .finish( + binary_task, + owner, + ledger.execution(binary_task, owner).await?, + TaskEnd::Done(binary.clone()), + ) + .await?; + ledger + .finish( + handle_task, + owner, + ledger.execution(handle_task, owner).await?, + TaskEnd::Done(handle.clone()), + ) + .await?; + ledger.acknowledge(binary_task, owner).await?; + assert_eq!(ledger.pending(binary_task, owner).await?, None); + assert!(ledger.terminal(binary_task, Uuid::new_v4()).await.is_err()); + drop(ledger); + let reopened = TaskLedger::new(adapter).await?; + assert_eq!( + reopened.terminal(binary_task, owner).await?, + Some(TaskEnd::Done(binary)) + ); + assert_eq!( + reopened.pending(handle_task, owner).await?, + Some(TaskEnd::Done(handle)) + ); + Ok(()) + } +} diff --git a/core/continuum-kernel/src/system_resources/disk_reporters/class_writer.rs b/core/continuum-kernel/src/system_resources/disk_reporters/class_writer.rs index ebf8d9d828..71f4161622 100644 --- a/core/continuum-kernel/src/system_resources/disk_reporters/class_writer.rs +++ b/core/continuum-kernel/src/system_resources/disk_reporters/class_writer.rs @@ -30,7 +30,10 @@ pub struct ClassWriter { impl TrackedDir { pub fn writer(self: &Arc) -> ClassWriter { - ClassWriter { dir: Arc::clone(self), scope: PathBuf::new() } + ClassWriter { + dir: Arc::clone(self), + scope: PathBuf::new(), + } } } @@ -56,7 +59,10 @@ impl ClassWriter { /// a citizen's. The one place an owner's directory name is formed; a caller names only its /// file. pub fn owned_by(&self, owner: uuid::Uuid) -> Self { - ClassWriter { dir: Arc::clone(&self.dir), scope: self.scope.join(owner.to_string()) } + ClassWriter { + dir: Arc::clone(&self.dir), + scope: self.scope.join(owner.to_string()), + } } /// This scope's directory, held open (created on first use). @@ -67,8 +73,18 @@ impl ClassWriter { /// `relative`'s directory, held open, and its file name. fn held_parent<'a>(&self, relative: &'a Path) -> io::Result<(confine::Dir, &'a Path)> { let relative = confine::plain(relative)?; - let name = relative.file_name().map(Path::new).ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("{} names no file", relative.display())))?; - let dirs = relative.parent().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("{} names no file", relative.display())))?; + let name = relative.file_name().map(Path::new).ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidInput, + format!("{} names no file", relative.display()), + ) + })?; + let dirs = relative.parent().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidInput, + format!("{} names no file", relative.display()), + ) + })?; Ok((confine::subdir(&self.held()?, dirs)?, name)) } @@ -80,7 +96,11 @@ impl ClassWriter { for entry in self.held()?.entries()? { let entry = entry?; if entry.file_type()?.is_dir() { - if let Some(owner) = entry.file_name().to_str().and_then(|name| uuid::Uuid::parse_str(name).ok()) { + if let Some(owner) = entry + .file_name() + .to_str() + .and_then(|name| uuid::Uuid::parse_str(name).ok()) + { owners.push(owner); } } @@ -93,7 +113,11 @@ impl ClassWriter { /// type: refused unless it is plain names. Writes never go through it; they go through the /// held directory. pub fn path(&self, relative: &Path) -> io::Result { - Ok(self.dir.path().join(&self.scope).join(confine::plain(relative)?)) + Ok(self + .dir + .path() + .join(&self.scope) + .join(confine::plain(relative)?)) } /// Replace a file whole: a reader sees the old bytes or the new ones, never half, and the @@ -105,6 +129,12 @@ impl ClassWriter { staging.replace(name) } + /// Finish the durability fence of an existing class-owned publication. + pub fn fence_existing(&self, relative: &Path) -> io::Result<()> { + let (dir, name) = self.held_parent(relative)?; + durable::fence_existing(&dir, name) + } + /// Publish an immutable file once: `AlreadyExists` if the name is taken, never an overwrite. /// A caller that may be replaying compares what is there. pub fn publish_new(&self, relative: &Path, bytes: &[u8]) -> io::Result<()> { @@ -117,7 +147,9 @@ impl ClassWriter { /// Open a file to append to (a log, a capture stream), creating it on first use. pub fn append(&self, relative: &Path) -> io::Result { let (dir, name) = self.held_parent(relative)?; - Ok(dir.open_with(name, confine::OpenOptions::new().create(true).append(true))?.into_std()) + Ok(dir + .open_with(name, confine::OpenOptions::new().create(true).append(true))? + .into_std()) } /// Lock `relative` exclusively (a lock file in the class), waiting for a holder when `wait`, @@ -144,7 +176,10 @@ mod tests { fn a_path_outside_the_class_is_refused() { let (_root, writer) = class(); for escape in ["", "/etc/passwd", "../sibling", "a/../../b", "./a"] { - assert!(writer.path(Path::new(escape)).is_err(), "{escape:?} must be refused"); + assert!( + writer.path(Path::new(escape)).is_err(), + "{escape:?} must be refused" + ); } assert!(writer.path(Path::new("peers/a/emission.json")).is_ok()); } @@ -159,10 +194,22 @@ mod tests { writer.replace(name, b"two").expect("second"); let path = writer.path(name).expect("path"); assert_eq!(std::fs::read(&path).expect("read"), b"two"); - let left: Vec<_> = std::fs::read_dir(path.parent().expect("parent")).expect("dir").collect(); + let left: Vec<_> = std::fs::read_dir(path.parent().expect("parent")) + .expect("dir") + .collect(); assert_eq!(left.len(), 1, "no staging file left beside it"); - assert_eq!(writer.publish_new(name, b"three").expect_err("taken").kind(), io::ErrorKind::AlreadyExists); - assert_eq!(std::fs::read(&path).expect("read"), b"two", "a refused publish changed nothing"); + assert_eq!( + writer + .publish_new(name, b"three") + .expect_err("taken") + .kind(), + io::ErrorKind::AlreadyExists + ); + assert_eq!( + std::fs::read(&path).expect("read"), + b"two", + "a refused publish changed nothing" + ); } // what this catches: an owner's file landing outside its owner's directory, or a caller @@ -172,17 +219,35 @@ mod tests { let (_root, writer) = class(); let owner = uuid::Uuid::from_u128(7); let mine = writer.owned_by(owner); - mine.replace(Path::new("emission.json"), b"{}").expect("write"); + mine.replace(Path::new("emission.json"), b"{}") + .expect("write"); assert_eq!( mine.path(Path::new("emission.json")).expect("path"), - writer.path(Path::new(&owner.to_string())).expect("owner dir").join("emission.json") + writer + .path(Path::new(&owner.to_string())) + .expect("owner dir") + .join("emission.json") + ); + assert!( + mine.path(Path::new("../other")).is_err(), + "an owner cannot reach a sibling" ); - assert!(mine.path(Path::new("../other")).is_err(), "an owner cannot reach a sibling"); // The mirror: the owners read back are exactly those written, and a stray file is not one. - writer.owned_by(uuid::Uuid::from_u128(3)).replace(Path::new("demand.json"), b"{}").expect("second owner"); - writer.replace(Path::new("README"), b"not an owner").expect("stray"); - assert_eq!(writer.owners().expect("owners"), vec![uuid::Uuid::from_u128(3), owner]); - assert_eq!(class().1.owners().expect("empty class"), Vec::::new()); + writer + .owned_by(uuid::Uuid::from_u128(3)) + .replace(Path::new("demand.json"), b"{}") + .expect("second owner"); + writer + .replace(Path::new("README"), b"not an owner") + .expect("stray"); + assert_eq!( + writer.owners().expect("owners"), + vec![uuid::Uuid::from_u128(3), owner] + ); + assert_eq!( + class().1.owners().expect("empty class"), + Vec::::new() + ); } // what this catches: a symlink inside the class sending a write outside the measured root @@ -193,30 +258,50 @@ mod tests { fn a_redirect_inside_the_class_writes_nothing_outside_it() { let (root, writer) = class(); let outside = tempfile::tempdir().expect("outside"); - writer.replace(Path::new("seed"), b"x").expect("the class root exists"); - std::os::unix::fs::symlink(outside.path(), root.path().join("class/away")).expect("dir link"); - assert!(writer.replace(Path::new("away/state.json"), b"leak").is_err()); + writer + .replace(Path::new("seed"), b"x") + .expect("the class root exists"); + std::os::unix::fs::symlink(outside.path(), root.path().join("class/away")) + .expect("dir link"); + assert!(writer + .replace(Path::new("away/state.json"), b"leak") + .is_err()); assert!(writer.append(Path::new("away/log")).is_err()); assert!(writer.lock(Path::new("away/.lock"), false).is_err()); std::fs::write(outside.path().join("target"), b"").expect("target"); - std::os::unix::fs::symlink(outside.path().join("target"), root.path().join("class/file-link")).expect("file link"); + std::os::unix::fs::symlink( + outside.path().join("target"), + root.path().join("class/file-link"), + ) + .expect("file link"); assert!(writer.append(Path::new("file-link")).is_err()); - assert_eq!(std::fs::read_dir(outside.path()).expect("outside").count(), 1, "nothing written outside the class"); + assert_eq!( + std::fs::read_dir(outside.path()).expect("outside").count(), + 1, + "nothing written outside the class" + ); } // what this catches: a writer that guesses a directory when its class is not registered. #[test] fn an_unregistered_class_has_no_writer() { - assert_eq!(ClassWriter::of("no-such-class").err().map(|e| e.kind()), Some(io::ErrorKind::NotFound)); + assert_eq!( + ClassWriter::of("no-such-class").err().map(|e| e.kind()), + Some(io::ErrorKind::NotFound) + ); } // what this catches: two holders of one lock at once. #[test] fn a_held_lock_refuses_a_second_holder() { let (_root, writer) = class(); - let held = writer.lock(Path::new("p/.volatile.lock"), false).expect("first"); + let held = writer + .lock(Path::new("p/.volatile.lock"), false) + .expect("first"); assert!(writer.lock(Path::new("p/.volatile.lock"), false).is_err()); drop(held); - writer.lock(Path::new("p/.volatile.lock"), false).expect("free again"); + writer + .lock(Path::new("p/.volatile.lock"), false) + .expect("free again"); } } diff --git a/core/continuum-mind/src/commands/persona/turn_frame/execute.rs b/core/continuum-mind/src/commands/persona/turn_frame/execute.rs index f771a841aa..d607ffb8e1 100644 --- a/core/continuum-mind/src/commands/persona/turn_frame/execute.rs +++ b/core/continuum-mind/src/commands/persona/turn_frame/execute.rs @@ -319,6 +319,9 @@ fn settle_step_to_json( SettleStep::InferenceFailed { error } => serde_json::json!({ "outcome": "inferenceFailed", "error": error, }), + SettleStep::ReceiptPersistenceFailed { error } => serde_json::json!({ + "outcome": "receiptPersistenceFailed", "error": error.to_string(), + }), }; if let Some(m) = metrics { base["metrics"] = serde_json::json!({ diff --git a/core/continuum-mind/src/modules/cognition.rs b/core/continuum-mind/src/modules/cognition.rs index 648b67eed1..56270f6650 100644 --- a/core/continuum-mind/src/modules/cognition.rs +++ b/core/continuum-mind/src/modules/cognition.rs @@ -31,15 +31,19 @@ //! //! Uses `Params` helper for typed parameter extraction. +use crate::cognition::conversation::types::{InboxMessage, Modality, SenderType}; use crate::gpu::GpuMemoryManager; use crate::logging::TimingGuard; -use continuum_text_analysis::LoopDetector; -use crate::persona::{PersonaCognition, PersonaInboxFrame, PersonaTurnFrame, PersonaTurnFrameReplayRecord}; -use crate::cognition::conversation::types::{InboxMessage, Modality, SenderType}; +use crate::persona::{ + PersonaCognition, PersonaInboxFrame, PersonaTurnFrame, PersonaTurnFrameReplayRecord, +}; use crate::rag::RagEngine; -use crate::runtime::{CommandResult, LateBound, ModuleConfig, ModuleContext, ModulePriority, ServiceModule}; use crate::runtime::params::Params; +use crate::runtime::{ + CommandResult, LateBound, ModuleConfig, ModuleContext, ModulePriority, ServiceModule, +}; use async_trait::async_trait; +use continuum_text_analysis::LoopDetector; use dashmap::DashMap; use serde_json::Value; use std::any::Any; @@ -105,8 +109,11 @@ impl CognitionState { } } +mod task_delivery; + pub struct CognitionModule { state: Arc, + task_replay: tokio::sync::Mutex, /// Shared late-bound executor slot. `Arc`-wrapped so the `cognition/vision-describe` /// command object can hold the same slot and re-enter the bus for `ai/generate` /// (same pattern as the `chat/*` family). @@ -117,6 +124,7 @@ impl CognitionModule { pub fn new(state: Arc) -> Self { Self { state, + task_replay: tokio::sync::Mutex::new(task_delivery::ReplaySweep::default()), executor: Arc::new(LateBound::new("cognition::executor")), } } @@ -189,7 +197,13 @@ impl ServiceModule for CognitionModule { in_flight = crate::cognition::turn_ingress::in_flight(), "citizens inside a turn right now — the drain budget's competitor, sampled before the drain instead of only at it" ); - checkpoint_residents(CheckpointBoundary::Periodic).await + let replay = self.reconcile_tasks().await; + let checkpoint = checkpoint_residents(CheckpointBoundary::Periodic).await; + match (replay, checkpoint) { + (Ok(()), Ok(())) => Ok(()), + (Err(error), Ok(())) | (Ok(()), Err(error)) => Err(error), + (Err(replay), Err(checkpoint)) => Err(format!("{replay}; {checkpoint}")), + } } async fn shutdown(&self) -> Result<(), String> { diff --git a/core/continuum-mind/src/modules/cognition/task_delivery.rs b/core/continuum-mind/src/modules/cognition/task_delivery.rs new file mode 100644 index 0000000000..de275a2302 --- /dev/null +++ b/core/continuum-mind/src/modules/cognition/task_delivery.rs @@ -0,0 +1,169 @@ +//! Durable replay rides cognition's existing lifecycle tick. No persona needs to +//! remember a handle or poll; cursors are scan progress, never delivery authority. +use super::CognitionModule; +use continuum_kernel::runtime::tasks::{TaskLedger, TaskOwnerSink}; +use std::collections::{BTreeMap, BTreeSet}; +use std::num::NonZeroUsize; +use uuid::Uuid; + +// Storage page policy, independent of prompt/context budgets. Each resident gets +// one bounded page per existing lifecycle tick, including through empty pages. +const REPLAY_PAGE_ROWS: usize = 64; + +#[derive(Default)] +pub(super) struct ReplaySweep { + after: BTreeMap>, +} + +impl ReplaySweep { + async fn advance( + &mut self, + ledger: &TaskLedger, + owners: Vec, + sink: &S, + limit: NonZeroUsize, + ) -> Result<(), String> { + let live: BTreeSet<_> = owners.into_iter().collect(); + self.after.retain(|owner, _| live.contains(owner)); + let mut failures = Vec::new(); + for owner in live { + let after = *self.after.entry(owner).or_insert(None); + match ledger.deliver_page(owner, after, limit, sink).await { + Ok(page) => { + // New ends can sort before our cursor. Every completed sweep + // starts again; acknowledged rows cannot repeat consumption. + self.after + .insert(owner, if page.exhausted { None } else { page.after }); + } + Err(error) => { + // No cursor advance on failure: the durable outbox retains + // every unacknowledged result, including failed consumption. + failures.push(format!("{owner}: {error}")); + } + } + } + if failures.is_empty() { + Ok(()) + } else { + Err(format!( + "resident task replay failed: {}", + failures.join("; ") + )) + } + } +} + +impl CognitionModule { + pub(super) async fn reconcile_tasks(&self) -> Result<(), String> { + let registry = crate::cognition::persona_workspace::global(); + let owners: Vec<_> = registry.roster().into_iter().map(|(id, _)| id).collect(); + if owners.is_empty() { + self.task_replay.lock().await.after.clear(); + return Ok(()); + } + let ledger = self.executor.require()?.task_ledger().await?; + let sink = crate::cognition::persona_workspace::ResidentTaskSink::new(registry); + let limit = + NonZeroUsize::new(REPLAY_PAGE_ROWS).ok_or("task replay page policy must be nonzero")?; + self.task_replay + .lock() + .await + .advance(ledger, owners, &sink, limit) + .await + } +} + +#[cfg(test)] +mod tests { + use super::*; + use continuum_kernel::runtime::tasks::{TaskEnd, TaskExecution}; + use std::sync::atomic::{AtomicBool, Ordering}; + + // Scheduling fixture only; real durable consumption is tested by cognition's + // ledger-to-resident integration test, not claimed by this in-memory sink. + struct Sink { + refused: Uuid, + refuse: AtomicBool, + } + #[async_trait::async_trait] + impl TaskOwnerSink for Sink { + type Error = std::io::Error; + async fn consume( + &self, + owner: Uuid, + ends: &[(Uuid, TaskEnd)], + ) -> Result, Self::Error> { + if owner == self.refused && self.refuse.load(Ordering::SeqCst) { + Err(std::io::Error::other("injected owner refusal")) + } else { + Ok(ends.iter().map(|(task, _)| *task).collect()) + } + } + } + + #[tokio::test] + async fn failed_owner_does_not_starve_peer_and_later_ends_are_revisited( + ) -> Result<(), Box> { + let (adapter, _directory) = continuum_kernel::orm::store::fresh_adapter().await; + let ledger = TaskLedger::new(adapter).await?; + let refused = Uuid::new_v4(); + let healthy = Uuid::new_v4(); + let execution = TaskExecution::new_command_executor(); + let blocked = ledger.accept(refused, "blocked".into(), execution).await?; + let ready = ledger.accept(healthy, "ready".into(), execution).await?; + let running = ledger.accept(healthy, "running".into(), execution).await?; + ledger + .finish( + blocked, + refused, + ledger.execution(blocked, refused).await?, + TaskEnd::Stopped, + ) + .await?; + ledger + .finish( + ready, + healthy, + ledger.execution(ready, healthy).await?, + TaskEnd::Stopped, + ) + .await?; + let sink = Sink { + refused, + refuse: AtomicBool::new(true), + }; + let mut sweep = ReplaySweep::default(); + let limit = NonZeroUsize::MIN; + // Scan through individual fact rows, including pages with no pending end. + for _ in 0..12 { + let _ = sweep + .advance(&ledger, vec![refused, healthy], &sink, limit) + .await; + } + assert_eq!(ledger.pending(ready, healthy).await?, None); + assert_eq!( + ledger.pending(blocked, refused).await?, + Some(TaskEnd::Stopped) + ); + // End an already-scanned acceptance. Fresh sweeps must find it. + ledger + .finish( + running, + healthy, + ledger.execution(running, healthy).await?, + TaskEnd::Lost, + ) + .await?; + sink.refuse.store(false, Ordering::SeqCst); + for _ in 0..16 { + sweep + .advance(&ledger, vec![refused, healthy], &sink, limit) + .await?; + } + assert_eq!(ledger.pending(running, healthy).await?, None); + assert_eq!(ledger.pending(blocked, refused).await?, None); + sweep.advance(&ledger, vec![healthy], &sink, limit).await?; + assert!(!sweep.after.contains_key(&refused)); + Ok(()) + } +} diff --git a/core/continuum-mind/src/persona/obligation/recover.rs b/core/continuum-mind/src/persona/obligation/recover.rs index bc4a92a83f..99d6dac23d 100644 --- a/core/continuum-mind/src/persona/obligation/recover.rs +++ b/core/continuum-mind/src/persona/obligation/recover.rs @@ -105,18 +105,25 @@ impl Obligations { /// Pin the row's notice on the cycle her turns in its room run on. `false` when she has /// no such cycle: nothing could carry it. fn pin_notice(&self, row: &PersonaObligation, now_ms: u64) -> bool { - let Some(cycle) = crate::cognition::persona_workspace::global().cycle_for_room(&self.persona_id, row.room_id) else { + let Some(cycle) = crate::cognition::persona_workspace::global() + .cycle_for_room(&self.persona_id, row.room_id) + else { return false; }; - let Some(body) = cycle.acting() else { return false }; - body.working_memory.pin_fact(¬ice_key(row.id), ¬ice(row, now_ms)); + let Some(body) = cycle.acting() else { + return false; + }; + body.working_memory + .pin_fact(¬ice_key(row.id), ¬ice(row, now_ms)); self.pinned.lock().insert(row.id, row.room_id); true } /// The row closed: its notice leaves with it. pub(super) fn unpin(&self, row: Uuid) { - let Some(room) = self.pinned.lock().remove(&row) else { return }; + let Some(room) = self.pinned.lock().remove(&row) else { + return; + }; if let Some(body) = crate::cognition::persona_workspace::global() .cycle_for_room(&self.persona_id, room) .as_ref() @@ -151,18 +158,23 @@ mod tests { resident_with(persona, crate::ai::HeuristicInferenceAdapter::new()) } - fn resident_with(persona: Uuid, adapter: crate::ai::HeuristicInferenceAdapter) -> Arc { + fn resident_with( + persona: Uuid, + adapter: crate::ai::HeuristicInferenceAdapter, + ) -> Arc { let cfg = crate::cognition::persona_workspace::PersonaBrainConfig { persona_id: persona, persona_name: "Rhea".into(), system_prompt: "You are Rhea.".into(), - admission: Arc::new(crate::cognition::admission_state::AdmissionState::new(Arc::new( - crate::cognition::recall_metadata::RecallMetadataRegistry::new(), - ))), + admission: Arc::new(crate::cognition::admission_state::AdmissionState::new( + Arc::new(crate::cognition::recall_metadata::RecallMetadataRegistry::new()), + )), adapter: Arc::new(adapter), grounding_sources: Vec::new(), embedder: None, - tool_executor: Some(Arc::new(crate::cognition::act_observe::test_support::ScriptedExecutor::new(["ok"]))), + tool_executor: Some(Arc::new( + crate::cognition::act_observe::test_support::ScriptedExecutor::new(["ok"]), + )), experience: None, // Roomy enough for framing + tools + a reply: a refused prompt is not what these test. context_window: 65_536, @@ -172,12 +184,94 @@ mod tests { forked: false, read_receipt: None, }; - crate::cognition::persona_workspace::global().register_from_cfg(cfg).unwrap() // unwrap: test fixture + crate::cognition::persona_workspace::global() + .register_from_cfg(cfg) + .unwrap() // unwrap: test fixture } fn interrupted_notices(cycle: &crate::cognition::workspace::WorkspaceCycle) -> Vec { let body = cycle.acting().unwrap(); // unwrap: the fixture registers her hands - body.working_memory.pinned_facts().into_iter().filter(|fact| fact.starts_with("[interrupted]")).collect() + body.working_memory + .pinned_facts() + .into_iter() + .filter(|fact| fact.starts_with("[interrupted]")) + .collect() + } + + // what this catches (stop-drain S3): an interrupted turn lost, or re-run twice, or told twice. + #[tokio::test] + async fn failed_receipt_checkpoint_keeps_input_and_effect_obligations_across_restart() { + use crate::cognition::act_observe::SettleStep; + use crate::cognition::persona_workspace::TaskSinkError; + use crate::persona::training_producer::test_support::served_receipt; + let home = tempfile::tempdir().expect("test: temporary home"); + let _home = crate::paths::test_home::HomeGuard::set(home.path()).await; + let executor = test_store_executor(); + let (persona, room, name) = (Uuid::new_v4(), Uuid::new_v4(), "checkpoint-custody"); + let cycle = resident(persona); + let untouched = trigger(room, "finish this"); + let acted = trigger(room, "previous tool batch"); + let rows = [ + PersonaObligation::admitted(persona, room, &untouched, Some(Uuid::new_v4()), 10), + PersonaObligation { + effect_at_ms: Some(21), + effects: Some(vec![RecordedEffect::ToolBatch { + calls: vec![("call-1".into(), "code/edit".into())], + }]), + ..PersonaObligation::admitted(persona, room, &acted, None, 20) + }, + ]; + let obligations = Obligations::new(&executor, persona, name); + assert!(obligations.report_interrupted(0).await.is_some()); + for row in &rows { + record(obligations.conn.as_ref(), name, row) + .await + .expect("test: durable row"); + } + let mut pending = PendingInput::for_persona(persona); + obligations + .recover(30, &mut pending, |_| TurnAttention::default()) + .await; + pending.observe_settlement( + room, + &untouched, + rows[0].wake_engram, + TurnAttention::default(), + &SettleStep::ReceiptPersistenceFailed { + error: Arc::new(TaskSinkError::OwnerGone(persona)), + }, + &[served_receipt("served before checkpoint failed", "qwen")], + ); + assert_eq!(pending.obligation_for(&untouched), Some(rows[0].id)); + assert!( + pending.take_answered().is_empty(), + "served alone cannot retire the effect-marked row" + ); + drop(pending); + let restarted = Obligations::new(&executor, persona, name); + let mut pending = PendingInput::for_persona(persona); + assert_eq!( + restarted + .recover(40, &mut pending, |_| TurnAttention::default()) + .await + .map(|r| r.open), + Some(2) + ); + assert_eq!(pending.obligation_for(&untouched), Some(rows[0].id)); + assert_eq!(pending.wake_engram_for(&untouched), rows[0].wake_engram); + assert_eq!( + pending.obligation_for(&acted), + None, + "previous effects must not replay" + ); + assert_eq!(interrupted_notices(&cycle).len(), 2); + assert_eq!( + open(restarted.conn.as_ref(), name, persona) + .await + .expect("test: read durable rows") + .len(), + 2 + ); } // what this catches (stop-drain S3): an interrupted turn lost, or re-run twice, or told twice. @@ -197,7 +291,10 @@ mod tests { PersonaObligation::admitted(persona, room, &second, None, 20), ]; let seed = Obligations::new(&executor, persona, name); - assert!(seed.report_interrupted(0).await.is_some(), "the store is readable"); + assert!( + seed.report_interrupted(0).await.is_some(), + "the store is readable" + ); for row in &rows { record(seed.conn.as_ref(), name, row).await.unwrap(); // unwrap: the store under test } @@ -205,23 +302,55 @@ mod tests { for start in [100, 200] { let obligations = Obligations::new(&executor, persona, name); let mut pending = PendingInput::for_persona(persona); - let report = obligations.recover(start, &mut pending, |_| TurnAttention::default()).await; - assert_eq!(report.map(|r| r.open), Some(2), "both turns are still owed at start {start}"); - assert_eq!(pending.obligation_for(&first), Some(rows[0].id), "handed back with its own row"); - assert_eq!(pending.wake_engram_for(&first), rows[0].wake_engram, "and its original engram"); + let report = obligations + .recover(start, &mut pending, |_| TurnAttention::default()) + .await; + assert_eq!( + report.map(|r| r.open), + Some(2), + "both turns are still owed at start {start}" + ); + assert_eq!( + pending.obligation_for(&first), + Some(rows[0].id), + "handed back with its own row" + ); + assert_eq!( + pending.wake_engram_for(&first), + rows[0].wake_engram, + "and its original engram" + ); assert_eq!(pending.obligation_for(&second), Some(rows[1].id)); - assert!(!pending.permits_self_tick(), "an owed turn comes before her own musing"); - assert_eq!(interrupted_notices(&cycle).len(), 2, "one notice per row, however many starts"); + assert!( + !pending.permits_self_tick(), + "an owed turn comes before her own musing" + ); + assert_eq!( + interrupted_notices(&cycle).len(), + 2, + "one notice per row, however many starts" + ); } // The retried turn finishes: its row closes and its notice leaves with it. let obligations = Obligations::new(&executor, persona, name); let mut pending = PendingInput::for_persona(persona); - obligations.recover(300, &mut pending, |_| TurnAttention::default()).await; + obligations + .recover(300, &mut pending, |_| TurnAttention::default()) + .await; obligations.close(Some(rows[0].id)).await; - assert_eq!(interrupted_notices(&cycle).len(), 1, "the closed row's notice is gone"); - let still = open(obligations.conn.as_ref(), name, persona).await.unwrap(); // unwrap: the store under test - assert_eq!(still.iter().map(|r| r.id).collect::>(), vec![rows[1].id]); + assert_eq!( + interrupted_notices(&cycle).len(), + 1, + "the closed row's notice is gone" + ); + let still = open(obligations.conn.as_ref(), name, persona) + .await + .unwrap(); // unwrap: the store under test + assert_eq!( + still.iter().map(|r| r.id).collect::>(), + vec![rows[1].id] + ); } // what this catches (stop-drain S3): a turn that began an effect being run a second time, or @@ -246,44 +375,86 @@ mod tests { }, PersonaObligation { effect_at_ms: Some(21), - effects: Some(vec![RecordedEffect::ToolBatch { calls: vec![("toolu_1".into(), "code/edit".into())] }]), + effects: Some(vec![RecordedEffect::ToolBatch { + calls: vec![("toolu_1".into(), "code/edit".into())], + }]), ..PersonaObligation::admitted(persona, room, &acted, None, 20) }, ]; let obligations = Obligations::new(&executor, persona, name); - assert!(obligations.report_interrupted(0).await.is_some(), "the store is readable"); + assert!( + obligations.report_interrupted(0).await.is_some(), + "the store is readable" + ); for row in &rows { record(obligations.conn.as_ref(), name, row).await.unwrap(); // unwrap: the store under test } let mut pending = PendingInput::for_persona(persona); - obligations.recover(60_000 + 20, &mut pending, |_| TurnAttention::default()).await; - assert_eq!(pending.obligation_for(&spoke), None, "a turn that began speaking is never retried"); - assert_eq!(pending.obligation_for(&acted), None, "nor one that began a tool batch"); + obligations + .recover(60_000 + 20, &mut pending, |_| TurnAttention::default()) + .await; + assert_eq!( + pending.obligation_for(&spoke), + None, + "a turn that began speaking is never retried" + ); + assert_eq!( + pending.obligation_for(&acted), + None, + "nor one that began a tool batch" + ); let notices = interrupted_notices(&cycle); - assert!(notices.iter().any(|n| n.contains("posting my reply")), "{notices:?}"); - assert!(notices.iter().any(|n| n.contains("code/edit (call toolu_1)") && n.contains("a minute ago")), "{notices:?}"); + assert!( + notices.iter().any(|n| n.contains("posting my reply")), + "{notices:?}" + ); + assert!( + notices + .iter() + .any(|n| n.contains("code/edit (call toolu_1)") && n.contains("a minute ago")), + "{notices:?}" + ); use crate::persona::training_producer::test_support::{receipt, served_receipt}; pending.notices_read(room, &[receipt("failed before generation")]); - assert!(pending.take_answered().is_empty(), "a failed inference read nothing"); + assert!( + pending.take_answered().is_empty(), + "a failed inference read nothing" + ); // A restart before any generation was served: the rows are still owed, notices still one each. let restarted = Obligations::new(&executor, persona, name); let mut pending = PendingInput::for_persona(persona); - let report = restarted.recover(120_000, &mut pending, |_| TurnAttention::default()).await; - assert_eq!(report.map(|r| r.open), Some(2), "nothing was closed by the failed turn"); + let report = restarted + .recover(120_000, &mut pending, |_| TurnAttention::default()) + .await; + assert_eq!( + report.map(|r| r.open), + Some(2), + "nothing was closed by the failed turn" + ); assert_eq!(interrupted_notices(&cycle).len(), 2, "re-pinned, not added"); let obligations = restarted; pending.notices_read(room, &[served_receipt("live", "qwen")]); let answered = pending.take_answered(); - assert_eq!(answered.len(), 2, "a completed turn on her live cycle answers both"); + assert_eq!( + answered.len(), + 2, + "a completed turn on her live cycle answers both" + ); for row in answered { obligations.close(Some(row)).await; } - assert!(interrupted_notices(&cycle).is_empty(), "closed rows take their notices"); - assert!(open(obligations.conn.as_ref(), name, persona).await.unwrap().is_empty()); // unwrap: the store under test + assert!( + interrupted_notices(&cycle).is_empty(), + "closed rows take their notices" + ); + assert!(open(obligations.conn.as_ref(), name, persona) + .await + .unwrap() + .is_empty()); // unwrap: the store under test } // what this catches (Codex on #5497): a row answered by a generation whose prompt did not @@ -300,27 +471,38 @@ mod tests { let requests = Arc::new(std::sync::Mutex::new(Vec::new())); let cycle = resident_with( persona, - crate::ai::HeuristicInferenceAdapter::new().with_canned_response("PASS: noted").with_request_recorder(requests.clone()), + crate::ai::HeuristicInferenceAdapter::new() + .with_canned_response("PASS: noted") + .with_request_recorder(requests.clone()), ); let row = PersonaObligation { effect_at_ms: Some(2), - effects: Some(vec![RecordedEffect::ToolBatch { calls: vec![("toolu_9".into(), "code/shell".into())] }]), + effects: Some(vec![RecordedEffect::ToolBatch { + calls: vec![("toolu_9".into(), "code/shell".into())], + }]), ..PersonaObligation::admitted(persona, room, &trigger(room, "run the tests"), None, 1) }; let obligations = Obligations::new(&executor, persona, name); - assert!(obligations.report_interrupted(0).await.is_some(), "the store is readable"); + assert!( + obligations.report_interrupted(0).await.is_some(), + "the store is readable" + ); record(obligations.conn.as_ref(), name, &row).await.unwrap(); // unwrap: the store under test let mut pending = PendingInput::for_persona(persona); - obligations.recover(3, &mut pending, |_| TurnAttention::default()).await; + obligations + .recover(3, &mut pending, |_| TurnAttention::default()) + .await; - let mut conversation = crate::cognition::conversation::scripted_conversation::ScriptedConversation::new(); + let mut conversation = + crate::cognition::conversation::scripted_conversation::ScriptedConversation::new(); conversation.prime().await.unwrap(); // unwrap: test fixture let burst = crate::cognition::workspace::Burst::raw_in( crate::identity::ActivityRoom::from_uuid(room).unwrap(), // unwrap: a fresh uuid is a valid room "a new line in the room".into(), ); let framing = crate::cognition::workspace::TurnFraming::message(TurnAttention::default()); - let settled = drive_to_settle_with_input(&cycle, burst, 8, framing, &mut conversation).await; + let settled = + drive_to_settle_with_input(&cycle, burst, 8, framing, &mut conversation).await; let (_, _, receipts) = SettleStep::from_settled(settled); let served: Vec = requests .lock() @@ -330,11 +512,18 @@ mod tests { .collect(); assert!(!served.is_empty(), "the turn reached the engine"); assert!( - served.iter().all(|request| request.contains("[interrupted]") && request.contains("code/shell (call toolu_9)")), + served + .iter() + .all(|request| request.contains("[interrupted]") + && request.contains("code/shell (call toolu_9)")), "every prompt this turn served carried the notice" ); pending.notices_read(room, &receipts); - assert_eq!(pending.take_answered(), vec![row.id], "and its served receipt answers the row"); + assert_eq!( + pending.take_answered(), + vec![row.id], + "and its served receipt answers the row" + ); } // what this catches: a row whose close failed losing its notice while it stays owed. The @@ -347,10 +536,16 @@ mod tests { let cycle = resident(persona); let room = Uuid::new_v4(); let row = PersonaObligation::admitted(persona, room, &trigger(room, "owed"), None, 1); - let no_store = Arc::new(crate::runtime::CommandExecutor::new(Arc::new(crate::runtime::ModuleRegistry::new()))); + let no_store = Arc::new(crate::runtime::CommandExecutor::new(Arc::new( + crate::runtime::ModuleRegistry::new(), + ))); let obligations = Obligations::new(&no_store, persona, "recover-no-store"); assert!(obligations.pin_notice(&row, 2), "her live cycle carries it"); obligations.close(Some(row.id)).await; - assert_eq!(interrupted_notices(&cycle).len(), 1, "the row may still be on disk: the notice stays"); + assert_eq!( + interrupted_notices(&cycle).len(), + 1, + "the row may still be on disk: the notice stays" + ); } } diff --git a/core/continuum-mind/src/persona/service_loop/burst_fingerprint.rs b/core/continuum-mind/src/persona/service_loop/burst_fingerprint.rs index 83cf4575df..962f702128 100644 --- a/core/continuum-mind/src/persona/service_loop/burst_fingerprint.rs +++ b/core/continuum-mind/src/persona/service_loop/burst_fingerprint.rs @@ -593,6 +593,10 @@ pub(super) async fn run_self_cycle( "self-thread act; result admitted as memory, re-perceives next tick" ); } + crate::cognition::act_observe::SettleStep::ReceiptPersistenceFailed { error } => { + tracing::error!(persona = %ctx.identity.agent_name, error = %error, + "self-cycle render receipt checkpoint failed; generation served, action not executed"); + } crate::cognition::act_observe::SettleStep::InferenceFailed { error } => { // Even on the self-thread a failed model call is surfaced, never swallowed // by the `_ => {}` sleep ([[fallbacks-are-illegal-fail-loud]]): a broken diff --git a/core/continuum-mind/src/persona/service_loop/serve_persona_loop_inner.rs b/core/continuum-mind/src/persona/service_loop/serve_persona_loop_inner.rs index 24a5496243..bda362c767 100644 --- a/core/continuum-mind/src/persona/service_loop/serve_persona_loop_inner.rs +++ b/core/continuum-mind/src/persona/service_loop/serve_persona_loop_inner.rs @@ -403,6 +403,12 @@ pub(super) async fn serve_persona_loop_inner( .await { CycleVerdict::Spoke(spoken) => spoken, + CycleVerdict::CheckpointFailed(error) => { + // The admitted row and its pre-effect marks remain durable. The + // existing recovery owner distinguishes untouched input from + // work that already acted; never replay it here as a fresh turn. + return Err(format!("receipt checkpoint failed for obligation {obligation}: {error}")); + } CycleVerdict::Skip => { // A refused or deferred input is still owed: PendingInput retains it for a // retry, so its row stays open with it (Codex on #5480). Only a finished diff --git a/core/continuum-mind/src/persona/service_loop/turn_cycle.rs b/core/continuum-mind/src/persona/service_loop/turn_cycle.rs index f2631793d0..879c38c0f7 100644 --- a/core/continuum-mind/src/persona/service_loop/turn_cycle.rs +++ b/core/continuum-mind/src/persona/service_loop/turn_cycle.rs @@ -6,6 +6,9 @@ pub(super) enum CycleVerdict { Spoke(SpokenTurn), /// No reply to publish this turn (deferred, acted, silent, failed, or yielded). Skip, + /// Custody failed after generation. The loop must leave its durable + /// obligation open and return to lifecycle supervision, not close a skip. + CheckpointFailed(std::sync::Arc), } /// The L2 producer's two provenance inputs are BORN inside the cycle — credit on her hands @@ -61,7 +64,9 @@ pub(super) async fn run_turn_cycle( // flip clears her KV). Unreadable: the genome she has. The receipt names the // genes that ran (GenerationReceipt::genes). let need = crate::cognition::recall_faculty::focused_query(&workspace_burst.rendered); - if let Some(phenotype) = crate::genome::composer::compose(ctx.identity.peer_id.as_uuid(), need).await { + if let Some(phenotype) = + crate::genome::composer::compose(ctx.identity.peer_id.as_uuid(), need).await + { continuum_base::probe!( class = "persona.genome.turn_genes", persona = %ctx.identity.agent_name, @@ -203,7 +208,8 @@ pub(super) async fn run_turn_cycle( // and got no record, so nothing on disk ever described a lived turn. // The driver stays a driver: no learning policy at any call site. turn_act_count = outcome.acts; - let (step, metrics, receipts) = crate::cognition::act_observe::SettleStep::from_settled(outcome); + let (step, metrics, receipts) = + crate::cognition::act_observe::SettleStep::from_settled(outcome); (step, metrics, receipts, credit, card_sync) }; // The credit is the turn's held CARD, captured with it, NOT read back out of @@ -240,9 +246,14 @@ pub(super) async fn run_turn_cycle( "deliberation generation cost" ); } - deferred_input.settle(msg, wake_engram, attention, &step); - // The room that chose this turn's cycle above, so the notices it read are the ones answered. - deferred_input.notices_read(turn_room, &turn_generation_receipts); + deferred_input.observe_settlement( + turn_room, + msg, + wake_engram, + attention, + &step, + &turn_generation_receipts, + ); // A turn with a reply hands its card sync to the publish; any other runs it now. let card_sync = if matches!(step, crate::cognition::act_observe::SettleStep::Spoke(_)) { card_sync @@ -257,10 +268,10 @@ pub(super) async fn run_turn_cycle( } crate::cognition::act_observe::SettleStep::Spoke(text) => { CycleVerdict::Spoke(SpokenTurn { - response_text: text, - turn_credit, - turn_generation_receipts, - card_sync, + response_text: text, + turn_credit, + turn_generation_receipts, + card_sync, }) } crate::cognition::act_observe::SettleStep::Acted { calls, intent } => { @@ -345,6 +356,11 @@ pub(super) async fn run_turn_cycle( outcome.turns_skipped += 1; return CycleVerdict::Skip; } + crate::cognition::act_observe::SettleStep::ReceiptPersistenceFailed { error } => { + tracing::error!(persona = %ctx.identity.agent_name, lamport = msg.lamport, + error = %error, "render receipt checkpoint failed; generation served, action not executed"); + return CycleVerdict::CheckpointFailed(error); + } crate::cognition::act_observe::SettleStep::InferenceFailed { error } => { // The model call FAILED (timeout, 5xx, the serving lane // refusing a model it isn't hosting) — NOT a chosen silence. diff --git a/core/continuum-mind/src/persona/wake_backlog.rs b/core/continuum-mind/src/persona/wake_backlog.rs index 6b77a393d0..a347c40809 100644 --- a/core/continuum-mind/src/persona/wake_backlog.rs +++ b/core/continuum-mind/src/persona/wake_backlog.rs @@ -627,7 +627,7 @@ mod tests { use crate::cognition::act_observe::test_support::{admission, body_with_wm, ActThenSpeak, RecordingExecutor}; use crate::cognition::act_observe::{drive_to_settle_with_input, SettleStep}; use crate::cognition::working_memory::WorkingMemory; - use crate::cognition::workspace::{Burst, SalienceArbiter, TurnAttention, TurnFraming, WorkspaceCycle}; + use crate::cognition::workspace::{Burst, Faculty, SalienceArbiter, TurnAttention, TurnFraming, WorkspaceCycle}; use std::sync::{Arc, Mutex}; use crate::cognition::conversation::scripted_conversation::ScriptedConversation; use crate::cognition::conversation::{IncomingMessage, PersonaConversation}; diff --git a/core/continuum-mind/src/persona/wake_backlog/recovered.rs b/core/continuum-mind/src/persona/wake_backlog/recovered.rs index 5b0f2ff3e4..9a877c8f12 100644 --- a/core/continuum-mind/src/persona/wake_backlog/recovered.rs +++ b/core/continuum-mind/src/persona/wake_backlog/recovered.rs @@ -13,10 +13,41 @@ use crate::cognition::conversation::IncomingMessage; use crate::cognition::workspace::TurnAttention; impl PendingInput { + /// Apply a completed generation to input and notice custody together. A receipt + /// checkpoint failure leaves both with their existing owner for restart recovery. + pub(crate) fn observe_settlement( + &mut self, + turn_room: Uuid, + message: &IncomingMessage, + wake_engram: Option, + attention: TurnAttention, + step: &crate::cognition::act_observe::SettleStep, + receipts: &[GenerationReceipt], + ) { + if matches!( + step, + crate::cognition::act_observe::SettleStep::ReceiptPersistenceFailed { .. } + ) { + return; + } + self.settle(message, wake_engram, attention, step); + self.notices_read(turn_room, receipts); + } + /// Hand an interrupted, untouched turn back: retried at the next beat with its original /// engram (memory already holds the trigger) and its own row id. Idempotent per row. - pub(crate) fn readmit(&mut self, message: IncomingMessage, engram: Option, attention: TurnAttention, obligation: Uuid) { - if self.inputs.iter().any(|input| input.obligation == Some(obligation)) { + pub(crate) fn readmit( + &mut self, + message: IncomingMessage, + engram: Option, + attention: TurnAttention, + obligation: Uuid, + ) { + if self + .inputs + .iter() + .any(|input| input.obligation == Some(obligation)) + { return; } self.inputs.push_back(RetainedInput { @@ -45,16 +76,22 @@ impl PendingInput { /// The step's kind is not evidence the model read anything; a served receipt is (Codex on /// #5497: a failed inference must never answer a row she was never shown). pub(crate) fn notices_read(&mut self, room: Uuid, receipts: &[GenerationReceipt]) { - if !receipts.iter().any(|r| matches!(r.outcome, GenerationOutcome::Served { .. })) { + if !receipts + .iter() + .any(|r| matches!(r.outcome, GenerationOutcome::Served { .. })) + { return; } let Some(persona) = self.persona else { return }; let private = crate::cognition::mind_room::is_private_room(persona, room); let (answered, owed): (Vec<_>, Vec<_>) = std::mem::take(&mut self.uncertain) .into_iter() - .partition(|(_, held)| crate::cognition::mind_room::is_private_room(persona, *held) == private); + .partition(|(_, held)| { + crate::cognition::mind_room::is_private_room(persona, *held) == private + }); self.uncertain = owed; - self.answered.extend(answered.into_iter().map(|(row, _)| row)); + self.answered + .extend(answered.into_iter().map(|(row, _)| row)); } } @@ -98,11 +135,49 @@ mod tests { pending.hold_uncertain(row, public); pending.notices_read(public, &[receipt("faulted")]); pending.notices_read(public, &[]); - assert!(pending.take_answered().is_empty(), "nothing served: the model read nothing"); + assert!( + pending.take_answered().is_empty(), + "nothing served: the model read nothing" + ); let private = crate::cognition::mind_room::mind_room_id(persona); pending.notices_read(private, &[served_receipt("mind", "m")]); - assert!(pending.take_answered().is_empty(), "her mind cycle never saw the live cycle's notice"); - pending.notices_read(Uuid::new_v4(), &[receipt("faulted"), served_receipt("live", "m")]); - assert_eq!(pending.take_answered(), vec![row], "held once, answered once"); + assert!( + pending.take_answered().is_empty(), + "her mind cycle never saw the live cycle's notice" + ); + pending.notices_read( + Uuid::new_v4(), + &[receipt("faulted"), served_receipt("live", "m")], + ); + assert_eq!( + pending.take_answered(), + vec![row], + "held once, answered once" + ); + } + // A recovered trigger's original room need not be the cycle selected for this turn. + #[test] + fn settlement_uses_the_selected_cycle_room_for_notice_receipts() { + use crate::cognition::act_observe::SettleStep; + use crate::persona::training_producer::test_support::served_receipt; + let persona = Uuid::new_v4(); + let public = Uuid::new_v4(); + let private = crate::cognition::mind_room::mind_room_id(persona); + let public_row = Uuid::new_v4(); + let private_row = Uuid::new_v4(); + let mut pending = PendingInput::for_persona(persona); + pending.hold_uncertain(public_row, public); + pending.hold_uncertain(private_row, private); + pending.observe_settlement( + private, + &message(public), + None, + TurnAttention::default(), + &SettleStep::Spoke("settled".into()), + &[served_receipt("mind", "m")], + ); + assert_eq!(pending.take_answered(), vec![private_row]); + pending.notices_read(public, &[served_receipt("live", "m")]); + assert_eq!(pending.take_answered(), vec![public_row]); } } diff --git a/core/continuum-process/src/kill9_windows_tests.rs b/core/continuum-process/src/kill9_windows_tests.rs index 7f55852587..d3ff1c8c57 100644 --- a/core/continuum-process/src/kill9_windows_tests.rs +++ b/core/continuum-process/src/kill9_windows_tests.rs @@ -1,4 +1,4 @@ -use super::terminate_windows_handle; +use super::{terminate_windows_handle, windows_handle_has_exited}; use continuum_kernel::system_resources::process_tree::ProcessIdentity; use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}; use std::process::{Child, Stdio}; @@ -68,3 +68,24 @@ fn live_process_access_denial_remains_a_refusal() -> Result<(), Box Result<(), Box> { + let mut child = waiting_child()?; + // SAFETY: query-only access deliberately omits the right required to wait. + let raw = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, child.id()) }; + let observed = if raw.is_null() { + Err(std::io::Error::last_os_error().to_string()) + } else { + // SAFETY: successful OpenProcess transferred one owned handle. + let handle = unsafe { OwnedHandle::from_raw_handle(raw) }; + windows_handle_has_exited(&handle) + }; + let still_live = child.try_wait()?.is_none(); + drop(child.stdin.take()); + child.wait()?; + assert!(!raw.is_null(), "fixture must acquire a query-only handle"); + assert!(observed.is_err_and(|error| error.contains("WaitForSingleObject"))); + assert!(still_live); + Ok(()) +} diff --git a/core/continuum-process/src/owned.rs b/core/continuum-process/src/owned.rs index 1b5da1167c..9974165949 100644 --- a/core/continuum-process/src/owned.rs +++ b/core/continuum-process/src/owned.rs @@ -105,9 +105,9 @@ pub fn signal_if_same(who: ProcessIdentity) -> Result { #[cfg(windows)] fn signal_windows_identity(who: ProcessIdentity) -> Result { use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}; - use windows_sys::Win32::Foundation::{FILETIME, ERROR_INVALID_PARAMETER, WAIT_OBJECT_0}; + use windows_sys::Win32::Foundation::{FILETIME, ERROR_INVALID_PARAMETER}; use windows_sys::Win32::System::Threading::{ - GetProcessTimes, OpenProcess, WaitForSingleObject, + GetProcessTimes, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_TERMINATE, PROCESS_SYNCHRONIZE, }; // Pin the incarnation before inspecting or signalling it: taskkill's PID @@ -134,13 +134,29 @@ fn signal_windows_identity(who: ProcessIdentity) -> Result { let ticks = (u64::from(creation.dwHighDateTime) << 32) | u64::from(creation.dwLowDateTime); let started = (ticks / 10_000_000).checked_sub(11_644_473_600) .ok_or("process creation time precedes the Unix epoch")?; - // SAFETY: the owned handle stays open through the nonblocking wait. - if started != who.start_time || unsafe { WaitForSingleObject(process.as_raw_handle(), 0) } == WAIT_OBJECT_0 { + if started != who.start_time || windows_handle_has_exited(&process)? { return Ok(false); } terminate_windows_handle(&process, who) } +// A failed observation is neither a live process nor proof of exit. Keep the +// native error, rather than permitting termination after an indeterminate wait. +#[cfg(windows)] +fn windows_handle_has_exited( + process: &impl std::os::windows::io::AsRawHandle, +) -> Result { + use windows_sys::Win32::Foundation::{WAIT_FAILED, WAIT_OBJECT_0, WAIT_TIMEOUT}; + use windows_sys::Win32::System::Threading::WaitForSingleObject; + // SAFETY: caller retains the handle throughout this nonblocking wait. + match unsafe { WaitForSingleObject(process.as_raw_handle(), 0) } { + WAIT_OBJECT_0 => Ok(true), + WAIT_TIMEOUT => Ok(false), + WAIT_FAILED => Err(format!("WaitForSingleObject: {}", std::io::Error::last_os_error())), + status => Err(format!("unexpected process wait status: {status}")), + } +} + // The caller has verified creation time while holding this handle. Keep the // termination/exit race on that handle, including when signalling fails. #[cfg(windows)] diff --git a/core/continuum-service/src/resident.rs b/core/continuum-service/src/resident.rs index 52a3e787c7..1a4b390a9b 100644 --- a/core/continuum-service/src/resident.rs +++ b/core/continuum-service/src/resident.rs @@ -29,6 +29,8 @@ pub enum Refusal { PromptCapacity { required_tokens: u32, budget_tokens: u32, context_window: Option }, /// The model call faulted and its retries were spent. InferenceFailed, + /// Inference was served, but the observed task end could not be checkpointed. + ReceiptPersistenceFailed, /// She waited at the serving gate and never reached the model. LaneStarved, } @@ -329,6 +331,7 @@ impl ResidentAlarm { format!(", prompt capacity {required_tokens} > {budget_tokens}{at}") } Some(Refusal::InferenceFailed) => ", inference failed".to_string(), + Some(Refusal::ReceiptPersistenceFailed) => ", receipt persistence failed".to_string(), Some(Refusal::LaneStarved) => ", lane starved".to_string(), None => String::new(), }; diff --git a/docs/architecture/HER-TASKS.md b/docs/architecture/HER-TASKS.md index 3764b25531..ccfb2be958 100644 --- a/docs/architecture/HER-TASKS.md +++ b/docs/architecture/HER-TASKS.md @@ -115,9 +115,19 @@ once; every kind of task is only its difference. The contract as built (Codex, #5585), which this design adopts: -- **Accept, durably, before spawning.** Starting a task is fallible: acceptance is written to - the ledger (an ORM entity) first, and only an accepted task runs. A refused start is said, never - silently retried in the foreground. +- **Accept, durably, before executing the command.** Starting a task is fallible. The shared + runtime admission gate takes custody before the first storage await. The existing execution + task owns acceptance, execution and terminal persistence; the caller observes its acceptance + receipt. Dropping that observer during a write cannot abandon committed acceptance. Only after + the ledger accepts does the command execute. A refused start is said, never silently retried + in the foreground. +- **Shutdown retains that custody through terminal persistence.** The same runtime gate closes + admission and waits for accepted work before modules drain, save or stop. An observation + deadline or terminal-write failure withholds module shutdown and process exit, with an explicit + nonquiet task receipt. Cancelling an observer never reopens admission. An explicit subsequent + shutdown request rejoins the existing operation or retries its custody-withheld attempt; it + does not create a second shutdown owner. This does not yet establish restart reconciliation or + adoption: the process-incarnation and execution-kind contracts below remain required. - **One terminal outcome, first writer wins.** The ledger stores an immutable terminal receipt (output kept whole, binary and typed handles included, with its effect certainty) before any event is emitted; a late writer can neither replace it nor resurrect delivery. A handler that diff --git a/protocol/typescript/cognition/GenerateResponseAdmissionPolicy.ts b/protocol/typescript/cognition/GenerateResponseAdmissionPolicy.ts deleted file mode 100644 index 94d4506a83..0000000000 --- a/protocol/typescript/cognition/GenerateResponseAdmissionPolicy.ts +++ /dev/null @@ -1,9 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { TargetSilicon } from "./TargetSilicon"; - -/** - * Per-call local-generation admission policy. This is the contract a - * host uses to ask Rust for response-generation capacity instead of - * owning slots itself. - */ -export type GenerateResponseAdmissionPolicy = { targetSilicon: TargetSilicon, maxConcurrency: number, maxCostUnits: number, costUnits: number, leaseTtlMs: number, }; diff --git a/protocol/typescript/cognition/GenerateResponseRequest.ts b/protocol/typescript/cognition/GenerateResponseRequest.ts index d5d22853e3..12b7961ee1 100644 --- a/protocol/typescript/cognition/GenerateResponseRequest.ts +++ b/protocol/typescript/cognition/GenerateResponseRequest.ts @@ -1,6 +1,5 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { AIDecisionContext } from "./AIDecisionContext"; -import type { GenerateResponseAdmissionPolicy } from "./GenerateResponseAdmissionPolicy"; /** * IPC request: ask the cognition service to assemble a response-prompt @@ -30,11 +29,4 @@ maxTokens?: number, * Hard cap on how long PR-2's async composer waits before * returning timeout. */ -timeoutMs?: number, -/** - * Rust-owned admission policy for this generation. When omitted, - * `evaluate_response` applies the local-generation defaults above. - * Hosts that know tighter resource limits should pass them here; - * they should not coordinate slots outside Rust. - */ -admission?: GenerateResponseAdmissionPolicy, }; +timeoutMs?: number, }; diff --git a/protocol/typescript/cognition/InfraUnavailable.ts b/protocol/typescript/cognition/InfraUnavailable.ts index a2c2d0b112..09e042dc9e 100644 --- a/protocol/typescript/cognition/InfraUnavailable.ts +++ b/protocol/typescript/cognition/InfraUnavailable.ts @@ -13,7 +13,7 @@ export type InfraUnavailable = { /** * Human cause: which axis broke (not-ready / connect-refused / not-the-served-model * / compute-error / stream-idle timeout), naming the task it broke on. Display-only - * — the classification that produced it is [`SettleOutcome::inference_error`], never + * — the classification that produced it is [`SettleOutcome::failure`], never * re-parsed from this string. */ reason: string, diff --git a/protocol/typescript/cognition/ResourceAdmissionPolicy.ts b/protocol/typescript/cognition/ResourceAdmissionPolicy.ts deleted file mode 100644 index 2f9a613ace..0000000000 --- a/protocol/typescript/cognition/ResourceAdmissionPolicy.ts +++ /dev/null @@ -1,6 +0,0 @@ -// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -import type { ResourceClass } from "./ResourceClass"; -import type { TargetSilicon } from "./TargetSilicon"; -import type { ThroughputLeaseRevocationPolicy } from "./ThroughputLeaseRevocationPolicy"; - -export type ResourceAdmissionPolicy = { resourceClass: ResourceClass, targetSilicon: TargetSilicon, maxConcurrency: number, maxCostUnits: number, costUnits: number, leaseTtlMs: number, revocationPolicy: ThroughputLeaseRevocationPolicy, }; diff --git a/protocol/typescript/cognition/index.ts b/protocol/typescript/cognition/index.ts index 2728442a52..c763f2579e 100644 --- a/protocol/typescript/cognition/index.ts +++ b/protocol/typescript/cognition/index.ts @@ -58,7 +58,6 @@ export type { GatingRagMetadata } from './GatingRagMetadata'; export type { GatingRecipeStrategy } from './GatingRecipeStrategy'; export type { GatingTriggerMessage } from './GatingTriggerMessage'; export type { GenerateRecipeOrchestratorParams } from './GenerateRecipeOrchestratorParams'; -export type { GenerateResponseAdmissionPolicy } from './GenerateResponseAdmissionPolicy'; export type { GenerateResponseRequest } from './GenerateResponseRequest'; export type { GenerateResponseResult } from './GenerateResponseResult'; export type { GetStateParams } from './GetStateParams'; @@ -116,7 +115,6 @@ export type { RegisterDomainKeywordsParams } from './RegisterDomainKeywordsParam export type { RegisterDomainKeywordsResult } from './RegisterDomainKeywordsResult'; export type { ResolutionError } from './ResolutionError'; export type { ResolvedModel } from './ResolvedModel'; -export type { ResourceAdmissionPolicy } from './ResourceAdmissionPolicy'; export type { ResourceClass } from './ResourceClass'; export type { ResponseDecision } from './ResponseDecision'; export type { ResponseProposal } from './ResponseProposal'; diff --git a/protocol/typescript/grid/ResidentRefusal.ts b/protocol/typescript/grid/ResidentRefusal.ts index 3181cc2a51..b2913b7558 100644 --- a/protocol/typescript/grid/ResidentRefusal.ts +++ b/protocol/typescript/grid/ResidentRefusal.ts @@ -3,4 +3,4 @@ /** * Why a resident's turn ended without completing, or ended parked after progress. */ -export type ResidentRefusal = { "class": "prompt_capacity", required_tokens: number, budget_tokens: number, context_window: number | null, } | { "class": "inference_failed" } | { "class": "lane_starved" }; +export type ResidentRefusal = { "class": "prompt_capacity", required_tokens: number, budget_tokens: number, context_window: number | null, } | { "class": "inference_failed" } | { "class": "receipt_persistence_failed" } | { "class": "lane_starved" }; diff --git a/protocol/typescript/index.ts b/protocol/typescript/index.ts index 4fb512488a..66f325a468 100644 --- a/protocol/typescript/index.ts +++ b/protocol/typescript/index.ts @@ -47,7 +47,6 @@ export type { GatingRagContext } from './cognition'; export type { GatingRagMetadata } from './cognition'; export type { GatingRecipeStrategy } from './cognition'; export type { GatingTriggerMessage } from './cognition'; -export type { GenerateResponseAdmissionPolicy } from './cognition'; export type { GenerateResponseRequest } from './cognition'; export type { GenerateResponseResult } from './cognition'; export type { HostCapability } from './cognition'; @@ -79,7 +78,6 @@ export type { RecipeTurnBatchRequest } from './cognition'; export type { RecipeTurnTrigger } from './cognition'; export type { ResolutionError } from './cognition'; export type { ResolvedModel } from './cognition'; -export type { ResourceAdmissionPolicy } from './cognition'; export type { ResourceClass } from './cognition'; export type { ResponseDecision } from './cognition'; export type { ResponseProposal } from './cognition'; diff --git a/protocol/typescript/system/ShutdownReceipt.ts b/protocol/typescript/system/ShutdownReceipt.ts index fd3cb62f47..4b34fae2f2 100644 --- a/protocol/typescript/system/ShutdownReceipt.ts +++ b/protocol/typescript/system/ShutdownReceipt.ts @@ -1,4 +1,5 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { DrainOutcome } from "./DrainOutcome"; import type { ModuleStop } from "./ModuleStop"; /** @@ -9,4 +10,8 @@ import type { ModuleStop } from "./ModuleStop"; * 0 whether every module had saved or none had. A stop whose result only exists in the * log of the process that just exited is not a result anybody can act on. */ -export type ShutdownReceipt = { modules: Array, total_ms: number, }; +export type ShutdownReceipt = { +/** + * Background acceptance and terminal persistence must settle before modules stop. + */ +tasks: DrainOutcome, modules: Array, total_ms: number, };