Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 103 additions & 0 deletions core/continuum-cognition/src/cognition/act_observe/settle/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,109 @@
assert_eq!(start.elapsed(), std::time::Duration::ZERO);
}

/// Her place in the grants queue as each checkpoint reads it, from a script of what she sees.
fn scripted_place(script: Vec<crate::capacity::window_grant::WaitingPlace>) -> impl FnMut() -> Option<crate::capacity::window_grant::WaitingPlace> {
let mut reads = script.into_iter();
let mut last = None;
move || {
last = reads.next().or(last);
last
}
}

// what this catches (IntelMac 2026-11-22: 20 acts dropped at the 25-min floor inside
// deliberation.window_grant, never dispatched): a grant that comes after the old act deadline,
// while her place moves, still lets her act run, and the wait is not charged to her act: the
// 9 s of work after a 25 s wait fits a 10 s bound.
#[tokio::test(start_paused = true)]
async fn a_grant_after_the_old_deadline_runs_and_her_act_time_excludes_the_wait() {
use crate::capacity::window_grant::WaitingPlace::{Granted, Owed};
let bound = std::time::Duration::from_secs(10);
let start = tokio::time::Instant::now();
let place = scripted_place(vec![Owed { ahead: 3 }, Owed { ahead: 2 }, Owed { ahead: 1 }, Granted]);
let (grant, granted) = tokio::sync::oneshot::channel::<()>();
let (finish, finished) = tokio::sync::oneshot::channel::<()>();
let step = async move {
admission_clock::window_grant_with(granted, place).await.expect("test: the grant is sent"); // test fixture
finished.await.expect("test: the work is finished"); // test fixture
};
let turn = tokio::spawn(super::until_act_stalls(start + bound, bound, None, step));
run_for(std::time::Duration::ZERO).await; // her turn starts and registers its wait at 0 s
// her place moves at the 10 s and 20 s checkpoints; the grant arrives at 25 s, past the old deadline
for seconds in [10, 10, 5] {
run_for(std::time::Duration::from_secs(seconds)).await;
}
grant.send(()).expect("test: her act still waits for the grant, never ended by its old deadline"); // test fixture
// 9 s of work after the grant fits her 10 s act only if the 25 s wait was not charged to it
run_for(std::time::Duration::from_secs(9)).await;
finish.send(()).expect("test: her act is still running: the wait was not charged to it"); // test fixture
assert!(turn.await.expect("test: the turn task").is_ok(), "her place moved at every checkpoint, so the wait never ended her act"); // test fixture
assert_eq!(start.elapsed(), std::time::Duration::from_secs(34));
}

/// Move the paused clock by `by`, letting every woken task run: events, never a sleep, move the work.
async fn run_for(by: std::time::Duration) {
tokio::time::advance(by).await;
for _ in 0..16 {
tokio::task::yield_now().await;
}
}

// what this catches: the grants churn (published every ~1.5 s on the IntelMac, #6070) read as
// her progress, which would hold a livelocked act forever. Other minds reordering, a newcomer
// ahead of her and going unqueued move nothing, so her act ends at its first checkpoint.
#[tokio::test(start_paused = true)]
async fn grants_churn_with_her_place_unmoved_ends_her_act_at_one_bound() {
use crate::capacity::window_grant::WaitingPlace::{Owed, Unqueued};
let bound = std::time::Duration::from_secs(10);
let start = tokio::time::Instant::now();
let place = scripted_place(vec![Owed { ahead: 2 }, Owed { ahead: 3 }, Unqueued, Owed { ahead: 2 }]);
let waiting = admission_clock::window_grant_with(std::future::pending::<()>(), place);
assert!(tokio::time::timeout(bound * 10, super::until_act_stalls(start + bound, bound, None, waiting)).await.expect("a regression fails here, never hangs").is_err());
assert_eq!(start.elapsed(), bound, "churn is not her place moving");
}

