use crate::headroom::is_reclaim_candidate;
use crate::model::{Group, GroupKind, Snapshot};
use crate::units::{parse_bytes, parse_duration_s, GIB, KIB, MIB, TIB};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::fmt;
use thiserror::Error;
pub const LOW_CONFIDENCE: f64 = 0.5;
pub const FRECENCY_LINK_BOOST: f64 = 0.5;
pub const MIN_LINK_SCORE: f64 = 0.3;
pub const MIN_TYPO_LEN: usize = 4;
#[derive(Debug, Error, Clone, PartialEq, Eq)]
pub enum QueryError {
#[error("unknown key {0:?} (expected kind, owner, name, mem, gpu, cpu, idle, age, duty, rent, stale, state, sandbox)")]
UnknownKey(String),
#[error("bad value {value:?} for {key}: {msg}")]
BadValue { key: String, value: String, msg: String },
#[error("unbalanced parentheses")]
Parens,
#[error("empty expression")]
Empty,
#[error("unterminated quote")]
Quote,
#[error("expression nested too deeply (more than {MAX_DEPTH} levels)")]
TooDeep,
}
pub const MAX_DEPTH: usize = 64;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Metric {
Mem,
Gpu,
Cpu,
Idle,
}
impl Metric {
pub fn as_str(self) -> &'static str {
match self {
Metric::Mem => "mem",
Metric::Gpu => "gpu",
Metric::Cpu => "cpu",
Metric::Idle => "idle",
}
}
pub fn parse(s: &str) -> Option<Metric> {
match s.trim().to_ascii_lowercase().as_str() {
"mem" | "memory" | "footprint" | "ram" => Some(Metric::Mem),
"gpu" | "vram" | "metal" => Some(Metric::Gpu),
"cpu" => Some(Metric::Cpu),
"idle" => Some(Metric::Idle),
_ => None,
}
}
pub fn label(self) -> &'static str {
match self {
Metric::Mem => "memory",
Metric::Gpu => "GPU memory",
Metric::Cpu => "CPU",
Metric::Idle => "idle time",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CmpOp {
Gt,
Ge,
Lt,
Le,
Eq,
}
impl CmpOp {
pub fn as_str(self) -> &'static str {
match self {
CmpOp::Gt => ">",
CmpOp::Ge => ">=",
CmpOp::Lt => "<",
CmpOp::Le => "<=",
CmpOp::Eq => "=",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FieldKey {
Kind,
Owner,
Name,
State,
Sandbox,
}
impl FieldKey {
pub fn as_str(self) -> &'static str {
match self {
FieldKey::Kind => "kind",
FieldKey::Owner => "owner",
FieldKey::Name => "name",
FieldKey::State => "state",
FieldKey::Sandbox => "sandbox",
}
}
pub fn parse(s: &str) -> Option<FieldKey> {
match s.trim().to_ascii_lowercase().as_str() {
"kind" | "type" => Some(FieldKey::Kind),
"owner" => Some(FieldKey::Owner),
"name" => Some(FieldKey::Name),
"state" | "is" => Some(FieldKey::State),
"sandbox" => Some(FieldKey::Sandbox),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TimeMetric {
Age,
Duty,
Rent,
Stale,
}
impl TimeMetric {
pub const ALL: [TimeMetric; 4] = [
TimeMetric::Age,
TimeMetric::Duty,
TimeMetric::Rent,
TimeMetric::Stale,
];
pub fn as_str(self) -> &'static str {
match self {
TimeMetric::Age => "age",
TimeMetric::Duty => "duty",
TimeMetric::Rent => "rent",
TimeMetric::Stale => "stale",
}
}
pub fn parse(s: &str) -> Option<TimeMetric> {
match s.trim().to_ascii_lowercase().as_str() {
"age" | "uptime" => Some(TimeMetric::Age),
"duty" | "duty_cycle" => Some(TimeMetric::Duty),
"rent" | "idle_rent" => Some(TimeMetric::Rent),
"stale" | "staleness" => Some(TimeMetric::Stale),
_ => None,
}
}
pub fn label(self) -> &'static str {
match self {
TimeMetric::Age => "age",
TimeMetric::Duty => "duty cycle",
TimeMetric::Rent => "idle rent",
TimeMetric::Stale => "staleness",
}
}
pub fn descending(self) -> bool {
!matches!(self, TimeMetric::Duty)
}
pub fn of_group(self, g: &Group) -> Option<f64> {
match self {
TimeMetric::Age => g.age_s.value.map(|a| a as f64),
TimeMetric::Duty => g.duty_pct.value,
TimeMetric::Rent => g.idle_rent_gib_h.value,
TimeMetric::Stale => (!crate::staleness::not_collected(&g.age_s)).then_some(g.staleness.score),
}
}
}
pub fn sort_groups_by_time(groups: &mut [&Group], m: TimeMetric) {
groups.sort_by(|a, b| {
let (x, y) = (m.of_group(a), m.of_group(b));
let ord = match (x, y) {
(Some(x), Some(y)) => {
let o = x.partial_cmp(&y).unwrap_or(std::cmp::Ordering::Equal);
if m.descending() {
o.reverse()
} else {
o
}
}
(Some(_), None) => std::cmp::Ordering::Less,
(None, Some(_)) => std::cmp::Ordering::Greater,
(None, None) => std::cmp::Ordering::Equal,
};
ord.then(a.id.cmp(&b.id))
});
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Term {
Field {
key: FieldKey,
values: Vec<String>,
},
Cmp {
metric: Metric,
op: CmpOp,
value: f64,
},
Word(String),
TimeCmp {
metric: TimeMetric,
op: CmpOp,
value: f64,
},
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Expr {
And(Vec<Expr>),
Or(Vec<Expr>),
Not(Box<Expr>),
Term(Term),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct Correction {
pub from: String,
pub to: String,
}
fn fmt_metric_value(metric: Metric, v: f64) -> String {
match metric {
Metric::Mem | Metric::Gpu => {
let b = v.max(0.0).round() as u64;
for (unit, suffix) in [(TIB, "T"), (GIB, "G"), (MIB, "M"), (KIB, "K")] {
if b >= unit && b.is_multiple_of(unit) {
return format!("{}{suffix}", b / unit);
}
}
for (unit, suffix) in [
(1_000_000_000_000u64, "TB"),
(1_000_000_000, "GB"),
(1_000_000, "MB"),
(1_000, "KB"),
] {
if b >= unit && b.is_multiple_of(unit) {
return format!("{}{suffix}", b / unit);
}
}
for (unit, suffix) in [(TIB, "T"), (GIB, "G"), (MIB, "M")] {
if b >= unit {
let x = b as f64 / unit as f64;
for decimals in 1..=3 {
let s = format!("{x:.decimals$}");
let back = s.parse::<f64>().map(|y| (y * unit as f64).round() as u64);
if back == Ok(b) {
let s = s.trim_end_matches('0').trim_end_matches('.');
return format!("{s}{suffix}");
}
}
}
}
if b == 0 {
"0".into()
} else {
format!("{b}B")
}
}
Metric::Cpu => format!("{v}"),
Metric::Idle => {
let s = v.max(0.0).round() as u64;
for (unit, suffix) in [(86_400, "d"), (3_600, "h"), (60, "m")] {
if s >= unit && s.is_multiple_of(unit) {
return format!("{}{suffix}", s / unit);
}
}
format!("{s}s")
}
}
}
fn quote_if_needed(v: &str, word: bool) -> String {
if v.is_empty()
|| v.chars()
.any(|c| c.is_whitespace() || matches!(c, '(' | ')' | ',' | '"' | QUOTED_COMMA))
|| v.starts_with(['-', '!'])
|| (word && v.contains([':', '<', '>', '=']))
|| (!word && v.starts_with(['<', '>', '=']))
|| ["or", "not", "and", "||", "|", "&&", "&"].contains(&v.to_ascii_lowercase().as_str())
{
format!("\"{}\"", v.replace('"', ""))
} else {
v.to_string()
}
}
impl fmt::Display for Term {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Term::Field { key, values } => {
let vs: Vec<String> = values.iter().map(|v| quote_if_needed(v, false)).collect();
write!(f, "{}:{}", key.as_str(), vs.join(","))
}
Term::Cmp { metric, op, value } => write!(
f,
"{}{}{}",
metric.as_str(),
op.as_str(),
fmt_metric_value(*metric, *value)
),
Term::Word(w) => write!(f, "{}", quote_if_needed(w, true)),
Term::TimeCmp { metric, op, value } => {
let v = match metric {
TimeMetric::Age => fmt_metric_value(Metric::Idle, *value),
_ => format!("{value}"),
};
write!(f, "{}{}{v}", metric.as_str(), op.as_str())
}
}
}
}
impl fmt::Display for Expr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Expr::Term(t) => write!(f, "{t}"),
Expr::Not(x) => match x.as_ref() {
Expr::Term(t) => write!(f, "-{t}"),
other => write!(f, "-({other})"),
},
Expr::And(xs) => {
let parts: Vec<String> = xs
.iter()
.map(|x| match x {
Expr::Or(_) => format!("({x})"),
_ => x.to_string(),
})
.collect();
write!(f, "{}", parts.join(" "))
}
Expr::Or(xs) => {
let parts: Vec<String> = xs.iter().map(|x| x.to_string()).collect();
write!(f, "{}", parts.join(" or "))
}
}
}
}
impl Expr {
pub fn metrics(&self) -> Vec<Metric> {
fn walk(e: &Expr, out: &mut Vec<Metric>) {
match e {
Expr::And(xs) | Expr::Or(xs) => xs.iter().for_each(|x| walk(x, out)),
Expr::Not(x) => walk(x, out),
Expr::Term(Term::Cmp { metric, .. }) => {
if !out.contains(metric) {
out.push(*metric);
}
}
Expr::Term(_) => {}
}
}
let mut v = Vec::new();
walk(self, &mut v);
v
}
fn and_all(mut parts: Vec<Expr>) -> Option<Expr> {
match parts.len() {
0 => None,
1 => parts.pop(),
_ => Some(Expr::And(parts)),
}
}
}
#[derive(Debug, Clone, PartialEq)]
enum Tok {
LParen,
RParen,
Or,
Not,
Neg,
Atom(String),
Lit(String),
}
const QUOTED_COMMA: char = '\u{1f}';
const QUOTED_OPS: [(char, char); 3] = [('<', '\u{1c}'), ('>', '\u{1d}'), ('=', '\u{1e}')];
fn protect_op(c: char) -> char {
QUOTED_OPS
.iter()
.find(|(op, _)| *op == c)
.map(|(_, p)| *p)
.unwrap_or(c)
}
fn is_protected(c: char) -> bool {
c == QUOTED_COMMA || QUOTED_OPS.iter().any(|(_, p)| *p == c)
}
fn unprotect(s: &str) -> String {
if !s.contains(is_protected) {
return s.to_string();
}
s.chars()
.map(|c| match QUOTED_OPS.iter().find(|(_, p)| *p == c) {
Some((op, _)) => *op,
None if c == QUOTED_COMMA => ',',
None => c,
})
.collect()
}
fn tokenize(input: &str) -> Result<Vec<Tok>, QueryError> {
#[derive(Default)]
struct Cur {
text: String,
any_quote: bool,
starts_quoted: bool,
neg: bool,
}
fn flush(cur: &mut Cur, toks: &mut Vec<Tok>) {
let Cur {
text,
any_quote,
starts_quoted,
neg,
} = std::mem::take(cur);
if text.is_empty() {
return;
}
if neg {
toks.push(Tok::Neg);
}
if starts_quoted {
toks.push(Tok::Lit(text));
return;
}
if !any_quote {
match text.to_ascii_lowercase().as_str() {
"or" | "||" | "|" => return toks.push(Tok::Or),
"not" | "!" => return toks.push(Tok::Not),
"and" | "&&" | "&" | "-" => return,
_ => {}
}
}
if let Some(rest) = text.strip_prefix(['-', '!']).filter(|r| !r.is_empty()) {
toks.push(Tok::Neg);
toks.push(Tok::Atom(rest.to_string()));
return;
}
toks.push(Tok::Atom(text));
}
let mut toks = Vec::new();
let mut cur = Cur::default();
let mut in_quote = false;
let mut value_lead = false;
for c in input.chars() {
if in_quote {
match c {
'"' => in_quote = false,
',' => cur.text.push(QUOTED_COMMA),
c if is_protected(c) => {}
c if value_lead && is_op_char(c) => cur.text.push(protect_op(c)),
c => cur.text.push(c),
}
value_lead &= in_quote && is_op_char(c);
continue;
}
match c {
'"' => {
if cur.text.is_empty() && !cur.any_quote {
cur.starts_quoted = true;
} else if !cur.any_quote && (cur.text == "-" || cur.text == "!") {
cur.text.clear();
cur.neg = true;
cur.starts_quoted = true;
}
cur.any_quote = true;
in_quote = true;
value_lead = cur.text.ends_with(':');
}
'(' => {
if !cur.any_quote && (cur.text == "-" || cur.text == "!") {
cur.text.clear();
toks.push(Tok::Neg);
} else {
flush(&mut cur, &mut toks);
}
toks.push(Tok::LParen);
}
')' => {
flush(&mut cur, &mut toks);
toks.push(Tok::RParen);
}
c if is_protected(c) => {}
c if c.is_whitespace() => flush(&mut cur, &mut toks),
c => cur.text.push(c),
}
}
if in_quote {
return Err(QueryError::Quote);
}
flush(&mut cur, &mut toks);
Ok(merge_spaced_comparisons(toks))
}
fn is_known_key(s: &str) -> bool {
Metric::parse(s).is_some() || FieldKey::parse(s).is_some() || TimeMetric::parse(s).is_some()
}
fn is_op_char(c: char) -> bool {
matches!(c, '<' | '>' | '=')
}
fn merge_spaced_comparisons(toks: Vec<Tok>) -> Vec<Tok> {
let mut out: Vec<Tok> = Vec::with_capacity(toks.len());
for t in toks {
if let Some(Tok::Atom(prev)) = out.last_mut() {
let prev_open = prev.ends_with(is_op_char) || prev.ends_with(':');
match &t {
Tok::Atom(next) if prev_open || (is_known_key(prev) && next.starts_with(is_op_char)) => {
prev.push_str(next);
continue;
}
Tok::Lit(next) if prev_open => {
let lead = if prev.ends_with(':') {
next.find(|c| !is_op_char(c)).unwrap_or(next.len())
} else {
0
};
prev.extend(next[..lead].chars().map(protect_op));
prev.push_str(&next[lead..]);
continue;
}
_ => {}
}
}
out.push(t);
}
out
}
struct Parser<'c> {
toks: Vec<Tok>,
pos: usize,
depth: usize,
corrections: &'c mut Vec<Correction>,
}
impl Parser<'_> {
fn peek(&self) -> Option<&Tok> {
self.toks.get(self.pos)
}
fn next(&mut self) -> Option<Tok> {
let t = self.toks.get(self.pos).cloned();
self.pos += 1;
t
}
fn or_expr(&mut self) -> Result<Expr, QueryError> {
let mut parts = vec![self.and_expr()?];
while self.peek() == Some(&Tok::Or) {
self.next();
parts.push(self.and_expr()?);
}
Ok(if parts.len() == 1 {
parts.remove(0)
} else {
Expr::Or(parts)
})
}
fn and_expr(&mut self) -> Result<Expr, QueryError> {
let mut parts = Vec::new();
while let Some(t) = self.peek() {
if matches!(t, Tok::Or | Tok::RParen) {
break;
}
parts.push(self.unary()?);
}
match parts.len() {
0 => Err(QueryError::Empty),
1 => Ok(parts.remove(0)),
_ => Ok(Expr::And(parts)),
}
}
fn descend(&mut self) -> Result<(), QueryError> {
self.depth += 1;
if self.depth > MAX_DEPTH {
return Err(QueryError::TooDeep);
}
Ok(())
}
fn unary(&mut self) -> Result<Expr, QueryError> {
match self.peek() {
Some(Tok::Not) | Some(Tok::Neg) => {
self.next();
self.descend()?;
let inner = self.unary()?;
self.depth -= 1;
Ok(Expr::Not(Box::new(inner)))
}
_ => self.atom(),
}
}
fn atom(&mut self) -> Result<Expr, QueryError> {
match self.next() {
Some(Tok::LParen) => {
self.descend()?;
let e = self.or_expr()?;
self.depth -= 1;
if self.next() != Some(Tok::RParen) {
return Err(QueryError::Parens);
}
Ok(e)
}
Some(Tok::Atom(a)) => Ok(Expr::Term(parse_term_with(&a, self.corrections)?)),
Some(Tok::Lit(w)) => Ok(Expr::Term(Term::Word(unprotect(&w)))),
Some(Tok::RParen) => Err(QueryError::Parens),
_ => Err(QueryError::Empty),
}
}
}
fn split_key_op(atom: &str) -> Option<(&str, &str, &str)> {
let i = atom.find(|c: char| c == ':' || is_op_char(c))?;
let key = &atom[..i];
if key.is_empty() || !key.chars().all(|c| c.is_ascii_alphabetic() || c == '_') {
return None;
}
let rest = &atom[i..];
let op_len = if let Some(after) = rest.strip_prefix(':') {
if after.starts_with(">=") || after.starts_with("<=") || after.starts_with("==") {
3
} else if after.starts_with(is_op_char) {
2
} else {
1
}
} else if rest.starts_with(">=") || rest.starts_with("<=") || rest.starts_with("==") {
2
} else {
1
};
Some((key, &rest[..op_len], &rest[op_len..]))
}
fn cmp_op(op: &str) -> Option<CmpOp> {
match op.trim_start_matches(':') {
">" => Some(CmpOp::Gt),
">=" => Some(CmpOp::Ge),
"<" => Some(CmpOp::Lt),
"<=" => Some(CmpOp::Le),
"=" | "==" => Some(CmpOp::Eq),
_ => None,
}
}
enum Key {
Metric(Metric),
Field(FieldKey),
Time(TimeMetric),
}
const CANONICAL_KEYS: &[&str] = &[
"kind", "owner", "name", "state", "sandbox", "mem", "memory", "gpu", "cpu", "idle", "age", "duty",
"rent", "stale",
];
fn resolve_key(raw: &str, corrections: &mut Vec<Correction>) -> Result<Key, QueryError> {
let k = raw.to_ascii_lowercase();
if let Some(m) = Metric::parse(&k) {
return Ok(Key::Metric(m));
}
if let Some(f) = FieldKey::parse(&k) {
return Ok(Key::Field(f));
}
if let Some(t) = TimeMetric::parse(&k) {
return Ok(Key::Time(t));
}
if k.chars().count() >= 3 {
if let Some(fixed) = closest(&k, CANONICAL_KEYS.iter().copied(), 3) {
corrections.push(Correction {
from: k.clone(),
to: fixed.to_string(),
});
return resolve_key(fixed, corrections);
}
}
Err(QueryError::UnknownKey(k))
}
fn kind_synonym(v: &str) -> Option<GroupKind> {
let v = v.trim().to_ascii_lowercase();
if let Some(k) = GroupKind::parse(&v) {
return Some(k);
}
let k = match v.as_str() {
"agents" | "session" | "sessions" | "agent_sessions" => GroupKind::AgentSession,
"apps" | "application" | "applications" => GroupKind::App,
"models" | "llm" | "llms" | "model_servers" => GroupKind::ModelServer,
"sandboxes" | "vm" | "vms" | "container" | "containers" | "microvm" | "microvms" => {
GroupKind::Sandbox
}
"daemons" | "build" | "builds" | "build_daemons" => GroupKind::BuildDaemon,
"sys" => GroupKind::System,
"others" => GroupKind::Other,
_ => return None,
};
Some(k)
}
const KIND_WORDS: &[&str] = &[
"agent",
"agents",
"app",
"apps",
"model",
"models",
"sandbox",
"sandboxes",
"daemon",
"daemons",
"system",
"other",
"containers",
"container",
"vms",
];
fn normalize_kind_value(v: &str, corrections: &mut Vec<Correction>) -> Option<String> {
if v == "*" {
return Some("*".into());
}
if let Some(k) = kind_synonym(v) {
return Some(k.alias().to_string());
}
let lower = v.to_ascii_lowercase();
if lower.chars().count() >= MIN_TYPO_LEN {
let names = GroupKind::ALL
.iter()
.flat_map(|k| [k.alias(), k.as_str()])
.chain(KIND_WORDS.iter().copied());
if let Some(fixed) = closest(&lower, names, MIN_TYPO_LEN) {
corrections.push(Correction {
from: lower.clone(),
to: fixed.to_string(),
});
return kind_synonym(fixed).map(|k| k.alias().to_string());
}
}
None
}
fn normalize_state_value(v: &str) -> String {
let v = v.trim().to_ascii_lowercase();
match v.as_str() {
"orphaned" | "orphans" => "orphan".into(),
"working" | "generating" | "running" => "busy".into(),
"lower_bound" | "lowerbound" => "partial".into(),
"mine" | "pin" => "pinned".into(),
"mute" => "muted".into(),
_ => v,
}
}
fn parse_metric_value(metric: Metric, key: &str, v: &str) -> Result<f64, QueryError> {
let bad = |msg: String| QueryError::BadValue {
key: key.into(),
value: v.into(),
msg,
};
let v = v.trim();
if v.is_empty() {
return Err(bad("missing value".into()));
}
match metric {
Metric::Mem | Metric::Gpu => {
let has_unit = v.chars().any(|c| c.is_ascii_alphabetic());
let b = parse_bytes(v).map_err(|e| bad(e.to_string()))?;
if !has_unit && b != 0 {
return Err(bad("add a unit, e.g. 2G or 500M".into()));
}
Ok(b as f64)
}
Metric::Cpu => {
let x = v
.trim_end_matches('%')
.parse::<f64>()
.map_err(|e| bad(e.to_string()))?;
if !x.is_finite() || x < 0.0 {
return Err(bad("expected a non-negative percentage".into()));
}
Ok(x)
}
Metric::Idle => parse_duration_s(v).map_err(|e| bad(e.to_string())),
}
}
fn parse_time_value(metric: TimeMetric, key: &str, v: &str) -> Result<f64, QueryError> {
let bad = |msg: &str| QueryError::BadValue {
key: key.into(),
value: v.into(),
msg: msg.into(),
};
let v = v.trim();
if v.is_empty() {
return Err(bad("missing value"));
}
let x = match metric {
TimeMetric::Age => return parse_duration_s(v).map_err(|e| bad(&e.to_string())),
TimeMetric::Duty => v.trim_end_matches('%').trim().parse::<f64>().ok(),
TimeMetric::Rent => {
let lower = v.to_ascii_lowercase();
let num = ["gib·h", "gib-h", "gibh", "gb·h", "gbh", "gh"]
.iter()
.find_map(|s| lower.strip_suffix(s))
.unwrap_or(&lower);
num.trim().parse::<f64>().ok()
}
TimeMetric::Stale => match v.strip_suffix('%') {
Some(p) => p.trim().parse::<f64>().ok().map(|x| x / 100.0),
None => v.parse::<f64>().ok(),
},
};
let x = x.filter(|x| x.is_finite() && *x >= 0.0).ok_or_else(|| {
bad(match metric {
TimeMetric::Duty => "expected a percentage of one core, e.g. 1%",
TimeMetric::Rent => "expected GiB-hours, e.g. 10",
_ => "expected a score from 0 to 1, e.g. 0.5",
})
})?;
if metric == TimeMetric::Stale && x > 1.0 {
return Err(bad("expected a score from 0 to 1, e.g. 0.5"));
}
Ok(x)
}
fn parse_term_with(atom: &str, corrections: &mut Vec<Correction>) -> Result<Term, QueryError> {
let Some((raw_key, op, value)) = split_key_op(atom) else {
return Ok(Term::Word(unprotect(atom)));
};
let key = resolve_key(raw_key, corrections)?;
let key_name = raw_key.to_ascii_lowercase();
let is_colon = op == ":";
match key {
Key::Time(metric) => {
let op = (!is_colon)
.then(|| cmp_op(op))
.flatten()
.ok_or_else(|| QueryError::BadValue {
key: key_name.clone(),
value: value.into(),
msg: format!(
"use a comparison, e.g. {}",
match metric {
TimeMetric::Age => "age>1d",
TimeMetric::Duty => "duty<1%",
TimeMetric::Rent => "rent>10",
TimeMetric::Stale => "stale>0.5 (or the word `stale`)",
}
),
})?;
Ok(Term::TimeCmp {
metric,
op,
value: parse_time_value(metric, &key_name, value)?,
})
}
Key::Metric(metric) => {
if is_colon {
return Err(QueryError::BadValue {
key: key_name,
value: value.into(),
msg: format!("use a comparison, e.g. {}>2G", metric.as_str()),
});
}
let op = cmp_op(op).ok_or_else(|| QueryError::BadValue {
key: key_name.clone(),
value: value.into(),
msg: "unknown operator".into(),
})?;
Ok(Term::Cmp {
metric,
op,
value: parse_metric_value(metric, &key_name, value)?,
})
}
Key::Field(fk) => {
if !(is_colon || op == "=" || op == "==") {
return Err(QueryError::BadValue {
key: key_name,
value: value.into(),
msg: "comparisons need mem, gpu, cpu, idle, age, duty, rent or stale".into(),
});
}
let raw_values: Vec<&str> = value
.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
.collect();
if raw_values.is_empty() {
return Err(QueryError::BadValue {
key: key_name,
value: value.into(),
msg: "missing value".into(),
});
}
let mut values = Vec::with_capacity(raw_values.len());
for val in raw_values {
let val = unprotect(val);
let val = val.as_str();
let v = match fk {
FieldKey::Kind => {
normalize_kind_value(val, corrections).ok_or_else(|| QueryError::BadValue {
key: key_name.clone(),
value: val.into(),
msg: "unknown kind (agent, app, model, sandbox, daemon, system, other)".into(),
})?
}
FieldKey::State => normalize_state_value(val),
_ => val.to_string(),
};
if !values.contains(&v) {
values.push(v);
}
}
Ok(Term::Field { key: fk, values })
}
}
}
pub fn parse_term(atom: &str) -> Result<Term, QueryError> {
parse_term_with(atom, &mut Vec::new())
}
fn parse_tokens(toks: Vec<Tok>, corrections: &mut Vec<Correction>) -> Result<Expr, QueryError> {
if toks.is_empty() {
return Err(QueryError::Empty);
}
let mut p = Parser {
toks,
pos: 0,
depth: 0,
corrections,
};
let e = p.or_expr()?;
if p.pos < p.toks.len() {
return Err(QueryError::Parens);
}
Ok(e)
}
pub fn parse_filter(input: &str) -> Result<Expr, QueryError> {
parse_tokens(tokenize(input)?, &mut Vec::new())
}
pub fn parse_filter_corrected(input: &str) -> Result<(Expr, Vec<Correction>), QueryError> {
let mut c = Vec::new();
let e = parse_tokens(tokenize(input)?, &mut c)?;
Ok((e, c))
}
pub const RUNTIME_FLAG_PREFIX: &str = "runtime:";
pub const TIME_FLAG_PREFIX: &str = "time:";
#[derive(Debug, Clone, PartialEq, Default)]
pub struct EntityView {
pub id: String,
pub kind: GroupKind,
pub name: String,
pub aliases: Vec<String>,
pub owner: Option<String>,
pub mem: Option<u64>,
pub gpu: Option<u64>,
pub cpu: Option<f64>,
pub idle_s: Option<u64>,
pub state: Vec<String>,
pub sandbox: Option<String>,
}
impl EntityView {
pub fn from_group(g: &Group, s: &Snapshot) -> Self {
let mut state = Vec::new();
let mut flag = |cond: bool, name: &str| {
if cond {
state.push(name.to_string());
}
};
flag(g.idle, "idle");
flag(g.orphan, "orphan");
flag(g.protected, "protected");
flag(g.is_self, "self");
flag(g.lower_bound, "partial");
flag(is_reclaim_candidate(g), "reclaimable");
let busy = s
.model_servers
.iter()
.any(|m| m.group_id.as_deref() == Some(g.id.as_str()) && m.busy.value == Some(true));
flag(busy, "busy");
let sandbox_rec = s.sandboxes.iter().find(|sb| {
g.root.map(|r| sb.host_pids.contains(&r)).unwrap_or(false)
|| sb.host_pids.iter().any(|p| g.members.iter().any(|m| m.id == *p))
});
if let Some(rt) = sandbox_rec.map(|sb| sb.runtime.trim()).filter(|r| !r.is_empty()) {
state.push(format!("{RUNTIME_FLAG_PREFIX}{}", rt.to_lowercase()));
}
let owner_id = g
.owner_group
.clone()
.or_else(|| sandbox_rec.and_then(|sb| sb.started_by_group.clone()));
let owner = owner_id
.as_deref()
.and_then(|o| s.group(o))
.map(|o| o.label.clone());
let is_sandbox = g.kind == GroupKind::Sandbox || sandbox_rec.is_some();
let sandbox = is_sandbox.then(|| {
sandbox_rec
.map(|sb| sb.label.clone())
.unwrap_or_else(|| g.label.clone())
});
if g.staleness.stale {
state.push("stale".into());
}
for m in TimeMetric::ALL {
if let Some(x) = m.of_group(g) {
state.push(format!("{TIME_FLAG_PREFIX}{}={x}", m.as_str()));
}
}
EntityView {
id: g.id.clone(),
kind: g.kind,
name: g.label.clone(),
aliases: Vec::new(),
owner,
mem: g.totals.footprint.value,
gpu: g.totals.gpu.value,
cpu: g.totals.cpu_pct.value,
idle_s: g.idle_for_s,
state,
sandbox,
}
}
pub fn time_value(&self, m: TimeMetric) -> Option<f64> {
let key = m.as_str();
self.state.iter().find_map(|s| {
s.strip_prefix(TIME_FLAG_PREFIX)?
.strip_prefix(key)?
.strip_prefix('=')?
.parse::<f64>()
.ok()
})
}
pub fn set_time_value(&mut self, m: TimeMetric, v: Option<f64>) {
let prefix = format!("{TIME_FLAG_PREFIX}{}=", m.as_str());
self.state.retain(|s| !s.starts_with(&prefix));
if let Some(v) = v.filter(|v| v.is_finite()) {
self.state.push(format!("{prefix}{v}"));
}
}
pub fn sandbox_runtime(&self) -> Option<&str> {
self.state
.iter()
.find_map(|s| s.strip_prefix(RUNTIME_FLAG_PREFIX))
}
pub fn add_state(&mut self, flag: &str) {
let f = flag.to_ascii_lowercase();
if !self.state.contains(&f) {
self.state.push(f);
}
}
pub fn add_alias(&mut self, alias: &str) {
if !alias.is_empty() && !self.aliases.iter().any(|a| a == alias) {
self.aliases.push(alias.to_string());
}
}
}
fn contains_ci(hay: &str, needle: &str) -> bool {
hay.to_lowercase().contains(&needle.to_lowercase())
}
fn text_match(text: &str, pat: &str) -> bool {
if !pat.contains('*') {
return contains_ci(text, pat);
}
let t: Vec<char> = text.to_lowercase().chars().collect();
let p: Vec<char> = pat.to_lowercase().chars().collect();
let (mut ti, mut pi) = (0usize, 0usize);
let mut star: Option<(usize, usize)> = None;
while ti < t.len() {
if pi < p.len() && p[pi] != '*' && p[pi] == t[ti] {
ti += 1;
pi += 1;
} else if pi < p.len() && p[pi] == '*' {
star = Some((pi, ti));
pi += 1;
} else if let Some((sp, st)) = star {
pi = sp + 1;
ti = st + 1;
star = Some((sp, st + 1));
} else {
return false;
}
}
p[pi..].iter().all(|c| *c == '*')
}
fn cmp(op: CmpOp, a: f64, b: f64) -> bool {
match op {
CmpOp::Gt => a > b,
CmpOp::Ge => a >= b,
CmpOp::Lt => a < b,
CmpOp::Le => a <= b,
CmpOp::Eq => (a - b).abs() <= f64::EPSILON.max(b.abs() * 1e-9),
}
}
fn name_match(v: &EntityView, pat: &str) -> bool {
text_match(&v.name, pat) || v.aliases.iter().any(|a| text_match(a, pat))
}
pub fn eval(e: &Expr, v: &EntityView) -> bool {
match e {
Expr::And(xs) => xs.iter().all(|x| eval(x, v)),
Expr::Or(xs) => xs.iter().any(|x| eval(x, v)),
Expr::Not(x) => !eval(x, v),
Expr::Term(t) => match t {
Term::Field { key, values } => values.iter().any(|val| match key {
FieldKey::Kind => val == "*" || kind_synonym(val) == Some(v.kind),
FieldKey::Owner => match v.owner.as_deref() {
Some(o) => val == "*" || text_match(o, val),
None => false,
},
FieldKey::Name => val == "*" || name_match(v, val),
FieldKey::State if val.contains('*') => v
.state
.iter()
.filter(|s| !s.starts_with(TIME_FLAG_PREFIX))
.any(|s| text_match(s, val)),
FieldKey::State => v
.state
.iter()
.filter(|s| !s.starts_with(TIME_FLAG_PREFIX))
.any(|s| s.eq_ignore_ascii_case(val)),
FieldKey::Sandbox => match v.sandbox.as_deref() {
Some(sb) => {
val == "*"
|| text_match(sb, val)
|| v.sandbox_runtime().map(|r| text_match(r, val)).unwrap_or(false)
}
None => false,
},
}),
Term::Cmp { metric, op, value } => {
let x = match metric {
Metric::Mem => v.mem.map(|b| b as f64),
Metric::Gpu => v.gpu.map(|b| b as f64),
Metric::Cpu => v.cpu,
Metric::Idle => v.idle_s.map(|s| s as f64),
};
x.map(|x| cmp(*op, x, *value)).unwrap_or(false)
}
Term::TimeCmp { metric, op, value } => v
.time_value(*metric)
.map(|x| cmp(*op, x, *value))
.unwrap_or(false),
Term::Word(w) => {
v.state.iter().any(|s| s.eq_ignore_ascii_case(w))
|| name_match(v, w)
|| v.owner.as_deref().map(|o| text_match(o, w)).unwrap_or(false)
|| kind_synonym(w) == Some(v.kind)
}
},
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum View {
Home,
Processes,
Models,
Sandboxes,
Reclaim,
Timeline,
}
impl View {
pub fn as_str(self) -> &'static str {
match self {
View::Home => "home",
View::Processes => "processes",
View::Models => "models",
View::Sandboxes => "sandboxes",
View::Reclaim => "reclaim",
View::Timeline => "timeline",
}
}
pub fn parse(s: &str) -> Option<View> {
nav_word(&s.trim().to_ascii_lowercase())
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Intent {
Find,
RankBy(Metric),
Explain,
Headroom,
Reclaim,
Navigate(View),
}
impl Intent {
pub fn label(&self) -> String {
match self {
Intent::Find => "find".into(),
Intent::RankBy(m) => format!("rank by {}", m.label()),
Intent::Explain => "explain slowdown".into(),
Intent::Headroom => "check headroom".into(),
Intent::Reclaim => "reclaim memory".into(),
Intent::Navigate(v) => format!("open {}", v.as_str()),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Command {
pub name: String,
pub args: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct VocabEntity {
pub id: String,
pub name: String,
pub aliases: Vec<String>,
pub frecency: f64,
pub prior: f64,
}
pub const PROCESS_ID_PREFIX: &str = "pid:";
pub const PINNED_FRECENCY_BONUS: f64 = 3.0;
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Vocabulary {
pub entities: Vec<VocabEntity>,
}
pub const VOCAB_MAX_PROCESSES: usize = 200;
pub const VOCAB_MAX_MEMBER_ALIASES: usize = 8;
impl Vocabulary {
pub fn from_snapshot(
s: &Snapshot,
frecency_by_fp: &HashMap<String, f64>,
renames_by_fp: &HashMap<String, String>,
pinned_fps: &HashSet<String>,
) -> Vocabulary {
let mut grouped: HashSet<crate::model::ProcId> = HashSet::new();
let mut entities: Vec<VocabEntity> = Vec::with_capacity(s.groups.len());
let priors = crate::ranking::ColdStartPriors::detect(s);
for g in &s.groups {
let mut aliases: Vec<String> = renames_by_fp.get(&g.fingerprint).cloned().into_iter().collect();
let label = g.label.to_lowercase();
for m in &g.members {
grouped.insert(m.id);
if aliases.len() >= VOCAB_MAX_MEMBER_ALIASES {
continue;
}
if let Some(p) = s.process(m.id) {
let n = p.name.trim();
if !n.is_empty()
&& n.to_lowercase() != label
&& !aliases.iter().any(|a| a.eq_ignore_ascii_case(n))
{
aliases.push(n.to_string());
}
}
}
entities.push(VocabEntity {
id: g.id.clone(),
name: g.label.clone(),
aliases,
prior: priors.map(|p| p.for_kind(g.kind)).unwrap_or(0.0),
frecency: frecency_by_fp
.get(&g.fingerprint)
.copied()
.unwrap_or(0.0)
.max(0.0)
+ if pinned_fps.contains(&g.fingerprint) {
PINNED_FRECENCY_BONUS
} else {
0.0
},
});
}
let mut procs: Vec<&crate::model::Process> = s
.processes
.iter()
.filter(|p| !p.name.is_empty() && !grouped.contains(&p.id))
.collect();
procs.sort_by(|a, b| {
b.mem
.footprint_or_pss
.value
.unwrap_or(0)
.cmp(&a.mem.footprint_or_pss.value.unwrap_or(0))
.then(a.id.pid.cmp(&b.id.pid))
});
let mut seen: HashSet<String> = HashSet::new();
let mut added = 0;
for p in procs {
if added >= VOCAB_MAX_PROCESSES {
break;
}
if !seen.insert(p.name.to_lowercase()) {
continue;
}
added += 1;
entities.push(VocabEntity {
id: format!("{PROCESS_ID_PREFIX}{}", p.id.pid),
name: p.name.clone(),
..Default::default()
});
}
Vocabulary { entities }
}
fn tokens(&self) -> HashSet<String> {
let mut out = HashSet::new();
for e in &self.entities {
for n in std::iter::once(&e.name).chain(e.aliases.iter()) {
out.extend(name_tokens(n));
}
}
out
}
}
pub fn name_tokens(name: &str) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
let mut push = |t: String| {
if !t.is_empty() && !out.contains(&t) {
out.push(t);
}
};
for word in name
.split(|c: char| !c.is_alphanumeric())
.filter(|w| !w.is_empty())
{
push(word.to_lowercase());
let chars: Vec<char> = word.chars().collect();
let mut start = 0;
for i in 1..chars.len() {
let hump = chars[i - 1].is_lowercase() && chars[i].is_uppercase();
let acronym_end = chars[i - 1].is_uppercase()
&& chars[i].is_uppercase()
&& chars.get(i + 1).is_some_and(|c| c.is_lowercase());
if hump || acronym_end {
push(chars[start..i].iter().collect::<String>().to_lowercase());
start = i;
}
}
if start > 0 {
push(chars[start..].iter().collect::<String>().to_lowercase());
}
}
out
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Interpretation {
pub intent: Intent,
#[serde(default)]
pub filter: Option<Expr>,
#[serde(default)]
pub sort: Option<Metric>,
#[serde(default)]
pub targets: Vec<(String, f64)>,
#[serde(default)]
pub need_bytes: Option<u64>,
pub label: String,
pub score: f64,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Understanding {
pub intent: Intent,
pub filter: Option<Expr>,
pub sort: Option<Metric>,
pub targets: Vec<(String, f64)>,
pub need_bytes: Option<u64>,
pub command: Option<Command>,
pub confidence: f64,
pub alternatives: Vec<Intent>,
#[serde(default)]
pub interpretations: Vec<Interpretation>,
#[serde(default)]
pub corrections: Vec<Correction>,
#[serde(default)]
pub normalized: String,
#[serde(default)]
pub error: Option<String>,
#[serde(default)]
pub sort_time: Option<TimeMetric>,
}
impl Understanding {
fn empty() -> Self {
Understanding {
intent: Intent::Find,
filter: None,
sort: None,
targets: Vec::new(),
need_bytes: None,
command: None,
confidence: 0.0,
alternatives: Vec::new(),
interpretations: Vec::new(),
corrections: Vec::new(),
normalized: String::new(),
error: None,
sort_time: None,
}
}
pub fn is_ambiguous(&self) -> bool {
self.confidence < LOW_CONFIDENCE
}
pub fn top_target(&self) -> Option<&str> {
self.targets.first().map(|(id, _)| id.as_str())
}
}
const STOPWORDS: &[&str] = &[
"what",
"whats",
"is",
"the",
"my",
"me",
"are",
"i",
"im",
"can",
"could",
"show",
"all",
"a",
"an",
"of",
"up",
"to",
"now",
"stuff",
"things",
"who",
"whos",
"which",
"please",
"it",
"its",
"this",
"that",
"for",
"on",
"in",
"any",
"much",
"how",
"do",
"does",
"anything",
"something",
"list",
"give",
"tell",
"get",
"with",
"there",
"so",
"be",
"being",
"am",
"and",
"or",
"by",
"from",
"at",
"if",
"right",
"currently",
"most",
"some",
"lot",
"lots",
"again",
"really",
"very",
"you",
"your",
"we",
"our",
"go",
"open",
];
const RANK_WORDS: &[&str] = &[
"hog",
"hogs",
"hogging",
"eating",
"eats",
"eat",
"using",
"uses",
"use",
"biggest",
"largest",
"big",
"heavy",
"heaviest",
"top",
"consumers",
"consuming",
"hungry",
"greedy",
"usage",
];
const MEM_WORDS: &[&str] = &["memory", "mem", "ram", "footprint"];
const GPU_WORDS: &[&str] = &["gpu", "vram", "metal"];
const CPU_WORDS: &[&str] = &["cpu", "processor", "cores"];
const EXPLAIN_STRONG: &[&str] = &[
"slow",
"slowly",
"slowness",
"lag",
"laggy",
"lagging",
"throttle",
"throttling",
"throttled",
"sluggish",
"slowdown",
"stutter",
"stuttering",
"freeze",
"freezing",
"frozen",
];
const EXPLAIN_WEAK: &[&str] = &["why", "hot", "heat", "fan", "thermal", "explain"];
const HEADROOM_VERBS: &[&str] = &["load", "fit", "fits", "run", "start", "launch"];
const HEADROOM_NOUNS: &[&str] = &["headroom", "room", "space", "enough", "available"];
const RECLAIM_STRONG: &[&str] = &[
"reclaim",
"reclaimable",
"leftovers",
"leftover",
"orphans",
"orphan",
"orphaned",
"cleanup",
"clean",
];
const RECLAIM_WEAK: &[&str] = &["idle", "unused", "free", "kill", "stop"];
fn nav_word(w: &str) -> Option<View> {
match w {
"models" | "model" => Some(View::Models),
"sandboxes" | "sandbox" | "vms" | "vm" | "containers" | "container" => Some(View::Sandboxes),
"processes" | "procs" | "process" => Some(View::Processes),
"timeline" | "history" => Some(View::Timeline),
"home" | "groups" => Some(View::Home),
_ => None,
}
}
const NAV_WORDS: &[&str] = &[
"models",
"sandboxes",
"processes",
"procs",
"timeline",
"history",
"home",
"groups",
];
fn lexicon() -> impl Iterator<Item = &'static str> {
RANK_WORDS
.iter()
.chain(MEM_WORDS)
.chain(GPU_WORDS)
.chain(CPU_WORDS)
.chain(EXPLAIN_STRONG)
.chain(EXPLAIN_WEAK)
.chain(HEADROOM_VERBS)
.chain(HEADROOM_NOUNS)
.chain(RECLAIM_STRONG)
.chain(RECLAIM_WEAK)
.chain(NAV_WORDS)
.chain(KIND_WORDS)
.copied()
}
fn in_lexicon(w: &str) -> bool {
lexicon().any(|l| l == w)
}
pub fn damerau_levenshtein(a: &str, b: &str) -> usize {
let a: Vec<char> = a.chars().collect();
let b: Vec<char> = b.chars().collect();
let (n, m) = (a.len(), b.len());
if n == 0 {
return m;
}
if m == 0 {
return n;
}
let mut prev2: Vec<usize> = vec![0; m + 1];
let mut prev: Vec<usize> = (0..=m).collect();
let mut cur: Vec<usize> = vec![0; m + 1];
for i in 1..=n {
cur[0] = i;
for j in 1..=m {
let cost = usize::from(a[i - 1] != b[j - 1]);
let mut d = (prev[j] + 1).min(cur[j - 1] + 1).min(prev[j - 1] + cost);
if i > 1 && j > 1 && a[i - 1] == b[j - 2] && a[i - 2] == b[j - 1] {
d = d.min(prev2[j - 2] + 1);
}
cur[j] = d;
}
std::mem::swap(&mut prev2, &mut prev);
std::mem::swap(&mut prev, &mut cur);
}
prev[m]
}
fn closest<'a>(w: &str, candidates: impl Iterator<Item = &'a str>, min_len: usize) -> Option<&'a str> {
let wl = w.chars().count();
candidates
.filter(|c| c.chars().count() >= min_len && *c != w)
.filter(|c| damerau_levenshtein(c, w) <= 1)
.min_by(|a, b| {
let da = (a.chars().count() as i64 - wl as i64).abs();
let db = (b.chars().count() as i64 - wl as i64).abs();
da.cmp(&db).then(a.cmp(b))
})
}
const SCORE_MATCH: f64 = 16.0;
const GAP_START: f64 = -3.0;
const GAP_EXT: f64 = -1.0;
const BONUS_BOUNDARY_WHITE: f64 = 10.0;
const BONUS_BOUNDARY: f64 = 8.0;
const BONUS_CAMEL: f64 = 7.0;
const BONUS_CONSECUTIVE: f64 = 4.0;
const FIRST_CHAR_MULT: f64 = 2.0;
fn char_bonus(prev: Option<char>, cur: char) -> f64 {
match prev {
None => BONUS_BOUNDARY_WHITE,
Some(p) if p.is_whitespace() => BONUS_BOUNDARY_WHITE,
Some('-' | '_' | '.' | '/' | '·' | ':' | ',' | '(' | '[' | '@' | '\\') => BONUS_BOUNDARY,
Some(p) if p.is_lowercase() && cur.is_uppercase() => BONUS_CAMEL,
Some(p) if p.is_alphabetic() && cur.is_ascii_digit() => BONUS_CAMEL,
_ => 0.0,
}
}
pub fn fuzzy_score(pattern: &str, text: &str) -> Option<f64> {
let p: Vec<char> = pattern
.to_lowercase()
.chars()
.filter(|c| !c.is_whitespace())
.collect();
if p.is_empty() {
return Some(0.0);
}
let orig: Vec<char> = text.chars().collect();
let t: Vec<char> = orig
.iter()
.map(|c| c.to_lowercase().next().unwrap_or(*c))
.collect();
let n = t.len();
if n < p.len() {
return None;
}
let bonus: Vec<f64> = (0..n)
.map(|j| char_bonus(if j == 0 { None } else { Some(orig[j - 1]) }, orig[j]))
.collect();
const NEG: f64 = f64::NEG_INFINITY;
let mut prev: Vec<f64> = vec![NEG; n];
for (j, &c) in t.iter().enumerate() {
if c == p[0] {
prev[j] = SCORE_MATCH + bonus[j] * FIRST_CHAR_MULT;
}
}
for &pc in p.iter().skip(1) {
let mut cur: Vec<f64> = vec![NEG; n];
let mut gap_best = NEG;
for j in 0..n {
if j >= 2 {
gap_best = (gap_best + GAP_EXT).max(prev[j - 2] + GAP_START);
}
if t[j] != pc {
continue;
}
let consecutive = if j >= 1 && prev[j - 1] > NEG {
prev[j - 1] + SCORE_MATCH + bonus[j].max(BONUS_CONSECUTIVE)
} else {
NEG
};
let gapped = if gap_best > NEG {
gap_best + SCORE_MATCH + bonus[j]
} else {
NEG
};
cur[j] = consecutive.max(gapped);
}
prev = cur;
}
let best = prev.into_iter().fold(NEG, f64::max);
if best == NEG {
return None;
}
Some(best - n as f64 * 0.01)
}
pub fn fuzzy_match(pattern: &str, text: &str) -> Option<f64> {
let m = pattern.chars().filter(|c| !c.is_whitespace()).count();
if m == 0 {
return Some(0.0);
}
let raw = fuzzy_score(pattern, text)?;
let ideal = SCORE_MATCH
+ BONUS_BOUNDARY_WHITE * FIRST_CHAR_MULT
+ (m as f64 - 1.0) * (SCORE_MATCH + BONUS_CONSECUTIVE);
Some((raw / ideal).clamp(0.0, 1.0))
}
fn kind_prior(e: &VocabEntity) -> f64 {
if e.id.starts_with(PROCESS_ID_PREFIX) {
-0.05
} else {
0.0
}
}
fn affinity(frecency: f64) -> f64 {
1.0 - (-frecency.max(0.0) / 5.0).exp()
}
fn name_match_quality(words: &[String], name: &str) -> f64 {
let lname = name.to_lowercase();
let joined = words.join(" ");
if lname == joined {
return 1.5; }
let mut best = fuzzy_match(&joined, name).unwrap_or(0.0);
if words.len() > 1 {
let per: Vec<f64> = words
.iter()
.map(|w| fuzzy_match(w, name).unwrap_or(0.0))
.collect();
if per.iter().all(|s| *s > 0.0) {
best = best.max(0.9 * per.iter().sum::<f64>() / per.len() as f64);
}
}
let tokens = name_tokens(name);
for w in words {
if w.chars().count() >= MIN_TYPO_LEN {
if tokens.iter().any(|t| t == w) {
best = best.max(1.0);
} else if tokens.iter().any(|t| damerau_levenshtein(t, w) <= 1) {
best = best.max(0.7);
}
}
}
best
}
pub fn link_entities(words: &[String], vocab: &Vocabulary) -> Vec<(String, f64)> {
let words: Vec<String> = words
.iter()
.map(|w| w.trim().to_lowercase())
.filter(|w| !w.is_empty())
.collect();
if words.is_empty() {
return Vec::new();
}
let mut out: Vec<(String, f64)> = Vec::new();
for e in &vocab.entities {
let m = std::iter::once(&e.name)
.chain(e.aliases.iter())
.map(|n| name_match_quality(&words, n))
.fold(0.0, f64::max);
if m < MIN_LINK_SCORE {
continue;
}
let cold = if e.frecency > 0.0 { 0.0 } else { e.prior.max(0.0) };
let s = m + FRECENCY_LINK_BOOST * affinity(e.frecency) + kind_prior(e) + cold;
out.push((e.id.clone(), (s * 1e6).round() / 1e6));
}
out.sort_by(|a, b| {
b.1.partial_cmp(&a.1)
.unwrap_or(std::cmp::Ordering::Equal)
.then(a.0.cmp(&b.0))
});
out
}
const BYTE_UNITS: &[&str] = &[
"b", "k", "kb", "kib", "m", "mb", "mib", "g", "gb", "gib", "t", "tb", "tib",
];
fn unit_alias(u: &str) -> Option<&'static str> {
Some(match u {
"gig" | "gigs" | "gigabyte" | "gigabytes" => "GB",
"meg" | "megs" | "megabyte" | "megabytes" => "MB",
"terabyte" | "terabytes" => "TB",
"kilobyte" | "kilobytes" => "KB",
"gibibyte" | "gibibytes" => "GiB",
_ => return None,
})
}
const TIME_UNITS: &[&str] = &[
"s", "sec", "secs", "min", "mins", "h", "hr", "hrs", "d", "day", "days", "hours", "hour", "minutes",
"minute",
];
fn time_alias(u: &str) -> Option<&'static str> {
Some(match u {
"hours" | "hour" => "h",
"minutes" | "minute" => "min",
"seconds" | "second" => "s",
_ => return None,
})
}
enum Quantity {
Bytes(u64),
Duration(f64),
}
fn split_num(w: &str) -> Option<(&str, &str)> {
let idx = w
.find(|c: char| !(c.is_ascii_digit() || c == '.'))
.unwrap_or(w.len());
if idx == 0 {
return None;
}
Some((&w[..idx], &w[idx..]))
}
fn quantity(w: &str, prefer_time: bool) -> Option<Quantity> {
let (num, unit) = split_num(w)?;
let unit_l = unit.to_ascii_lowercase();
if unit_l.is_empty() {
return None;
}
if unit_l == "m" {
return if prefer_time {
parse_duration_s(w).ok().map(Quantity::Duration)
} else {
parse_bytes(w).ok().map(Quantity::Bytes)
};
}
if BYTE_UNITS.contains(&unit_l.as_str()) {
return parse_bytes(w).ok().map(Quantity::Bytes);
}
if let Some(u) = unit_alias(&unit_l) {
return parse_bytes(&format!("{num}{u}")).ok().map(Quantity::Bytes);
}
if TIME_UNITS.contains(&unit_l.as_str()) || time_alias(&unit_l).is_some() {
let u = time_alias(&unit_l).unwrap_or(unit_l.as_str());
return parse_duration_s(&format!("{num}{u}"))
.ok()
.map(Quantity::Duration);
}
parse_duration_s(w).ok().map(Quantity::Duration)
}
fn normalize_raw_words(input: &str) -> Vec<String> {
let cleaned: String = input
.to_lowercase()
.replace(['\u{2019}', '\''], "")
.chars()
.map(|c| {
if c.is_alphanumeric() || matches!(c, '.' | '-' | '_') {
c
} else {
' '
}
})
.collect();
let raw: Vec<&str> = cleaned
.split_whitespace()
.map(|w| w.trim_matches(|c| c == '.' || c == '-'))
.filter(|w| !w.is_empty())
.collect();
let mut out: Vec<String> = Vec::with_capacity(raw.len());
let mut i = 0;
while i < raw.len() {
let w = raw[i];
let is_num =
w.chars().all(|c| c.is_ascii_digit() || c == '.') && w.chars().any(|c| c.is_ascii_digit());
if is_num && i + 1 < raw.len() {
let u = raw[i + 1];
if BYTE_UNITS.contains(&u)
|| unit_alias(u).is_some()
|| TIME_UNITS.contains(&u)
|| time_alias(u).is_some()
{
out.push(format!("{w}{u}"));
i += 2;
continue;
}
}
out.push(w.to_string());
i += 1;
}
out
}
fn is_adjacent_transposition(a: &str, b: &str) -> bool {
let (a, b): (Vec<char>, Vec<char>) = (a.chars().collect(), b.chars().collect());
if a.len() != b.len() {
return false;
}
let diff: Vec<usize> = (0..a.len()).filter(|&i| a[i] != b[i]).collect();
diff.len() == 2 && diff[1] == diff[0] + 1 && a[diff[0]] == b[diff[1]] && a[diff[1]] == b[diff[0]]
}
fn fix_typo(w: &str, entity_tokens: &HashSet<String>, corrections: &mut Vec<Correction>) -> String {
let len = w.chars().count();
if len < MIN_TYPO_LEN
|| in_lexicon(w)
|| STOPWORDS.contains(&w)
|| entity_tokens.contains(w)
|| entity_tokens.iter().any(|t| t.starts_with(w))
|| w.chars().any(|c| c.is_ascii_digit())
{
return w.to_string();
}
let fixed = if len == MIN_TYPO_LEN {
lexicon().filter(|c| is_adjacent_transposition(c, w)).min()
} else {
closest(w, lexicon(), MIN_TYPO_LEN)
};
match fixed {
Some(fixed) => {
corrections.push(Correction {
from: w.to_string(),
to: fixed.to_string(),
});
fixed.to_string()
}
None => w.to_string(),
}
}
struct WordAnalysis {
need: Option<u64>,
idle_for: Option<f64>,
kinds: Vec<GroupKind>,
content: Vec<String>,
scores: Vec<(Intent, f64)>,
said_idle: bool,
}
fn has(words: &[String], set: &[&str]) -> bool {
words.iter().any(|w| set.contains(&w.as_str()))
}
fn analyze_words(words: &[String]) -> WordAnalysis {
let time_words = has(words, &["idle", "since", "ago", "older", "unused"]);
let room_words = has(words, HEADROOM_VERBS) || has(words, HEADROOM_NOUNS);
let prefer_time = time_words || (has(words, &["for"]) && !room_words);
let mut need = None;
let mut idle_for = None;
let mut rest: Vec<String> = Vec::new();
for w in words {
match quantity(w, prefer_time) {
Some(Quantity::Bytes(b)) => need = Some(b),
Some(Quantity::Duration(d)) => idle_for = Some(d),
None => rest.push(w.clone()),
}
}
let metric = if has(&rest, GPU_WORDS) {
Some(Metric::Gpu)
} else if has(&rest, CPU_WORDS) {
Some(Metric::Cpu)
} else if has(&rest, MEM_WORDS) {
Some(Metric::Mem)
} else {
None
};
let mut kinds: Vec<GroupKind> = Vec::new();
for w in &rest {
if KIND_WORDS.contains(&w.as_str()) {
if let Some(k) = kind_synonym(w) {
if !kinds.contains(&k) {
kinds.push(k);
}
}
}
}
let content: Vec<String> = rest
.iter()
.filter(|w| !STOPWORDS.contains(&w.as_str()) && !in_lexicon(w))
.cloned()
.collect();
let meaningful: Vec<&String> = rest.iter().filter(|w| !STOPWORDS.contains(&w.as_str())).collect();
let mut scores: Vec<(Intent, f64)> = Vec::new();
let headroom_verb = has(&rest, HEADROOM_VERBS);
let headroom_noun = has(&rest, HEADROOM_NOUNS);
if need.is_some() {
let s = if headroom_verb || headroom_noun {
0.95
} else if meaningful.is_empty() {
0.85
} else {
0.7
};
scores.push((Intent::Headroom, s));
} else if headroom_noun {
scores.push((Intent::Headroom, 0.75));
}
if has(&rest, EXPLAIN_STRONG) {
scores.push((Intent::Explain, 0.9));
} else if has(&rest, EXPLAIN_WEAK) {
scores.push((Intent::Explain, 0.75));
}
let rank_metric = metric.unwrap_or(Metric::Mem);
if has(&rest, RANK_WORDS) {
scores.push((Intent::RankBy(rank_metric), 0.9));
} else if metric.is_some()
&& meaningful.iter().all(|w| {
MEM_WORDS.contains(&w.as_str())
|| GPU_WORDS.contains(&w.as_str())
|| CPU_WORDS.contains(&w.as_str())
})
{
scores.push((Intent::RankBy(rank_metric), 0.8));
} else if metric.is_some() {
scores.push((Intent::RankBy(rank_metric), 0.55));
}
if has(&rest, RECLAIM_STRONG) {
scores.push((Intent::Reclaim, 0.9));
} else if has(&rest, &["idle", "unused"]) {
scores.push((Intent::Reclaim, 0.8));
} else if has(&rest, &["free"]) && has(&rest, &["up"]) || has(&rest, &["kill", "stop"]) {
scores.push((Intent::Reclaim, 0.75));
} else if has(&rest, &["free"]) {
scores.push((Intent::Reclaim, 0.5));
if need.is_none() {
scores.push((Intent::Headroom, 0.55));
}
}
if let Some(v) = rest.iter().find_map(|w| nav_word(w)) {
let only = meaningful.len() == 1;
scores.push((Intent::Navigate(v), if only { 0.8 } else { 0.45 }));
}
WordAnalysis {
need,
idle_for,
kinds,
content,
scores,
said_idle: has(&rest, &["idle", "unused"]),
}
}
fn kind_filter(kinds: &[GroupKind]) -> Option<Expr> {
(!kinds.is_empty()).then(|| {
Expr::Term(Term::Field {
key: FieldKey::Kind,
values: kinds.iter().map(|k| k.alias().to_string()).collect(),
})
})
}
fn state_filter(v: &str) -> Expr {
Expr::Term(Term::Field {
key: FieldKey::State,
values: vec![v.to_string()],
})
}
fn fmt_need(b: u64) -> String {
if b >= GIB && b.is_multiple_of(GIB) {
format!("{} GiB", b / GIB)
} else if b >= 1_000_000_000 && b.is_multiple_of(1_000_000_000) {
format!("{} GB", b / 1_000_000_000)
} else if b >= MIB && b.is_multiple_of(MIB) {
format!("{} MiB", b / MIB)
} else if b >= 1_000_000 && b.is_multiple_of(1_000_000) {
format!("{} MB", b / 1_000_000)
} else {
crate::headline::format_amount(b, crate::units::UnitSystem::Si)
}
}
const STRONG_INTENT: f64 = 0.75;
const STRONG_INTENT_LEAD: f64 = 0.2;
fn targets_intent(i: &Intent) -> bool {
matches!(i, Intent::Explain | Intent::Reclaim | Intent::RankBy(_))
}
fn describe(intent: &Intent, filter: Option<&Expr>, need: Option<u64>, target_name: Option<&str>) -> String {
let base = match intent {
Intent::Find => match (target_name, filter) {
(Some(n), _) => format!("go to {n}"),
(None, Some(f)) => format!("filter {f}"),
(None, None) => "find".into(),
},
Intent::Headroom => match need {
Some(b) => format!("can {} fit?", fmt_need(b)),
None => "check headroom".into(),
},
other => match target_name {
Some(n) => format!("{} · {n}", other.label()),
None => other.label(),
},
};
match (intent, filter) {
(Intent::Find, _) | (_, None) => base,
(_, Some(f)) => format!("{base} ({f})"),
}
}
fn finish(mut u: Understanding, mut interps: Vec<Interpretation>) -> Understanding {
interps.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal));
let mut seen = HashSet::new();
interps.retain(|i| seen.insert(i.label.clone()));
interps.truncate(3);
if let Some(best) = interps.first() {
u.intent = best.intent.clone();
u.filter = best.filter.clone();
u.sort = best.sort;
u.need_bytes = best.need_bytes.or(u.need_bytes);
let second = interps.get(1).map(|i| i.score).unwrap_or(0.0);
u.confidence = if best.score - second < 0.1 {
best.score.min(0.45)
} else {
best.score
};
}
u.alternatives = if u.confidence < LOW_CONFIDENCE {
interps.iter().skip(1).map(|i| i.intent.clone()).collect()
} else {
Vec::new()
};
u.interpretations = interps;
u
}
fn fallback_interpretations() -> Vec<Interpretation> {
[
(Intent::RankBy(Metric::Mem), 0.2),
(Intent::Explain, 0.19),
(Intent::Reclaim, 0.18),
]
.into_iter()
.map(|(intent, score)| Interpretation {
label: intent.label(),
sort: match intent {
Intent::RankBy(m) => Some(m),
_ => None,
},
intent,
filter: None,
targets: Vec::new(),
need_bytes: None,
score,
})
.collect()
}
fn find_confidence(targets: &[(String, f64)], vocab: &Vocabulary) -> f64 {
let name = |id: &str| {
vocab
.entities
.iter()
.find(|e| e.id == id)
.map(|e| e.name.to_lowercase())
.unwrap_or_else(|| id.to_string())
};
let Some((top_id, a)) = targets.first() else {
return 0.0;
};
let top_name = name(top_id);
match targets.iter().skip(1).find(|(id, _)| name(id) != top_name) {
None if *a >= 0.9 => 0.9,
None if *a >= 0.6 => 0.7,
None => 0.45,
Some((_, b)) => {
let margin = a - b;
if margin >= 0.25 {
0.9
} else if margin >= 0.1 {
0.7
} else {
0.4
}
}
}
}
fn lexicon_filters(intent: &Intent, wa: &WordAnalysis) -> Vec<Expr> {
let mut parts = Vec::new();
if *intent == Intent::Reclaim {
if let Some(d) = wa.idle_for {
parts.push(Expr::Term(Term::Cmp {
metric: Metric::Idle,
op: CmpOp::Ge,
value: d,
}));
} else if wa.said_idle {
parts.push(state_filter("idle"));
}
}
if !matches!(intent, Intent::Navigate(_) | Intent::Headroom | Intent::Explain) {
parts.extend(kind_filter(&wa.kinds));
}
parts
}
fn plain_interpretations(
wa: &WordAnalysis,
extra_filter: Option<Expr>,
vocab: &Vocabulary,
) -> (Vec<Interpretation>, Vec<(String, f64)>) {
let targets = link_entities(&wa.content, vocab);
let name_of = |id: &str| vocab.entities.iter().find(|e| e.id == id).map(|e| e.name.clone());
let mut interps = Vec::new();
for (intent, score) in &wa.scores {
let mut parts: Vec<Expr> = extra_filter.iter().cloned().collect();
parts.extend(lexicon_filters(intent, wa));
let filter = Expr::and_all(parts);
let sort = match intent {
Intent::RankBy(m) => Some(*m),
_ => None,
};
let about = if targets_intent(intent) {
targets.first().and_then(|(id, _)| name_of(id))
} else {
None
};
interps.push(Interpretation {
label: describe(intent, filter.as_ref(), wa.need, about.as_deref()),
intent: intent.clone(),
filter,
sort,
targets: if matches!(intent, Intent::Find) {
Vec::new()
} else {
targets.iter().take(3).cloned().collect()
},
need_bytes: if matches!(intent, Intent::Headroom) {
wa.need
} else {
None
},
score: *score,
});
}
let strong_intent = wa
.scores
.iter()
.filter(|(i, s)| targets_intent(i) && *s >= STRONG_INTENT)
.map(|(_, s)| *s)
.fold(0.0, f64::max);
let mut fc = find_confidence(&targets, vocab);
if strong_intent > 0.0 {
fc = fc.min(strong_intent - STRONG_INTENT_LEAD);
}
for (rank, (id, _)) in targets.iter().take(3).enumerate() {
let name = name_of(id).unwrap_or_else(|| id.clone());
interps.push(Interpretation {
intent: Intent::Find,
filter: extra_filter.clone(),
sort: None,
targets: targets.iter().skip(rank).take(3).cloned().collect(),
need_bytes: None,
label: describe(&Intent::Find, None, None, Some(&name)),
score: if rank == 0 {
fc
} else {
(fc - 0.1 * rank as f64).clamp(0.05, 0.44)
},
});
}
if !wa.kinds.is_empty() {
let mut parts: Vec<Expr> = extra_filter.iter().cloned().collect();
parts.extend(kind_filter(&wa.kinds));
let filter = Expr::and_all(parts);
interps.push(Interpretation {
label: describe(&Intent::Find, filter.as_ref(), None, None),
intent: Intent::Find,
filter,
sort: None,
targets: Vec::new(),
need_bytes: None,
score: 0.65,
});
}
(interps, targets)
}
const COMMANDS: &[&str] = &[
"reclaim",
"headroom",
"fit",
"why",
"pin",
"unpin",
"mute",
"unmute",
"rename",
"mode",
"sort",
"save",
"view",
"filter",
"help",
"quit",
"less",
"watch",
"stop",
"suspend",
"resume",
"models",
"sandboxes",
"processes",
"timeline",
"home",
"settings",
"theme",
"clear",
"compare",
"undo",
];
fn understand_command(cmd: &str, vocab: &Vocabulary) -> Understanding {
let mut u = Understanding::empty();
let mut parts = cmd.split_whitespace().map(str::to_string);
let raw_name = parts.next().unwrap_or_default().to_lowercase();
let args: Vec<String> = parts.collect();
let (name, known) = if COMMANDS.contains(&raw_name.as_str()) {
(raw_name.clone(), true)
} else if let Some(fixed) = (raw_name.chars().count() >= 3)
.then(|| closest(&raw_name, COMMANDS.iter().copied(), 3))
.flatten()
{
u.corrections.push(Correction {
from: raw_name.clone(),
to: fixed.to_string(),
});
(fixed.to_string(), true)
} else {
(raw_name.clone(), false)
};
u.normalized = std::iter::once(format!(":{name}"))
.chain(args.iter().cloned())
.collect::<Vec<_>>()
.join(" ");
let joined_args = normalize_raw_words(&args.join(" "));
let link_args = |a: &[String]| link_entities(&normalize_raw_words(&a.join(" ")), vocab);
let intent = match name.as_str() {
"reclaim" => Intent::Reclaim,
"headroom" | "fit" => {
u.need_bytes = joined_args.iter().find_map(|w| match quantity(w, false) {
Some(Quantity::Bytes(b)) => Some(b),
_ => None,
});
if u.need_bytes.is_none() {
if let Some(n) = joined_args
.iter()
.find(|w| w.parse::<f64>().is_ok_and(|x| x.is_finite()))
{
u.error = Some(format!("add a unit to {n}, e.g. {n}G or {n}GB"));
}
}
Intent::Headroom
}
"why" => Intent::Explain,
"sort" => match args.first().and_then(|a| TimeMetric::parse(a)) {
Some(t) => {
u.sort_time = Some(t);
Intent::Find
}
None => {
let m = args.first().and_then(|a| Metric::parse(a)).unwrap_or(Metric::Mem);
u.sort = Some(m);
Intent::RankBy(m)
}
},
"view" => args
.first()
.and_then(|a| View::parse(a))
.map(Intent::Navigate)
.unwrap_or(Intent::Find),
"models" | "sandboxes" | "processes" | "timeline" | "home" => {
Intent::Navigate(View::parse(&name).unwrap_or(View::Home))
}
"filter" => {
match parse_filter_corrected(&args.join(" ")) {
Ok((f, c)) => {
u.filter = Some(f);
u.corrections.extend(c);
}
Err(e) => u.error = Some(e.to_string()),
}
Intent::Find
}
"pin" | "unpin" | "mute" | "unmute" | "watch" | "stop" | "suspend" | "resume" | "less" => {
u.targets = link_args(&args);
Intent::Find
}
"rename" => {
if args.len() >= 2 {
u.targets = link_args(&args[..args.len() - 1]);
}
Intent::Find
}
_ => Intent::Find,
};
u.intent = intent.clone();
u.command = Some(Command { name, args });
u.confidence = if !known {
0.3
} else if u.corrections.is_empty() {
1.0
} else {
0.9
};
if !known {
let mut sugg: Vec<(&str, f64)> = COMMANDS
.iter()
.filter_map(|c| fuzzy_match(&raw_name, c).map(|s| (*c, s)))
.collect();
sugg.sort_by(|a, b| {
b.1.partial_cmp(&a.1)
.unwrap_or(std::cmp::Ordering::Equal)
.then(a.0.cmp(b.0))
});
u.interpretations = sugg
.into_iter()
.take(3)
.map(|(c, s)| Interpretation {
intent: Intent::Find,
filter: None,
sort: None,
targets: Vec::new(),
need_bytes: None,
label: format!(":{c}"),
score: (s * 0.4).min(0.4),
})
.collect();
} else {
u.interpretations = vec![Interpretation {
intent,
filter: u.filter.clone(),
sort: u.sort,
targets: u.targets.clone(),
need_bytes: u.need_bytes,
label: format!(":{}", u.command.as_ref().map(|c| c.name.as_str()).unwrap_or("")),
score: u.confidence,
}];
}
u
}
fn looks_structured(toks: &[Tok]) -> bool {
toks.iter().any(|t| match t {
Tok::LParen | Tok::RParen | Tok::Or | Tok::Not | Tok::Neg | Tok::Lit(_) => true,
Tok::Atom(a) => split_key_op(a).is_some(),
})
}
pub fn understand(input: &str, vocab: &Vocabulary) -> Understanding {
let input = input.trim();
if let Some(cmd) = input.strip_prefix(':') {
return understand_command(cmd, vocab);
}
let mut u = Understanding::empty();
if input.is_empty() {
u.confidence = 1.0;
return u;
}
let entity_tokens = vocab.tokens();
match tokenize(input) {
Ok(toks) if looks_structured(&toks) => {
let mut corrections = Vec::new();
match parse_tokens(toks, &mut corrections) {
Ok(expr) => return understand_structured(expr, corrections, vocab, &entity_tokens),
Err(e) => {
u.error = Some(e.to_string());
u.corrections = corrections;
u.normalized = input.to_lowercase();
return u;
}
}
}
Ok(_) => {}
Err(e) => {
u.error = Some(e.to_string());
u.normalized = input.to_lowercase();
return u;
}
}
let raw = normalize_raw_words(input);
let words: Vec<String> = raw
.iter()
.map(|w| fix_typo(w, &entity_tokens, &mut u.corrections))
.collect();
u.normalized = words.join(" ");
let wa = analyze_words(&words);
u.need_bytes = wa.need;
let (interps, targets) = plain_interpretations(&wa, None, vocab);
u.targets = targets;
if interps.is_empty() {
u.confidence = 0.2;
u.interpretations = fallback_interpretations();
u.alternatives = u.interpretations.iter().map(|i| i.intent.clone()).collect();
u
} else {
finish(u, interps)
}
}
fn understand_structured(
expr: Expr,
corrections: Vec<Correction>,
vocab: &Vocabulary,
entity_tokens: &HashSet<String>,
) -> Understanding {
let mut u = Understanding::empty();
u.corrections = corrections;
let is_phrase = |x: &str| {
!x.chars()
.all(|c| c.is_alphanumeric() || matches!(c, '-' | '_' | '.'))
};
let mut phrases: Vec<String> = Vec::new();
let (structured, words): (Vec<Expr>, Vec<String>) = match expr {
Expr::And(parts) => {
let mut s = Vec::new();
let mut w = Vec::new();
for p in parts {
match p {
Expr::Term(Term::Word(x)) if !is_phrase(&x) => w.push(x),
Expr::Term(Term::Word(x)) => {
phrases.push(x.clone());
s.push(Expr::Term(Term::Word(x)));
}
other => s.push(other),
}
}
(s, w)
}
Expr::Term(Term::Word(x)) if !is_phrase(&x) => (Vec::new(), vec![x]),
Expr::Term(Term::Word(x)) => {
phrases.push(x.clone());
(vec![Expr::Term(Term::Word(x))], Vec::new())
}
other => (vec![other], Vec::new()),
};
let norm_words: Vec<String> = normalize_raw_words(&words.join(" "))
.iter()
.map(|w| fix_typo(w, entity_tokens, &mut u.corrections))
.collect();
let wa = analyze_words(&norm_words);
let mut parts = structured;
for w in &wa.content {
parts.push(Expr::Term(Term::Word(w.clone())));
}
let filter = Expr::and_all(parts);
let intent_words: Vec<String> = norm_words
.iter()
.filter(|w| !wa.content.contains(w))
.cloned()
.collect();
let filter_text = filter.as_ref().map(|f| f.to_string()).unwrap_or_default();
u.normalized = format!("{} {filter_text}", intent_words.join(" "))
.trim()
.to_string();
let link_words: Vec<String> = wa.content.iter().chain(phrases.iter()).cloned().collect();
u.targets = link_entities(&link_words, vocab);
u.need_bytes = wa.need;
let metrics = filter.as_ref().map(|f| f.metrics()).unwrap_or_default();
let default_sort = (metrics.len() == 1).then(|| metrics[0]);
let with_lexicon = |intent: &Intent| -> Option<Expr> {
let extra = lexicon_filters(intent, &wa);
if extra.is_empty() {
return filter.clone();
}
Expr::and_all(filter.iter().cloned().chain(extra).collect())
};
let mut interps: Vec<Interpretation> = wa
.scores
.iter()
.map(|(intent, score)| {
let filter = with_lexicon(intent);
Interpretation {
label: describe(intent, filter.as_ref(), wa.need, None),
intent: intent.clone(),
filter,
sort: match intent {
Intent::RankBy(m) => Some(*m),
_ => default_sort,
},
targets: u.targets.iter().take(3).cloned().collect(),
need_bytes: wa.need,
score: *score,
}
})
.collect();
let filter = with_lexicon(&Intent::Find);
interps.push(Interpretation {
label: describe(&Intent::Find, filter.as_ref(), None, None),
intent: Intent::Find,
filter: filter.clone(),
sort: default_sort,
targets: u.targets.iter().take(3).cloned().collect(),
need_bytes: None,
score: if wa.scores.is_empty() { 1.0 } else { 0.6 },
});
let mut u = finish(u, interps);
if u.filter.is_none() {
u.filter = filter;
}
if u.sort.is_none() {
u.sort = default_sort;
}
if wa.scores.is_empty() {
u.confidence = 1.0;
}
u
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SuggestionKind {
PastQuery,
Entity,
Command,
Key,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Suggestion {
pub text: String,
pub kind: SuggestionKind,
pub score: f64,
}
const FILTER_KEYS: &[&str] = &[
"kind:", "owner:", "name:", "state:", "sandbox:", "mem>", "gpu>", "cpu>", "idle>",
];
pub fn suggest(input: &str, past: &[(String, f64)], vocab: &Vocabulary, limit: usize) -> Vec<Suggestion> {
let q = input.trim();
let mut out: Vec<Suggestion> = Vec::new();
let push = |out: &mut Vec<Suggestion>, text: String, kind, score: f64| {
if !out.iter().any(|s| s.text == text) && text != q {
out.push(Suggestion { text, kind, score });
}
};
if let Some(c) = q.strip_prefix(':') {
for cmd in COMMANDS {
if let Some(s) = fuzzy_match(c, cmd) {
if c.is_empty() || s > 0.3 {
push(&mut out, format!(":{cmd}"), SuggestionKind::Command, 1.0 + s);
}
}
}
}
for (text, fr) in past {
let s = if q.is_empty() {
Some(0.5)
} else if text.to_lowercase().starts_with(&q.to_lowercase()) {
Some(1.0)
} else {
fuzzy_match(q, text)
};
if let Some(s) = s.filter(|s| *s >= MIN_LINK_SCORE) {
push(
&mut out,
text.clone(),
SuggestionKind::PastQuery,
s + affinity(*fr),
);
}
}
if !q.is_empty() && !q.starts_with(':') {
let last = q.split_whitespace().last().unwrap_or("");
for (id, s) in link_entities(&[last.to_string()], vocab).into_iter().take(limit) {
if let Some(e) = vocab.entities.iter().find(|e| e.id == id) {
push(&mut out, e.name.clone(), SuggestionKind::Entity, s);
}
}
if last.chars().all(|c| c.is_ascii_alphabetic()) && !last.is_empty() {
for k in FILTER_KEYS {
if k.starts_with(&last.to_ascii_lowercase()) {
push(&mut out, (*k).to_string(), SuggestionKind::Key, 0.4);
}
}
}
}
out.sort_by(|a, b| {
b.score
.partial_cmp(&a.score)
.unwrap_or(std::cmp::Ordering::Equal)
.then(a.text.cmp(&b.text))
});
out.truncate(limit);
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::units::GIB;
fn view(kind: GroupKind, name: &str, mem: u64, gpu: u64) -> EntityView {
EntityView {
kind,
name: name.into(),
mem: Some(mem),
gpu: Some(gpu),
..Default::default()
}
}
#[test]
fn grammar_example() {
let e = parse_filter("kind:model,agent or gpu>1G -muted").unwrap();
let m = view(GroupKind::ModelServer, "sd-server", 10 * GIB, 0);
let c = view(GroupKind::App, "Chrome", GIB, 2 * GIB);
let mut muted = view(GroupKind::App, "Chrome", GIB, 2 * GIB);
muted.state.push("muted".into());
let x = view(GroupKind::App, "Slack", GIB, 0);
assert!(eval(&e, &m));
assert!(eval(&e, &c));
assert!(!eval(&e, &muted));
assert!(!eval(&e, &x));
assert_eq!(e.to_string(), "kind:model,agent or gpu>1G -muted");
assert_eq!(parse_filter(&e.to_string()).unwrap(), e);
}
#[test]
fn structured_filters() {
let e = parse_filter("mem>2G kind:daemon idle>30m").unwrap();
let mut v = view(GroupKind::BuildDaemon, "GradleDaemon", 3 * GIB, 0);
v.idle_s = Some(5 * 3600);
assert!(eval(&e, &v));
v.idle_s = Some(60);
assert!(!eval(&e, &v));
assert!(eval(&parse_filter("not (kind:app or kind:system)").unwrap(), &v));
assert!(eval(&parse_filter("-(kind:app or kind:system)").unwrap(), &v));
assert!(eval(&parse_filter(r#"name:"Gradle""#).unwrap(), &v));
assert!(eval(&parse_filter("name:grad*").unwrap(), &v));
assert!(!eval(&parse_filter("name:kot*").unwrap(), &v));
assert!(matches!(parse_filter("foo:bar"), Err(QueryError::UnknownKey(_))));
assert!(matches!(
parse_filter("kind:nope"),
Err(QueryError::BadValue { .. })
));
assert!(matches!(parse_filter("(kind:app"), Err(QueryError::Parens)));
assert!(matches!(parse_filter("kind:app)"), Err(QueryError::Parens)));
assert!(matches!(parse_filter("\"open"), Err(QueryError::Quote)));
assert!(matches!(parse_filter("mem>2"), Err(QueryError::BadValue { .. })));
assert!(matches!(parse_filter("mem:2G"), Err(QueryError::BadValue { .. })));
assert!(matches!(
parse_filter("name>2G"),
Err(QueryError::BadValue { .. })
));
assert!(matches!(parse_filter("a or"), Err(QueryError::Empty)));
}
#[test]
fn spaced_and_alias_forms() {
let a = parse_filter("mem > 2G").unwrap();
let b = parse_filter("mem>2G").unwrap();
let c = parse_filter("mem:>2G").unwrap();
let d = parse_filter("memory >2g").unwrap();
assert_eq!(a, b);
assert_eq!(b, c);
assert_eq!(c, d);
assert_eq!(
parse_filter("kind:models,daemons").unwrap().to_string(),
"kind:model,daemon"
);
assert_eq!(parse_filter("is:orphaned").unwrap().to_string(), "state:orphan");
assert_eq!(parse_filter("cpu>=50%").unwrap().to_string(), "cpu>=50");
assert_eq!(parse_filter("idle>1h30m").unwrap().to_string(), "idle>90m");
let (e, c) = parse_filter_corrected("knid:modle").unwrap();
assert_eq!(e.to_string(), "kind:model");
assert_eq!(c.len(), 2);
}
#[test]
fn unavailable_metric_never_matches() {
let mut v = view(GroupKind::App, "x", 0, 0);
v.gpu = None;
assert!(!eval(&parse_filter("gpu<1G").unwrap(), &v));
assert!(!eval(&parse_filter("gpu>=0").unwrap(), &v));
assert!(eval(&parse_filter("-gpu>1G").unwrap(), &v));
}
#[test]
fn sandbox_and_owner() {
let mut v = view(GroupKind::Sandbox, "Claude VM", GIB, 0);
v.sandbox = Some("Claude VM".into());
v.add_state("runtime:virtualization.framework");
v.owner = Some("Claude Code".into());
assert!(eval(&parse_filter("sandbox:*").unwrap(), &v));
assert!(eval(&parse_filter("sandbox:virtualization*").unwrap(), &v));
assert!(eval(&parse_filter(r#"owner:"Claude Code""#).unwrap(), &v));
assert!(!eval(&parse_filter("owner:codex").unwrap(), &v));
let app = view(GroupKind::App, "Chrome", GIB, 0);
assert!(!eval(&parse_filter("sandbox:*").unwrap(), &app));
}
#[test]
fn plain_words_intents() {
let v = Vocabulary::default();
assert_eq!(understand("gpu hogs", &v).intent, Intent::RankBy(Metric::Gpu));
assert_eq!(
understand("what's eating memory", &v).intent,
Intent::RankBy(Metric::Mem)
);
assert_eq!(understand("why slow", &v).intent, Intent::Explain);
let u = understand("idle stuff", &v);
assert_eq!(u.intent, Intent::Reclaim);
assert_eq!(u.filter.unwrap().to_string(), "state:idle");
assert_eq!(understand("models", &v).intent, Intent::Navigate(View::Models));
let u = understand("can I load 13g", &v);
assert_eq!(u.intent, Intent::Headroom);
assert_eq!(u.need_bytes, Some(13 * GIB));
let u = understand("can I load 13 GB", &v);
assert_eq!(u.need_bytes, Some(13_000_000_000));
let u = understand("throtle", &v);
assert_eq!(u.intent, Intent::Explain, "typo corrected");
assert_eq!(u.corrections[0].to, "throttle");
let u = understand("mem>2G", &v);
assert!(u.filter.is_some());
let u = understand(":headroom 13G", &v);
assert_eq!(u.intent, Intent::Headroom);
assert_eq!(u.need_bytes, Some(13 * GIB));
let u = understand("idle daemons", &v);
assert_eq!(u.intent, Intent::Reclaim);
assert_eq!(u.filter.unwrap().to_string(), "state:idle kind:daemon");
let u = understand("idle for 2h", &v);
assert_eq!(u.filter.unwrap().to_string(), "idle>=2h");
}
#[test]
fn mixed_words_and_filters() {
let v = Vocabulary::default();
let u = understand("gpu hogs kind:model", &v);
assert_eq!(u.intent, Intent::RankBy(Metric::Gpu));
assert_eq!(u.filter.unwrap().to_string(), "kind:model");
let u = understand("chrome mem>1G", &v);
assert_eq!(u.intent, Intent::Find);
assert_eq!(u.filter.unwrap().to_string(), "mem>1G chrome");
}
#[test]
fn mixed_queries_keep_lexicon_filters() {
let v = Vocabulary::default();
let u = understand("daemons mem>1G", &v);
assert_eq!(u.filter.unwrap().to_string(), "mem>1G kind:daemon");
let plain = understand("idle daemons", &v);
assert_eq!(plain.intent, Intent::Reclaim);
let plain_filter = plain.filter.unwrap().to_string();
assert!(
plain_filter.contains("state:idle") && plain_filter.contains("kind:daemon"),
"{plain_filter}"
);
let u = understand("idle daemons mem>1G", &v);
assert_eq!(u.intent, Intent::Reclaim);
let f = u.filter.unwrap().to_string();
assert!(
f.contains("mem>1G") && f.contains("state:idle") && f.contains("kind:daemon"),
"{f}"
);
let u = understand("reclaim agents idle for 30m gpu>1G", &v);
assert_eq!(u.intent, Intent::Reclaim);
let f = u.filter.unwrap().to_string();
assert!(
f.contains("gpu>1G") && f.contains("idle>=30m") && f.contains("kind:agent"),
"{f}"
);
}
#[test]
fn quoted_operator_values_round_trip_and_depth_limit() {
for q in [
r#"name:">x""#,
r#"name: ">x""#,
r#"name:"=a,<b""#,
r#"owner:">=""#,
] {
let e = parse_filter(q).unwrap_or_else(|e| panic!("{q}: {e}"));
let again = parse_filter(&e.to_string()).unwrap_or_else(|err| panic!("{q} → {e}: {err}"));
assert_eq!(e, again, "{q} → {e}");
}
assert_eq!(
parse_filter(r#"name:">x""#).unwrap(),
Expr::Term(Term::Field {
key: FieldKey::Name,
values: vec![">x".into()]
})
);
assert!(parse_filter("name:>x").is_err());
for q in [
"mem>1500B",
"mem>1B",
"mem>0",
"mem>=1.337G",
"gpu<1234567K",
"mem>1.5G",
"mem>2G",
"mem>3GB",
"mem>1023B",
"mem>1.0001G",
"cpu>12.345",
"cpu>=0.5",
"cpu<100",
"idle>90s",
"idle>=30m",
] {
let e = parse_filter(q).unwrap_or_else(|e| panic!("{q}: {e}"));
let shown = e.to_string();
let again = parse_filter(&shown).unwrap_or_else(|err| panic!("{q} → {shown}: {err}"));
assert_eq!(e, again, "{q} → {shown}");
}
assert_eq!(parse_filter("mem>1.5G").unwrap().to_string(), "mem>1536M");
assert_eq!(parse_filter("mem>1500B").unwrap().to_string(), "mem>1500B");
assert_eq!(parse_filter("mem>0").unwrap().to_string(), "mem>0");
let nest = |n: usize| format!("{}x{}", "(".repeat(n), ")".repeat(n));
assert!(parse_filter(&nest(MAX_DEPTH)).is_ok());
assert_eq!(parse_filter(&nest(MAX_DEPTH + 1)), Err(QueryError::TooDeep));
assert_eq!(parse_filter(&nest(200_000)), Err(QueryError::TooDeep));
assert_eq!(
parse_filter(&format!("{}x", "not ".repeat(200_000))),
Err(QueryError::TooDeep)
);
assert_eq!(
parse_filter(&format!("{}x", "-(".repeat(100_000))),
Err(QueryError::TooDeep)
);
let wide = vec!["(a or b)"; 500].join(" ");
assert!(parse_filter(&wide).is_ok());
let _ = understand(&nest(200_000), &Vocabulary::default());
}
#[test]
fn commands() {
let vocab = Vocabulary {
entities: vec![VocabEntity {
id: "model:sd".into(),
name: "sd-server".into(),
..Default::default()
}],
};
let u = understand(":pin sd-server", &vocab);
assert_eq!(u.command.as_ref().unwrap().name, "pin");
assert_eq!(u.targets[0].0, "model:sd");
let u = understand(":reclam", &vocab);
assert_eq!(u.intent, Intent::Reclaim);
assert_eq!(u.confidence, 0.9);
let u = understand(":sort gpu", &vocab);
assert_eq!(u.intent, Intent::RankBy(Metric::Gpu));
let u = understand(":zzzz", &vocab);
assert!(u.is_ambiguous());
let u = understand(":mode pressure", &vocab);
assert_eq!(u.command.unwrap().args, vec!["pressure".to_string()]);
}
#[test]
fn cl_prefers_frecent_claude() {
let vocab = Vocabulary {
entities: vec![
VocabEntity {
id: "pid:42".into(),
name: "clang".into(),
..Default::default()
},
VocabEntity {
id: "agent:claude".into(),
name: "Claude Code".into(),
frecency: 12.0,
..Default::default()
},
],
};
let u = understand("cl", &vocab);
assert_eq!(u.intent, Intent::Find);
assert_eq!(u.targets[0].0, "agent:claude");
let u = understand("clang", &vocab);
assert_eq!(u.targets[0].0, "pid:42");
}
#[test]
fn fuzzy_scoring() {
assert!(fuzzy_score("cl", "clang").is_some());
assert!(fuzzy_score("xz", "clang").is_none());
assert_eq!(fuzzy_score("", "x"), Some(0.0));
let a = fuzzy_score("cc", "Claude Code").unwrap();
let b = fuzzy_score("cc", "accept").unwrap();
assert!(a > b, "{a} {b}");
assert!(fuzzy_match("sd", "sd-server").unwrap() > 0.95);
assert!(fuzzy_match("gd", "GradleDaemon").unwrap() > fuzzy_match("gd", "bigdata").unwrap());
assert!(fuzzy_match("code", "Claude Code").unwrap() > 0.95);
}
#[test]
fn dl_distance() {
assert_eq!(damerau_levenshtein("throttle", "throtle"), 1);
assert_eq!(damerau_levenshtein("ab", "ba"), 1);
assert_eq!(damerau_levenshtein("", "abc"), 3);
assert_eq!(damerau_levenshtein("kitten", "sitting"), 3);
assert_eq!(damerau_levenshtein("daemons", "daemnos"), 1);
}
#[test]
fn typo_never_rewrites_entity_names() {
let vocab = Vocabulary {
entities: vec![VocabEntity {
id: "app:slot".into(),
name: "Slot".into(),
..Default::default()
}],
};
let u = understand("slot", &vocab);
assert_eq!(u.intent, Intent::Find);
assert!(u.corrections.is_empty());
assert_eq!(u.targets[0].0, "app:slot");
}
#[test]
fn suggestions() {
let vocab = Vocabulary {
entities: vec![VocabEntity {
id: "agent:c".into(),
name: "Claude Code".into(),
frecency: 3.0,
..Default::default()
}],
};
let past = vec![("gpu hogs".to_string(), 4.0), ("kind:model".to_string(), 1.0)];
let s = suggest("gp", &past, &vocab, 5);
assert_eq!(s[0].text, "gpu hogs");
let s = suggest("cla", &past, &vocab, 5);
assert!(s.iter().any(|x| x.text == "Claude Code"));
let s = suggest(":rec", &past, &vocab, 3);
assert_eq!(s[0].text, ":reclaim");
let s = suggest("ki", &past, &vocab, 5);
assert!(s.iter().any(|x| x.text == "kind:"));
}
}