Skip to main content

agentmux_srv_core/backend/jobs/
poll.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! A job on the `poll` source asks AgentMux's own state a question every so often and starts one run for each item
5//! that is new in the answer (docs/specs/SPEC_DRONE_REAL_WORLD_JOBS_2026_11_11.md ยง3.2). Polling spends no agent
6//! tokens: the question is one of the App query's, answered by srv.
7//!
8//! The job's filter says what to ask and how often:
9//!   * `query`           required: `tasks`, `jobs`, `agents` or `lan_peers`, as the App query block reads them.
10//!   * `every_minutes`   required: 1 to 1440.
11//!   * `holder`, `state`, `pr`   (`tasks`) and `job` (`jobs`, required: the runs of that one job), `limit` (both):
12//!     the App query's own filters. An answer is cut to `limit`, which a poll leaves at the most the query gives (200
13//!     tasks, 100 runs): a new item past the cut, because more than that appeared between two looks, is never seen.
14//!     `agents` lists at most 20 problems.
15//!   * `include_existing`   optional true: the items that are already there when the job is turned on run too.
16//!     Left out, the first poll only takes note of them, so turning a job on does not start a run for everything
17//!     that happened before.
18//!
19//! What counts as an item, and what makes it new:
20//!   * `tasks`      each task, by its number.
21//!   * `jobs`       each run of the named job, by its id.
22//!   * `agents`     each agent that is wanted running and is not up, by its name and state: an agent that goes down
23//!                  again in another way is new.
24//!   * `lan_peers`  each machine, by its host name.
25//!
26//! The run reads `{{trigger.query}}`, `{{trigger.key}}` (the item's id) and `{{trigger.item}}` (the item as the
27//! query lists it). An item is never reported twice: the job's event ids (`backend::storage::job_events`) remember
28//! it for a week, and an item that is still in the answer is remembered for as long as it is there. (An item that is
29//! still there when srv restarts more than a week after it was reported is reported again: its id has been forgotten.) A poll that finds
30//! more than [`MAX_NEW_PER_POLL`] new items starts that many and leaves the rest for the next poll. A poll whose
31//! question fails (the ledger is not ready yet, say) is skipped and asked again at the next time.
32
33use std::collections::{HashMap, HashSet};
34use std::future::Future;
35use std::pin::Pin;
36use std::sync::Arc;
37use std::time::Duration;
38
39use futures_util::StreamExt;
40use serde_json::{json, Map, Value};
41use sha2::{Digest, Sha256};
42
43use super::definition::{event_source, trigger_kind};
44use crate::backend::cron::{CronScheduler, JobEvent};
45use crate::backend::storage::cron::CronJob;
46use crate::backend::storage::store::Store;
47
48/// The questions a poll may ask.
49pub const QUERIES: [&str; 5] = ["tasks", "jobs", "agents", "lan_peers", "api"];
50pub const MIN_EVERY_MINUTES: u64 = 1;
51pub const MAX_EVERY_MINUTES: u64 = 24 * 60;
52/// How often a poll may ask a site outside AgentMux: not more than every few minutes, so a drone cannot spend a site's
53/// rate limit (or the person's API quota) in a minute.
54pub const MIN_API_EVERY_MINUTES: u64 = 5;
55/// How many items a poll of `api` keeps when the filter gives no `limit`, and the most it ever keeps.
56pub const API_DEFAULT_ITEMS: usize = 100;
57pub const API_MAX_ITEMS: usize = 200;
58/// The most tasks and runs the App query returns (its own caps), which is what a poll asks for unless `limit` says less.
59const MAX_TASKS: u64 = 200;
60const MAX_RUNS: u64 = 100;
61/// The most new items one poll starts a run for.
62pub const MAX_NEW_PER_POLL: usize = 20;
63/// How often the poller looks at which jobs are due.
64const TICK: Duration = Duration::from_secs(30);
65/// How many `api` questions one pass asks at once. Each may wait out its own timeout on a site that is down, so they
66/// are asked together, but not without a bound: a pass of dozens of jobs must not open dozens of connections.
67pub const API_ASKS_AT_ONCE: usize = 4;
68
69const COMMON_KEYS: [&str; 3] = ["query", "every_minutes", "include_existing"];
70
71/// Asks the App query `filter["query"]` with the filter's own keys and returns its answer. Supplied by the
72/// binary, which has the App query; the tests supply a fake.
73pub type Check = Arc<dyn Fn(Map<String, Value>) -> Pin<Box<dyn Future<Output = Result<Value, String>> + Send>> + Send + Sync>;
74
75/// Where a query's items are in its answer, and which of their fields make one item's id.
76struct Shape {
77    items: &'static str,
78    id: &'static [&'static str],
79}
80
81fn shape_of(query: &str) -> Option<Shape> {
82    match query {
83        "tasks" => Some(Shape { items: "tasks", id: &["num"] }),
84        "jobs" => Some(Shape { items: "runs", id: &["id"] }),
85        "agents" => Some(Shape { items: "problems", id: &["agent", "state"] }),
86        "lan_peers" => Some(Shape { items: "peers", id: &["host"] }),
87        // `api_poll::ask` has already put each item under `item` with its id: the id is the item's own path, not a list of fields.
88        "api" => Some(Shape { items: "items", id: &["id"] }),
89        _ => None,
90    }
91}
92
93/// The filter keys a query takes besides the common ones.
94fn own_keys(query: &str) -> &'static [&'static str] {
95    match query {
96        "tasks" => &["holder", "state", "pr", "limit"],
97        "jobs" => &["job", "limit"],
98        "api" => &["url", "auth", "headers", "items", "id", "limit"],
99        _ => &[],
100    }
101}
102
103/// A `poll` trigger's filter: the question, how often, and the question's own filters.
104pub fn validate_filter(filter: &Map<String, Value>) -> Result<(), String> {
105    let query = filter.get("query").and_then(Value::as_str).unwrap_or("");
106    if !QUERIES.contains(&query) {
107        return Err(format!("trigger: a poll filter names its query, one of {}", QUERIES.join(", ")));
108    }
109    let own = own_keys(query);
110    if let Some(key) = filter.keys().find(|k| !COMMON_KEYS.contains(&k.as_str()) && !own.contains(&k.as_str())) {
111        let mut has: Vec<&str> = COMMON_KEYS.to_vec();
112        has.extend(own);
113        return Err(format!("trigger: a poll of {query} has no filter key {key:?}; it has {}", has.join(", ")));
114    }
115    match filter.get("every_minutes").and_then(Value::as_u64) {
116        Some(n) if (MIN_EVERY_MINUTES..=MAX_EVERY_MINUTES).contains(&n) => {}
117        _ => return Err(format!("trigger: a poll filter has every_minutes, a whole number of {MIN_EVERY_MINUTES} to {MAX_EVERY_MINUTES}")),
118    }
119    if filter.get("include_existing").is_some_and(|v| !v.is_boolean()) {
120        return Err("trigger: include_existing is true or false".to_string());
121    }
122    for key in ["holder", "state", "pr", "job"] {
123        if filter.get(key).is_some_and(|v| !v.is_string()) {
124            return Err(format!("trigger: poll filter {key:?} is text"));
125        }
126    }
127    if query == "jobs" && !filter.get("job").and_then(Value::as_str).is_some_and(|j| !j.trim().is_empty()) {
128        // Without `job` the query lists only the newest run of each job, so a job that finishes two runs between looks would lose one.
129        return Err("trigger: a poll of jobs has job, the name or id of the job whose runs it watches".to_string());
130    }
131    if filter.get("limit").is_some_and(|v| !v.as_u64().is_some_and(|n| (1..=200).contains(&n))) {
132        return Err("trigger: poll filter \"limit\" is a whole number of 1 to 200".to_string());
133    }
134    if query == "api" {
135        validate_api_filter(filter)?;
136    }
137    Ok(())
138}
139
140/// What a poll of `api` takes: a site written out in the job, asked at most every few minutes, with a credential or none.
141fn validate_api_filter(filter: &Map<String, Value>) -> Result<(), String> {
142    let url = filter.get("url").and_then(Value::as_str).unwrap_or("").trim();
143    if url.is_empty() {
144        return Err("trigger: a poll of api has url, the https address of the list".to_string());
145    }
146    if url.contains("{{") {
147        return Err("trigger: a poll of api writes its url out: no {{reference}} in it".to_string());
148    }
149    let parsed = reqwest::Url::parse(url).map_err(|e| format!("trigger: the poll's url is not an address: {e}"))?;
150    if parsed.scheme() != "https" || parsed.host_str().is_none() || !parsed.username().is_empty() || parsed.password().is_some() {
151        return Err("trigger: a poll of api calls an https address with no user name or password in it".to_string());
152    }
153    if filter.get("every_minutes").and_then(Value::as_u64).is_some_and(|n| n < MIN_API_EVERY_MINUTES) {
154        return Err(format!("trigger: a poll of api asks at most every {MIN_API_EVERY_MINUTES} minutes: every_minutes is {MIN_API_EVERY_MINUTES} or more"));
155    }
156    if let Some(auth) = filter.get("auth").filter(|a| !a.is_null()) {
157        // The API block checks the rest (the header name, the entry) when it runs; the shape is checked here.
158        let obj = auth.as_object().ok_or("trigger: poll filter \"auth\" is { \"vault\": \"<entry>\", \"as\": \"bearer\" }")?;
159        if let Some(key) = obj.keys().find(|k| !matches!(k.as_str(), "vault" | "as")) {
160            return Err(format!("trigger: poll auth has no {key:?}: it takes vault and as"));
161        }
162        if !obj.get("vault").and_then(Value::as_str).is_some_and(|v| !v.trim().is_empty() && !v.contains("{{")) {
163            return Err("trigger: poll auth names its Vault entry in vault, written out".to_string());
164        }
165    }
166    if let Some(headers) = filter.get("headers") {
167        let Some(obj) = headers.as_object() else { return Err("trigger: poll filter \"headers\" is an object of text".to_string()) };
168        for (name, value) in obj {
169            if !value.is_string() || value.as_str().is_some_and(|v| v.contains("{{")) {
170                return Err(format!("trigger: poll header {name:?} is plain text, with no {{{{reference}}}}"));
171            }
172        }
173    }
174    for key in ["items", "id"] {
175        if filter.get(key).is_some_and(|v| !v.is_string()) {
176            return Err(format!("trigger: poll filter {key:?} is a dotted path, like data.items"));
177        }
178    }
179    Ok(())
180}
181
182/// What a poll job asks, read from its filter.
183#[derive(Debug, PartialEq)]
184struct Plan {
185    query: String,
186    every_ms: i64,
187    include_existing: bool,
188    /// What the check is asked: the query and its own filters, without how often.
189    ask: Map<String, Value>,
190    /// Changes when the question does, so a job that is edited starts again from what is there.
191    signature: String,
192}
193
194fn plan_of(job: &CronJob) -> Option<Plan> {
195    if !job.enabled || job.trigger_kind != trigger_kind::EVENT {
196        return None;
197    }
198    let t = &job.trigger_event;
199    if t.get("source").and_then(Value::as_str) != Some(event_source::POLL) {
200        return None;
201    }
202    let filter = t.get("filter").and_then(Value::as_object)?;
203    validate_filter(filter).ok()?;
204    let mut ask = filter.clone();
205    ask.remove("every_minutes");
206    // Ask for the most the query gives: an answer is cut to `limit`, and a new item past the cut is not seen.
207    match filter.get("query").and_then(Value::as_str) {
208        Some("tasks") => {
209            ask.entry("limit").or_insert(json!(MAX_TASKS));
210        }
211        Some("jobs") => {
212            ask.entry("limit").or_insert(json!(MAX_RUNS));
213        }
214        Some("api") => {
215            ask.entry("limit").or_insert(json!(API_DEFAULT_ITEMS));
216        }
217        _ => {}
218    }
219    let include_existing = ask.remove("include_existing").and_then(|v| v.as_bool()).unwrap_or(false);
220    let signature = hex::encode(&Sha256::digest(Value::Object(ask.clone()).to_string().as_bytes())[..6]);
221    Some(Plan {
222        query: filter.get("query").and_then(Value::as_str)?.to_string(),
223        every_ms: filter.get("every_minutes").and_then(Value::as_u64)? as i64 * 60_000,
224        include_existing,
225        ask,
226        signature,
227    })
228}
229
230/// A field of an item as the text an id is made of.
231fn part(item: &Value, field: &str) -> Option<String> {
232    match item.get(field)? {
233        Value::String(s) if !s.is_empty() => Some(s.clone()),
234        Value::Number(n) => Some(n.to_string()),
235        _ => None,
236    }
237}
238
239/// The items of an answer, each with its id. An item that lacks an id field is not one.
240fn items_of(query: &str, answer: &Value) -> Vec<(String, Value)> {
241    let Some(shape) = shape_of(query) else { return Vec::new() };
242    let Some(items) = answer.get(shape.items).and_then(Value::as_array) else { return Vec::new() };
243    let mut seen = HashSet::new();
244    items
245        .iter()
246        .filter_map(|item| {
247            let parts = shape.id.iter().map(|f| part(item, f)).collect::<Option<Vec<_>>>()?;
248            let id = parts.join(":");
249            // An `api` answer wraps each item with its id; the run is given the item itself.
250            let item = if query == "api" { item.get("item").cloned()? } else { item.clone() };
251            seen.insert(id.clone()).then(|| (id, item))
252        })
253        .collect()
254}
255
256#[cfg(test)]
257pub(crate) fn items_of_for_test(query: &str, answer: &Value) -> Vec<(String, Value)> {
258    items_of(query, answer)
259}
260
261/// The id under which a job's first look is kept with its event ids.
262fn baseline_marker(signature: &str) -> String {
263    format!("poll:baseline:{signature}")
264}
265
266#[cfg(test)]
267pub(crate) fn marker_of_for_test(job: &CronJob) -> Option<String> {
268    plan_of(job).map(|p| baseline_marker(&p.signature))
269}
270
271fn event_id(query: &str, id: &str) -> String {
272    format!("poll:{query}:{id}")
273}
274
275/// What one job's poll remembers between times.
276struct JobPoll {
277    signature: String,
278    next_due_ms: i64,
279    /// The ids in the last answer that have been looked at.
280    seen: HashSet<String>,
281    baselined: bool,
282}
283
284/// The poller's memory: one entry per poll job.
285#[derive(Default)]
286pub struct PollState {
287    jobs: HashMap<String, JobPoll>,
288}
289
290/// Which poll jobs a pass looks at. The `api` questions go out over the network and can take their whole timeout each,
291/// so they are a pass of their own (see [`spawn`]): an outage on an external site must not hold up the local polls and
292/// the `expect` checks (the dead-man's switch) that run beside them.
293#[derive(Debug, Clone, Copy, PartialEq, Eq)]
294pub enum PollKind {
295    /// Every poll job, asked one after another: the pass a test steps.
296    All,
297    /// Everything but `api`: questions of AgentMux's own state, quick.
298    Local,
299    /// Only `api`: asked [`API_ASKS_AT_ONCE`] at a time.
300    Api,
301}
302
303impl PollKind {
304    fn takes(self, query: &str) -> bool {
305        match self {
306            PollKind::All => true,
307            PollKind::Local => query != "api",
308            PollKind::Api => query == "api",
309        }
310    }
311}
312
313/// Asks the question of every poll job that is due and starts a run for each new item. Returns how many runs it
314/// started or queued. `now` is a parameter so a test can step the clock.
315pub async fn poll_due(scheduler: &CronScheduler, all: &[CronJob], check: &Check, state: &mut PollState, now: i64) -> usize {
316    poll_due_of(PollKind::All, scheduler, all, check, state, now).await
317}
318
319/// [`poll_due`] for the jobs of one [`PollKind`]. The due questions are asked first, the `api` ones a few at a time
320/// and the rest one after another, and the answers are then handled in the jobs' order.
321pub async fn poll_due_of(kind: PollKind, scheduler: &CronScheduler, all: &[CronJob], check: &Check, state: &mut PollState, now: i64) -> usize {
322    // The job's event ids live with the run ledger (what the scheduler admits events against), which is not always the
323    // store the jobs are listed from: the baseline and the items are claimed where `fire_event` looks.
324    let Some(ledger) = scheduler.runs().cloned() else { return 0 };
325    let store = ledger.store().clone();
326    let polling: Vec<(&CronJob, Plan)> = all.iter().filter_map(|j| plan_of(j).map(|p| (j, p))).filter(|(_, p)| kind.takes(&p.query)).collect();
327    // Each kind of pass keeps its own jobs' memory, so one pass does not forget what the other remembers.
328    state.jobs.retain(|id, _| polling.iter().any(|(j, _)| &j.id == id));
329    let mut offered = 0;
330    // The questions that are due, in the jobs' order.
331    let mut due: Vec<(usize, Map<String, Value>)> = Vec::new();
332    for (idx, (job, plan)) in polling.iter().enumerate() {
333        let st = state.jobs.entry(job.id.clone()).or_insert_with(|| JobPoll { signature: plan.signature.clone(), next_due_ms: now, seen: HashSet::new(), baselined: false });
334        if st.signature != plan.signature {
335            *st = JobPoll { signature: plan.signature.clone(), next_due_ms: now, seen: HashSet::new(), baselined: false };
336        }
337        if now < st.next_due_ms {
338            continue;
339        }
340        st.next_due_ms = now + plan.every_ms;
341        let mut question = plan.ask.clone();
342        if plan.query == "api" {
343            // Who a Vault credential is granted to: the drone this job runs. Not part of the question's signature.
344            let drone = (job.action_kind == super::definition::action_kind::DRONE).then(|| job.action.get("drone_id").and_then(Value::as_str)).flatten();
345            question.insert("drone_id".to_string(), json!(drone.unwrap_or("")));
346        }
347        due.push((idx, question));
348    }
349    let at_once = if kind == PollKind::Api { API_ASKS_AT_ONCE } else { 1 };
350    let answers: Vec<(usize, Result<Value, String>)> = futures_util::stream::iter(due)
351        .map(|(idx, question)| {
352            let asking = check(question);
353            async move { (idx, asking.await) }
354        })
355        .buffered(at_once)
356        .collect()
357        .await;
358    for (idx, answer) in answers {
359        let (job, plan) = &polling[idx];
360        let Some(st) = state.jobs.get_mut(&job.id) else { continue };
361        let answer = match answer {
362            Ok(answer) => answer,
363            Err(e) => {
364                tracing::warn!(job_id = %job.id, query = %plan.query, error = %e, "jobs: a poll's question failed; asking again next time");
365                continue;
366            }
367        };
368        let items = items_of(&plan.query, &answer);
369        let present: HashSet<String> = items.iter().map(|(id, _)| id.clone()).collect();
370        let marker = baseline_marker(&plan.signature);
371        if !plan.include_existing {
372            // The marker is an id like the others and would go with the week's sweep: each look moves it forward, so
373            // a restart after a long stop still knows this is not the first look.
374            let _ = store.job_event_touch(&job.id, &marker, now);
375        }
376        if !st.baselined {
377            if !plan.include_existing {
378                // The first poll of a job takes note of what is there, once.
379                // The marker and what is there are claimed together, so the marker is never seen without them.
380                let ids: Vec<String> = items.iter().map(|(id, _)| event_id(&plan.query, id)).collect();
381                match store.job_event_claim_baseline(&job.id, &marker, &ids, now) {
382                    Ok(true) => {
383                        st.baselined = true;
384                        st.seen = present;
385                        continue;
386                    }
387                    Ok(false) => {}
388                    Err(e) => {
389                        // Not knowing whether this is the first poll must not start a run for everything that is there.
390                        tracing::warn!(job_id = %job.id, error = %e, "jobs: a poll couldn't record its first look; trying again next time");
391                        continue;
392                    }
393                }
394            }
395            st.baselined = true;
396        }
397        let mut started = 0;
398        for (id, item) in items {
399            if st.seen.contains(&id) {
400                continue;
401            }
402            if started >= MAX_NEW_PER_POLL {
403                break;
404            }
405            started += 1;
406            st.seen.insert(id.clone());
407            let input = json!({ "query": plan.query, "key": id, "item": item });
408            let fired = scheduler.fire_event(job, JobEvent { id: event_id(&plan.query, &id), source: event_source::POLL.to_string(), input }).await;
409            // An item the job already heard of, or that a cap or the policy refused, starts nothing.
410            offered += usize::from(fired.run_id.is_some());
411        }
412        st.seen.retain(|id| present.contains(id));
413    }
414    offered
415}
416
417/// Start the poller, which also looks after the `expect` jobs. `check` answers the App query. The `api` polls run in a
418/// task of their own, so a site that does not answer holds up nothing else.
419pub fn spawn(jobs: Arc<Store>, scheduler: Arc<CronScheduler>, check: Check) {
420    if tokio::runtime::Handle::try_current().is_err() {
421        return;
422    }
423    {
424        let (jobs, scheduler, check) = (jobs.clone(), scheduler.clone(), check.clone());
425        tokio::spawn(async move {
426            let mut state = PollState::default();
427            let mut expects = super::expect::ExpectState::default();
428            loop {
429                tokio::time::sleep(TICK).await;
430                let all = enabled_jobs(&jobs).await;
431                let now = agentmux_common::time::now_ms();
432                poll_due_of(PollKind::Local, &scheduler, &all, &check, &mut state, now).await;
433                super::expect::expect_due(&scheduler, &all, &check, &mut expects, now).await;
434            }
435        });
436    }
437    tokio::spawn(async move {
438        let mut state = PollState::default();
439        loop {
440            tokio::time::sleep(TICK).await;
441            let all = enabled_jobs(&jobs).await;
442            poll_due_of(PollKind::Api, &scheduler, &all, &check, &mut state, agentmux_common::time::now_ms()).await;
443        }
444    });
445}
446
447async fn enabled_jobs(jobs: &Arc<Store>) -> Vec<CronJob> {
448    let listing = jobs.clone();
449    tokio::task::spawn_blocking(move || listing.cron_list_enabled()).await.ok().and_then(Result::ok).unwrap_or_default()
450}