//! Response policy: which call Jarvis answers, in what order, and when an answer stops //! (`app/src/conversation.spec.md`). //! //! A state machine driven by events with the time passed in. It never plays or asks anything itself: //! every call returns the actions for the caller to carry out. use std::collections::{HashMap, HashSet}; use std::time::{Duration, Instant}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PolicyKind { /// 처음 대화만: new requests are dropped while an answer runs (default). First, /// 들어온 순서대로: answered one after another in end-time order. InOrder, /// 마지막 대화만: the newest request replaces everything else, even a running answer. Latest, /// 제일 중요한 대화만: candidates are collected and the best one is answered. Important, } #[derive(Debug, Clone, PartialEq)] pub struct PolicySettings { pub kind: PolicyKind, pub queue_max: usize, pub collect: Duration, pub settle: Duration, pub priorities: HashMap, /// How long the brain's importance ranking is waited for. pub rank_timeout: Duration, /// `latest` and `important`: a new request may stop the running answer. Off: the answer is /// spoken to its end and the new request waits for it. pub interrupt: bool, } impl Default for PolicySettings { fn default() -> Self { Self { kind: PolicyKind::Latest, queue_max: 5, collect: Duration::from_millis(700), settle: Duration::from_millis(800), priorities: HashMap::new(), rank_timeout: Duration::from_millis(1500), interrupt: true, } } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Request { pub id: u64, pub speaker: u64, pub text: String, /// Called by a wake word. pub direct: bool, /// When the utterance ended. pub ended_at: Instant, /// When its final arrived. pub arrived_at: Instant, } #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum MissReason { /// `first`: an answer was running or another caller finished first. Busy, /// `inOrder`: the queue was full. QueueFull, /// `latest`: a newer request took its place. Replaced, /// The answer was stopped for a newer or more important request. Interrupted, /// `important`: another candidate was chosen. LowerScore, /// A stop command. Stopped, } #[derive(Debug, Clone, PartialEq, Eq)] pub enum Action { /// Start answering this request. Answer(Request), /// Stop the running answer with this id (its speech and its reply). StopAnswer(u64), /// Not answered, or stopped: for the "놓친 요청" list. Missed(Request, MissReason), /// Ask the brain to rank these tied candidates by importance; answer with `ranked(id, ..)`. A newer /// `Rank` replaces an older one, whose answer is then ignored. Rank { id: u64, candidates: Vec }, } #[derive(Debug, Default)] struct Open { /// When the speaker stopped sending audio, if they have. stopped_at: Option, } pub struct Policy { s: PolicySettings, current: Option, waiting: Vec, open: HashMap, /// `important`: no choice before this. collect_until: Option, /// `important`: a ranking the brain was asked for. ranking: Option, next_rank_id: u64, } struct Ranking { rank_id: u64, ids: HashSet, deadline: Instant, /// Asked about interrupting the running answer with this id (it is one of `ids`). against: Option, } impl Policy { pub fn new(s: PolicySettings) -> Self { Self { s, current: None, waiting: vec![], open: HashMap::new(), collect_until: None, ranking: None, next_rank_id: 0 } } pub fn settings(&self) -> &PolicySettings { &self.s } /// The id of the running answer. pub fn current(&self) -> Option { self.current.as_ref().map(|r| r.id) } pub fn waiting(&self) -> usize { self.waiting.len() } /// An utterance started (`speech_start`). pub fn utterance_open(&mut self, speaker: u64) { self.open.insert(speaker, Open::default()); } /// The speaker stopped sending audio; their final is still to come. pub fn speaking_stopped(&mut self, speaker: u64, at: Instant) { if let Some(o) = self.open.get_mut(&speaker) { o.stopped_at.get_or_insert(at); } } /// The speaker's final arrived and was not a call (or the speaker left). pub fn utterance_closed(&mut self, speaker: u64, now: Instant) -> Vec { self.open.remove(&speaker); self.choose(now, None) } fn score(&self, r: &Request) -> (i64, bool) { (self.s.priorities.get(&r.speaker).copied().unwrap_or(0), r.direct) } /// The speaker's final was a call. pub fn request(&mut self, req: Request, now: Instant) -> Vec { self.open.remove(&req.speaker); let mut out = vec![]; if let Some(cur) = self.current.clone() { match self.s.kind { PolicyKind::First => out.push(Action::Missed(req, MissReason::Busy)), PolicyKind::InOrder => self.enqueue(req, &mut out), PolicyKind::Latest => { // Newer than the running answer and than every waiting request (only possible // without interrupting: otherwise the newest is already the running one). let newest = self.waiting.iter().map(|r| r.ended_at).max().map_or(cur.ended_at, |w| w.max(cur.ended_at)); if req.ended_at > newest { if self.s.interrupt { self.interrupt(&mut out); } for r in self.waiting.drain(..) { out.push(Action::Missed(r, MissReason::Replaced)); } self.waiting.push(req); } else { out.push(Action::Missed(req, MissReason::Replaced)); } } PolicyKind::Important => { let (new, running) = (self.score(&req), self.score(&cur)); self.enqueue(req, &mut out); if !self.s.interrupt { // Kept as a candidate; the best one is answered when the running answer ends. } else if new > running { self.interrupt(&mut out); self.collect_until = None; self.ranking = None; } else if new == running { // A tie on priority and wake word: the brain's importance decides, over the // running answer and every candidate tied with it (a pending ranking is replaced, // keeping its deadline). let mut cands = vec![cur.clone()]; cands.extend(self.waiting.iter().filter(|r| self.score(r) == running).cloned()); let deadline = self.ranking.as_ref().map_or(now + self.s.rank_timeout, |r| r.deadline); out.push(self.ask_rank(cands, deadline, Some(cur.id))); } } } } else { if self.s.kind == PolicyKind::Important && self.waiting.is_empty() && self.ranking.is_none() { self.collect_until = Some(now + self.s.collect); } let score = self.score(&req); self.enqueue(req, &mut out); // A candidate arriving while tied candidates are being ranked: a tie joins a new ranking // (same deadline); a better one makes the ranking moot. if let Some(r) = &self.ranking { let ranked_score = self.waiting.iter().find(|q| r.ids.contains(&q.id)).map(|q| self.score(q)); let deadline = r.deadline; match ranked_score { Some(t) if score == t => { let cands: Vec = self.waiting.iter().filter(|q| self.score(q) == t).cloned().collect(); out.push(self.ask_rank(cands, deadline, None)); } Some(t) if score > t => self.ranking = None, _ => {} } } } out.extend(self.choose(now, None)); out } fn enqueue(&mut self, req: Request, out: &mut Vec) { let at = self.waiting.partition_point(|r| r.ended_at <= req.ended_at); self.waiting.insert(at, req); if self.s.kind == PolicyKind::InOrder { while self.waiting.len() > self.s.queue_max.max(1) { out.push(Action::Missed(self.waiting.remove(0), MissReason::QueueFull)); } } } fn ask_rank(&mut self, candidates: Vec, deadline: Instant, against: Option) -> Action { self.next_rank_id += 1; self.ranking = Some(Ranking { rank_id: self.next_rank_id, ids: candidates.iter().map(|r| r.id).collect(), deadline, against, }); Action::Rank { id: self.next_rank_id, candidates } } fn interrupt(&mut self, out: &mut Vec) { if let Some(cur) = self.current.take() { out.push(Action::StopAnswer(cur.id)); out.push(Action::Missed(cur, MissReason::Interrupted)); } } /// The request is taken back before its answer was heard: its speaker went on talking and it is /// joined to what they said next (conversation.spec.md, "Going on"). Not a missed request. When /// it is the running answer it is stopped; nothing else starts until the joined request comes. pub fn withdraw(&mut self, id: u64) -> Vec { if self.current.as_ref().is_some_and(|r| r.id == id) { self.current = None; return vec![Action::StopAnswer(id)]; } self.waiting.retain(|r| r.id != id); if self.ranking.as_ref().is_some_and(|r| r.ids.contains(&id)) { self.ranking = None; } vec![] } /// A stop command: stop the answer and drop everything waiting. pub fn stop(&mut self) -> Vec { let mut out = vec![]; if let Some(cur) = self.current.take() { out.push(Action::StopAnswer(cur.id)); out.push(Action::Missed(cur, MissReason::Stopped)); } for r in self.waiting.drain(..) { out.push(Action::Missed(r, MissReason::Stopped)); } self.collect_until = None; self.ranking = None; out } /// The answer's speech ended, failed or was stopped. pub fn answer_done(&mut self, id: u64, now: Instant) -> Vec { if self.current.as_ref().map(|r| r.id) != Some(id) { return vec![]; } self.current = None; // An interruption ranking is moot once the answer it was about has ended. if self.ranking.as_ref().is_some_and(|r| r.against.is_some()) { self.ranking = None; } self.choose(now, None) } /// The brain's answer to ranking `rank_id`, best first. An answer to any other ranking (replaced or /// dropped) is ignored; one after the deadline counts as a timeout. pub fn ranked(&mut self, rank_id: u64, order: &[u64], now: Instant) -> Vec { if self.ranking.as_ref().map(|r| r.rank_id) != Some(rank_id) { return vec![]; } let r = self.ranking.take().expect("checked"); let winner = if now >= r.deadline { None } else { order.iter().copied().find(|id| r.ids.contains(id)) }; self.resolve(r, winner, now) } fn resolve(&mut self, r: Ranking, winner: Option, now: Instant) -> Vec { let Some(running) = r.against else { return self.choose(now, Some(winner)) }; // Interrupt only when the ranking put a waiting request above the running answer; a timeout // keeps the running answer, which ended first. let mut out = vec![]; match winner { Some(w) if w != running && self.current() == Some(running) && self.waiting.iter().any(|q| q.id == w) => { self.interrupt(&mut out); self.collect_until = None; out.extend(self.choose(now, Some(Some(w)))); } _ => out.extend(self.choose(now, None)), } out } /// Timers: settling, collecting and the ranking timeout. pub fn tick(&mut self, now: Instant) -> Vec { if self.ranking.as_ref().is_some_and(|r| now >= r.deadline) { let r = self.ranking.take().expect("checked"); return self.resolve(r, None, now); } self.choose(now, None) } /// When `tick` should run next. pub fn next_deadline(&self) -> Option { if let Some(r) = &self.ranking { return Some(r.deadline); } if self.current.is_some() || self.waiting.is_empty() { return None; } // Nothing can start before the collect timer ends. if let Some(t) = self.collect_until { return Some(t); } // The settle deadline matters only while an ending utterance holds the choice up. if self.open.values().any(|o| o.stopped_at.is_some()) { return self.waiting.iter().map(|r| r.arrived_at).min().map(|t| t + self.s.settle); } None } /// Wait for an ending utterance that may still be a call that should come first. fn blocked(&self, now: Instant) -> bool { let ending: Vec = self.open.values().filter_map(|o| o.stopped_at).collect(); if ending.is_empty() { return false; } let Some(first_arrival) = self.waiting.iter().map(|r| r.arrived_at).min() else { return false }; if now >= first_arrival + self.s.settle { return false; } match self.s.kind { PolicyKind::Latest => false, PolicyKind::First | PolicyKind::InOrder => { let head = self.waiting[0].ended_at; ending.iter().any(|t| *t < head) } PolicyKind::Important => true, } } /// Start the next answer if the policy allows one now. `rank`: `Some(winner)` once a ranking /// finished or gave up. fn choose(&mut self, now: Instant, rank: Option>) -> Vec { let mut out = vec![]; if self.current.is_some() || self.waiting.is_empty() || (self.ranking.is_some() && rank.is_none()) { return out; } if rank.is_none() { if let Some(t) = self.collect_until { if now < t { return out; } self.collect_until = None; } if self.blocked(now) { return out; } } let winner = match self.s.kind { PolicyKind::First | PolicyKind::InOrder => 0, PolicyKind::Latest => self.waiting.len() - 1, PolicyKind::Important => { let best = self.waiting.iter().map(|r| self.score(r)).max().expect("not empty"); let tied: Vec = (0..self.waiting.len()).filter(|&i| self.score(&self.waiting[i]) == best).collect(); match rank { Some(Some(id)) if tied.iter().any(|&i| self.waiting[i].id == id) => { tied.into_iter().find(|&i| self.waiting[i].id == id).expect("present") } // A ranking that failed, timed out, or named nobody still tied: the earliest-ended. Some(_) => tied[0], None if tied.len() >= 2 => { let cands: Vec = tied.iter().map(|&i| self.waiting[i].clone()).collect(); let deadline = now + self.s.rank_timeout; out.push(self.ask_rank(cands, deadline, None)); return out; } None => tied[0], } } }; let chosen = self.waiting.remove(winner); let others = match self.s.kind { PolicyKind::InOrder => vec![], PolicyKind::First => std::mem::take(&mut self.waiting).into_iter().map(|r| (r, MissReason::Busy)).collect(), PolicyKind::Latest => std::mem::take(&mut self.waiting).into_iter().map(|r| (r, MissReason::Replaced)).collect(), PolicyKind::Important => { std::mem::take(&mut self.waiting).into_iter().map(|r| (r, MissReason::LowerScore)).collect() } }; for (r, why) in others { out.push(Action::Missed(r, why)); } self.collect_until = None; self.current = Some(chosen.clone()); out.push(Action::Answer(chosen)); out } } #[cfg(test)] mod tests { use super::*; const A: u64 = 1; const B: u64 = 2; const C: u64 = 3; struct T { p: Policy, t0: Instant, next_id: u64, } impl T { fn new(kind: PolicyKind) -> Self { Self::with(PolicySettings { kind, ..PolicySettings::default() }) } fn with(s: PolicySettings) -> Self { Self { p: Policy::new(s), t0: Instant::now(), next_id: 0 } } fn at(&self, ms: u64) -> Instant { self.t0 + Duration::from_millis(ms) } /// A call from `speaker` that ended at `ended` ms and arrived at `arrived` ms. fn call(&mut self, speaker: u64, direct: bool, ended: u64, arrived: u64) -> (u64, Vec) { self.next_id += 1; let r = Request { id: self.next_id, speaker, text: String::new(), direct, ended_at: self.at(ended), arrived_at: self.at(arrived) }; let now = self.at(arrived); (self.next_id, self.p.request(r, now)) } } fn answered(a: &[Action]) -> Vec { a.iter().filter_map(|x| if let Action::Answer(r) = x { Some(r.id) } else { None }).collect() } fn missed(a: &[Action]) -> Vec<(u64, MissReason)> { a.iter().filter_map(|x| if let Action::Missed(r, w) = x { Some((r.id, *w)) } else { None }).collect() } /// Every ranking asked for: (ranking id, candidate ids). fn ranks(a: &[Action]) -> Vec<(u64, Vec)> { a.iter().filter_map(|x| if let Action::Rank { id, candidates } = x { Some((*id, candidates.iter().map(|r| r.id).collect())) } else { None }).collect() } fn rank_of(a: &[Action]) -> (u64, Vec) { let r = ranks(a); assert_eq!(r.len(), 1, "one ranking asked for: {a:?}"); r[0].clone() } fn stopped(a: &[Action]) -> Vec { a.iter().filter_map(|x| if let Action::StopAnswer(id) = x { Some(*id) } else { None }).collect() } #[test] fn first_answers_at_once_and_drops_what_comes_while_busy() { let mut t = T::new(PolicyKind::First); let (a, out) = t.call(A, true, 0, 200); assert_eq!(answered(&out), vec![a]); let (b, out) = t.call(B, true, 300, 500); assert_eq!(missed(&out), vec![(b, MissReason::Busy)]); assert!(t.p.answer_done(a, t.at(2000)).is_empty()); let (c, out) = t.call(C, true, 2100, 2300); assert_eq!(answered(&out), vec![c]); } #[test] fn first_waits_for_an_earlier_ended_utterance_and_answers_it_if_it_is_a_call() { let mut t = T::new(PolicyKind::First); // B stopped talking at 100 ms but is still being transcribed; A ended at 150 ms. t.p.utterance_open(B); t.p.speaking_stopped(B, t.at(100)); let (a, out) = t.call(A, true, 150, 300); assert!(answered(&out).is_empty(), "waits for B"); let (b, out) = t.call(B, true, 100, 500); assert_eq!(answered(&out), vec![b], "B finished speaking first"); assert_eq!(missed(&out), vec![(a, MissReason::Busy)]); } #[test] fn settling_ends_when_the_earlier_utterance_is_not_a_call_or_takes_too_long() { let mut t = T::new(PolicyKind::First); t.p.utterance_open(B); t.p.speaking_stopped(B, t.at(100)); let (a, _) = t.call(A, true, 150, 300); assert_eq!(answered(&t.p.utterance_closed(B, t.at(400))), vec![a]); let mut t = T::new(PolicyKind::First); t.p.utterance_open(B); t.p.speaking_stopped(B, t.at(100)); let (a, _) = t.call(A, true, 150, 300); assert_eq!(t.p.next_deadline(), Some(t.at(300 + 800))); assert!(answered(&t.p.tick(t.at(1000))).is_empty()); assert_eq!(answered(&t.p.tick(t.at(1100))), vec![a]); } #[test] fn an_utterance_still_being_spoken_or_ended_later_does_not_hold_up_the_answer() { let mut t = T::new(PolicyKind::First); t.p.utterance_open(B); // still talking t.p.utterance_open(C); t.p.speaking_stopped(C, t.at(400)); // ended after A let (a, out) = t.call(A, true, 150, 300); assert_eq!(answered(&out), vec![a]); } #[test] fn in_order_follows_end_times_not_arrival_and_drops_the_oldest_when_full() { let mut t = T::with(PolicySettings { kind: PolicyKind::InOrder, queue_max: 2, ..PolicySettings::default() }); let (a, out) = t.call(A, true, 0, 100); assert_eq!(answered(&out), vec![a]); let (c, _) = t.call(C, true, 900, 1000); // ended later, arrived first let (b, _) = t.call(B, true, 600, 1500); // long utterance: ended earlier, arrived later assert_eq!(answered(&t.p.answer_done(a, t.at(2000))), vec![b]); assert_eq!(answered(&t.p.answer_done(b, t.at(3000))), vec![c]); let (_, out) = t.call(A, true, 3100, 3200); assert!(answered(&out).is_empty()); let (e, _) = t.call(B, true, 3300, 3400); let (_f, out) = t.call(C, true, 3500, 3600); assert_eq!(t.p.waiting(), 2); assert_eq!(missed(&out).len(), 1, "third waiting request pushes the oldest out"); assert_eq!(answered(&t.p.answer_done(c, t.at(4000))), vec![e]); } #[test] fn latest_interrupts_for_a_newer_request_and_drops_older_ones() { let mut t = T::new(PolicyKind::Latest); let (a, _) = t.call(A, true, 0, 100); let (b, out) = t.call(B, true, 500, 700); assert_eq!(stopped(&out), vec![a]); assert_eq!(missed(&out), vec![(a, MissReason::Interrupted)]); assert_eq!(answered(&out), vec![b]); // A late final from before B's end is not newer. let (c, out) = t.call(C, true, 400, 900); assert_eq!(missed(&out), vec![(c, MissReason::Replaced)]); assert!(stopped(&out).is_empty()); // The stopped answer's late "done" changes nothing. assert!(t.p.answer_done(a, t.at(1000)).is_empty()); assert_eq!(t.p.current(), Some(b)); } #[test] fn without_interrupting_latest_finishes_the_answer_then_answers_the_newest_waiting() { let mut t = T::with(PolicySettings { kind: PolicyKind::Latest, interrupt: false, ..PolicySettings::default() }); let (a, _) = t.call(A, true, 0, 100); let (b, out) = t.call(B, true, 500, 700); assert!(stopped(&out).is_empty(), "the answer keeps playing"); assert!(answered(&out).is_empty()); let (c, out) = t.call(C, true, 800, 900); assert_eq!(missed(&out), vec![(b, MissReason::Replaced)], "a newer waiting request replaces it"); assert_eq!(answered(&t.p.answer_done(a, t.at(2000))), vec![c]); } #[test] fn without_interrupting_latest_keeps_the_newest_waiting_request_whatever_order_finals_arrive_in() { let mut t = T::with(PolicySettings { kind: PolicyKind::Latest, interrupt: false, ..PolicySettings::default() }); let (a, _) = t.call(A, true, 0, 100); let (b, _) = t.call(B, true, 700, 800); // C ended before B but its final came later: B stays, C is replaced. let (c, out) = t.call(C, true, 500, 900); assert_eq!(missed(&out), vec![(c, MissReason::Replaced)]); assert_eq!(answered(&t.p.answer_done(a, t.at(2000))), vec![b]); } #[test] fn without_interrupting_important_waits_for_the_answer_even_for_a_better_request() { let s = PolicySettings { kind: PolicyKind::Important, collect: Duration::ZERO, interrupt: false, priorities: HashMap::from([(B, 5)]), ..PolicySettings::default() }; let mut t = T::with(s); let (a, _) = t.call(A, true, 0, 100); let (b, out) = t.call(B, true, 500, 700); assert!(stopped(&out).is_empty() && ranks(&out).is_empty(), "no stop and no ranking against the answer"); assert_eq!(answered(&t.p.answer_done(a, t.at(2000))), vec![b]); } #[test] fn latest_answers_the_newest_of_several_waiting() { let mut t = T::new(PolicyKind::Latest); t.p.utterance_open(C); let (a, out) = t.call(A, true, 0, 100); assert_eq!(answered(&out), vec![a], "latest never settles"); let (b, _) = t.call(B, true, 200, 300); assert_eq!(t.p.current(), Some(b)); } #[test] fn important_collects_then_answers_the_best_by_priority_then_wake_word() { let mut s = PolicySettings { kind: PolicyKind::Important, ..PolicySettings::default() }; s.priorities.insert(C, 5); let mut t = T::with(s); let (a, out) = t.call(A, true, 0, 100); assert!(answered(&out).is_empty(), "collecting for 700 ms"); let (b, _) = t.call(B, false, 100, 200); let (c, _) = t.call(C, false, 200, 300); assert_eq!(t.p.next_deadline(), Some(t.at(800))); let out = t.p.tick(t.at(800)); assert_eq!(answered(&out), vec![c], "priority wins over the wake word"); let mut m = missed(&out); m.sort_by_key(|(id, _)| *id); assert_eq!(m, vec![(a, MissReason::LowerScore), (b, MissReason::LowerScore)]); } #[test] fn important_asks_for_a_ranking_only_on_a_tie_and_falls_back_on_timeout() { let mut t = T::new(PolicyKind::Important); let (a, _) = t.call(A, true, 0, 100); let (b, _) = t.call(B, true, 50, 200); let out = t.p.tick(t.at(800)); let (r, ids) = rank_of(&out); assert_eq!(ids, vec![a, b]); assert!(answered(&out).is_empty()); assert_eq!(answered(&t.p.ranked(r, &[b, a], t.at(900))), vec![b]); let mut t = T::new(PolicyKind::Important); let (a, _) = t.call(A, true, 0, 100); let (b, _) = t.call(B, true, 50, 200); let (r, _) = rank_of(&t.p.tick(t.at(800))); assert_eq!(t.p.next_deadline(), Some(t.at(800 + 1500))); assert_eq!(answered(&t.p.tick(t.at(2300))), vec![a], "timeout: earliest-ended wins"); assert!(t.p.ranked(r, &[b], t.at(2400)).is_empty(), "a late ranking is ignored"); // One candidate: no ranking, no extra delay beyond collecting. let mut t = T::new(PolicyKind::Important); let (a, _) = t.call(A, true, 0, 100); assert_eq!(answered(&t.p.tick(t.at(800))), vec![a]); } #[test] fn important_interrupts_only_for_a_higher_score_and_otherwise_answers_after() { let mut s = PolicySettings { kind: PolicyKind::Important, collect: Duration::ZERO, ..PolicySettings::default() }; s.priorities.insert(C, 1); let mut t = T::with(s); let (a, out) = t.call(A, false, 0, 100); assert_eq!(answered(&out), vec![a]); let (b, out) = t.call(B, false, 200, 300); assert!(stopped(&out).is_empty(), "same score: keep going"); assert_eq!(answered(&t.p.answer_done(a, t.at(1000))), vec![b]); let (c, out) = t.call(C, false, 1100, 1200); assert_eq!(stopped(&out), vec![b]); assert_eq!(missed(&out), vec![(b, MissReason::Interrupted)]); assert_eq!(answered(&out), vec![c]); } #[test] fn important_asks_the_ranking_when_a_new_request_ties_the_running_answer() { let s = PolicySettings { kind: PolicyKind::Important, collect: Duration::ZERO, ..PolicySettings::default() }; // The ranking says the new one matters more: the answer stops for it. let mut t = T::with(s.clone()); let (a, _) = t.call(A, true, 0, 100); let (b, out) = t.call(B, true, 200, 300); let (r, ids) = rank_of(&out); assert_eq!(ids, vec![a, b]); assert!(stopped(&out).is_empty(), "keeps speaking while ranking"); let out = t.p.ranked(r, &[b, a], t.at(400)); assert_eq!(stopped(&out), vec![a]); assert_eq!(missed(&out), vec![(a, MissReason::Interrupted)]); assert_eq!(answered(&out), vec![b]); // The ranking keeps the running answer: the new one waits for it. let mut t = T::with(s.clone()); let (a, _) = t.call(A, true, 0, 100); let (b, out) = t.call(B, true, 200, 300); let (r, _) = rank_of(&out); assert!(stopped(&t.p.ranked(r, &[a, b], t.at(400))).is_empty()); assert_eq!(answered(&t.p.answer_done(a, t.at(1000))), vec![b]); // No ranking in time: the running answer ended first, so it goes on. let mut t = T::with(s); let (a, _) = t.call(A, true, 0, 100); let (b, _) = t.call(B, true, 200, 300); assert!(stopped(&t.p.tick(t.at(300 + 1500))).is_empty()); assert_eq!(answered(&t.p.answer_done(a, t.at(2000))), vec![b]); } #[test] fn a_ranking_after_its_deadline_counts_as_a_timeout() { let mut t = T::new(PolicyKind::Important); let (a, _) = t.call(A, true, 0, 100); let (b, _) = t.call(B, true, 50, 200); let (r, _) = rank_of(&t.p.tick(t.at(800))); assert_eq!(answered(&t.p.ranked(r, &[b, a], t.at(2400))), vec![a], "late: earliest-ended wins"); } #[test] fn candidates_collected_while_busy_keep_end_time_order_for_the_fallback() { let mut t = T::with(PolicySettings { kind: PolicyKind::Important, collect: Duration::ZERO, ..PolicySettings::default() }); let (a, _) = t.call(A, false, 0, 100); let (_late, _) = t.call(B, false, 900, 1000); let (early, _) = t.call(C, false, 600, 1200); // ended first, arrived last let out = t.p.answer_done(a, t.at(1300)); assert_eq!(rank_of(&out).1, vec![early, _late]); assert_eq!(answered(&t.p.tick(t.at(1300 + 1500))), vec![early]); } #[test] fn a_finished_collect_timer_is_not_reported_again_while_settling() { let mut t = T::new(PolicyKind::Important); t.p.utterance_open(B); t.p.speaking_stopped(B, t.at(50)); let (a, _) = t.call(A, true, 0, 100); assert_eq!(t.p.next_deadline(), Some(t.at(800))); assert!(answered(&t.p.tick(t.at(800))).is_empty(), "still waiting for B"); assert_eq!(t.p.next_deadline(), Some(t.at(100 + 800)), "the settle deadline, not the spent collect timer"); assert_eq!(answered(&t.p.tick(t.at(900))), vec![a]); } #[test] fn a_tie_arriving_during_a_ranking_against_the_answer_is_ranked_too() { let mut t = T::with(PolicySettings { kind: PolicyKind::Important, collect: Duration::ZERO, ..PolicySettings::default() }); let (a, _) = t.call(A, true, 0, 100); let (b, out) = t.call(B, true, 200, 300); let (r1, _) = rank_of(&out); let (c, out) = t.call(C, true, 400, 500); let (r2, ids) = rank_of(&out); assert_ne!(r1, r2); assert_eq!(ids, vec![a, b, c], "the running answer and every tied candidate"); assert_eq!(t.p.next_deadline(), Some(t.at(300 + 1500)), "the first ranking's deadline is kept"); assert!(t.p.ranked(r1, &[b, a], t.at(600)).is_empty(), "the replaced ranking's result is ignored"); let out = t.p.ranked(r2, &[c, b, a], t.at(700)); assert_eq!(stopped(&out), vec![a]); assert_eq!(answered(&out), vec![c]); assert_eq!(missed(&out), vec![(a, MissReason::Interrupted), (b, MissReason::LowerScore)]); } #[test] fn a_tie_arriving_during_a_ranking_while_idle_is_ranked_too() { let mut t = T::new(PolicyKind::Important); let (a, _) = t.call(A, true, 0, 100); let (b, _) = t.call(B, true, 50, 200); let (r1, _) = rank_of(&t.p.tick(t.at(800))); let (c, out) = t.call(C, true, 850, 900); let (r2, ids) = rank_of(&out); assert_eq!(ids, vec![a, b, c]); assert!(t.p.ranked(r1, &[b], t.at(950)).is_empty()); let out = t.p.ranked(r2, &[c], t.at(1000)); assert_eq!(answered(&out), vec![c]); assert_eq!(missed(&out), vec![(a, MissReason::LowerScore), (b, MissReason::LowerScore)]); } #[test] fn a_dropped_rankings_late_result_does_not_decide_the_next_one() { let mut t = T::with(PolicySettings { kind: PolicyKind::Important, collect: Duration::ZERO, ..PolicySettings::default() }); let (a, _) = t.call(A, true, 0, 100); let (b, out) = t.call(B, true, 200, 300); let (r1, _) = rank_of(&out); let (_c, _) = t.call(C, true, 250, 350); // A ends: the ranking about interrupting it is dropped, and B and C are ranked anew. let (r2, ids) = rank_of(&t.p.answer_done(a, t.at(400))); assert_eq!(ids, vec![b, _c]); assert!(t.p.ranked(r1, &[b, a], t.at(450)).is_empty(), "the dropped ranking's result is ignored"); assert_eq!(answered(&t.p.ranked(r2, &[_c, b], t.at(500))), vec![_c]); } #[test] fn with_no_settle_time_the_next_deadline_is_the_collect_timer() { let mut t = T::with(PolicySettings { kind: PolicyKind::Important, settle: Duration::ZERO, ..PolicySettings::default() }); let (a, _) = t.call(A, true, 0, 100); assert_eq!(t.p.next_deadline(), Some(t.at(800))); assert!(t.p.tick(t.at(100)).is_empty()); assert_eq!(t.p.next_deadline(), Some(t.at(800)), "moves forward, not stuck at a passed time"); assert_eq!(answered(&t.p.tick(t.at(800))), vec![a]); } #[test] fn stop_ends_the_answer_and_drops_the_queue_in_every_policy() { for kind in [PolicyKind::First, PolicyKind::InOrder, PolicyKind::Latest, PolicyKind::Important] { let mut t = T::with(PolicySettings { kind, collect: Duration::ZERO, ..PolicySettings::default() }); let _ = t.call(A, true, 0, 100); let _ = t.call(B, true, 50, 200); let running = t.p.current().expect("an answer runs"); let out = t.p.stop(); assert_eq!(stopped(&out), vec![running], "{kind:?}"); assert!(missed(&out).iter().any(|(id, _)| *id == running), "{kind:?}"); assert!(missed(&out).iter().all(|(_, w)| *w == MissReason::Stopped), "{kind:?}"); assert_eq!(t.p.current(), None); assert_eq!(t.p.waiting(), 0); } } }