Skip to content

Commit dfa18d5

Browse files
MengqingCaoclaude
andcommitted
feat(mesh): charge non-streaming single-worker prefill, release on the KV event
A non-streaming single-worker request charged no prefill, so agentic saw a worker prefilling a long prompt as idle until the response ended. - The planner charges a single-worker prompt whether or not it streams. - KvEventMonitor::watch_prefill registers a non-streaming request's charge on the selected rank's lane, keyed by the prefix hash of the prompt's last full block; called on HTTP, ext-proc and gRPC. - The index writer releases one watch per stored block, oldest first, and skips charges the first byte already released; a released lane drops its watches and the sweep prunes watches whose guard is gone. Registration holds the subscription's map entry, so a lane cannot be released and reused mid-register. - The first byte stays the fallback: cached repeats, sub-block prompts and workers without a KV event subscription (gRPC single workers today). - docs/agentic_cost.md and the mesh_worker_prefill_tokens help no longer list an uncharged single-worker path. Co-Authored-By: Claude <noreply@anthropic.com>
1 parent 6011237 commit dfa18d5

14 files changed

Lines changed: 514 additions & 32 deletions

File tree

‎atom/mesh/docs/agentic_cost.md‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,11 @@ with no extra bonus, as in the engine's `least_tokens` DP balancer.
2222
| `request_token_equivalent` | `--agentic-request-token-equivalent` (512). Keep it equal to the engine's `ATOM_DP_LB_REQ_EQUIV`. |
2323

2424
The selected worker is charged its `uncached_tokens`, released when its P/D
25-
prefill response completes or at a streaming response's first chunk: the first
26-
HTTP frame, the first ext-proc response body message, or the first gRPC engine
27-
chunk. A cancelled or failed request releases it when its load guard drops.
28-
Non-streaming single-worker requests, on every path, are not charged, so their
29-
prefills weigh only through `inflight_requests`. Under
25+
prefill response completes or at a single-worker response's first chunk: the
26+
first HTTP frame, the first ext-proc response body message, or the first gRPC
27+
engine chunk. A non-streaming single-worker request is released earlier when
28+
the selected rank's KV events (`--kv-events`) store its prompt's last full
29+
block. A cancelled or failed request releases it when its load guard drops. Under
3030
idx2idx the planner selects decode first, so `agentic` chooses among the
3131
prefill workers on its rank. For a request the index can match, `agentic`
3232
predicts the selected worker's blocks (`on_routed`) and reports an estimated

‎atom/mesh/src/core/placement/planner.rs‎

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -122,13 +122,7 @@ impl DefaultPlanner {
122122

123123
Ok(PlacementPlan::Single {
124124
policy_name: policy.name(),
125-
// The router releases the charge at the response's first frame, which a
126-
// non-streaming response sends only after decoding.
127-
prefill_tokens: if req.stream {
128-
prefill_tokens(&chosen, req)
129-
} else {
130-
0
131-
},
125+
prefill_tokens: prefill_tokens(&chosen, req),
132126
worker: chosen.worker,
133127
})
134128
}

‎atom/mesh/src/core/placement/tests.rs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -615,18 +615,18 @@ mod c_regular_planning {
615615
}
616616

