From cc9afc85a0e385b2b191ce675a07b284a0be69d4 Mon Sep 17 00:00:00 2001 From: joelteply Date: Tue, 3 Nov 2026 10:39:50 -0600 Subject: [PATCH 1/2] The turn ledger keys a turn by its own id, so two turns of one mind are two turns Fable on #5736 (card 7471b449): IN_FLIGHT and CONFIRMED were sets of persona ids. A mind holding two turns at once (a fork beside her act) counted once, and the first to end removed the other's mark: a confirmed turn ending cleared her CONFIRMED entry while the other was still confirmed, an unconfirmed one ending cleared IN_FLIGHT under a still-running turn. The settle's bound and `awaited()` then miscounted while both ran. - One map, TURNS: TurnId -> Turn { persona, started_ms, confirmed }. begin_turn issues the id; confirm() and Drop touch only their own entry. "Confirmed" is a field of the turn, not a second set kept in step with the first. - in_flight_turns: one entry per turn, elapsed from that turn's own start (the per-persona start lookup and its map_or are gone). confirmed_in_flight counts confirmed turns. - turn_in_flight(persona): any turn of hers. in_flight_starts: one row per mind, her longest-running turn's start, which is what its one consumer (resident_service::close_windows) asks. - Test two_turns_of_one_mind_are_two_turns: two turns of one persona, one confirmed; ending the confirmed one leaves the other in flight and the confirmed count back where it started. Not changed: continuum-engine's slot_work IN_FLIGHT is keyed by persona too; it is a different map (slot custody), raised on the card rather than folded in here. continuum card 7471b449 Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE --- core/continuum-vitals/src/turn_ledger.rs | 122 +++++++++++++++-------- 1 file changed, 83 insertions(+), 39 deletions(-) diff --git a/core/continuum-vitals/src/turn_ledger.rs b/core/continuum-vitals/src/turn_ledger.rs index 246d963d21..dd40e1b7d1 100644 --- a/core/continuum-vitals/src/turn_ledger.rs +++ b/core/continuum-vitals/src/turn_ledger.rs @@ -54,19 +54,36 @@ impl TurnShape { pub(super) static TURN_SHAPES: std::sync::LazyLock< parking_lot::Mutex>, > = std::sync::LazyLock::new(|| parking_lot::Mutex::new(std::collections::HashMap::new())); -pub(super) static IN_FLIGHT: std::sync::LazyLock>> = - std::sync::LazyLock::new(|| parking_lot::Mutex::new(std::collections::HashSet::new())); -/// The minds whose turn in flight holds a CONFIRMED obligation (stop-drain S2): a stop that -/// cuts it leaves a durable row that the next start hands back (S3), so the stop need not -/// wait for it (S4). -pub(super) static CONFIRMED: std::sync::LazyLock>> = - std::sync::LazyLock::new(|| parking_lot::Mutex::new(std::collections::HashSet::new())); +/// One admitted turn's identity, issued by [`begin_turn`]. A mind can hold two turns at once (a +/// fork beside her act), so a turn is keyed by its own id and her persona is its attribute: +/// keyed by persona, two turns counted once and the first to end erased the other's mark (Fable +/// on #5736, card 7471b449). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct TurnId(u64); + +static NEXT_TURN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// A turn in flight as the ledger holds it. +#[derive(Debug, Clone, Copy)] +pub(super) struct Turn { + pub(super) persona: uuid::Uuid, + /// The clock [`begin_turn`] was stamped with, ms. + pub(super) started_ms: u64, + /// Its obligation is confirmed durable (stop-drain S2): a stop that cuts it leaves a durable + /// row the next start hands back (S3), so the stop need not wait for it (S4). + pub(super) confirmed: bool, +} + +/// Every turn in flight, by its own id. +pub(super) static TURNS: std::sync::LazyLock>> = + std::sync::LazyLock::new(|| parking_lot::Mutex::new(std::collections::HashMap::new())); /// A turn in flight for `persona`: stamps the start (as [`note_turn_started`]) and marks -/// her IN FLIGHT until dropped — so every exit of the service-loop turn, including a +/// it IN FLIGHT until dropped — so every exit of the service-loop turn, including a /// `continue`, ends the turn and records its shape. The placement switch moves a mind -/// only when this is not held (a move mid-turn is a torn turn). +/// only when she holds none (a move mid-turn is a torn turn). pub struct TurnInFlight { + id: TurnId, persona: uuid::Uuid, started: std::time::Instant, previous_start_ms: Option, @@ -74,22 +91,24 @@ pub struct TurnInFlight { pub fn begin_turn(persona: uuid::Uuid, now_ms: u64) -> TurnInFlight { let previous_start_ms = LAST_TURN_MS.lock().insert(persona, now_ms); - IN_FLIGHT.lock().insert(persona); - TurnInFlight { persona, started: std::time::Instant::now(), previous_start_ms } + let id = TurnId(NEXT_TURN.fetch_add(1, std::sync::atomic::Ordering::Relaxed)); + TURNS.lock().insert(id, Turn { persona, started_ms: now_ms, confirmed: false }); + TurnInFlight { id, persona, started: std::time::Instant::now(), previous_start_ms } } impl TurnInFlight { /// This turn's obligation is confirmed durable: from here a stop may cut it, because the /// next start hands it back (stop-drain S3), so the stop no longer waits for it (S4). pub fn confirm(&self) { - CONFIRMED.lock().insert(self.persona); + if let Some(turn) = TURNS.lock().get_mut(&self.id) { + turn.confirmed = true; + } } } impl Drop for TurnInFlight { fn drop(&mut self) { - CONFIRMED.lock().remove(&self.persona); - IN_FLIGHT.lock().remove(&self.persona); + TURNS.lock().remove(&self.id); let turn_ms = self.started.elapsed().as_millis() as u64; let gap_ms = self .previous_start_ms @@ -102,17 +121,19 @@ impl Drop for TurnInFlight { /// Is a turn of `persona`'s in flight right now? pub fn turn_in_flight(persona: uuid::Uuid) -> bool { - IN_FLIGHT.lock().contains(&persona) + TURNS.lock().values().any(|t| t.persona == persona) } -/// Every mind with a turn in flight right now, and when that turn started (ms, the clock -/// [`begin_turn`] was stamped with). A resident's service window reads this so a turn that -/// never settles still counts as demand (card 1c157668). Locks taken one at a time. +/// Every mind with a turn in flight right now, and when her longest-running one started (ms, the +/// clock [`begin_turn`] was stamped with). A resident's service window reads this so a turn that +/// never settles still counts as demand (card 1c157668). pub fn in_flight_starts() -> Vec<(uuid::Uuid, u64)> { - let personas: Vec = IN_FLIGHT.lock().iter().copied().collect(); - let starts = LAST_TURN_MS.lock(); - // begin_turn stamps the start before marking in flight, so a mind in flight has a start. - personas.into_iter().filter_map(|p| starts.get(&p).map(|s| (p, *s))).collect() + let mut earliest: std::collections::HashMap = std::collections::HashMap::new(); + for turn in TURNS.lock().values() { + let start = earliest.entry(turn.persona).or_insert(turn.started_ms); + *start = (*start).min(turn.started_ms); + } + earliest.into_iter().collect() } /// One turn in flight, as the settle before a stop reads it. @@ -126,31 +147,24 @@ pub(crate) struct InFlightTurn { pub(crate) confirmed: bool, } -/// Every turn in flight right now. The settle before a stop sizes its wait from the ones not -/// yet confirmed ([`crate::turn_ingress::settle_bound_ms`]). `now_ms` is the clock -/// [`begin_turn`] was stamped with. Locks taken one at a time, never nested. +/// Every turn in flight right now, one per turn (a mind with two counts twice). The settle before +/// a stop sizes its wait from the ones not yet confirmed ([`crate::turn_ingress::settle_bound_ms`]). +/// `now_ms` is the clock [`begin_turn`] was stamped with. pub(crate) fn in_flight_turns(now_ms: u64) -> Vec { - let personas: Vec = IN_FLIGHT.lock().iter().copied().collect(); - let starts = LAST_TURN_MS.lock(); - let started: Vec<(uuid::Uuid, u64)> = personas - .into_iter() - .map(|p| (p, starts.get(&p).map_or(0, |s| now_ms.saturating_sub(*s)))) // map_or: begin_turn stamps the start before marking in flight, so a miss is a race at most — 0 elapsed waits LONGER, never shorter - .collect(); - drop(starts); - let confirmed = CONFIRMED.lock().clone(); - started + let turns: Vec = TURNS.lock().values().copied().collect(); + turns .into_iter() - .map(|(p, elapsed_ms)| InFlightTurn { - elapsed_ms, - typical_ms: turn_shape_of(p).map(|s| s.turn_ms), - confirmed: confirmed.contains(&p), + .map(|t| InFlightTurn { + elapsed_ms: now_ms.saturating_sub(t.started_ms), + typical_ms: turn_shape_of(t.persona).map(|s| s.turn_ms), + confirmed: t.confirmed, }) .collect() } /// How many turns in flight hold a confirmed obligation right now. pub(crate) fn confirmed_in_flight() -> u64 { - CONFIRMED.lock().len() as u64 + TURNS.lock().values().filter(|t| t.confirmed).count() as u64 } /// Self-ticks in flight: a mind's own initiative (`Wake::Tick` / `Wake::Mind`), which consumes @@ -199,3 +213,33 @@ pub fn typical_turn_ms(personas: &[uuid::Uuid]) -> Option { turns.sort_unstable(); Some(turns[turns.len() / 2]) } + +#[cfg(test)] +mod tests { + use super::*; + + // what this catches (Fable on #5736, card 7471b449): a ledger keyed by persona. Two turns of + // one mind (a fork beside her act) counted once, and the first to end erased the other's + // mark, so the settle and `awaited()` under-counted while both ran. Each turn is its own + // entry: ending one leaves the other in flight, confirmed or not, and her start is the + // longest-running turn's. + #[test] + fn two_turns_of_one_mind_are_two_turns() { + let persona = uuid::Uuid::new_v4(); + let before = confirmed_in_flight(); + let act = begin_turn(persona, 1_000); + let fork = begin_turn(persona, 2_000); + act.confirm(); + assert_eq!(confirmed_in_flight(), before + 1, "only the confirmed one counts as confirmed"); + let hers = |turns: &[(uuid::Uuid, u64)]| turns.iter().find(|(p, _)| *p == persona).map(|(_, s)| *s); + assert_eq!(hers(&in_flight_starts()), Some(1_000), "her start is the longest-running turn's"); + + drop(act); + assert!(turn_in_flight(persona), "ending the confirmed turn leaves the fork in flight"); + assert_eq!(confirmed_in_flight(), before, "and its confirmation ends with it, not the fork's state"); + assert_eq!(hers(&in_flight_starts()), Some(2_000)); + + drop(fork); + assert!(!turn_in_flight(persona), "both ended: she has none"); + } +} From d4a6e8480a0de2c1cf377bf4c55fd3479af70fa4 Mon Sep 17 00:00:00 2001 From: joelteply Date: Tue, 3 Nov 2026 10:55:24 -0600 Subject: [PATCH 2/2] turn_ledger tests count their own mind's turns, never the global confirmed count (Fable on #5737) Both two_turns_of_one_mind_are_two_turns and the settle's confirmed-turn test asserted the global confirmed_in_flight() as before/before+1, which another test thread can move between the reads: a flake. A test-only confirmed_turns_of(persona) counts hers, and the settle test's any-turn closure (satisfiable by another thread's turn) becomes the same per-persona check. continuum card 7471b449 Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE --- core/continuum-vitals/src/turn_ingress.rs | 13 +++++-------- core/continuum-vitals/src/turn_ledger.rs | 12 +++++++++--- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/core/continuum-vitals/src/turn_ingress.rs b/core/continuum-vitals/src/turn_ingress.rs index bd1df19550..71e8604ece 100644 --- a/core/continuum-vitals/src/turn_ingress.rs +++ b/core/continuum-vitals/src/turn_ingress.rs @@ -308,17 +308,14 @@ mod tests { let persona = uuid::Uuid::new_v4(); let now = EpochMs::now().millis(); - let before = crate::turn_ledger::confirmed_in_flight(); let turn = crate::turn_ledger::begin_turn(persona, now); - let mine = |confirmed: bool| { - crate::turn_ledger::in_flight_turns(now).iter().any(|t| t.confirmed == confirmed) - }; - assert!(mine(false), "begun, not confirmed: the settle sizes its bound from it"); + // Her own turn only: the global counts move under every other test thread (Fable on #5737). + assert!(crate::turn_ledger::turn_in_flight(persona), "begun"); + assert_eq!(crate::turn_ledger::confirmed_turns_of(persona), 0, "begun, not confirmed: the settle sizes its bound from it"); turn.confirm(); - assert_eq!(crate::turn_ledger::confirmed_in_flight(), before + 1); - assert!(mine(true), "confirmed: left out of the bound"); + assert_eq!(crate::turn_ledger::confirmed_turns_of(persona), 1, "confirmed: left out of the bound"); drop(turn); - assert_eq!(crate::turn_ledger::confirmed_in_flight(), before, "the confirmation ends with the turn"); + assert_eq!(crate::turn_ledger::confirmed_turns_of(persona), 0, "the confirmation ends with the turn"); } // what this catches (stop-drain S4b, card 161d2590; the IntelMac 2026-11-03 07:31Z stop: diff --git a/core/continuum-vitals/src/turn_ledger.rs b/core/continuum-vitals/src/turn_ledger.rs index dd40e1b7d1..e2d5b28a70 100644 --- a/core/continuum-vitals/src/turn_ledger.rs +++ b/core/continuum-vitals/src/turn_ledger.rs @@ -167,6 +167,13 @@ pub(crate) fn confirmed_in_flight() -> u64 { TURNS.lock().values().filter(|t| t.confirmed).count() as u64 } +/// How many of `persona`'s turns in flight are confirmed. Tests count their own mind's turns, since +/// the global count moves under every other test thread (Fable on #5737). +#[cfg(test)] +pub(crate) fn confirmed_turns_of(persona: uuid::Uuid) -> usize { + TURNS.lock().values().filter(|t| t.persona == persona && t.confirmed).count() +} + /// Self-ticks in flight: a mind's own initiative (`Wake::Tick` / `Wake::Mind`), which consumes /// no external input. What it writes is in-memory and recomputed from the world each beat, and /// its notices are marked read only after its generation, so a stop that cuts one loses nothing @@ -226,17 +233,16 @@ mod tests { #[test] fn two_turns_of_one_mind_are_two_turns() { let persona = uuid::Uuid::new_v4(); - let before = confirmed_in_flight(); let act = begin_turn(persona, 1_000); let fork = begin_turn(persona, 2_000); act.confirm(); - assert_eq!(confirmed_in_flight(), before + 1, "only the confirmed one counts as confirmed"); + assert_eq!(confirmed_turns_of(persona), 1, "only the confirmed one counts as confirmed"); let hers = |turns: &[(uuid::Uuid, u64)]| turns.iter().find(|(p, _)| *p == persona).map(|(_, s)| *s); assert_eq!(hers(&in_flight_starts()), Some(1_000), "her start is the longest-running turn's"); drop(act); assert!(turn_in_flight(persona), "ending the confirmed turn leaves the fork in flight"); - assert_eq!(confirmed_in_flight(), before, "and its confirmation ends with it, not the fork's state"); + assert_eq!(confirmed_turns_of(persona), 0, "and its confirmation ends with it, not the fork's state"); assert_eq!(hers(&in_flight_starts()), Some(2_000)); drop(fork);