Files
leleka/control-plane/src/queue.rs
T
Pavlo Ratushnyi c1aa6d0194 STRA-338 size-gw: 13 more production functions of control-plane and desktop-core within the limits (helpers extracted, behaviour unchanged)
The five operator_*_execution parsers of the inference binary share select_execution_flag; the others are
mtp_pack::check, preflight_space, check_activation_link, service_install show, validate_auto, Ssh Config::arguments,
Manager::with_journal, Terminal::feed, Pool::acquire, Agent::build, enqueue_with, GenerationMetrics::finish and
NativeModel::validate.

Test ids: 543 before and after, 0 missing, 0 outcome changes; warnings in the two crates 0.
Counts (strata-control / strata-desktop-core), functions over 30 lines / complexity 10 / nesting 4 / wide lines, prod:
166/130/17/194 -> 158/127/17/194 and 77/59/6/54 -> 67/58/6/54.
2026-11-06 13:50:36 +01:00

223 lines
7.2 KiB
Rust

//! Optional queue deadline. Claim and expiration have one atomic winner.
use crate::{adapters::SystemClock, ports::SharedClock, 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,
clock: SharedClock,
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 self.clock.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,
}
/// [`enqueue_with`] on the system clock.
pub async fn enqueue(
sender: &mpsc::Sender<GenerationCommand>,
command: GenerationCommand,
budget: Option<Duration>,
) -> Result<(), Error> {
enqueue_with(sender, command, budget, SystemClock::shared()).await
}
/// Queue a command; with a `budget` it must be claimed by the worker before `clock.now() + budget`.
pub async fn enqueue_with(
sender: &mpsc::Sender<GenerationCommand>,
mut command: GenerationCommand,
budget: Option<Duration>,
clock: SharedClock,
) -> Result<(), Error> {
let Some(budget) = budget else {
return sender.send(command).await.map_err(|_| Error::Closed);
};
let deadline = clock.now() + budget;
let state = Arc::new(AtomicU8::new(QUEUED));
let (started, received) = oneshot::channel();
command.queue = Some(Ticket {
deadline,
clock,
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(())) => (),
}
await_start(received, &state, deadline).await
}
/// Wait until the worker takes the request off the queue, or expire it at `deadline` if nobody has claimed it.
async fn await_start(
mut received: oneshot::Receiver<()>,
state: &AtomicU8,
deadline: Instant,
) -> Result<(), Error> {
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,
..Default::default()
},
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,
clock: SystemClock::shared(),
state,
started
}
.claim()
);
}
}
#[tokio::test]
async fn queue_deadline_follows_the_injected_clock() {
let clock = crate::ports::fakes::ManualClock::new(0);
let (sender, mut pending) = mpsc::channel(1);
let (job, _result) = command();
let submit_clock = clock.clone();
let submit = tokio::spawn(async move {
enqueue_with(&sender, job, Some(Duration::from_secs(30)), submit_clock).await
});
let ticket = pending.recv().await.unwrap().queue.unwrap();
// 31 s pass on the injected clock only; no real time does.
clock.advance(Duration::from_secs(31));
assert!(
!ticket.claim(),
"a claim after the deadline of the injected clock must be refused"
);
assert_eq!(submit.await.unwrap(), Err(Error::Expired));
}
}