From 58f277c84993629381a2f57f531a83c7c300e2ec Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 10 Aug 2026 07:13:14 +0100 Subject: [PATCH] Close coordinator runtime sessions atomically --- .../src/bin/epiphany-mvp-coordinator.rs | 6 +- epiphany-core/src/lib.rs | 1 + epiphany-core/src/runtime_spine.rs | 273 +++++++++++++++++- epiphany-core/src/runtime_store_backend.rs | 13 + notes/epiphany-current-algorithmic-map.md | 15 + notes/fresh-workspace-handoff.md | 22 ++ state/ledgers.msgpack | Bin 598858 -> 599489 bytes state/map.yaml | 4 +- vendor/cultcache-rs | 2 +- 9 files changed, 328 insertions(+), 8 deletions(-) diff --git a/epiphany-core/src/bin/epiphany-mvp-coordinator.rs b/epiphany-core/src/bin/epiphany-mvp-coordinator.rs index 1f037f42..778102b9 100644 --- a/epiphany-core/src/bin/epiphany-mvp-coordinator.rs +++ b/epiphany-core/src/bin/epiphany-mvp-coordinator.rs @@ -18,10 +18,10 @@ use epiphany_core::RuntimeSpineInitOptions; use epiphany_core::RuntimeSpineSessionOptions; use epiphany_core::append_runtime_event; use epiphany_core::create_runtime_session; +use epiphany_core::finalize_coordinator_run; use epiphany_core::hands_action_review_for_intent; use epiphany_core::initialize_runtime_spine; use epiphany_core::load_epiphany_cultmesh_swarm_brake; -use epiphany_core::put_coordinator_run_receipt; use epiphany_core::put_hands_action_intent; use epiphany_core::put_hands_action_review; use epiphany_core::put_repo_frontier_hands_authority; @@ -1043,7 +1043,6 @@ fn run_coordinator(args: &Args) -> Result { } let operator_final_status = status_cli::sanitize_for_operator(final_status); - let runtime_status = runtime_spine_status(&runtime_store)?; let final_rendered = status_cli::render_status(&operator_final_status); let operator_steps = status_cli::sanitize_for_operator(Value::Array(steps)); let artifact_manifest = vec![ @@ -1106,7 +1105,8 @@ fn run_coordinator(args: &Args) -> Result { .cloned(), resident_executable_digest: args.resident_binding.get("executable-digest").cloned(), }; - put_coordinator_run_receipt(&runtime_store, &coordinator_run_receipt)?; + finalize_coordinator_run(&runtime_store, &coordinator_run_receipt)?; + let runtime_status = runtime_spine_status(&runtime_store)?; let summary = json!({ "objective": "Coordinate the Epiphany MVP lanes through native typed state and runtime organs.", "artifactDir": artifact_dir, diff --git a/epiphany-core/src/lib.rs b/epiphany-core/src/lib.rs index 161fb240..44d3107e 100644 --- a/epiphany-core/src/lib.rs +++ b/epiphany-core/src/lib.rs @@ -1059,6 +1059,7 @@ pub use runtime_spine::create_runtime_job; pub use runtime_spine::create_runtime_session; pub use runtime_spine::ensure_runtime_repo_model; pub use runtime_spine::ensure_runtime_session; +pub use runtime_spine::finalize_coordinator_run; pub use runtime_spine::initialize_runtime_spine; pub use runtime_spine::intake_user_repo_frontier_proposal; pub use runtime_spine::migrate_legacy_repo_model_projection_obligation; diff --git a/epiphany-core/src/runtime_spine.rs b/epiphany-core/src/runtime_spine.rs index 12a5ab22..fd172dd1 100644 --- a/epiphany-core/src/runtime_spine.rs +++ b/epiphany-core/src/runtime_spine.rs @@ -9783,6 +9783,15 @@ pub fn put_coordinator_run_receipt( store_path: impl AsRef, receipt: &EpiphanyCoordinatorRunReceipt, ) -> Result<()> { + validate_coordinator_run_receipt(receipt)?; + let mut cache = runtime_spine_cache(store_path)?; + cache.pull_all_backing_stores()?; + require_identity(&cache)?; + cache.put(&receipt.receipt_id, receipt)?; + Ok(()) +} + +fn validate_coordinator_run_receipt(receipt: &EpiphanyCoordinatorRunReceipt) -> Result<()> { validate_non_empty(&receipt.receipt_id, "coordinator run receipt id")?; validate_non_empty(&receipt.session_id, "coordinator run receipt session id")?; validate_non_empty(&receipt.thread_id, "coordinator run receipt thread id")?; @@ -9793,11 +9802,114 @@ pub fn put_coordinator_run_receipt( "coordinator run receipt final action", )?; validate_non_empty(&receipt.created_at, "coordinator run receipt created at")?; + chrono::DateTime::parse_from_rfc3339(&receipt.created_at) + .map_err(|error| anyhow!("coordinator run receipt timestamp is invalid: {error}"))?; + Ok(()) +} + +pub fn finalize_coordinator_run( + store_path: impl AsRef, + receipt: &EpiphanyCoordinatorRunReceipt, +) -> Result { + finalize_coordinator_run_with_before_commit(store_path, receipt, || Ok(())) +} + +fn finalize_coordinator_run_with_before_commit( + store_path: impl AsRef, + receipt: &EpiphanyCoordinatorRunReceipt, + before_commit: F, +) -> Result +where + F: FnOnce() -> Result<()>, +{ + validate_coordinator_run_receipt(receipt)?; + let store_path = store_path.as_ref(); let mut cache = runtime_spine_cache(store_path)?; cache.pull_all_backing_stores()?; require_identity(&cache)?; - cache.put(&receipt.receipt_id, receipt)?; - Ok(()) + let mut session = cache + .get::(&receipt.session_id)? + .ok_or_else(|| { + anyhow!( + "coordinator run receipt session {:?} does not exist", + receipt.session_id + ) + })?; + let completion_event_id = format!("event-session-completed-{}", receipt.session_id); + let completion_summary = format!( + "Coordinator run {:?} terminalized with status {:?}.", + receipt.receipt_id, receipt.status + ); + let expected_event = EpiphanyRuntimeEvent { + schema_version: RUNTIME_SPINE_SCHEMA_VERSION.to_string(), + event_id: completion_event_id.clone(), + occurred_at: receipt.created_at.clone(), + event_type: "session.completed".to_string(), + source: "epiphany-mvp-coordinator".to_string(), + session_id: Some(receipt.session_id.clone()), + job_id: None, + summary: completion_summary.clone(), + metadata: BTreeMap::new(), + }; + if session.status == EpiphanyRuntimeSessionStatus::Completed { + let existing_receipt = cache.get::(&receipt.receipt_id)?; + let existing_event = cache.get::(&completion_event_id)?; + if existing_receipt.as_ref() == Some(receipt) + && existing_event.as_ref() == Some(&expected_event) + && session.updated_at == receipt.created_at + && session.coordinator_note == completion_summary + { + return Ok(session); + } + return Err(anyhow!( + "completed coordinator session does not match the terminal run transaction" + )); + } + if session.status != EpiphanyRuntimeSessionStatus::Active { + return Err(anyhow!( + "coordinator run session {:?} is not active", + receipt.session_id + )); + } + if cache + .get_all::()? + .iter() + .any(|job| job.session_id == receipt.session_id) + { + return Err(anyhow!( + "coordinator run finalization refuses a session with runtime jobs" + )); + } + if cache + .get_all::()? + .iter() + .any(|existing| existing.session_id == receipt.session_id) + || cache + .get::(&completion_event_id)? + .is_some() + { + return Err(anyhow!( + "coordinator run session already has partial terminal authority" + )); + } + let snapshot = cache.snapshot_envelopes(); + session.status = EpiphanyRuntimeSessionStatus::Completed; + session.updated_at = receipt.created_at.clone(); + session.coordinator_note = completion_summary; + let replacements = vec![ + cache.prepare_entry(&session.session_id, &session)?.0, + cache.prepare_entry(&receipt.receipt_id, receipt)?.0, + cache.prepare_entry(&completion_event_id, &expected_event)?.0, + ]; + before_commit()?; + if !runtime_spine_backing_store(store_path)? + .replace_and_append_if_snapshot_unchanged(&snapshot, replacements)? + { + return Err(anyhow!( + "coordinator run finalization lost its full snapshot fence" + )); + } + Ok(session) } pub fn coordinator_run_receipts( @@ -15239,6 +15351,163 @@ pub(crate) mod tests { Ok(()) } + #[test] + fn coordinator_run_finalization_is_atomic_idempotent_and_snapshot_fenced() -> Result<()> { + let temp = tempdir()?; + let store = temp.path().join("runtime.msgpack"); + initialize_runtime_spine( + &store, + RuntimeSpineInitOptions { + runtime_id: "epiphany-coordinator-finalization-test".to_string(), + display_name: "Epiphany Coordinator Finalization Test".to_string(), + created_at: "2026-08-10T08:00:00Z".to_string(), + }, + )?; + let receipt_for = |session_id: &str, receipt_id: &str, thread_id: &str| { + EpiphanyCoordinatorRunReceipt { + schema_version: COORDINATOR_RUN_RECEIPT_SCHEMA_VERSION.to_string(), + receipt_id: receipt_id.to_string(), + session_id: session_id.to_string(), + thread_id: thread_id.to_string(), + mode: "default".to_string(), + status: "completed".to_string(), + final_action: "manualRegather".to_string(), + final_reason: None, + step_count: 1, + created_at: "2026-08-10T08:01:00Z".to_string(), + model_provider: None, + runtime_store: store.display().to_string(), + artifact_refs: Vec::new(), + sealed_artifact_refs: Vec::new(), + metadata: BTreeMap::new(), + resident_grant_id: None, + resident_launch_digest: None, + resident_policy_digest: None, + resident_argv_digest: None, + resident_objective_digest: None, + resident_release_commit: None, + resident_release_manifest_digest: None, + resident_executable_digest: None, + } + }; + let create_coordinator_session = |session_id: &str| -> Result<()> { + create_runtime_session( + &store, + RuntimeSpineSessionOptions { + session_id: session_id.to_string(), + objective: "Coordinate one terminal run.".to_string(), + created_at: "2026-08-10T08:00:01Z".to_string(), + coordinator_note: "Native coordinator session opened.".to_string(), + }, + )?; + append_runtime_event( + &store, + RuntimeSpineEventOptions { + event_id: format!("event-coordinator-started-{session_id}"), + occurred_at: "2026-08-10T08:00:01Z".to_string(), + event_type: "coordinator.started".to_string(), + source: "epiphany-mvp-coordinator".to_string(), + session_id: Some(session_id.to_string()), + job_id: None, + summary: "Native coordinator session opened.".to_string(), + }, + )?; + Ok(()) + }; + + create_coordinator_session("coordinator-thread-1")?; + let receipt = receipt_for( + "coordinator-thread-1", + "coordinator-receipt-1", + "thread-1", + ); + let completed = finalize_coordinator_run(&store, &receipt)?; + assert_eq!(completed.status, EpiphanyRuntimeSessionStatus::Completed); + assert_eq!(finalize_coordinator_run(&store, &receipt)?, completed); + let status = runtime_spine_status(&store)?; + assert_eq!(status.sessions, 1); + assert_eq!(status.active_sessions, 0); + let mut cache = runtime_spine_cache(&store)?; + cache.pull_all_backing_stores()?; + assert_eq!( + cache.get::(&receipt.receipt_id)?, + Some(receipt.clone()) + ); + assert_eq!( + cache + .get::( + "event-session-completed-coordinator-thread-1" + )? + .as_ref() + .map(|event| event.source.as_str()), + Some("epiphany-mvp-coordinator") + ); + + create_coordinator_session("coordinator-thread-jobs")?; + create_runtime_job( + &store, + RuntimeSpineJobOptions { + job_id: "coordinator-job".to_string(), + session_id: "coordinator-thread-jobs".to_string(), + role: "unexpected".to_string(), + created_at: "2026-08-10T08:00:02Z".to_string(), + summary: "Must block coordinator finalization.".to_string(), + artifact_refs: Vec::new(), + }, + )?; + let job_receipt = receipt_for( + "coordinator-thread-jobs", + "coordinator-receipt-jobs", + "thread-jobs", + ); + assert!(finalize_coordinator_run(&store, &job_receipt).is_err()); + + create_coordinator_session("coordinator-thread-race")?; + let raced_receipt = receipt_for( + "coordinator-thread-race", + "coordinator-receipt-race", + "thread-race", + ); + let race = finalize_coordinator_run_with_before_commit(&store, &raced_receipt, || { + append_runtime_event( + &store, + RuntimeSpineEventOptions { + event_id: "unrelated-racing-event".to_string(), + occurred_at: "2026-08-10T08:00:59Z".to_string(), + event_type: "unrelated".to_string(), + source: "test".to_string(), + session_id: None, + job_id: None, + summary: "Changes the full snapshot.".to_string(), + }, + )?; + Ok(()) + }); + assert!(race.is_err()); + let mut cache = runtime_spine_cache(&store)?; + cache.pull_all_backing_stores()?; + assert_eq!( + cache + .get::("coordinator-thread-race")? + .expect("raced session") + .status, + EpiphanyRuntimeSessionStatus::Active + ); + assert!( + cache + .get::(&raced_receipt.receipt_id)? + .is_none() + ); + assert!( + cache + .get::( + "event-session-completed-coordinator-thread-race" + )? + .is_none() + ); + Ok(()) + } + #[test] fn coordinator_run_receipt_retention_preserves_authority_and_cannot_resurrect_work() -> Result<()> { diff --git a/epiphany-core/src/runtime_store_backend.rs b/epiphany-core/src/runtime_store_backend.rs index bbb99c6c..b6138d9d 100644 --- a/epiphany-core/src/runtime_store_backend.rs +++ b/epiphany-core/src/runtime_store_backend.rs @@ -75,6 +75,19 @@ impl RuntimeSpineBackingStore { ), } } + + pub(crate) fn replace_and_append_if_snapshot_unchanged( + &self, + expected_snapshot: &[CultCacheEnvelope], + replacements: Vec, + ) -> Result { + match self.selected()? { + SelectedBackingStore::Snapshot(store) => store + .replace_and_append_if_snapshot_unchanged(expected_snapshot, replacements), + SelectedBackingStore::Keyed(store) => store + .replace_and_append_if_snapshot_unchanged(expected_snapshot, replacements), + } + } } impl CacheBackingStore for RuntimeSpineBackingStore { diff --git a/notes/epiphany-current-algorithmic-map.md b/notes/epiphany-current-algorithmic-map.md index 4175a9c4..8895b13f 100644 --- a/notes/epiphany-current-algorithmic-map.md +++ b/notes/epiphany-current-algorithmic-map.md @@ -2765,6 +2765,21 @@ Authority map for the cut: package proof that terminal coordinator sessions plateau without changing resident authority. +The first owner cut is implemented. `finalize_coordinator_run` validates the +exact active jobless session and absence of partial terminal authority, then +uses CultCache's full-snapshot-fenced replace-and-append transaction to persist +the receipt, Completed session, and deterministic completion event together. +Exact replay returns the same terminal session; a changed snapshot, a session +job, partial prior receipt/event, or non-Active state refuses every write. The +coordinator now derives runtime status after this transaction. CultCache exact +`e1fc4c0` owns the new primitive for snapshot, keyed, and owned-keyed stores; +its hostile concurrency test proves an unknown row invalidates the transaction. +The full core library passes 647 tests with one intentional ignored helper. + +Legacy repair and completed coordinator-family archival remain deliberately +separate follow-up work. The source still must not let generic receipt retention +delete a receipt while its runtime session survives. + ### Semantic logical lifecycle implementation `retain_memory_semantic_projection_lifecycles` now realizes the safe unattempted diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 43e10902..eab2aad2 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -1948,3 +1948,25 @@ refusals or infer terminality from age. Next: implement the owner cut with hostile CAS/replay/legacy tests, then package and prove copied-state plateau. Preserve active c005. Yggdrasil never builds. + +## Atomic coordinator terminalization implemented — 2026-08-10 + +`finalize_coordinator_run` now commits the immutable coordinator receipt, +Completed runtime session, and deterministic `session.completed` event as one +full-snapshot-fenced transaction. Exact replay is idempotent. A concurrent +unknown row, any session job, partial terminal receipt/event, or non-Active +session refuses the complete write. `epiphany-mvp-coordinator` uses this owner +and records post-terminal runtime status. + +The first attempted implementation exposed a real CultCache gap: scoped CAS +could not fence unknown identities, while the compaction primitive required a +deletion. No dummy deletion was added. CultCache exact `e1fc4c0` introduces +`replace_and_append_if_snapshot_unchanged` for snapshot, keyed, and owned-keyed +stores, with a hostile concurrent-row test. All 38 CultCache tests and the full +Epiphany core library (647 passed, one ignored) are green; the coordinator +release target checks with `coordinator-runtime` enabled. + +Next: repair only exact legacy false-Active coordinator sessions, archive the +whole completed coordinator family under one owner, and make generic receipt +retention preserve receipts still bound to runtime sessions. This source is not +yet packaged. Active c005 remains untouched; Yggdrasil never builds. diff --git a/state/ledgers.msgpack b/state/ledgers.msgpack index 3975872acaad9eb14bcbfa58e5bae751c9b9184f..3f63332127ca4a09216928b3528eea1d4e6a0a02 100644 GIT binary patch delta 621 zcmY+Bv2GJV5QaGi5?s(wP=Pc8cleyM6PYNfA{U6Bism%go3l6G+uiKWVoZSx3SI!q z9R*K-gb<>nNdYg#oFhx2__cdG`~UOJ-kqPwDdqJ7bU=>E@jr~3mQe*QHoM&rCV$%n=3qRrY|9qd0|bzYvc zYqSF8T&T1~b^(||BU_{2BWq_tH{MV~mZ=&*eN&GLY<7sqeUNQj`NzVqA1oT zFz*z!4wNk3i{`$uVQO6iKmDD#YGZr#3);3RNYM;u)2*e