use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use arc_swap::ArcSwap;
use crate::lifecycle_identity::{
AuthorityIdentity, GenerationAuthority, ObserverToken, OperationKind, OperationReceipt,
PublicationIdentity, RetryAdvice, SourceRefusal, SourceRefusalKind,
};
#[cfg(all(test, feature = "server"))]
use crate::lifecycle_identity::GenerationIdentity;
use super::registry::ProjectKey;
#[derive(Debug)]
pub struct DarkRuntimeFactory {
root: String,
}
impl DarkRuntimeFactory {
#[cfg(all(test, feature = "server"))]
pub fn for_test_root(root: &str) -> Self {
Self {
root: root.to_string(),
}
}
pub fn project_runtime(&self, key: ProjectKey) -> ProjectIndexRuntime {
ProjectIndexRuntime {
root: self.root.clone(),
_key: key,
next_source: AtomicU64::new(1),
sources: Mutex::new(HashMap::new()),
publication: ProjectPublicationRoot {
inner: ArcSwap::new(Arc::new(ProjectRuntimePublication {
publication_identity: PublicationIdentity::fresh(),
sources: HashMap::new(),
})),
},
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SourceRuntimePhase {
Loading,
Current,
Refreshing,
Blocked,
Stopping,
Stopped,
}
#[derive(Debug)]
#[cfg_attr(not(test), allow(dead_code))]
enum SourceRuntimeState {
Loading,
Current {
generation: Arc<VerifiedGeneration>,
},
Refreshing {
retained: Arc<VerifiedGeneration>,
permit_issued: bool,
},
Blocked {
_retained: Option<Arc<VerifiedGeneration>>,
},
Stopping {
_retained: Option<Arc<VerifiedGeneration>>,
},
}
#[derive(Debug)]
struct SourceEntry {
state: SourceRuntimeState,
tombstoned: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct DarkSourceHandle(u64);
#[derive(Debug)]
pub struct VerifiedGeneration {
generation_authority: Arc<GenerationAuthority>,
complete: bool,
}
impl VerifiedGeneration {
pub fn identity(&self) -> AuthorityIdentity {
self.generation_authority.identity()
}
pub fn scope_certificate_is_complete(&self) -> bool {
self.complete
}
pub fn generation_authority(&self) -> Arc<GenerationAuthority> {
Arc::clone(&self.generation_authority)
}
}
#[derive(Debug)]
pub struct StrictLease {
generation: Arc<VerifiedGeneration>,
}
impl StrictLease {
pub fn generation(&self) -> Arc<VerifiedGeneration> {
Arc::clone(&self.generation)
}
}
#[derive(Debug)]
pub struct ProjectPublicationRoot {
inner: ArcSwap<ProjectRuntimePublication>,
}
impl ProjectPublicationRoot {
pub fn load(&self) -> Arc<ProjectRuntimePublication> {
self.inner.load_full()
}
}
#[derive(Debug)]
pub struct ProjectRuntimePublication {
publication_identity: PublicationIdentity,
sources: HashMap<u64, Arc<SourceStatePublication>>,
}
impl ProjectRuntimePublication {
pub fn publication_identity(&self) -> PublicationIdentity {
self.publication_identity
}
pub fn source_publication(
&self,
source: &DarkSourceHandle,
) -> Option<Arc<SourceStatePublication>> {
self.sources.get(&source.0).cloned()
}
}
#[derive(Debug)]
pub struct SourceStatePublication {
phase: SourceRuntimePhase,
}
impl SourceStatePublication {
pub fn phase(&self) -> SourceRuntimePhase {
self.phase
}
}
#[derive(Debug)]
pub struct SourceView {
publication_identity: PublicationIdentity,
observer_token: Option<ObserverToken>,
}
impl SourceView {
pub fn publication_identity(&self) -> PublicationIdentity {
self.publication_identity
}
pub fn observer_token(&self) -> Option<ObserverToken> {
self.observer_token
}
}
#[derive(Debug)]
pub struct DarkMutationPermit {
_sealed: (),
}
impl DarkMutationPermit {
#[cfg(all(test, feature = "server"))]
pub fn rollback_with_no_side_effect_proof_for_test(self) {}
}
#[derive(Debug)]
pub struct DarkShutdownReceipt {
_sealed: (),
}
impl DarkShutdownReceipt {
#[cfg(all(test, feature = "server"))]
pub fn wait_for_test(self) -> Result<DarkShutdownReport, SourceRefusal> {
Ok(DarkShutdownReport { joined_workers: 0 })
}
}
#[derive(Debug)]
pub struct DarkShutdownReport {
joined_workers: u64,
}
impl DarkShutdownReport {
pub fn joined_workers(&self) -> u64 {
self.joined_workers
}
}
#[derive(Debug)]
pub struct ProjectIndexRuntime {
#[cfg_attr(not(test), allow(dead_code))]
root: String,
_key: ProjectKey,
#[cfg_attr(not(test), allow(dead_code))]
next_source: AtomicU64,
sources: Mutex<HashMap<u64, SourceEntry>>,
publication: ProjectPublicationRoot,
}
impl ProjectIndexRuntime {
pub fn publication_root(&self) -> &ProjectPublicationRoot {
&self.publication
}
#[cfg(all(test, feature = "server"))]
pub fn admit_loading_source_for_test(&self, _name: &str) -> DarkSourceHandle {
self.insert_source(SourceRuntimeState::Loading)
}
#[cfg(all(test, feature = "server"))]
pub fn admit_current_source_for_test(&self, _name: &str) -> DarkSourceHandle {
let generation = Arc::new(VerifiedGeneration {
generation_authority: Arc::new(GenerationAuthority::captured(
AuthorityIdentity::fresh(),
GenerationIdentity::fresh(),
self.root.clone(),
)),
complete: true,
});
self.insert_source(SourceRuntimeState::Current { generation })
}
#[cfg(all(test, feature = "server"))]
pub fn begin_reload_refresh_for_test(&self, source: &DarkSourceHandle) {
self.transition(source, |state| match state {
SourceRuntimeState::Current { generation } => SourceRuntimeState::Refreshing {
retained: generation,
permit_issued: false,
},
other => other,
});
}
#[cfg(all(test, feature = "server"))]
pub fn grant_mutation_permit_for_test(
&self,
source: &DarkSourceHandle,
) -> Result<DarkMutationPermit, SourceRefusal> {
let mut granted = false;
self.transition(source, |state| match state {
SourceRuntimeState::Refreshing { retained, .. } => {
granted = true;
SourceRuntimeState::Refreshing {
retained,
permit_issued: true,
}
}
other => other,
});
if granted {
Ok(DarkMutationPermit { _sealed: () })
} else {
Err(self.refusal(OperationKind::RefreshSource, None))
}
}
#[cfg(all(test, feature = "server"))]
pub fn block_source_for_test(&self, source: &DarkSourceHandle) {
self.transition(source, |state| {
let retained = retained_of(state);
SourceRuntimeState::Blocked {
_retained: retained,
}
});
}
#[cfg(all(test, feature = "server"))]
pub fn stop_source_for_test(&self, source: &DarkSourceHandle) {
self.transition(source, |state| {
let retained = retained_of(state);
SourceRuntimeState::Stopping {
_retained: retained,
}
});
}
#[cfg(all(test, feature = "server"))]
pub fn complete_stop_for_test(&self, source: &DarkSourceHandle) {
let mut sources = self.sources.lock().expect("runtime lock");
if let Some(entry) = sources.get_mut(&source.0) {
entry.tombstoned = true;
}
drop(sources);
self.republish(Some(source.0));
}
pub fn acquire_strict(&self, source: &DarkSourceHandle) -> Result<StrictLease, SourceRefusal> {
let sources = self.sources.lock().expect("runtime lock");
let Some(entry) = sources.get(&source.0) else {
return Err(self.refusal(OperationKind::AcquireRuntime, None));
};
if entry.tombstoned {
return Err(self.refusal(OperationKind::AcquireRuntime, None));
}
match &entry.state {
SourceRuntimeState::Current { generation } => Ok(StrictLease {
generation: Arc::clone(generation),
}),
SourceRuntimeState::Refreshing {
retained,
permit_issued: false,
} => Ok(StrictLease {
generation: Arc::clone(retained),
}),
SourceRuntimeState::Refreshing {
retained,
permit_issued: true,
} => Err(self.refusal(OperationKind::AcquireRuntime, Some(retained.identity()))),
SourceRuntimeState::Loading
| SourceRuntimeState::Blocked { .. }
| SourceRuntimeState::Stopping { .. } => {
Err(self.refusal(OperationKind::AcquireRuntime, None))
}
}
}
pub fn source_phase(&self, source: &DarkSourceHandle) -> SourceRuntimePhase {
let sources = self.sources.lock().expect("runtime lock");
let Some(entry) = sources.get(&source.0) else {
return SourceRuntimePhase::Stopped;
};
if entry.tombstoned {
return SourceRuntimePhase::Stopped;
}
match &entry.state {
SourceRuntimeState::Loading => SourceRuntimePhase::Loading,
SourceRuntimeState::Current { .. } => SourceRuntimePhase::Current,
SourceRuntimeState::Refreshing { .. } => SourceRuntimePhase::Refreshing,
SourceRuntimeState::Blocked { .. } => SourceRuntimePhase::Blocked,
SourceRuntimeState::Stopping { .. } => SourceRuntimePhase::Stopping,
}
}
pub fn capture_source_view(
&self,
source: &DarkSourceHandle,
) -> Result<SourceView, SourceRefusal> {
let first = self.publication.load();
if first.source_publication(source).is_none() {
return Err(self.refusal(OperationKind::AcquireRuntime, None));
}
let revalidated = self.publication.load();
if revalidated.publication_identity() != first.publication_identity() {
return Err(self.refusal(OperationKind::AcquireRuntime, None));
}
Ok(SourceView {
publication_identity: revalidated.publication_identity(),
observer_token: None,
})
}
#[cfg(all(test, feature = "server"))]
pub fn begin_shutdown_for_test(&self) -> DarkShutdownReceipt {
DarkShutdownReceipt { _sealed: () }
}
#[cfg_attr(not(test), allow(dead_code))]
fn insert_source(&self, state: SourceRuntimeState) -> DarkSourceHandle {
let id = self.next_source.fetch_add(1, Ordering::Relaxed);
self.sources.lock().expect("runtime lock").insert(
id,
SourceEntry {
state,
tombstoned: false,
},
);
self.republish(Some(id));
DarkSourceHandle(id)
}
#[cfg_attr(not(test), allow(dead_code))]
fn transition(
&self,
source: &DarkSourceHandle,
apply: impl FnOnce(SourceRuntimeState) -> SourceRuntimeState,
) {
let mut sources = self.sources.lock().expect("runtime lock");
if let Some(entry) = sources.remove(&source.0) {
let next = apply(entry.state);
sources.insert(
source.0,
SourceEntry {
state: next,
tombstoned: entry.tombstoned,
},
);
}
drop(sources);
self.republish(Some(source.0));
}
#[cfg_attr(not(test), allow(dead_code))]
fn republish(&self, changed: Option<u64>) {
let sources = self.sources.lock().expect("runtime lock");
let previous = self.publication.load();
let mut published: HashMap<u64, Arc<SourceStatePublication>> = HashMap::new();
for (id, entry) in sources.iter() {
let phase = if entry.tombstoned {
SourceRuntimePhase::Stopped
} else {
match &entry.state {
SourceRuntimeState::Loading => SourceRuntimePhase::Loading,
SourceRuntimeState::Current { .. } => SourceRuntimePhase::Current,
SourceRuntimeState::Refreshing { .. } => SourceRuntimePhase::Refreshing,
SourceRuntimeState::Blocked { .. } => SourceRuntimePhase::Blocked,
SourceRuntimeState::Stopping { .. } => SourceRuntimePhase::Stopping,
}
};
let record = match (changed, previous.sources.get(id)) {
(Some(changed_id), Some(existing)) if *id != changed_id => Arc::clone(existing),
(_, Some(existing)) if existing.phase == phase => Arc::clone(existing),
_ => Arc::new(SourceStatePublication { phase }),
};
published.insert(*id, record);
}
self.publication
.inner
.store(Arc::new(ProjectRuntimePublication {
publication_identity: PublicationIdentity::fresh(),
sources: published,
}));
}
fn refusal(&self, kind: OperationKind, evidence: Option<AuthorityIdentity>) -> SourceRefusal {
SourceRefusal::for_runtime(
SourceRefusalKind::SourceUnavailable,
OperationReceipt::for_dark_refusal(kind),
RetryAdvice::OnEvent,
evidence,
)
}
}
#[cfg_attr(not(test), allow(dead_code))]
fn retained_of(state: SourceRuntimeState) -> Option<Arc<VerifiedGeneration>> {
match state {
SourceRuntimeState::Current { generation } => Some(generation),
SourceRuntimeState::Refreshing { retained, .. } => Some(retained),
SourceRuntimeState::Blocked { _retained } => _retained,
SourceRuntimeState::Stopping { _retained } => _retained,
SourceRuntimeState::Loading => None,
}
}
#[cfg(all(test, feature = "server"))]
mod dark_runtime_oracles {
use std::sync::Arc;
use super::super::embedded::{EmbeddedSourceFactory, ReceiptWaitError};
use super::super::public_api::{
EmbeddedSourceSpec, ProcessRuntimeApi, SourceRuntimePhase as PublicSourceRuntimePhase,
};
use super::super::registry::ProjectKey;
use super::{DarkRuntimeFactory, ProjectIndexRuntime, SourceRuntimePhase};
use crate::protocol::format::claim_provenance::SourceRefusalKind;
fn a_project_key(name: &str) -> ProjectKey {
ProjectKey::new(name)
}
fn a_dark_runtime(root: &str) -> ProjectIndexRuntime {
DarkRuntimeFactory::for_test_root(root).project_runtime(a_project_key("project-a"))
}
#[test]
fn loading_blocked_stopping_refuse_strict_acquisition() {
let runtime = a_dark_runtime("root-a");
let source = runtime.admit_loading_source_for_test("src-a");
let refusal = runtime
.acquire_strict(&source)
.expect_err("Loading retains nothing and must refuse strict acquisition");
assert_eq!(refusal.kind(), SourceRefusalKind::SourceUnavailable);
runtime.block_source_for_test(&source);
let refusal = runtime
.acquire_strict(&source)
.expect_err("Blocked retentions are recovery evidence, never a lane");
assert_eq!(refusal.kind(), SourceRefusalKind::SourceUnavailable);
runtime.stop_source_for_test(&source);
let refusal = runtime
.acquire_strict(&source)
.expect_err("Stopping retentions are accounting, never a lane");
assert_eq!(refusal.kind(), SourceRefusalKind::SourceUnavailable);
let current = runtime.admit_current_source_for_test("src-b");
let lease = runtime
.acquire_strict(¤t)
.expect("a COMPLETE verified generation is the one acquirable thing");
assert!(lease.generation().scope_certificate_is_complete());
}
#[test]
fn refreshing_serves_retained_only_until_a_permit_is_granted() {
let runtime = a_dark_runtime("root-a");
let source = runtime.admit_current_source_for_test("src-a");
let retained = runtime
.acquire_strict(&source)
.expect("current is acquirable")
.generation()
.identity();
runtime.begin_reload_refresh_for_test(&source);
let lease = runtime
.acquire_strict(&source)
.expect("a reload-entered Refreshing keeps serving its retention");
assert_eq!(
lease.generation().identity(),
retained,
"the retention is the SAME complete generation, not a rebuild"
);
let _permit = runtime
.grant_mutation_permit_for_test(&source)
.expect("the refresh may issue its permit");
let refusal = runtime
.acquire_strict(&source)
.expect_err("the moment a permit exists, the retention stops being a lane");
assert_eq!(refusal.kind(), SourceRefusalKind::SourceUnavailable);
}
#[test]
fn permit_grant_is_itself_a_publication() {
let runtime = a_dark_runtime("root-a");
let source = runtime.admit_current_source_for_test("src-a");
runtime.begin_reload_refresh_for_test(&source);
let before = runtime.publication_root().load().publication_identity();
let permit = runtime
.grant_mutation_permit_for_test(&source)
.expect("grant");
let after = runtime.publication_root().load().publication_identity();
assert_ne!(
before, after,
"the grant must PUBLISH — a grant that only flips side-band state \
leaves the publication identity unchanged and fails here"
);
assert!(
runtime.acquire_strict(&source).is_err(),
"after the published grant the retention stops being a lane"
);
let _ends_without_committing = permit;
}
#[test]
fn no_terminal_permit_path_restores_prior_current() {
let runtime = a_dark_runtime("root-a");
let source = runtime.admit_current_source_for_test("src-a");
runtime.begin_reload_refresh_for_test(&source);
let permit = runtime
.grant_mutation_permit_for_test(&source)
.expect("grant");
let _ = permit;
assert!(
runtime.acquire_strict(&source).is_err(),
"a dropped permit must not restore the prior publication"
);
let source_b = runtime.admit_current_source_for_test("src-b");
runtime.begin_reload_refresh_for_test(&source_b);
let permit = runtime
.grant_mutation_permit_for_test(&source_b)
.expect("grant");
permit.rollback_with_no_side_effect_proof_for_test();
assert!(
runtime.acquire_strict(&source_b).is_err(),
"even a proven no-op rollback returns to Current only through a \
fresh candidate publication, never by restoring the prior one"
);
}
#[test]
fn sealed_transition_rebases_one_source_and_preserves_siblings() {
let runtime = a_dark_runtime("root-a");
let source_a = runtime.admit_current_source_for_test("src-a");
let source_b = runtime.admit_current_source_for_test("src-b");
let before = runtime.publication_root().load();
let sibling_before = before.source_publication(&source_b).expect("sibling");
runtime.begin_reload_refresh_for_test(&source_a);
let after = runtime.publication_root().load();
assert_ne!(
before.publication_identity(),
after.publication_identity(),
"a transition publishes a NEW never-reused publication identity"
);
let sibling_after = after.source_publication(&source_b).expect("sibling");
assert!(
Arc::ptr_eq(&sibling_before, &sibling_after),
"the untouched sibling's publication is the SAME Arc, not a rebuild"
);
}
#[test]
fn capture_source_view_is_atomic_and_invents_no_token() {
let runtime = a_dark_runtime("root-a");
let source = runtime.admit_current_source_for_test("src-a");
let view = runtime
.capture_source_view(&source)
.expect("a stable root yields a coherent capture");
assert_eq!(
view.publication_identity(),
runtime.publication_root().load().publication_identity(),
"the view is validated against the root it was captured under"
);
assert!(
view.observer_token().is_none(),
"no observer is registered in the dark runtime, so the capture \
must not invent a token"
);
}
#[test]
fn stopped_phase_derives_from_tombstone_not_a_machine_state() {
let runtime = a_dark_runtime("root-a");
let source = runtime.admit_current_source_for_test("src-a");
runtime.stop_source_for_test(&source);
assert_eq!(runtime.source_phase(&source), SourceRuntimePhase::Stopping);
runtime.complete_stop_for_test(&source);
assert_eq!(
runtime.source_phase(&source),
SourceRuntimePhase::Stopped,
"Stopped is the tombstone's phase; the machine itself never holds it"
);
}
#[test]
fn verified_generation_requires_exact_authority_and_complete_artifacts() {
let runtime = a_dark_runtime("root-a");
let source = runtime.admit_current_source_for_test("src-a");
let lease = runtime.acquire_strict(&source).expect("current");
let generation = lease.generation();
assert!(generation.scope_certificate_is_complete());
let authority_a = generation.generation_authority();
let authority_b = generation.generation_authority();
assert!(
Arc::ptr_eq(&authority_a, &authority_b),
"the generation retains ONE exact authority Arc, never a re-mint"
);
}
#[test]
fn begin_close_is_infallible_and_self_wait_fails_at_wait() {
let factory = EmbeddedSourceFactory::new();
let handle = factory
.open(a_project_key("src-a"))
.expect("an open registry admits a fresh key");
let receipt = handle.begin_close();
let report = receipt
.wait_for_test()
.expect("an ordinary wait on the close receipt completes");
assert!(report.finalized());
let handle_b = factory
.open(a_project_key("src-b"))
.expect("an open registry admits a second key");
let error = handle_b
.self_wait_probe_for_test()
.expect_err("waiting on your own close from inside the finalizer refuses");
let _ = error;
}
#[test]
fn shutdown_report_reflects_observed_counts_only() {
let runtime = a_dark_runtime("root-a");
let receipt = runtime.begin_shutdown_for_test();
let report = receipt
.wait_for_test()
.expect("shutdown of a runtime that spawned nothing completes");
assert_eq!(
report.joined_workers(),
0,
"nothing was spawned, so nothing was joined; any other number is \
a report of an unobserved completion"
);
}
#[test]
fn contract_waits_guard_self_wait_and_open_refuses_a_held_source() {
let factory = EmbeddedSourceFactory::new();
let handle = factory
.open(ProjectKey::new("src-close"))
.expect("an open registry admits a fresh key");
assert_eq!(
handle.runtime_view().phase,
PublicSourceRuntimePhase::Loading
);
let receipt = handle.begin_close();
assert_eq!(
handle.runtime_view().phase,
PublicSourceRuntimePhase::Stopped,
"a closed handle must not report Loading"
);
let error = handle
.finalize(|| receipt.wait(std::time::Instant::now()))
.expect_err("the contract wait carries the self-wait guard, not just wait_for_test");
assert_eq!(error, ReceiptWaitError::WouldSelfWait);
let report = receipt
.wait(std::time::Instant::now())
.expect("outside the finalizer the same wait completes");
assert!(
!report.already_terminal,
"this close performed the shutdown, so reporting it as \
joined-terminal would be a false claim about who tore the \
source down"
);
assert_eq!(
report.terminal_source_version, 0,
"dark sources hold version 0"
);
let joined = handle
.begin_close()
.wait(std::time::Instant::now())
.expect("joining an already-terminal close completes");
assert!(
joined.already_terminal,
"the second close joined a terminal source; reporting it as \
having performed the shutdown would claim work this call did \
not do"
);
let runtime = ProcessRuntimeApi::acquire().expect("the dark acquisition admits");
let shutdown = runtime
.begin_shutdown()
.wait(std::time::Instant::now())
.expect("a shutdown that owned nothing completes");
assert_eq!(shutdown.closed_sources, 0);
assert_eq!(shutdown.joined_workers, 0);
let root = tempfile::tempdir().expect("temporary embedded root");
let root = root.path().to_path_buf();
let held = runtime
.open_embedded_source(EmbeddedSourceSpec::current_worktree(root.clone()))
.expect("the first open of a source admits");
let refusal = runtime
.open_embedded_source(EmbeddedSourceSpec::current_worktree(root))
.expect_err("the sole handle is out; a second open must refuse");
assert_eq!(refusal.kind_name(), "SelectionUnavailable");
drop(held);
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ProjectStateDir(pub std::path::PathBuf);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TeamArtifactState {
pub exported_bytes: Option<usize>,
}