Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
69 changes: 63 additions & 6 deletions crates/skippy-server/src/frontend/generation_receipt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,29 +161,56 @@ impl GenerationLifecycleObservation {
pub trait GenerationLifecycleIngress: Send + Sync {
fn try_submit(&self, observation: GenerationLifecycleObservation) -> Result<()>;

/// Submits an observation and waits until it has been delivered. Direct
/// ingresses can use their ordered submission path; queued adapters
/// override this to avoid dropping a commit when their queue is full.
fn submit_ordered(&self, observation: GenerationLifecycleObservation) -> Result<()> {
self.try_submit(observation)?;
self.flush()
}

/// Waits until all observations submitted before this call have been
/// delivered. Direct ingresses are already ordered at submission time;
/// queued adapters override this to provide an explicit boundary.
fn flush(&self) -> Result<()> {
Ok(())
}

/// Asynchronous delivery failures observed after a successful submission.
fn delivery_failures(&self) -> u64 {
0
}
}

enum QueuedGenerationLifecycleMessage {
Observation(GenerationLifecycleObservation),
Barrier(SyncSender<Result<()>>),
}

struct QueuedGenerationReceiptSink {
sender: SyncSender<GenerationLifecycleObservation>,
sender: SyncSender<QueuedGenerationLifecycleMessage>,
delivery_failures: Arc<AtomicU64>,
}

impl QueuedGenerationReceiptSink {
fn new(sink: Arc<dyn GenerationReceiptSink>) -> Self {
let (sender, receiver) =
sync_channel::<GenerationLifecycleObservation>(GENERATION_RECEIPT_QUEUE_CAPACITY);
sync_channel::<QueuedGenerationLifecycleMessage>(GENERATION_RECEIPT_QUEUE_CAPACITY);
let delivery_failures = Arc::new(AtomicU64::new(0));
let worker_delivery_failures = Arc::clone(&delivery_failures);
std::thread::Builder::new()
.name("skippy-generation-receipts".into())
.spawn(move || {
while let Ok(observation) = receiver.recv() {
if observation.deliver_to(sink.as_ref()).is_err() {
worker_delivery_failures.fetch_add(1, Ordering::Relaxed);
while let Ok(message) = receiver.recv() {
match message {
QueuedGenerationLifecycleMessage::Observation(observation) => {
if observation.deliver_to(sink.as_ref()).is_err() {
worker_delivery_failures.fetch_add(1, Ordering::Relaxed);
}
}
QueuedGenerationLifecycleMessage::Barrier(completion) => {
let _ = completion.send(Ok(()));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}
}
})
Expand All @@ -198,7 +225,7 @@ impl QueuedGenerationReceiptSink {
impl GenerationLifecycleIngress for QueuedGenerationReceiptSink {
fn try_submit(&self, observation: GenerationLifecycleObservation) -> Result<()> {
self.sender
.try_send(observation)
.try_send(QueuedGenerationLifecycleMessage::Observation(observation))
.map_err(|error| match error {
TrySendError::Full(_) => anyhow::anyhow!("generation lifecycle queue is full"),
TrySendError::Disconnected(_) => {
Expand All @@ -210,6 +237,23 @@ impl GenerationLifecycleIngress for QueuedGenerationReceiptSink {
fn delivery_failures(&self) -> u64 {
self.delivery_failures.load(Ordering::Relaxed)
}

fn flush(&self) -> Result<()> {
let (completion, completed) = sync_channel(0);
self.sender
.send(QueuedGenerationLifecycleMessage::Barrier(completion))
.map_err(|_| anyhow::anyhow!("generation lifecycle delivery worker is unavailable"))?;
completed
.recv()
.map_err(|_| anyhow::anyhow!("generation lifecycle delivery worker is unavailable"))?
}

fn submit_ordered(&self, observation: GenerationLifecycleObservation) -> Result<()> {
self.sender
.send(QueuedGenerationLifecycleMessage::Observation(observation))
.map_err(|_| anyhow::anyhow!("generation lifecycle delivery worker is unavailable"))?;
self.flush()
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

/// Optional local-generation observation.
Expand Down Expand Up @@ -284,6 +328,19 @@ impl GenerationReceiptConfig {
self.enqueue(GenerationLifecycleObservation::Committed(commit));
}

/// Commits a token and waits until the lifecycle ingress has delivered it.
/// Local generation uses this before the next proposal lookup so consumers
/// cannot observe a stale canonical position.
pub(crate) fn committed_before_proposal(&self, commit: GenerationCommit) {
if self
.ingress
.submit_ordered(GenerationLifecycleObservation::Committed(commit))
.is_err()
{
self.submission_failures.fetch_add(1, Ordering::Relaxed);
}
}

pub(crate) fn abort(&self, abort: GenerationAbort) {
self.enqueue(GenerationLifecycleObservation::Aborted(abort));
}
Expand Down
46 changes: 45 additions & 1 deletion crates/skippy-server/src/frontend/local_generation/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use crate::frontend::generation::{
LocalGeneration, OpenAiBackendMode, OpenAiCacheHints, OpenAiGenerationIds, StageOpenAiBackend,
TokenControl,
};
use crate::frontend::local_generation::token_generation::commit_local_generation_token;
use crate::frontend::local_generation::{
native_mtp_dispatch_counts_for_test, prompt_fits_single_prefill_sample,
};
Expand All @@ -30,6 +31,7 @@ use crate::telemetry::{Telemetry, TelemetryLevel};
#[derive(Default)]
struct RecordingReceiptSink {
receipts: Mutex<Vec<GenerationReceipt>>,
commits: Mutex<Vec<GenerationCommit>>,
fail: AtomicBool,
}

Expand All @@ -38,7 +40,8 @@ impl GenerationReceiptSink for RecordingReceiptSink {
Ok(())
}

fn committed(&self, _commit: &GenerationCommit) -> Result<()> {
fn committed(&self, commit: &GenerationCommit) -> Result<()> {
self.commits.lock().unwrap().push(commit.clone());
Ok(())
}

Expand All @@ -65,6 +68,16 @@ fn wait_for_receipts(sink: &RecordingReceiptSink, expected: usize) {
panic!("timed out waiting for {expected} generation receipts");
}

fn wait_for_commits(sink: &RecordingReceiptSink, expected: usize) {
for _ in 0..100 {
if sink.commits.lock().unwrap().len() >= expected {
return;
}
thread::sleep(Duration::from_millis(1));
}
panic!("timed out waiting for {expected} generation commits");
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@coderabbitai does rust have a stronger pattern for this instead of busy-wait looping?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ndizazzo Yes. Use std::sync::Condvar with the commit storage.

RecordingReceiptSink::committed can notify the condition variable after it pushes a commit. Then wait_for_commits can use Condvar::wait_timeout_while to block until the expected count arrives or a single timeout expires.

This avoids the 1 ms polling interval and reduces test scheduler sensitivity. A channel with recv_timeout is also valid, but Condvar fits the existing shared Vec<GenerationCommit> state best.

You are interacting with an AI system.

#[test]
fn single_prefill_sample_requires_prompt_to_fit_session_batch() {
assert!(!prompt_fits_single_prefill_sample(0, 2048));
Expand All @@ -73,6 +86,27 @@ fn single_prefill_sample_requires_prompt_to_fit_session_batch() {
assert!(!prompt_fits_single_prefill_sample(2049, 2048));
}

#[test]
fn local_generation_commit_helper_preserves_ordered_counts() {
let sink = Arc::new(RecordingReceiptSink::default());
let config = GenerationReceiptConfig::new(sink.clone());
let mut generated_token_count = 0;

commit_local_generation_token(Some(&config), 11, 22, &mut generated_token_count, 33);
commit_local_generation_token(Some(&config), 11, 22, &mut generated_token_count, 44);

let commits = sink.commits.lock().unwrap();
assert_eq!(commits.len(), 2);
assert_eq!(commits[0].request_id, 11);
assert_eq!(commits[0].session_id, 22);
assert_eq!(commits[0].generated_token_count, 1);
assert_eq!(commits[0].token_ids.as_ref(), [33]);
assert_eq!(commits[1].request_id, 11);
assert_eq!(commits[1].session_id, 22);
assert_eq!(commits[1].generated_token_count, 2);
assert_eq!(commits[1].token_ids.as_ref(), [44]);
}

#[test]
fn local_native_mtp_decode_uses_non_frame_runtime_api() {
let (sampled_calls, frame_calls) = native_mtp_dispatch_counts_for_test();
Expand Down Expand Up @@ -188,7 +222,17 @@ fn local_generation_eventually_delivers_receipts_and_cleanup_survives_sink_error
},
)?;

wait_for_commits(&sink, emitted.len());
wait_for_receipts(&sink, 1);
let commits = sink.commits.lock().unwrap();
assert_eq!(commits.len(), emitted.len());
for (index, (commit, token_id)) in commits.iter().zip(&emitted).enumerate() {
assert_eq!(commit.request_id, ids.request_id);
assert_eq!(commit.session_id, ids.session_id);
assert_eq!(commit.generated_token_count, index + 1);
assert_eq!(commit.token_ids.as_ref(), [*token_id]);
}
drop(commits);
let receipts = sink.receipts.lock().unwrap();
assert_eq!(receipts.len(), 1);
assert_eq!(receipts[0].request_id, ids.request_id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ use crate::frontend::generation::OpenAiGenerationIds;
use crate::frontend::generation::PhaseTimer;
use crate::frontend::generation::StageOpenAiBackend;
use crate::frontend::generation::TokenControl;
use crate::frontend::generation_receipt::{GenerationStart, complete_generation_before_cleanup};
use crate::frontend::generation_receipt::{
GenerationCommit, GenerationStart, complete_generation_before_cleanup,
};
use crate::frontend::linear_proposal::greedy_linear_proposal_admitted;
use crate::frontend::util::openai_backend_error;
use crate::frontend::util::saturating_u32;
Expand All @@ -29,6 +31,25 @@ use std::time::Duration;

use super::{LocalGenerationReceiptFinalization, prompt_fits_single_prefill_sample};

pub(super) fn commit_local_generation_token(
config: Option<&crate::frontend::GenerationReceiptConfig>,
request_id: u64,
session_id: u64,
generated_token_count: &mut usize,
token_id: i32,
) {
let Some(config) = config else {
return;
};
*generated_token_count = generated_token_count.saturating_add(1);
config.committed_before_proposal(GenerationCommit {
request_id,
session_id,
generated_token_count: *generated_token_count,
token_ids: vec![token_id].into_boxed_slice(),
});
}

struct PromptPrefillResult {
prompt_prefill_sample: Option<i32>,
chat_sampling_configured: bool,
Expand Down Expand Up @@ -109,12 +130,20 @@ impl StageOpenAiBackend {
let mut receipt_cancelled = false;
let mut receipt_model_generation_elapsed = None;
let mut cache_stats = GenerationCacheStats::default();
let mut lifecycle_committed_token_count = 0usize;
let mut emit_token = |token_id| {
if let Some(observation) = receipt_observation.as_ref()
&& let Some(observation) = observation.borrow_mut().as_mut()
{
observation.record_token(token_id, request.ids.request_started_at.elapsed());
}
commit_local_generation_token(
self.generation_receipt.as_ref(),
receipt_request_id,
receipt_session_id,
&mut lifecycle_committed_token_count,
token_id,
);
let control = on_token(token_id)?;
if control == TokenControl::Stop
&& let Some(observation) = receipt_observation.as_ref()
Expand Down
Loading