Skip to main content

qualia_core_db/net/peer/cells/
workers.rs

1//! Worker start / fail / drain / handover with generation fencing (E10.3).
2//!
3//! Handover temporarily double-reserves the cell bytes on the shared
4//! [`HostAdmission`], then releases the old slot. Cancel during drain returns
5//! [`QdnfError::Cancelled`] and leaves the old reservation until
6//! [`release_worker`]. Stale generation cannot complete handover.
7
8use super::admit::{CellProfile, CellSlot};
9use super::host_owner::HostAdmission;
10use crate::net::qdnf::errors::QdnfError;
11use crate::net::qdnf::types::Generation;
12
13/// Exclusive writer fence. Not `Copy`: two live writers are [`QdnfError::Conflict`].
14pub struct WorkerFence {
15    pub generation: Generation,
16    pub draining: bool,
17    epoch: Generation,
18    slot: Option<CellSlot>,
19    cancelled: bool,
20    failed: bool,
21    writer: bool,
22}
23
24impl WorkerFence {
25    /// `WorkerFence::vacant`.
26    pub const fn vacant() -> Self {
27        Self {
28            generation: Generation::ZERO,
29            draining: false,
30            epoch: Generation::ZERO,
31            slot: None,
32            cancelled: false,
33            failed: false,
34            writer: false,
35        }
36    }
37
38    #[inline]
39    /// `WorkerFence::epoch`.
40    pub const fn epoch(&self) -> Generation {
41        self.epoch
42    }
43
44    #[inline]
45    /// `WorkerFence::cancelled`.
46    pub const fn cancelled(&self) -> bool {
47        self.cancelled
48    }
49
50    #[inline]
51    /// `true` when failed.
52    pub const fn failed(&self) -> bool {
53        self.failed
54    }
55
56    #[inline]
57    /// `true` when writer.
58    pub const fn is_writer(&self) -> bool {
59        self.writer
60    }
61}
62
63/// Admit a cell and take exclusive writer ownership.
64pub fn start_worker(
65    host: &mut HostAdmission,
66    profile: CellProfile,
67    bytes: u64,
68) -> Result<WorkerFence, QdnfError> {
69    let slot = host.admit_cell(profile, bytes)?;
70    let generation = Generation::ZERO.next()?;
71    Ok(WorkerFence {
72        generation,
73        draining: false,
74        epoch: generation,
75        slot: Some(slot),
76        cancelled: false,
77        failed: false,
78        writer: true,
79    })
80}
81
82/// Mark failure and begin drain. Vacant fence → [`QdnfError::Incomplete`].
83pub fn fail_worker(worker: &mut WorkerFence) -> Result<(), QdnfError> {
84    if !worker.writer || worker.slot.is_none() {
85        return Err(QdnfError::Incomplete);
86    }
87    if worker.generation != worker.epoch {
88        return Err(QdnfError::StaleGeneration);
89    }
90    worker.failed = true;
91    worker.draining = true;
92    worker.epoch = worker.epoch.next()?;
93    worker.generation = worker.epoch;
94    Ok(())
95}
96
97/// Cancel during drain (E03.5). Old reservation remains until [`release_worker`].
98pub fn cancel_worker(worker: &mut WorkerFence) -> Result<(), QdnfError> {
99    if worker.slot.is_none() {
100        return Err(QdnfError::Incomplete);
101    }
102    if worker.generation != worker.epoch {
103        return Err(QdnfError::StaleGeneration);
104    }
105    worker.cancelled = true;
106    worker.draining = true;
107    Ok(())
108}
109
110/// Release the worker cell on success, error, cancel, or unwind (E03.5).
111pub fn release_worker(worker: &mut WorkerFence, host: &mut HostAdmission) -> Result<(), QdnfError> {
112    let slot = match worker.slot.take() {
113        Some(s) => s,
114        None => return Err(QdnfError::DoubleRelease),
115    };
116    worker.writer = false;
117    worker.draining = false;
118    host.release_cell(slot)
119}
120
121/// Drain `old` and hand exclusive ownership to `new`.
122///
123/// Temporary double-reservation of the cell bytes, then release of `old`.
124/// Cancelled drain leaves `old` reserved. Two live writers → Conflict.
125pub fn drain_and_handover(
126    old: &mut WorkerFence,
127    new: &mut WorkerFence,
128    host: &mut HostAdmission,
129) -> Result<(), QdnfError> {
130    if old.generation != old.epoch {
131        return Err(QdnfError::StaleGeneration);
132    }
133    if new.generation != new.epoch {
134        return Err(QdnfError::StaleGeneration);
135    }
136    let old_slot = match old.slot {
137        Some(s) if old.writer => s,
138        _ => return Err(QdnfError::Incomplete),
139    };
140    if new.writer || new.slot.is_some() {
141        return Err(QdnfError::Conflict);
142    }
143    old.draining = true;
144    if old.cancelled {
145        return Err(QdnfError::Cancelled);
146    }
147    let before = host.remaining_host_bytes();
148    let fresh = match host.admit_cell(old_slot.profile, old_slot.bytes) {
149        Ok(s) => s,
150        Err(e) => return Err(e),
151    };
152    let after_double = host.remaining_host_bytes();
153    if after_double != before.saturating_sub(old_slot.bytes) {
154        let _ = host.release_cell(fresh);
155        return Err(QdnfError::Incomplete);
156    }
157    host.release_cell(old_slot)?;
158    old.slot = None;
159    old.writer = false;
160    old.draining = false;
161    let generation = old.epoch.next()?;
162    *new = WorkerFence {
163        generation,
164        draining: false,
165        epoch: generation,
166        slot: Some(fresh),
167        cancelled: false,
168        failed: false,
169        writer: true,
170    };
171    Ok(())
172}
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177    use crate::net::peer::cells::admit::CellProfile;
178    use crate::net::qdnf::errors::QdnfError;
179
180    const MIB: u64 = 1024 * 1024;
181
182    #[test]
183    fn handover_double_reserves_then_releases_old() {
184        let mut host = HostAdmission::new(2 * MIB).unwrap();
185        let mut old = start_worker(&mut host, CellProfile::NetworkSmall, MIB).unwrap();
186        assert_eq!(host.remaining_host_bytes(), MIB);
187        assert_eq!(host.occupied_cells(), 1);
188        let mut new = WorkerFence::vacant();
189        drain_and_handover(&mut old, &mut new, &mut host).expect("handover");
190        assert!(!old.is_writer());
191        assert!(new.is_writer());
192        assert_eq!(host.occupied_cells(), 1);
193        assert_eq!(host.remaining_host_bytes(), MIB);
194        release_worker(&mut new, &mut host).unwrap();
195        assert_eq!(host.occupied_cells(), 0);
196    }
197
198    #[test]
199    fn cancel_during_drain_keeps_old_reservation() {
200        let mut host = HostAdmission::new(2 * MIB).unwrap();
201        let mut old = start_worker(&mut host, CellProfile::NetworkSmall, MIB).unwrap();
202        cancel_worker(&mut old).unwrap();
203        let mut new = WorkerFence::vacant();
204        assert_eq!(
205            drain_and_handover(&mut old, &mut new, &mut host),
206            Err(QdnfError::Cancelled)
207        );
208        assert!(old.is_writer());
209        assert_eq!(host.occupied_cells(), 1);
210        assert_eq!(host.remaining_host_bytes(), MIB);
211        release_worker(&mut old, &mut host).unwrap();
212        assert_eq!(host.occupied_cells(), 0);
213    }
214
215    #[test]
216    fn stale_generation_cannot_handover() {
217        let mut host = HostAdmission::new(2 * MIB).unwrap();
218        let mut old = start_worker(&mut host, CellProfile::NetworkSmall, MIB).unwrap();
219        old.generation = Generation(99);
220        let mut new = WorkerFence::vacant();
221        assert_eq!(
222            drain_and_handover(&mut old, &mut new, &mut host),
223            Err(QdnfError::StaleGeneration)
224        );
225        old.generation = old.epoch();
226        release_worker(&mut old, &mut host).unwrap();
227    }
228
229    #[test]
230    fn two_writers_conflict() {
231        let mut host = HostAdmission::new(2 * MIB).unwrap();
232        let mut old = start_worker(&mut host, CellProfile::NetworkSmall, MIB).unwrap();
233        let mut other = start_worker(&mut host, CellProfile::NetworkSmall, MIB).unwrap();
234        assert_eq!(
235            drain_and_handover(&mut old, &mut other, &mut host),
236            Err(QdnfError::Conflict)
237        );
238        release_worker(&mut old, &mut host).unwrap();
239        release_worker(&mut other, &mut host).unwrap();
240    }
241
242    #[test]
243    fn vacant_drain_is_incomplete() {
244        let mut host = HostAdmission::new(MIB).unwrap();
245        let mut old = WorkerFence::vacant();
246        let mut new = WorkerFence::vacant();
247        assert_eq!(
248            drain_and_handover(&mut old, &mut new, &mut host),
249            Err(QdnfError::Incomplete)
250        );
251    }
252
253    #[test]
254    fn double_reserve_needs_host_headroom() {
255        let mut host = HostAdmission::new(MIB).unwrap();
256        let mut old = start_worker(&mut host, CellProfile::NetworkSmall, MIB).unwrap();
257        let mut new = WorkerFence::vacant();
258        assert_eq!(
259            drain_and_handover(&mut old, &mut new, &mut host),
260            Err(QdnfError::BudgetExhausted)
261        );
262        assert_eq!(host.occupied_cells(), 1);
263        release_worker(&mut old, &mut host).unwrap();
264    }
265
266    #[test]
267    fn fail_worker_starts_drain() {
268        let mut host = HostAdmission::new(2 * MIB).unwrap();
269        let mut old = start_worker(&mut host, CellProfile::NetworkSmall, MIB).unwrap();
270        fail_worker(&mut old).unwrap();
271        assert!(old.failed());
272        assert!(old.draining);
273        let mut new = WorkerFence::vacant();
274        drain_and_handover(&mut old, &mut new, &mut host).unwrap();
275        release_worker(&mut new, &mut host).unwrap();
276    }
277}