// what this catches: granted at every checkpoint while her hold is refused (the 9,547
// 'her grant moved between her decision and her act' re-decisions) read as progress. Becoming
// granted is one move; staying granted is none.
#[tokio::test(start_paused = true)]
async fn staying_granted_while_her_hold_is_refused_moves_her_once() {
use crate::capacity::window_grant::WaitingPlace::{Granted, Owed};
let bound = std::time::Duration::from_secs(10);
let start = tokio::time::Instant::now();
let place = scripted_place(vec![Owed { ahead: 1 }, Granted]);
let waiting = admission_clock::window_grant_with(std::future::pending::<()>(), place);
assert!(tokio::time::timeout(bound * 10, super::until_act_stalls(start + bound, bound, None, waiting)).await.expect("a regression fails here, never hangs").is_err());
assert_eq!(start.elapsed(), bound * 2, "the grant earned one checkpoint, never a standing exemption");
}

// what this catches: a cancelled caller leaving her grant wait alive (its acquisition and its
// place observer held past the act that owned them).
#[tokio::test(start_paused = true)]
async fn a_cancelled_caller_releases_her_grant_wait() {
use crate::capacity::window_grant::WaitingPlace::Owed;
let held = std::sync::Arc::new(());
let (acquired, observed) = (std::sync::Arc::clone(&held), std::sync::Arc::clone(&held));
let bound = std::time::Duration::from_secs(10);
let start = tokio::time::Instant::now();
let acquire = async move {
let _acquired = acquired;
std::future::pending::<()>().await
};
let mut ahead = 9;
let place = move || {
let _observed = &observed;
ahead -= 1;
Some(Owed { ahead })
};
let turn = tokio::spawn(super::until_act_stalls(start + bound, bound, None, admission_clock::window_grant_with(acquire, place)));
tokio::task::yield_now().await;
assert_eq!(std::sync::Arc::strong_count(&held), 3, "the wait holds its acquisition and its observer");
turn.abort();
assert!(turn.await.is_err_and(|e| e.is_cancelled()));
assert_eq!(std::sync::Arc::strong_count(&held), 1, "cancelling her act released both");
}

