Make coordinator launch atomic

This commit is contained in:
Meta Vens 2026-07-11 20:24:48 +01:00
commit 41f5a3dceb
8 changed files with 386 additions and 103 deletions

View file

@ -1,5 +1,6 @@
use crate::*;
use anyhow::{Result, anyhow};
use cultcache_rs::{CultCache, CultCacheEnvelope};
use epiphany_state_model::{EpiphanyRuntimeLink, EpiphanyThreadState};
use std::path::Path;
@ -12,6 +13,91 @@ pub struct EpiphanyCoordinatorJobLaunchPlan {
pub state_update: EpiphanyStateUpdate,
}
pub fn commit_coordinator_job_launch(
store: &Path,
thread_id: &str,
current_state: &EpiphanyThreadState,
request: &EpiphanyJobLaunchRequest,
plan: &EpiphanyCoordinatorJobLaunchPlan,
created_at: String,
) -> Result<EpiphanyJobLaunchResult> {
if let Some(persisted) = read_accepted_coordinator_state(store)?
&& persisted != *current_state
{
return Err(anyhow!(
"authoritative coordinator state changed before launch commit"
));
}
let mut cache = coordinator_acceptance_cache(store)?;
commit_coordinator_job_launch_in_cache(
&mut cache,
thread_id,
current_state,
request,
plan,
created_at,
Vec::new(),
)
}
fn commit_coordinator_job_launch_in_cache(
cache: &mut CultCache,
thread_id: &str,
current_state: &EpiphanyThreadState,
request: &EpiphanyJobLaunchRequest,
plan: &EpiphanyCoordinatorJobLaunchPlan,
created_at: String,
injected_envelopes: Vec<CultCacheEnvelope>,
) -> Result<EpiphanyJobLaunchResult> {
let next_state =
apply_coordinator_state_update_to_state(current_state, plan.state_update.clone(), None)?;
let prepared = prepare_runtime_spine_heartbeat_job(
&cache,
RuntimeSpineHeartbeatJobOptions {
runtime_id: "epiphany-local".to_string(),
display_name: "Epiphany Local".to_string(),
session_id: "epiphany-main".to_string(),
objective: plan
.planning_state
.objective
.clone()
.filter(|objective| !objective.trim().is_empty())
.unwrap_or_else(|| "Epiphany heartbeat activation".to_string()),
coordinator_note: "Native coordinator launch transaction opened this session."
.to_string(),
job_id: plan.backend_job_id.clone(),
role: request.owner_role.clone(),
binding_id: request.binding_id.clone(),
authority_scope: request.authority_scope.clone(),
instruction: request.instruction.clone(),
launch_document: request.launch_document.clone(),
output_contract_id: request.output_contract_id.clone(),
organ_launch_contract: request.organ_launch_contract.clone(),
created_at: created_at.clone(),
},
)?;
let mut batch = prepared.envelopes;
if request.binding_id == EPIPHANY_RESEARCH_ROLE_BINDING_ID {
let grant = substrate_gate_repo_access_grant_for_launch(
format!("substrate-grant-{}", plan.backend_job_id),
plan.backend_job_id.clone(),
request,
created_at,
);
batch.push(cache.prepare_entry(&grant.receipt_id, &grant)?.0);
}
let state_entry = EpiphanyThreadStateEntry::from_state(thread_id, &next_state)?;
batch.push(cache.prepare_entry(THREAD_STATE_KEY, &state_entry)?.0);
batch.extend(injected_envelopes);
cache.put_prepared_batch(batch)?;
Ok(EpiphanyJobLaunchResult {
epiphany_state: next_state,
binding_id: request.binding_id.clone(),
launcher_job_id: plan.launcher_job_id.clone(),
backend_job_id: plan.backend_job_id.clone(),
})
}
pub fn plan_coordinator_job_launch(
state: &EpiphanyThreadState,
request: &EpiphanyJobLaunchRequest,
@ -113,6 +199,17 @@ fn terminal_runtime_link_for_binding(
mod tests {
use super::*;
fn research_launch(state: &EpiphanyThreadState) -> EpiphanyJobLaunchRequest {
build_epiphany_role_launch_request(
"thread-1",
EpiphanyRoleResultRoleId::Research,
Some(state.revision),
Some(60),
state,
)
.expect("research launch request")
}
#[test]
fn stale_revision_refuses_launch_before_runtime_writes() {
let state = EpiphanyThreadState {
@ -137,4 +234,122 @@ mod tests {
.expect_err("stale launch must fail");
assert!(error.to_string().contains("revision mismatch"));
}
#[test]
fn launch_documents_state_and_grant_share_one_snapshot() -> Result<()> {
let temp = tempfile::tempdir()?;
let store = temp.path().join("launch.cc");
let state = EpiphanyThreadState::default();
let request = research_launch(&state);
let plan = plan_coordinator_job_launch(
&state,
&request,
&store,
"launcher-1".to_string(),
"backend-1".to_string(),
)?;
let result = commit_coordinator_job_launch(
&store,
"thread-1",
&state,
&request,
&plan,
"2026-07-11T00:00:00Z".to_string(),
)?;
assert_eq!(result.epiphany_state.revision, 1);
let cache = coordinator_acceptance_cache(&store)?;
assert!(
cache
.get::<EpiphanyRuntimeIdentity>(RUNTIME_IDENTITY_KEY)?
.is_some()
);
assert!(
cache
.get::<EpiphanyRuntimeSession>("epiphany-main")?
.is_some()
);
assert!(cache.get::<EpiphanyRuntimeJob>("backend-1")?.is_some());
assert!(
cache
.get::<EpiphanyRuntimeWorkerLaunchRequest>("backend-1")?
.is_some()
);
assert!(
cache
.get::<EpiphanyRuntimeEvent>("event-job-opened-backend-1")?
.is_some()
);
assert!(
cache
.get::<SubstrateGateRepoAccessGrantReceipt>("substrate-grant-backend-1")?
.is_some()
);
assert_eq!(
cache
.get_required::<EpiphanyThreadStateEntry>(THREAD_STATE_KEY)?
.state()?,
result.epiphany_state
);
Ok(())
}
#[test]
fn refused_batch_preserves_prior_snapshot_without_partial_launch() -> Result<()> {
let temp = tempfile::tempdir()?;
let store = temp.path().join("launch-refused.cc");
let state = EpiphanyThreadState::default();
let mut cache = coordinator_acceptance_cache(&store)?;
let initial = EpiphanyThreadStateEntry::from_state("thread-1", &state)?;
cache.put(THREAD_STATE_KEY, &initial)?;
let request = research_launch(&state);
let plan = plan_coordinator_job_launch(
&state,
&request,
&store,
"launcher-refused".to_string(),
"backend-refused".to_string(),
)?;
let poison = CultCacheEnvelope {
key: "injected-refusal".to_string(),
r#type: "unregistered.injected_failure".to_string(),
payload: Vec::new(),
stored_at: "2026-07-11T00:00:00Z".to_string(),
schema_id: None,
};
assert!(
commit_coordinator_job_launch_in_cache(
&mut cache,
"thread-1",
&state,
&request,
&plan,
"2026-07-11T00:00:00Z".to_string(),
vec![poison],
)
.is_err()
);
let cache = coordinator_acceptance_cache(&store)?;
assert_eq!(
cache
.get_required::<EpiphanyThreadStateEntry>(THREAD_STATE_KEY)?
.state()?,
state
);
assert!(
cache
.get::<EpiphanyRuntimeJob>("backend-refused")?
.is_none()
);
assert!(
cache
.get::<EpiphanyRuntimeWorkerLaunchRequest>("backend-refused")?
.is_none()
);
assert!(
cache
.get::<SubstrateGateRepoAccessGrantReceipt>("substrate-grant-backend-refused")?
.is_none()
);
Ok(())
}
}

View file

@ -141,6 +141,7 @@ pub use coordinator_acceptance::reorient_acceptance_claimed_effects;
pub use coordinator_acceptance::role_acceptance_claimed_effects;
pub use coordinator_acceptance::role_acceptance_enforceable_receipts;
pub use coordinator_launch::EpiphanyCoordinatorJobLaunchPlan;
pub use coordinator_launch::commit_coordinator_job_launch;
pub use coordinator_launch::plan_coordinator_job_launch;
pub use coordinator_results::EpiphanyCoordinatorReorientResultSnapshot;
pub use coordinator_results::EpiphanyCoordinatorRoleResultSnapshot;
@ -719,6 +720,7 @@ pub use runtime_spine::EpiphanyRuntimeSessionStatus;
pub use runtime_spine::EpiphanyRuntimeSpineStatus;
pub use runtime_spine::EpiphanyRuntimeWorkerLaunchRequest;
pub use runtime_spine::EpiphanyToolInvocationStatus;
pub use runtime_spine::PreparedRuntimeSpineHeartbeatJob;
pub use runtime_spine::RUNTIME_EVENT_TYPE;
pub use runtime_spine::RUNTIME_IDENTITY_KEY;
pub use runtime_spine::RUNTIME_IDENTITY_TYPE;
@ -750,6 +752,7 @@ pub use runtime_spine::ensure_runtime_session;
pub use runtime_spine::initialize_runtime_spine;
pub use runtime_spine::open_runtime_spine_heartbeat_job;
pub use runtime_spine::plan_runtime_spine_heartbeat_launch;
pub use runtime_spine::prepare_runtime_spine_heartbeat_job;
pub use runtime_spine::put_continuity_recovery_receipt;
pub use runtime_spine::put_coordinator_run_receipt;
pub use runtime_spine::put_eyes_evidence_packet;

View file

@ -64,6 +64,7 @@ use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use cultcache_rs::CultCache;
use cultcache_rs::CultCacheEnvelope;
use cultcache_rs::DatabaseEntry;
use cultcache_rs::SingleFileMessagePackBackingStore;
use cultnet_rs::CultNetDocumentMutationContract;
@ -632,6 +633,12 @@ pub struct RuntimeSpineHeartbeatJobOptions {
pub created_at: String,
}
#[derive(Clone, Debug, PartialEq)]
pub struct PreparedRuntimeSpineHeartbeatJob {
pub job: EpiphanyRuntimeJob,
pub envelopes: Vec<CultCacheEnvelope>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct RuntimeSpineHeartbeatLaunchPlanOptions {
pub binding_id: String,
@ -1050,6 +1057,136 @@ pub fn open_runtime_spine_heartbeat_job(
Ok(job)
}
pub fn prepare_runtime_spine_heartbeat_job(
cache: &CultCache,
options: RuntimeSpineHeartbeatJobOptions,
) -> Result<PreparedRuntimeSpineHeartbeatJob> {
validate_non_empty(&options.runtime_id, "runtime id")?;
validate_non_empty(&options.display_name, "display name")?;
validate_non_empty(&options.session_id, "session id")?;
validate_non_empty(&options.objective, "objective")?;
validate_non_empty(&options.job_id, "job id")?;
validate_non_empty(&options.role, "role")?;
validate_non_empty(&options.binding_id, "binding id")?;
validate_non_empty(&options.authority_scope, "authority scope")?;
validate_non_empty(&options.instruction, "instruction")?;
validate_non_empty(
options.launch_document.thread_id(),
"worker launch document thread id",
)?;
validate_non_empty(&options.output_contract_id, "output contract id")?;
if options.output_contract_id != options.launch_document.output_contract_id() {
return Err(anyhow!(
"worker launch output_contract_id must match the typed launch document"
));
}
validate_launch_organ_contract(
&options.organ_launch_contract,
&options.authority_scope,
options.launch_document.document_kind(),
&options.output_contract_id,
)?;
validate_non_empty(&options.created_at, "created at")?;
let existing_identity = cache.get::<EpiphanyRuntimeIdentity>(RUNTIME_IDENTITY_KEY)?;
let identity = EpiphanyRuntimeIdentity {
schema_version: RUNTIME_SPINE_SCHEMA_VERSION.to_string(),
runtime_id: options.runtime_id,
display_name: options.display_name,
runtime_kind: "epiphany.native".to_string(),
created_at: existing_identity
.as_ref()
.map(|value| value.created_at.clone())
.unwrap_or_else(|| options.created_at.clone()),
updated_at: options.created_at.clone(),
supported_document_types: supported_runtime_document_types(),
metadata: BTreeMap::from([("codexEvacuationBridge".to_string(), "temporary".to_string())]),
};
let session = match cache.get::<EpiphanyRuntimeSession>(&options.session_id)? {
Some(existing)
if matches!(
existing.status,
EpiphanyRuntimeSessionStatus::Completed | EpiphanyRuntimeSessionStatus::Archived
) =>
{
return Err(anyhow!(
"runtime session {:?} is terminal and cannot accept jobs",
options.session_id
));
}
Some(existing) => existing,
None => EpiphanyRuntimeSession {
schema_version: RUNTIME_SPINE_SCHEMA_VERSION.to_string(),
session_id: options.session_id.clone(),
objective: options.objective,
status: EpiphanyRuntimeSessionStatus::Active,
created_at: options.created_at.clone(),
updated_at: options.created_at.clone(),
coordinator_note: options.coordinator_note,
metadata: BTreeMap::new(),
},
};
if cache.get::<EpiphanyRuntimeJob>(&options.job_id)?.is_some() {
return Err(anyhow!("runtime job {:?} already exists", options.job_id));
}
if cache
.get::<EpiphanyRuntimeWorkerLaunchRequest>(&options.job_id)?
.is_some()
{
return Err(anyhow!(
"runtime worker launch request {:?} already exists",
options.job_id
));
}
let job = EpiphanyRuntimeJob {
schema_version: RUNTIME_SPINE_SCHEMA_VERSION.to_string(),
job_id: options.job_id.clone(),
session_id: options.session_id.clone(),
role: options.role.clone(),
status: EpiphanyRuntimeJobStatus::Queued,
created_at: options.created_at.clone(),
updated_at: options.created_at.clone(),
summary: format!(
"Heartbeat activation queued for binding {} with authority {}.",
options.binding_id, options.authority_scope
),
artifact_refs: Vec::new(),
metadata: BTreeMap::new(),
};
let event = EpiphanyRuntimeEvent {
schema_version: RUNTIME_SPINE_SCHEMA_VERSION.to_string(),
event_id: format!("event-job-opened-{}", options.job_id),
occurred_at: options.created_at,
event_type: "job.opened".to_string(),
source: "runtime-spine".to_string(),
session_id: Some(options.session_id),
job_id: Some(options.job_id.clone()),
summary: "Native runtime job opened.".to_string(),
metadata: BTreeMap::new(),
};
let request = EpiphanyRuntimeWorkerLaunchRequest {
schema_version: RUNTIME_WORKER_LAUNCH_REQUEST_SCHEMA_VERSION.to_string(),
job_id: options.job_id.clone(),
binding_id: options.binding_id,
role: options.role,
authority_scope: options.authority_scope,
instruction: options.instruction,
output_contract_id: options.output_contract_id,
document_kind: worker_launch_document_kind(&options.launch_document).to_string(),
launch_document_msgpack: encode_worker_launch_document(&options.launch_document)?,
metadata: BTreeMap::new(),
organ_launch_contract: options.organ_launch_contract,
};
let envelopes = vec![
cache.prepare_entry(RUNTIME_IDENTITY_KEY, &identity)?.0,
cache.prepare_entry(&session.session_id, &session)?.0,
cache.prepare_entry(&job.job_id, &job)?.0,
cache.prepare_entry(&event.event_id, &event)?.0,
cache.prepare_entry(&request.job_id, &request)?.0,
];
Ok(PreparedRuntimeSpineHeartbeatJob { job, envelopes })
}
pub fn runtime_job_snapshot(
store_path: impl AsRef<Path>,
job_id: &str,