617617
#[tokio::test]
618-
async fn test_single_charges_the_prompt_only_when_streaming() {
618+
async fn test_single_charges_the_prompt_prefill_streaming_or_not() {
619619
let src = MockWorkerSource::new().add_worker(make_regular_http("http://m1-w:8000", "m1"));
620620
let planner = make_planner(src, MockPolicySource::new());
621621
let tokens = [1u32, 2, 3];
622-
for (stream, charged) in [(true, 3), (false, 0)] {
622+
for stream in [true, false] {
623623
let descriptor = RequestDescriptor {
624624
stream,
625625
..make_descriptor(Some("m1"), None, Some(&tokens), None)
626626
};
627627
match planner.plan(&descriptor).await.unwrap() {
628628
PlacementPlan::Single { prefill_tokens, .. } => {
629-
assert_eq!(prefill_tokens, charged, "stream={stream}");
629+
assert_eq!(prefill_tokens, 3, "stream={stream}");
630630
}
631631
other => panic!("expected Single, got {:?}", other),
632632
}

‎atom/mesh/src/core/worker.rs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1208,11 +1208,13 @@ impl PrefillCharge {
12081208
})
12091209
}
12101210

1211-
pub fn release(&self) {
1211+
/// True when this call released the tokens, false when there were none left.
1212+
pub fn release(&self) -> bool {
12121213
let tokens = self.tokens.swap(0, Ordering::AcqRel);
12131214
if tokens > 0 {
12141215
self.worker.release_prefill_tokens(tokens);
12151216
}
1217+
tokens > 0
12161218
}
12171219
}
12181220

‎atom/mesh/src/ext_proc/routing.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,13 @@ impl EndpointRouter {
162162
};
163163
let load = WorkerLoadGuard::new(worker.clone(), Some(&request.headers))
164164
.with_prefill_tokens(prefill_tokens);
165+
if let (false, Some(monitor), Some(tokens)) = (
166+
input.stream,
167+
&self.app.kv_event_monitor,
168+
input.tokens.as_deref(),
169+
) {
170+
monitor.watch_prefill(worker.url(), tokens, &load.prefill_charge());
171+
}
165172
let address = match resolved.get(worker.url()) {
166173
Some(address) => *address,
167174
None => Self::address(worker.as_ref()).await?,

‎atom/mesh/src/kv_events/monitor.rs‎

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ use super::{
3434
wire::{self, DecodedBatch},
3535
};
3636
use crate::{
37-
core::Worker,
37+
core::{worker::PrefillCharge, Worker},
3838
kv_index::{match_lanes, Holder, Lane, Partition, Predictor, PrefixMatchProvider},
3939
observability::metrics::schema::names,
4040
};
@@ -210,6 +210,19 @@ impl KvEventMonitor {
210210
self.subscriptions.remove(worker);
211211
}
212212

213+
/// Releases `charge` when `worker`'s followed rank stores the last full block of
214+
/// `tokens`. Nothing waits without a followed rank or a full block.
215+
pub fn watch_prefill(&self, worker: &str, tokens: &[u32], charge: &Arc<PrefillCharge>) {
216+
// Under the entry's lock, so the rank keeps its lane until the charge waits on it, and
217+
// the lane's release drops the charge with the rank's other watches.
218+
let Some(subscription) = self.subscriptions.get(worker) else {
219+
return;
220+
};
221+
if let Some(((partition, lane), _)) = subscription.events() {
222+
partition.watch_prefill(lane, tokens, charge);
223+
}
224+
}
225+
213226
fn partition(&self, model_id: &str, pool: &'static str, block_size: u32) -> Arc<Partition> {
214227
self.partitions
215228
.entry((model_id.into(), pool, block_size))
@@ -599,7 +612,7 @@ fn record(status: &mut SourceStatus, trust: Trust, seq: u64, batch: &DecodedBatc
599612
}
600613

601614
#[cfg(test)]
602-
mod tests {
615+
pub(crate) mod tests {
603616
use zeromq::{util::PeerIdentity, PubSocket, RouterSocket};
604617

605618
use super::*;
@@ -740,6 +753,33 @@ mod tests {
740753
format!("tcp://{}", listener.local_addr().unwrap())
741754
}
742755

756+
/// Follows rank 1 of `worker`, alone on `monitor`, from a publisher of blocks of 4
757+
/// tokens, once its stream is joined.
758+
pub(crate) async fn followed(monitor: &KvEventMonitor, worker: &str) -> PubSocket {
759+
let endpoint = free_endpoint();
760+
let source = KvEventSource {
761+
endpoint: endpoint.clone(),
762+
topic: "kv".into(),
763+
block_size: 4,
764+
..Default::default()
765+
};
766+
monitor.attach(worker, "m", "regular", 1, source);
767+
let mut publisher = bind(&endpoint).await;
768+
clear_until(&mut publisher, monitor, |s| s.batches > 0).await;
769+
publisher
770+
}
771+
772+
/// Publishes rank 1's store of the full blocks of `tokens` from the root, each block
773+
/// hashed as its last token.
774+
pub(crate) async fn publish_stored(publisher: &mut PubSocket, seq: u64, tokens: &[u32]) {
775+
let blocks = &tokens[..tokens.len() / 4 * 4];
776+
let hashes: Vec<u32> = blocks.chunks(4).map(|block| block[3]).collect();
777+
let stored = format!(
778+
r#"[{{"type": "BlockStored", "block_hashes": {hashes:?}, "token_ids": {blocks:?}, "block_size": 4, "medium": "GPU"}}]"#
779+
);
780+
publish(publisher, "kv", seq, &stored, 1).await;
781+
}
782+
743783
/// Waits for the writers to apply the prompts routed, until `workers` match `hits`.
744784
async fn matched(
745785
monitor: &KvEventMonitor,

‎atom/mesh/src/kv_index/partition.rs‎

Lines changed: 67 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,11 @@
22
//! and the writer thread that alone applies their admitted batches, in order. The prompts
33
//! routed to each worker are predictions on lanes of a second index, kept apart from the
44
//! events. A predicted block matches until the first sweep after a TTL from its last
5-
//! routing, so for up to TTL + TTL/8.
5+
//! routing, so for up to TTL + TTL/8. A non-streaming prefill's charge waits on its rank's
6+
//! lane for the store of its last full prompt block.
67
78
use std::{
8-
collections::HashMap,
9+
collections::{HashMap, VecDeque},
910
sync::{
1011
atomic::{AtomicBool, AtomicUsize, Ordering},
1112
Arc, Weak,
@@ -26,7 +27,13 @@ use super::{
2627
index::{find_matches, HolderTable, Op, PrefixIndex},
2728
HolderId, PrefixHash,
2829
};
29-
use crate::kv_events::{model::KvEvent, SourceStatus};
30+
use crate::{
31+
core::worker::PrefillCharge,
32+
kv_events::{
33+
model::{KvEvent, StoredBlock},
34+
SourceStatus,
35+
},
36+
};
3037

3138
/// Admitted batches a partition's writer may fall behind by before its ranks wait.
3239
const QUEUED_BATCHES: usize = 1024;
@@ -55,6 +62,8 @@ pub(crate) struct Partition {
5562
predictions: mpsc::Sender<Write>,
5663
/// Tokens of the prompts queued in `predictions`.
5764
queued_tokens: AtomicUsize,
65+
/// Prefill charges by the lane and last full prompt block they wait for, oldest first.
66+
pub(super) watches: Mutex<HashMap<(HolderId, PrefixHash), VecDeque<Weak<PrefillCharge>>>>,
5867
}
5968

6069
enum Write {
@@ -92,6 +101,7 @@ impl Partition {
92101
behind: AtomicBool::new(false),
93102
predictions,
94103
queued_tokens: AtomicUsize::new(0),
104+
watches: Mutex::default(),
95105
});
96106
let writer = Arc::downgrade(&partition);
97107
std::thread::Builder::new()
@@ -130,6 +140,40 @@ impl Partition {
130140
}
131141
predictor
132142
}
143+
144+
/// Releases `charge` when the rank on `lane` stores the last full block of `tokens`;
145+
/// a prompt shorter than a block has none to wait for.
146+
pub(crate) fn watch_prefill(
147+
&self,
148+
lane: HolderId,
149+
tokens: &[u32],
150+
charge: &Arc<PrefillCharge>,
151+
) {
152+
if let Some(&last) = hash::prefix_hashes(tokens, self.block_size).last() {
153+
let mut watches = self.watches.lock();
154+
let waiting = watches.entry((lane, last)).or_default();
155+
waiting.push_back(Arc::downgrade(charge));
156+
}
157+
}
158+
159+
/// Each block stored on `lane` releases the oldest charge waiting for it that is still
160+
/// held, as each prefill that computes the block stores it once.
161+
fn release_prefills(&self, lane: HolderId, stored: &[PrefixHash]) {
162+
let mut watches = self.watches.lock();
163+
for &hash in stored {
164+
let Some(waiting) = watches.get_mut(&(lane, hash)) else {
165+
continue;
166+
};
167+
while let Some(watch) = waiting.pop_front() {
168+
if watch.upgrade().is_some_and(|charge| charge.release()) {
169+
break;
170+
}
171+
}
172+
if waiting.is_empty() {
173+
watches.remove(&(lane, hash));
174+
}
175+
}
176+
}
133177
}
134178

135179
fn take(lanes: &Mutex<u64>) -> Option<HolderId> {
@@ -277,6 +321,10 @@ async fn write(
277321
});
278322
partition.predicted.apply(lane, &mut ops);
279323
}
324+
partition.watches.lock().retain(|_, waiting| {
325+
waiting.retain(|watch| watch.strong_count() > 0);
326+
!waiting.is_empty()
327+
});
280328
continue;
281329
}
282330
};
@@ -294,11 +342,22 @@ async fn write(
294342
if reset {
295343
table.clear(&mut ops);
296344
}
345+
// Each stored block's prefix, held already or new.
346+
let mut stored = Vec::new();
297347
let dropped: Vec<_> = events
298348
.iter()
299-
.filter_map(|event| table.apply(event, &mut ops).err())
349+
.filter_map(|event| {
350+
let applied = table.apply(event, &mut ops);
351+
if let KvEvent::Stored { blocks, .. } = event {
352+
let prefix =
353+
|block: &StoredBlock| table.prefixes.get(&block.hash).copied();
354+
stored.extend(blocks.iter().filter_map(prefix));
355+
}
356+
applied.err()
357+
})
300358
.collect();
301359
partition.index.apply(holder, &mut ops);
360+
partition.release_prefills(holder, &stored);
302361
let mut status = status.lock();
303362
status.indexed_blocks = Some(table.len() as u64);
304363
for reason in dropped {
@@ -310,6 +369,10 @@ async fn write(
310369
table.clear(&mut ops);
311370
partition.index.apply(holder, &mut ops);
312371
}
372+
partition
373+
.watches
374+
.lock()
375+
.retain(|&(lane, _), _| lane != holder);
313376
*partition.lanes.lock() &= !(1 << holder.0);
314377
}
315378
Write::Predict(lane, tokens) => {

0 commit comments

Comments
 (0)