async fn queued(gate: &LaneAdmission, count: usize) {
for _ in 0..100 {
if gate.work_waiting() == count { return; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,62 @@ pub(crate) async fn waiting<T>(wait: LaneWait, acquire: impl Future<Output = T>)
waiting_with_probe(acquire, || sample(&wait)).await
}

/// Her wait for a window grant ([`window_grant`]), registered like a lane wait: its time is the scheduler's, never her
/// act's. It ends at a checkpoint only if HER place did not move, not if grants merely changed. The
/// IntelMac, 2026-11-22: 20 acts waited the whole 25-minute floor in `deliberation.window_grant`
/// (9,547 `delib.window.waiting` re-decisions) and were dropped by the act timer, never dispatched.
/// The ONE way deliberation waits for her window: the named stage and its registration together, so
/// the call site cannot take one without the other.
pub(crate) async fn window_grant<T>(persona: uuid::Uuid, acquire: impl Future<Output = T>) -> T {
window_grant_with(acquire, move || crate::capacity::window_grant::waiting_place(persona)).await
}

/// [`window_grant`] with her place read from `place`: the production stage and registration, with
/// only the place source a test scripts.
pub(crate) async fn window_grant_with<T>(
acquire: impl Future<Output = T>,
mut place: impl FnMut() -> Option<crate::capacity::window_grant::WaitingPlace>,
) -> T {
let mut moved = GrantPlace::default();
stage("deliberation.window_grant", waiting_with_probe(acquire, move || std::future::ready(moved.observe(place())))).await
}

/// What counts as her moving toward a grant, across checkpoints: being granted where she was not,
/// or fewer owed minds ahead of her than she has ever had. Churn, minds reordering, a newcomer ahead
/// of her, or staying granted while her hold is refused, move nothing.
#[derive(Default)]
struct GrantPlace {
granted: bool,
fewest_ahead: Option<usize>,
moves: u64,
}

impl GrantPlace {
fn observe(&mut self, place: Option<crate::capacity::window_grant::WaitingPlace>) -> QueueProgress {
use crate::capacity::window_grant::WaitingPlace;
match place {
Some(WaitingPlace::Granted) => {
if !self.granted {
self.moves += 1;
}
self.granted = true;
}
Some(WaitingPlace::Owed { ahead }) => {
self.granted = false;
if self.fewest_ahead.is_none_or(|fewest| ahead < fewest) {
// the first sighting sets her baseline; only a later, smaller count is a move
if self.fewest_ahead.is_some() {
self.moves += 1;
}
self.fewest_ahead = Some(ahead);
}
}
Some(WaitingPlace::Unqueued) | None => self.granted = false,
}
QueueProgress { grants: (self.moves, 0), holders: Vec::new() }
}
}

pub(crate) async fn waiting_with_probe<T, P, S>(acquire: impl Future<Output = T>, mut probe: P) -> T
where
P: FnMut() -> S,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ impl LlmDeliberationFaculty {
// first grants evaluation after it: granted, she decides again; not, her turn defers with its reason.
// Her window, decided and (a grant) HELD for this act (`decide_and_hold`): a seat being reclaimed
// or moved before the hold is waited for within her turn, never a failed turn (card d50e8e66).
let (decided, mut act_hold) = match super::admission_clock::stage("deliberation.window_grant", crate::capacity::mind_window::decide_and_hold(
let (decided, mut act_hold) = match super::admission_clock::window_grant(self.persona_id, crate::capacity::mind_window::decide_and_hold(
self.persona_id,
|| crate::capacity::mind_window::mind_window(self.persona_id, loaded.adapter.as_ref(), loaded.context_window),
|| {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ async fn a_stamped_admission_on_her_current_lease_dispatches() {
by_mind: std::collections::BTreeMap::from([(persona, 148_838)]),
engine: Some(engine),
revisions: Default::default(),
owed: Default::default(),
};
crate::capacity::window_grant::stamp_revisions(None, &mut grants);
let (_publisher, receiver) = tokio::sync::watch::channel(Some(grants));
Expand Down
2 changes: 1 addition & 1 deletion core/continuum-engine/src/capacity/dyno/service/world.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ impl World {
pub(crate) fn start_published(&mut self, grants: &[(usize, u32)]) {
let mut next = PoolGrants {
pool_tokens: self.pool, per_sequence_cap: self.ceiling, engine: Some(self.engine),
by_mind: grants.iter().map(|(i, tokens)| (self.mind(*i), *tokens)).collect(), revisions: BTreeMap::new(),
by_mind: grants.iter().map(|(i, tokens)| (self.mind(*i), *tokens)).collect(), revisions: BTreeMap::new(), owed: BTreeMap::new(),
};
crate::capacity::window_grant::stamp_revisions(None, &mut next);
for (i, tokens) in grants {
Expand Down
46 changes: 46 additions & 0 deletions core/continuum-engine/src/capacity/window_grant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,9 +115,19 @@ pub struct PoolGrants {
pub engine: Option<crate::inference::engine_residency::EngineIncarnation>,
/// Each mind's grant revision ([`stamp_revisions`]).
pub revisions: BTreeMap<uuid::Uuid, GrantRevision>,
/// Each mind owed a seat, at the publication she became owed (the dispatch owner's queue, oldest
/// first by value). A waiting mind reads her place in it ([`Self::owed_rank`]), never the churn.
pub owed: BTreeMap<uuid::Uuid, u64>,
}

impl PoolGrants {
/// How many owed minds wait ahead of her (owed at an earlier publication, ties by id), when she
/// is owed. `None` when she is not owed: granted, or not waiting on this pool.
pub fn owed_rank(&self, persona: uuid::Uuid) -> Option<usize> {
let since = *self.owed.get(&persona)?;
Some(self.owed.iter().filter(|(mind, at)| (**at, **mind) < (since, persona)).count())
}

/// Her grant, when she is one of the minds on this pool.
pub fn grant_for(&self, persona: uuid::Uuid) -> Option<u32> {
self.by_mind.get(&persona).copied()
Expand Down Expand Up @@ -159,6 +169,28 @@ pub fn current_lease(persona: uuid::Uuid) -> Option<GrantLease> {
GRANTS.get()?.borrow().as_ref()?.lease_for(persona)
}

/// Where a mind waiting for her window stands in the latest publication.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WaitingPlace {
/// She holds a grant: her wait is answered.
Granted,
/// She is owed a seat behind this many owed minds.
Owed { ahead: usize },
/// Neither granted nor owed: the dispatch owner has not queued her.
Unqueued,
}

/// Her place in the latest publication, or `None` when no grants are published in this process.
pub fn waiting_place(persona: uuid::Uuid) -> Option<WaitingPlace> {
let grants = GRANTS.get()?.borrow();
let grants = grants.as_ref()?;
Some(match (grants.grant_for(persona), grants.owed_rank(persona)) {
(Some(_), _) => WaitingPlace::Granted,
(None, Some(ahead)) => WaitingPlace::Owed { ahead },
(None, None) => WaitingPlace::Unqueued,
})
}

/// How wide one seat on this node's engine is: the most ONE mind may be granted, as the grant owner
/// reads it off the engine (one slot on fixed slots, the pool capped at the trained window on a shared
/// one). Never the snapshot's equal share of the pool (`sequence_share`, a KV charge): an unreported
Expand Down Expand Up @@ -618,6 +650,20 @@ mod tests {
Demand { mind, need: t(need), target: t(need), wish: t(need), in_flight, settled: true, ceiling }
}

// what this catches (Codex on card 06254dcc): a waiting mind's place read wrong, which her grant
// wait counts as progress. Minds owed at the same publication are one cohort, ordered by id as the
// dispatch owner iterates them; a mind not owed has no rank, which is not rank zero.
#[test]
fn her_rank_counts_older_cohorts_then_ids_and_absent_is_not_rank_zero() {
let mind = uuid::Uuid::from_u128;
let grants = PoolGrants { owed: BTreeMap::from([(mind(1), 7), (mind(2), 9), (mind(3), 9), (mind(4), 12)]), ..PoolGrants::default() };
assert_eq!(grants.owed_rank(mind(1)), Some(0), "the oldest waits behind no one");
assert_eq!(grants.owed_rank(mind(2)), Some(1), "same publication as mind 3: the lower id goes first");
assert_eq!(grants.owed_rank(mind(3)), Some(2), "behind the older one and her cohort's lower id");
assert_eq!(grants.owed_rank(mind(4)), Some(3));
assert_eq!(grants.owed_rank(mind(5)), None, "not owed: no rank, never rank zero");
}

// what this catches: a window divided by a count (Joel, 2026-11-03: "What a mind needs not what
// you dictate"). Minds that fit get exactly what they need, never an equal split, never past one
// sequence's ceiling; what is left stays in the pool, granted to no one.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ impl Reservations {
dispatch.changed.insert(d.mind, served);
}
}
let mut next = PoolGrants { pool_tokens: pool, per_sequence_cap: ceiling, by_mind: grants, engine, revisions: BTreeMap::new() };
let mut next = PoolGrants { pool_tokens: pool, per_sequence_cap: ceiling, by_mind: grants, engine, revisions: BTreeMap::new(), owed: dispatch.owed.clone() };
stamp_revisions(current.as_ref(), &mut next);
// An owed mind is owed each seat she may take when its holder's act ends: every such holder
// is armed, so her next reserve after a completed act is refused at the receipt boundary and
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ mod tests {
],
);
state.receipts.insert(holder, (None, 8));
let next = PoolGrants { pool_tokens: 100, per_sequence_cap: 100, by_mind: BTreeMap::from([(holder, 60)]), engine: None, revisions: BTreeMap::new() };
let next = PoolGrants { pool_tokens: 100, per_sequence_cap: 100, by_mind: BTreeMap::from([(holder, 60)]), engine: None, revisions: BTreeMap::new(), owed: BTreeMap::new() };
let snapshot = DispatchDiagnosis::capture(&dispatch, &state, &next);
assert_eq!(snapshot.owed, vec![(waiter, 3)]);
let held = &snapshot.holders[&holder];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,7 @@ mod tests {
let kv = NonZeroU64::new(M5_KV_PER_TOKEN).expect("test: a nonzero cost"); // expect: a positive literal
let served = NonZeroU32::new(480_430).expect("test: the M5's pool after #5989"); // expect: a positive literal
let (her, other) = (1, 2);
let granted = PoolGrants { pool_tokens: served.get(), per_sequence_cap: 262_144, by_mind: [(uuid::Uuid::from_u128(her), 140_000)].into(), engine: None, revisions: Default::default() };
let granted = PoolGrants { pool_tokens: served.get(), per_sequence_cap: 262_144, by_mind: [(uuid::Uuid::from_u128(her), 140_000)].into(), engine: None, revisions: Default::default(), owed: Default::default() };
let demands = [demand(her, 100_000, true), demand(other, 60_000, false), demand(3, 40_000, false)];
let floor = need_floor(&demands, Some(&granted));
assert_eq!(floor, 140_000 + 60_000, "her act in flight keeps the grant it began on; the largest waiting need is held for the next seat, the smaller waiter holds no standing share");
Expand Down
Loading