Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
182 lines
5.7 KiB
Rust
182 lines
5.7 KiB
Rust
//! Optional queue deadline. Claim and expiration have one atomic winner.
|
|
use crate::worker::GenerationCommand;
|
|
use std::sync::{
|
|
Arc,
|
|
atomic::{AtomicU8, Ordering},
|
|
};
|
|
use std::time::Duration;
|
|
use tokio::{
|
|
sync::{mpsc, oneshot},
|
|
time::{Instant, timeout_at},
|
|
};
|
|
|
|
const QUEUED: u8 = 0;
|
|
const CLAIMED: u8 = 1;
|
|
const EXPIRED: u8 = 2;
|
|
|
|
pub struct Ticket {
|
|
deadline: Instant,
|
|
state: Arc<AtomicU8>,
|
|
started: oneshot::Sender<()>,
|
|
}
|
|
impl Ticket {
|
|
pub(crate) fn claim(self) -> bool {
|
|
if self
|
|
.state
|
|
.compare_exchange(QUEUED, CLAIMED, Ordering::AcqRel, Ordering::Acquire)
|
|
.is_err()
|
|
{
|
|
return false;
|
|
}
|
|
// Check after the CAS: a thread may have been preempted across the
|
|
// deadline before claiming. The requester waits for acknowledgment
|
|
// after losing its expiry CAS, so a late claimant can still refuse.
|
|
if Instant::now() >= self.deadline {
|
|
self.state.store(EXPIRED, Ordering::Release);
|
|
return false;
|
|
}
|
|
// A requester that disappeared before acknowledgment must not start work.
|
|
self.started.send(()).is_ok()
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, PartialEq, Eq)]
|
|
pub enum Error {
|
|
Expired,
|
|
Closed,
|
|
}
|
|
|
|
pub async fn enqueue(
|
|
sender: &mpsc::Sender<GenerationCommand>,
|
|
mut command: GenerationCommand,
|
|
budget: Option<Duration>,
|
|
) -> Result<(), Error> {
|
|
let Some(budget) = budget else {
|
|
return sender.send(command).await.map_err(|_| Error::Closed);
|
|
};
|
|
let deadline = Instant::now() + budget;
|
|
let state = Arc::new(AtomicU8::new(QUEUED));
|
|
let (started, mut received) = oneshot::channel();
|
|
command.queue = Some(Ticket {
|
|
deadline,
|
|
state: state.clone(),
|
|
started,
|
|
});
|
|
match timeout_at(deadline, sender.send(command)).await {
|
|
Err(_) => return Err(Error::Expired),
|
|
Ok(Err(_)) => return Err(Error::Closed),
|
|
Ok(Ok(())) => (),
|
|
}
|
|
let acknowledged = tokio::select! {
|
|
biased;
|
|
result = &mut received => result,
|
|
_ = tokio::time::sleep_until(deadline) => {
|
|
if state.compare_exchange(QUEUED, EXPIRED, Ordering::AcqRel, Ordering::Acquire).is_ok() {
|
|
return Err(Error::Expired);
|
|
}
|
|
// The worker won the claim race. Its synchronous acknowledgment or
|
|
// channel closure resolves this wait; the queue clock no longer applies.
|
|
received.await
|
|
}
|
|
};
|
|
acknowledged.map_err(|_| {
|
|
if state.load(Ordering::Acquire) == EXPIRED {
|
|
Error::Expired
|
|
} else {
|
|
Error::Closed
|
|
}
|
|
})
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::{wire::Generate, worker::GenerationResult};
|
|
fn command() -> (
|
|
GenerationCommand,
|
|
oneshot::Receiver<Result<Vec<crate::wire::Event>, String>>,
|
|
) {
|
|
let (result, received) = oneshot::channel();
|
|
(
|
|
GenerationCommand {
|
|
queue: None,
|
|
activity: None,
|
|
request: Generate {
|
|
token_ids: vec![65],
|
|
max_new: 1,
|
|
temperature: None,
|
|
top_p: None,
|
|
},
|
|
result: GenerationResult::Buffered(result),
|
|
},
|
|
received,
|
|
)
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn full_channel_and_unclaimed_jobs_expire_without_claim() {
|
|
let (sender, mut pending) = mpsc::channel(1);
|
|
let (first, _first_result) = command();
|
|
sender.send(first).await.unwrap();
|
|
let (second, _second_result) = command();
|
|
assert_eq!(
|
|
enqueue(&sender, second, Some(Duration::from_millis(10))).await,
|
|
Err(Error::Expired)
|
|
);
|
|
drop(pending.recv().await.unwrap());
|
|
assert!(
|
|
pending.try_recv().is_err(),
|
|
"channel-timeout job was never queued"
|
|
);
|
|
let (third, _third_result) = command();
|
|
assert_eq!(
|
|
enqueue(&sender, third, Some(Duration::from_millis(10))).await,
|
|
Err(Error::Expired)
|
|
);
|
|
assert!(!pending.recv().await.unwrap().queue.unwrap().claim());
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn claim_removes_queue_deadline_and_closed_queue_is_distinct() {
|
|
let (sender, mut pending) = mpsc::channel(1);
|
|
let (job, _result) = command();
|
|
let submit =
|
|
tokio::spawn(async move { enqueue(&sender, job, Some(Duration::from_secs(1))).await });
|
|
let mut job = pending.recv().await.unwrap();
|
|
assert!(job.queue.take().unwrap().claim());
|
|
assert_eq!(submit.await.unwrap(), Ok(()));
|
|
// A claimed job has no remaining ticket/timer attached to execution.
|
|
assert!(job.queue.is_none());
|
|
let (sender, pending) = mpsc::channel(1);
|
|
drop(pending);
|
|
let (job, _result) = command();
|
|
assert_eq!(
|
|
enqueue(&sender, job, Some(Duration::from_secs(1))).await,
|
|
Err(Error::Closed)
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn worker_claim_rejects_late_expired_and_abandoned_tickets() {
|
|
for (deadline, initial, abandoned) in [
|
|
(Instant::now() - Duration::from_secs(1), QUEUED, false),
|
|
(Instant::now() + Duration::from_secs(10), EXPIRED, false),
|
|
(Instant::now() + Duration::from_secs(10), QUEUED, true),
|
|
] {
|
|
let (started, received) = oneshot::channel();
|
|
let state = Arc::new(AtomicU8::new(initial));
|
|
if abandoned {
|
|
drop(received);
|
|
}
|
|
assert!(
|
|
!Ticket {
|
|
deadline,
|
|
state,
|
|
started
|
|
}
|
|
.claim()
|
|
);
|
|
}
|
|
}
|
|
}
|