Close coordinator runtime sessions atomically

This commit is contained in:
Meta Vens 2026-08-10 07:13:14 +01:00
commit 58f277c849
9 changed files with 328 additions and 8 deletions

View file

@ -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<Value> {
}
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<Value> {
.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,

View file

@ -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;

View file

@ -9783,6 +9783,15 @@ pub fn put_coordinator_run_receipt(
store_path: impl AsRef<Path>,
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<Path>,
receipt: &EpiphanyCoordinatorRunReceipt,
) -> Result<EpiphanyRuntimeSession> {
finalize_coordinator_run_with_before_commit(store_path, receipt, || Ok(()))
}
fn finalize_coordinator_run_with_before_commit<F>(
store_path: impl AsRef<Path>,
receipt: &EpiphanyCoordinatorRunReceipt,
before_commit: F,
) -> Result<EpiphanyRuntimeSession>
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::<EpiphanyRuntimeSession>(&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::<EpiphanyCoordinatorRunReceipt>(&receipt.receipt_id)?;
let existing_event = cache.get::<EpiphanyRuntimeEvent>(&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::<EpiphanyRuntimeJob>()?
.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::<EpiphanyCoordinatorRunReceipt>()?
.iter()
.any(|existing| existing.session_id == receipt.session_id)
|| cache
.get::<EpiphanyRuntimeEvent>(&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::<EpiphanyCoordinatorRunReceipt>(&receipt.receipt_id)?,
Some(receipt.clone())
);
assert_eq!(
cache
.get::<EpiphanyRuntimeEvent>(
"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::<EpiphanyRuntimeSession>("coordinator-thread-race")?
.expect("raced session")
.status,
EpiphanyRuntimeSessionStatus::Active
);
assert!(
cache
.get::<EpiphanyCoordinatorRunReceipt>(&raced_receipt.receipt_id)?
.is_none()
);
assert!(
cache
.get::<EpiphanyRuntimeEvent>(
"event-session-completed-coordinator-thread-race"
)?
.is_none()
);
Ok(())
}
#[test]
fn coordinator_run_receipt_retention_preserves_authority_and_cannot_resurrect_work()
-> Result<()> {

View file

@ -75,6 +75,19 @@ impl RuntimeSpineBackingStore {
),
}
}
pub(crate) fn replace_and_append_if_snapshot_unchanged(
&self,
expected_snapshot: &[CultCacheEnvelope],
replacements: Vec<CultCacheEnvelope>,
) -> Result<bool> {
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 {

View file

@ -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

View file

@ -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.

Binary file not shown.

View file

@ -36,7 +36,7 @@ invariants:
current_status:
summary: Epiphany is a supervised engineering alpha on Starfire, not deployment-ready. Exact b8138a6b active-child SIGTERM and restart, exact 9f369528 deterministic warm packaging, exact c930f505 cross-container ownership, exact ed15f83a resident lifecycle retention, exact 16c4b19f coordinator receipt and Heartbeat artifact retention, exact cce2b8ac narrow model-generation retention, exact eea15e82 model-turn JSON ingress, exact b1e8c89a semantic unattempted-generation retention, exact 6bc3ec3f semantic physical-epoch retirement, and exact 44230a05 Persona conversation retention are proven. Gamecult-ops 059821f owns Yggdrasil stream retention and exact 6ee08a4 owns stable Starfire Persona-permit firewall ingress. Exact 16c4b19f genuine idle and exact a987d2f7 active cognition completed 900-pulse bounded plateaus. Runtime-owned typed fulfillment is accepted live under exact 6dd9b132. Yggdrasil is the small public crossing body, never the release forge.
latest_phase: Runtime-history mapping found the remaining live growth fault: exact model-adapter sessions are already fully archived, but native coordinator sessions write terminal receipts without closing their runtime session and remain falsely Active forever. The next cut atomically owns receipt plus session completion plus completion event, then lets one coordinator-session archive own the whole old family. Generic receipt retention must preserve receipts still named by runtime sessions.
latest_phase: Native coordinator terminalization now uses one runtime-spine full-snapshot transaction for the immutable run receipt, Completed session, and deterministic completion event. CultCache e1fc4c0 adds the required replace-and-append snapshot primitive across snapshot, keyed, and owned-keyed stores; hostile concurrent rows refuse the whole mutation. The coordinator binary uses the transaction and reports post-terminal runtime status. Completed coordinator-session archival and legacy false-Active repair remain next.
operational_state:
local_worktree: persona_conversation_retention_accepted_clean
operator_wireguard: restored
@ -70,7 +70,7 @@ current_status:
yggdrasil_epiphany_service_contract: repaired_in_gamecult_ops_812b427_not_installed
resident_physiology: authenticated_9b8df0b4_c005_bound_to_eyes_tools_nervous_system_with_217dd_and_bd96305e_helpers_running
unresolved_authority: Coordinator receipt, Heartbeat pulse-artifact, deployed supervisor/projector log retention, genuine-idle and active resource plateaus, exact-grant terminality, restart-persistent cooldown refusal, schedule/action issuance cardinality, runtime-owned typed fulfillment, narrow model-generation retention, published model-turn JSON ingress, semantic logical/physical retention, Persona conversation retention, stable Starfire firewall ownership, and completed model-adapter session archival are accepted. Native coordinator sessions remain falsely Active after a terminal receipt and therefore cannot retire. Historical migrated semantic attempts without recorded physical namespace remain durable and non-retirable. Repository Body observation still performs two authenticated full-tree Git index/manifest passes. Execute-mode workers require a persistent process body. Keyed storage has not earned live migration. One completed Discord consequence remains blocked by the absent Yggdrasil credential.
next_action: Implement atomic coordinator receipt/session closure and single-owner completed coordinator-session archival with hostile replay, CAS, legacy repair, and non-resurrection tests. Preserve active c005 and exact prior receipts. Yggdrasil never builds.
next_action: Implement single-owner completed coordinator-session archival plus exact legacy false-Active repair; make generic receipt retention preserve every receipt still bound to a runtime session. Then prove non-resurrection and bounded plateau. Preserve active c005 and exact prior receipts. Yggdrasil never builds.
active_subgoals:
- Prove Persona, Self, Eyes, Modeling, Imagination, Hands, Soul, Mind, Continuity, and nervous-system behavior individually.

2
vendor/cultcache-rs vendored

@ -1 +1 @@
Subproject commit 9cae27799232db29b33ef19fabafffcce1a996e1
Subproject commit e1fc4c05a04e3fa31965892a3febc30097d19d82