Merge branch 'worktree-agent-acd2587ce4944ff56' into claude/prefill-latency

This commit is contained in:
Pavlo Ratushnyi
2026-11-11 00:47:02 +01:00
4 changed files with 110 additions and 16 deletions
@@ -143,10 +143,11 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
ring_prefetch::stage_target(self.slots.len(), self.stage_next, |s| self.slots[s].state)
}
/// Whether source `index` can be staged now. Always true without reserved slots (the literal ring); with them a
/// copy waits for a gather when the next free slot is still ungathered (the reserved slots shrink the lookahead).
/// Whether source `index` can be staged now: it needs no copy, or some unreserved slot is free. Always true for the
/// literal ring (no prefetch adopted); after a prefetch, a copy waits for a gather when every unreserved slot still
/// holds an unread copy (also once every hit was gathered: the slot order no longer follows the gather order).
pub(in super::super::super) fn stage_room(&self, index: usize) -> bool {
if self.reserved == 0 || index >= self.sources.len() {
if index >= self.sources.len() {
return true;
}
!matches!(self.stage_needed(index), Ok(true)) || self.stage_target().is_ok()
+16 -9
View File
@@ -237,16 +237,23 @@ pub fn stage_needed(no_copy: bool, prefetched: bool, has_slot: bool) -> Result<b
if has_slot { Err(RingRefusal::SourceAlreadyStaged) } else { Ok(true) }
}
/// The slot `stage_one` copies into from `start`: the next unreserved one, refused when every slot is reserved or when
/// that slot still holds a copy no gather read (the literal ring never gets there; with reserved slots the stage-ahead
/// walk waits instead, see `stage_room`).
/// The slot `stage_one` copies into: the first one from `start` (in ring order, wrapping) that no prefetched source
/// holds and that is free (never filled, or its copy already gathered). Refused when every slot is reserved, or when
/// every unreserved slot still holds a copy no gather read; the stage-ahead walk then waits for a gather
/// (`Ring::stage_room`).
///
/// The literal ring always finds `start` itself: its copies and gathers run in the same order and its lookahead is one
/// slot short of the ring, so the next slot in order holds the oldest copy, already gathered. With prefetched sources
/// the copies skip the hits, the slot order is no longer the gather order, and the next slot in order can hold a copy
/// of an earlier source of the same layer that is not gathered yet (PET.1: layers 46/47, 410-460 sources on 384 slots,
/// `stage.slot_not_gathered` with no slot reserved); the search skips it.
pub fn stage_target(slots: usize, start: usize, state: impl Fn(usize) -> SlotState) -> Result<usize, RingRefusal> {
let sl = next_unreserved_slot(start, slots, |s| state(s).reserved).ok_or(RingRefusal::AllSlotsReserved)?;
let target = state(sl);
if target.live && !target.gathered {
return Err(RingRefusal::SlotNotGathered);
}
Ok(sl)
next_unreserved_slot(start, slots, |s| state(s).reserved).ok_or(RingRefusal::AllSlotsReserved)?;
let free = |s: usize| {
let target = state(s);
!target.reserved && (!target.live || target.gathered)
};
(0..slots).map(|step| (start + step) % slots).find(|s| free(*s)).ok_or(RingRefusal::SlotNotGathered)
}
#[cfg(test)]
+73 -4
View File
@@ -119,10 +119,10 @@ impl RingModel {
/// `Ring::stage_room`: always true without reserved slots (the literal ring).
fn room(&self, index: usize) -> bool {
let reserved = self.ring.iter().any(|s| s.reserved);
!reserved
|| self.kinds[index] != Kind::Copy
|| stage_target(self.ring.len(), self.next, |s| self.ring[s]).is_ok()
let found = stage_target(self.ring.len(), self.next, |s| self.ring[s]).is_ok();
let free = self.ring.iter().any(|s| !s.reserved && (!s.live || s.gathered));
assert_eq!(found, free, "stage_target refuses only when no unreserved slot is free (PET.1)");
self.kinds[index] != Kind::Copy || found
}
/// `Ring::stage_one`.
@@ -133,6 +133,8 @@ impl RingModel {
return Ok(());
}
let sl = stage_target(self.ring.len(), self.next, |s| self.ring[s])?;
let target = self.ring[sl];
assert!(!target.reserved && !(target.live && !target.gathered), "source {index} overwrites slot {sl}");
self.ring[sl].staged();
self.at[index] = Some(sl);
self.next = (sl + 1) % self.ring.len();
@@ -256,3 +258,70 @@ fn the_drains_stay_context_wide_unless_detached() {
assert!(!policy.detach_drains);
assert!(policy.with_detached_drains(true).detach_drains);
}
/// A small deterministic generator for the randomized ring walks.
struct Lcg(u64);
impl Lcg {
fn below(&mut self, n: usize) -> usize {
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
((self.0 >> 33) as usize) % n
}
}
/// `sources` routed experts on `slots` stage slots: about a tenth resident, and the prefetch's `budget` entries in
/// slots `0..budget`, each consumed (a hit) with probability ~55 % by a random copy source among the first ones.
fn prefetched_layer(seed: u64, sources: usize, slots: usize) -> Vec<Kind> {
let mut rng = Lcg(seed);
let mut kinds: Vec<Kind> =
(0..sources).map(|_| if rng.below(10) == 0 { Kind::Resident } else { Kind::Copy }).collect();
let budget = RingPrefetchPolicy::new(150, 8).budget(slots);
for slot in 0..budget {
if rng.below(100) < 55 {
let source = rng.below(sources.min(300));
if kinds[source] == Kind::Copy {
kinds[source] = Kind::Hit(slot);
}
}
}
kinds
}
#[test]
fn more_sources_than_slots_with_prefetch_hits_never_stage_onto_an_unread_slot() {
// PET.1: layers 46/47 route 410-460 experts on the 384-slot ring; the stage order wraps past the hits
for seed in 0..200 {
let kinds = prefetched_layer(seed, 460, 384);
let at = walk(384, &kinds);
for (i, kind) in kinds.iter().enumerate() {
match kind {
Kind::Resident => assert_eq!(at[i], None),
Kind::Hit(slot) => assert_eq!(at[i], Some(*slot), "seed {seed}: hit {i} reads its prefetched slot"),
Kind::Copy => assert!(at[i].is_some(), "seed {seed}: copy {i} was staged"),
}
}
}
}
#[test]
fn the_next_slot_in_order_may_be_unread_after_hits_and_the_search_skips_it() {
// slot 1 holds an unread copy (an earlier source), slot 2 is free: the literal "next in order" would be refused
let mut ring = [SlotState::default(); 4];
ring[0].staged();
ring[0].gathered();
ring[1].staged();
assert_eq!(stage_target(4, 1, |s| ring[s]), Ok(2));
ring[2].staged();
ring[3].staged();
assert_eq!(stage_target(4, 1, |s| ring[s]), Ok(0), "wraps to the gathered slot");
}
#[test]
fn every_size_and_seed_keeps_the_ring_sound() {
for (sources, slots) in [(40, 32), (100, 32), (200, 96), (460, 384), (512, 384), (300, 384)] {
for seed in 0..50 {
let kinds = prefetched_layer(seed, sources, slots);
assert!(walk(slots, &kinds).iter().zip(&kinds).all(|(at, k)| at.is_some() == (*k != Kind::Resident)));
}
}
}
+17
View File
@@ -130,3 +130,20 @@ of the small-chunk mixers and routers while the copies are pending. A drain in t
registered, for example the QSA resident-transfer side stream. This is a suspect, not a proven cause: the error code
alone does not say which check refused. That mode is now opt-in
(`_DETACH`). If the failure persists with it off, the `RING-REFUSE` line names the check.
## Second GPU run (pkg-s16, 51b36adf7): `stage.slot_not_gathered` on layers 46/47
9 of 30 requests failed with the same refusal in both arms (with and without `_DETACH`):
`RING-REFUSE layer=46|47 check=stage.slot_not_gathered source=391..435 stage_next=7..191 reserved=0 slots=384
sources=410..460`. So the detached drains were not the cause. The cause was the slot search. Without a prefetch,
copies and gathers run in the same order and the lookahead is one slot short of the ring, so the next slot in ring order
always holds the oldest copy, already gathered. With prefetch hits, the copies skip the hit sources, and once the
layer's sources exceed the ring, the wrap reaches a slot that holds an earlier source's copy that is not gathered yet.
The old `stage_room` shortcut (`reserved == 0`, true once every hit was gathered) then let `stage_one` refuse.
Fix: `stage_target` searches forward, wrapping, for the first slot that is not reserved and is free (never filled, or
already gathered). Without a prefetch it finds `stage_next` itself, as in the literal ring. `stage_room` is now always
"needs no copy, or `stage_target` finds a slot", so the walk waits for a gather instead of refusing. Host tests: 200
seeds of 460 sources on 384 slots with random prefetch hits among the first 300 sources, plus other sizes. The model
asserts that no stage targets a reserved or unread slot, and that `stage_target` refuses only when no unreserved slot is
free. With the old `stage_target`, both assertions fail.