fix(app): important policy ranks a tie against the running answer; timer and ordering fixes

- A new request that ties the running answer on priority and wake word
  is ranked against it by the brain; a win interrupts, a loss or a
  timeout lets the answer go on. The ranking is dropped when the answer
  ends first.
- A ranking that arrives after its deadline counts as a timeout.
- Candidates collected while an answer runs keep end-time order, so the
  timeout fallback picks the earliest-ended one.
- A spent collect timer is cleared, so next_deadline reports the settle
  deadline instead of a time already passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-11 22:09:57 +09:00
parent 6fc3983a40
commit 46eebcd256
2 changed files with 130 additions and 19 deletions

View File

@@ -97,8 +97,15 @@ pub struct Policy {
open: HashMap<u64, Open>,
/// `important`: no choice before this.
collect_until: Option<Instant>,
/// `important`: the tied candidates being ranked and when to give up waiting.
ranking: Option<(HashSet<u64>, Instant)>,
/// `important`: a ranking the brain was asked for.
ranking: Option<Ranking>,
}
struct Ranking {
ids: HashSet<u64>,
deadline: Instant,
/// Asked about interrupting the running answer with this id (it is one of `ids`).
against: Option<u64>,
}
impl Policy {
@@ -161,11 +168,20 @@ impl Policy {
}
}
PolicyKind::Important => {
let beats = self.score(&req) > self.score(&cur);
self.waiting.push(req);
if beats {
let (new, running) = (self.score(&req), self.score(&cur));
self.enqueue(req.clone(), &mut out);
if new > running {
self.interrupt(&mut out);
self.collect_until = None;
self.ranking = None;
} else if new == running && self.ranking.is_none() {
// A tie on priority and wake word: the brain's importance decides.
self.ranking = Some(Ranking {
ids: [cur.id, req.id].into(),
deadline: now + self.s.rank_timeout,
against: Some(cur.id),
});
out.push(Action::Rank(vec![cur, req]));
}
}
}
@@ -217,31 +233,50 @@ impl Policy {
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 ranking of the tied candidates, best first.
/// The brain's ranking of the tied candidates, best first. After the deadline it counts as a
/// timeout.
pub fn ranked(&mut self, order: &[u64], now: Instant) -> Vec<Action> {
let Some((tied, _)) = self.ranking.take() else { return vec![] };
let winner = order.iter().copied().find(|id| tied.contains(id));
self.choose(now, Some(winner))
let Some(r) = self.ranking.take() else { return vec![] };
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<u64>, now: Instant) -> Vec<Action> {
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<Action> {
if let Some((_, deadline)) = &self.ranking {
if now >= *deadline {
self.ranking = None;
return self.choose(now, Some(None));
}
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<Instant> {
if let Some((_, t)) = &self.ranking {
return Some(*t);
if let Some(r) = &self.ranking {
return Some(r.deadline);
}
let mut d: Vec<Instant> = vec![];
if self.current.is_none() && !self.waiting.is_empty() {
@@ -287,6 +322,7 @@ impl Policy {
if now < t {
return out;
}
self.collect_until = None;
}
if self.blocked(now) {
return out;
@@ -306,7 +342,11 @@ impl Policy {
Some(_) => tied[0],
None if tied.len() >= 2 => {
let cands: Vec<Request> = tied.iter().map(|&i| self.waiting[i].clone()).collect();
self.ranking = Some((cands.iter().map(|r| r.id).collect(), now + self.s.rank_timeout));
self.ranking = Some(Ranking {
ids: cands.iter().map(|r| r.id).collect(),
deadline: now + self.s.rank_timeout,
against: None,
});
out.push(Action::Rank(cands));
return out;
}
@@ -534,6 +574,71 @@ mod tests {
assert_eq!(answered(&out), vec![c]);
}
fn ranks(a: &[Action]) -> Vec<Vec<u64>> {
a.iter().filter_map(|x| if let Action::Rank(c) = x { Some(c.iter().map(|r| r.id).collect()) } else { None })
.collect()
}
#[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);
assert_eq!(ranks(&out), vec![vec![a, b]]);
assert!(stopped(&out).is_empty(), "keeps speaking while ranking");
let out = t.p.ranked(&[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, _) = t.call(B, true, 200, 300);
assert!(stopped(&t.p.ranked(&[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);
t.p.tick(t.at(800));
assert_eq!(answered(&t.p.ranked(&[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!(ranks(&out), vec![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 stop_ends_the_answer_and_drops_the_queue_in_every_policy() {
for kind in [PolicyKind::First, PolicyKind::InOrder, PolicyKind::Latest, PolicyKind::Important] {