ifc_lite_core/
execution_owner.rs

1// SPDX-License-Identifier: MPL-2.0
2//! Stable execution ownership for warm decoder/router workers. A reservation
3//! is owned data, never a mutex/TLS guard, and may survive a scheduling yield.
4use std::{
5    fmt,
6    sync::{
7        atomic::{AtomicBool, AtomicU64, Ordering},
8        Arc, Mutex, OnceLock,
9    },
10};
11
12mod resource_context;
13pub use resource_context::{SourceResourceContext, SourceStopHandle};
14mod allocation_account;
15pub use allocation_account::{
16    AllocationAccount, AllocationClass, AllocationCost, AllocationObserver, StorageEvent,
17};
18use resource_context::ActiveSource;
19mod work;
20use work::WorkEpoch;
21pub use work::{ExecutionChildCapability, ExecutionSourceScope, ExecutionWork};
22
23static NEXT_ID: AtomicU64 = AtomicU64::new(1);
24fn next_id() -> u64 {
25    NEXT_ID
26        .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
27            value.checked_add(1)
28        })
29        .expect("execution identity space exhausted")
30}
31
32/// Instance plus configuration generation. Opaque and independent of addresses,
33/// IFC express ids, allocation reuse, and identical bytes in another decoder.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
35pub struct ExecutionIdentity {
36    instance: u64,
37    generation: u64,
38}
39
40impl ExecutionIdentity {
41    /// Whether both identities name one owner instance, whatever their
42    /// configuration generations: maintenance changes a generation, only a
43    /// replacement changes the instance.
44    pub fn same_instance(&self, other: &Self) -> bool {
45        self.instance == other.instance
46    }
47}
48
49/// Unique reservation identity; a later lease on the same owner is distinct.
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
51pub struct ExecutionLeaseId(u64);
52
53#[derive(Debug)]
54struct State {
55    generation: AtomicU64,
56    reserved: AtomicBool,
57    alive: AtomicBool,
58    /// Ordered scope stack; empty is the base (no authority) state.
59    active_source: Mutex<Vec<(u64, ActiveSource)>>,
60    cache_authority: Mutex<CacheAuthority>,
61}
62
63// Baseline owner metadata, independent of configuration generation. A weak
64// source link cannot keep a source alive or form an owner/source cycle.
65#[derive(Debug, Clone, Default)]
66struct CacheAuthority {
67    revision: u64,
68    source: std::sync::Weak<crate::SourceBundle>,
69}
70
71/// Private state of one execution owner. Move preserves identity; construction
72/// creates a distinct owner. Ordinary nested geometry calls remain permitted.
73#[derive(Debug)]
74pub struct ExecutionOwner {
75    instance: u64,
76    generation: u64,
77    state: OnceLock<Arc<State>>,
78    cache_authority: CacheAuthority,
79}
80impl Default for ExecutionOwner {
81    fn default() -> Self {
82        // Warm per-job decoder/router construction must remain allocation-free.
83        Self {
84            instance: next_id(),
85            generation: 0,
86            state: OnceLock::new(),
87            cache_authority: CacheAuthority::default(),
88        }
89    }
90}
91impl ExecutionOwner {
92    pub fn identity(&self) -> ExecutionIdentity {
93        ExecutionIdentity {
94            instance: self.instance,
95            generation: self.generation,
96        }
97    }
98    /// Invalidate pending work without releasing its owner's reservation.
99    pub fn changed(&mut self) {
100        self.generation = self
101            .generation
102            .checked_add(1)
103            .expect("execution generation space exhausted");
104        if let Some(state) = self.state.get() {
105            state.generation.store(self.generation, Ordering::Release);
106        }
107    }
108    /// Revoke captured cache work before a cache mutation. This does not change
109    /// configuration generation or the canonical/raw cache provenance marker.
110    pub(crate) fn cache_changed(&mut self) {
111        self.cache_authority.revision = self
112            .cache_authority
113            .revision
114            .checked_add(1)
115            .expect("execution cache revision space exhausted");
116        if let Some(state) = self.state.get() {
117            let previous = std::mem::replace(
118                &mut *state.cache_authority.lock().unwrap_or_else(|poisoned| poisoned.into_inner()),
119                self.cache_authority.clone(),
120            );
121            drop(previous); // Final Weak destruction happens outside the lock.
122        }
123    }
124    pub(crate) fn publish_cache_source(&mut self, source: Option<&Arc<crate::SourceBundle>>) {
125        self.cache_authority.source = source.map_or_else(Default::default, Arc::downgrade);
126        self.cache_changed();
127    }
128    pub fn try_lease(&self) -> Result<ExecutionLease, ExecutionLeaseError> {
129        let id = ExecutionLeaseId(next_id());
130        let state = self.state.get_or_init(|| {
131            Arc::new(State {
132                generation: AtomicU64::new(self.generation),
133                reserved: AtomicBool::new(false),
134                alive: AtomicBool::new(true),
135                active_source: Mutex::new(Vec::new()),
136                cache_authority: Mutex::new(self.cache_authority.clone()),
137            })
138        });
139        state
140            .reserved
141            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
142            .map_err(|_| ExecutionLeaseError::AlreadyLeased)?;
143        Ok(ExecutionLease {
144            identity: self.identity(),
145            id,
146            state: state.clone(),
147            parent: None,
148            source_borrow: false,
149            resources: None,
150        })
151    }
152    pub(crate) fn try_source_borrow_lease(
153        &mut self,
154    ) -> Result<Option<ExecutionLease>, ExecutionLeaseError> {
155        let Some(state) = self.state.get() else {
156            return Ok(None);
157        };
158        let source = state
159            .active_source
160            .lock()
161            .unwrap_or_else(|poisoned| poisoned.into_inner())
162            .last()
163            .map(|(_, source)| source.clone())
164            .unwrap_or_default();
165        let Some(epoch) = source.epoch.upgrade() else {
166            return Ok(None);
167        };
168        epoch.validate(true)?;
169        if !state.alive.load(Ordering::Acquire) {
170            return Err(ExecutionLeaseError::OwnerDropped);
171        }
172        if !state.reserved.load(Ordering::Acquire) {
173            return Err(ExecutionLeaseError::ExpiredWork);
174        }
175        Ok(Some(ExecutionLease {
176            identity: self.identity(),
177            id: ExecutionLeaseId(next_id()),
178            state: state.clone(),
179            parent: Some(epoch),
180            source_borrow: true,
181            resources: source.resources,
182        }))
183    }
184}
185impl Drop for ExecutionOwner {
186    fn drop(&mut self) {
187        if let Some(state) = self.state.get() {
188            state.alive.store(false, Ordering::Release);
189        }
190    }
191}
192
193/// Exclusive product reservation. Send, not Clone: no borrow or thread-bound
194/// guard survives a poll. Drop releases admission on normal/error/panic paths.
195/// This does not prohibit direct router calls: the executor must keep those
196/// calls within its product owner while the reservation is live.
197#[derive(Debug)]
198pub struct ExecutionLease {
199    identity: ExecutionIdentity,
200    id: ExecutionLeaseId,
201    state: Arc<State>,
202    parent: Option<Arc<WorkEpoch>>,
203    source_borrow: bool,
204    resources: Option<SourceResourceContext>,
205}
206impl ExecutionLease {
207    fn validate_parent(&self) -> Result<(), ExecutionLeaseError> {
208        if let Some(parent) = &self.parent {
209            parent.validate(self.source_borrow)?;
210        }
211        Ok(())
212    }
213    /// Read only an active source-borrow resource context. This does not install
214    /// any execution state or grant a router lease on another thread.
215    pub fn source_resource_context(
216        &self,
217    ) -> Result<Option<SourceResourceContext>, ExecutionLeaseError> {
218        self.validate_parent()?;
219        Ok(self.resources.clone())
220    }
221    pub fn source_stop_handle(&self) -> Result<Option<SourceStopHandle>, ExecutionLeaseError> {
222        self.validate_parent()?;
223        Ok(self
224            .parent
225            .as_ref()
226            .map(|epoch| SourceStopHandle::new(Arc::clone(epoch))))
227    }
228    pub fn id(&self) -> ExecutionLeaseId {
229        self.id
230    }
231    pub fn identity(&self) -> ExecutionIdentity {
232        self.identity
233    }
234    /// Begin trusted synchronous executor work after validating its current
235    /// owner. Only this scope may acknowledge configuration/cache mutations
236    /// made by existing callbacks. Acceptance of a reply must use `validate`
237    /// instead; reply-supplied identities cannot authorize a refresh.
238    pub fn begin_synchronous_work(
239        &mut self,
240        current: ExecutionIdentity,
241    ) -> Result<ExecutionWork<'_>, ExecutionLeaseError> {
242        self.validate(current)?;
243        Ok(ExecutionWork {
244            lease: self,
245            epoch: std::cell::OnceCell::new(),
246            _thread_bound: std::marker::PhantomData,
247        })
248    }
249    /// Supply the owner's freshly read identity, never a cached ticket value.
250    pub fn validate(&self, current: ExecutionIdentity) -> Result<(), ExecutionLeaseError> {
251        self.validate_parent()?;
252        if !self.state.alive.load(Ordering::Acquire) {
253            return Err(ExecutionLeaseError::OwnerDropped);
254        }
255        if current.instance != self.identity.instance {
256            return Err(ExecutionLeaseError::WrongOwner);
257        }
258        if current != self.identity
259            || self.state.generation.load(Ordering::Acquire) != self.identity.generation
260        {
261            return Err(ExecutionLeaseError::ConfigurationChanged);
262        }
263        Ok(())
264    }
265}
266impl Drop for ExecutionLease {
267    fn drop(&mut self) {
268        if self.parent.is_none() {
269            self.state.reserved.store(false, Ordering::Release);
270        }
271    }
272}
273
274/// Why an execution lease, work scope or source borrow was refused.
275/// Admission/acceptance failures have no geometry or diagnostic side effects.
276#[derive(Debug, Clone, Copy, PartialEq, Eq)]
277pub enum ExecutionLeaseError {
278    AlreadyLeased,
279    WrongOwner,
280    ConfigurationChanged,
281    OwnerDropped,
282    ExpiredWork,
283}
284impl fmt::Display for ExecutionLeaseError {
285    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
286        formatter.write_str(match self {
287            Self::AlreadyLeased => "execution owner already has a product lease",
288            Self::WrongOwner => "execution lease belongs to a different owner",
289            Self::ConfigurationChanged => "execution configuration changed while work was pending",
290            Self::OwnerDropped => "execution owner was dropped",
291            Self::ExpiredWork => "synchronous ancestor work is no longer active on this thread",
292        })
293    }
294}
295impl std::error::Error for ExecutionLeaseError {}
296
297#[cfg(test)]
298#[path = "execution_owner/resource_context_tests.rs"]
299mod resource_context_tests;
300#[cfg(test)]
301#[path = "execution_owner_tests.rs"]
302mod tests;