Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions crates/axe-core/src/task_policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,28 @@ pub fn finish(tx: &Transaction, actor: &Actor, run: i64, b: &Value) -> Result<Va
[r.task_id],
)?;
}
} else if !retry
&& !aborted
&& b["code"].as_i64() == Some(0)
&& timed_wait(tx, r.task_id, &events, start)?
{
// The session scheduled its own next run (`axe task wait --until/--for`):
// a daily or polling task resumes on its clock, so these runs are not
// counted against max_runs. Crashes, failures, aborts, drains and runs
// ending any other way (done, escalated, `wait --on`, nothing) count.
let runs = db::get_task(tx, r.task_id)?.runs;
db::refund_run(tx, r.task_id)?;
db::write_event(
tx,
actor,
r.task_id,
"runs",
Some(&runs.to_string()),
Some(&(runs - 1).max(0).to_string()),
Some(&format!(
"run {run} ended in a timed wait; not counted against max_runs"
)),
)?;
} else if !retry && !aborted {
let changes = Changes {
state: Some("escalated".into()),
Expand All @@ -185,6 +207,19 @@ pub fn finish(tx: &Transaction, actor: &Actor, run: i64, b: &Value) -> Result<Va
Ok(json!(retry))
}

/// Whether the task is pending on a wake time its session set during the run
/// starting after event `start` (a timed `axe task wait`), and still is.
fn timed_wait(tx: &Transaction, id: i64, events: &[db::Event], start: i64) -> Result<bool> {
let task = db::get_task(tx, id)?;
if task.state != "pending" || task.not_before.is_none() {
return Ok(false);
}
Ok(events
.iter()
.rfind(|e| e.id > start && e.kind == "wake")
.is_some_and(|e| e.actor != "dispatcher" && e.to_value == task.not_before))
}

/// Seconds before a task retries after the run ended on `api_error` (a
/// `failure::Failure` object): an exhausted quota waits for its reset (an hour
/// when unknown), anything else backs off by `streak`.
Expand Down
157 changes: 157 additions & 0 deletions crates/axe/tests/wait_runs.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
//! Run budget across timed waits: a run that ends in its own `axe task wait
//! --until/--for` is not counted against max_runs (a daily task never
//! escalates for it); crashes and runs ending any other way still count.
use axe::db::{self, Actor, Changes, Claim};
use axe::remote;
use rusqlite::Connection;
use serde_json::{json, Value};

const MAX_RUNS: i64 = 3;

/// A registered node speaking the dispatcher protocol.
struct Node {
generation: Value,
ops: u32,
}

impl Node {
fn register(c: &Connection) -> Node {
let reg = remote::register(c, &json!({"id":"one","generation":""})).unwrap();
Node {
generation: reg["generation"].clone(),
ops: 0,
}
}

fn call(&mut self, c: &Connection, op: &str, body: Value) -> Value {
self.ops += 1;
let v = json!({"dispatcher":"one","generation":self.generation,
"operation_id":format!("{op}{}", self.ops),"op":op,"body":body});
remote::operation(c, &v).unwrap()
}

/// Claims and starts a run of `task`: the run id, or `None` when max_runs
/// escalated the task instead.
fn start(&mut self, c: &Connection, task: i64) -> Option<i64> {
let claim = format!("dispatch:{}", self.ops);
let r = self.call(
c,
"claim",
json!({"project":"p","claim":claim,"max_runs":MAX_RUNS}),
);
match serde_json::from_value(r).unwrap() {
Claim::Claimed(_) => {}
Claim::Blocked(_) => return None,
Claim::None => panic!("nothing to claim"),
}
let run = self
.call(
c,
"prepare",
json!({"task":task,"claim":claim,"agent":"a","mode":"fresh","session_id":"s",
"log":"/tmp/x.log","session":{"agent":"a","session_id":"s","resume_count":0},
"event":{}}),
)
.as_i64()
.unwrap();
self.call(c, "started", json!({"run":run}));
Some(run)
}

fn finish(&mut self, c: &Connection, run: i64, code: i64) {
self.call(
c,
"finish",
json!({"run":run,"code":code,"resumed":false,"note":"exit","event":{}}),
);
}
}

fn setup(dir: &std::path::Path) -> (Connection, i64, Node) {
let mut c = db::open(&dir.join("db")).unwrap();
let t = db::NewTask {
agent: None,
project: "p",
title: "daily",
detail: "",
state: "pending",
};
let id = db::add_task(&mut c, &Actor::new("human"), &t).unwrap();
let node = Node::register(&c);
(c, id, node)
}

/// The session parks the task for a day (`axe task wait --for 1d`).
fn wait_a_day(c: &mut Connection, id: i64) {
db::wait(c, &Actor::new("session"), id, &[], Some("+1d"), "next day").unwrap();
}

/// The day passes, without sleeping.
fn wake(c: &Connection, id: i64) {
c.execute(
"UPDATE tasks SET not_before = '2000-01-01T00:00:00Z' WHERE id = ?1",
[id],
)
.unwrap();
}

#[test]
fn timed_wait_resumes_do_not_count_toward_max_runs() {
let d = tempfile::tempdir().unwrap();
let (mut c, id, mut node) = setup(d.path());
let cycles = MAX_RUNS * 3;
for _ in 0..cycles {
let run = node
.start(&c, id)
.expect("a task waiting daily is never escalated for max_runs");
wait_a_day(&mut c, id);
node.finish(&c, run, 0);
let t = db::get_task(&c, id).unwrap();
assert_eq!((t.state.as_str(), t.runs), ("pending", 0));
wake(&c, id);
}
let refunds: Vec<_> = db::events(&c, id)
.unwrap()
.into_iter()
.filter(|e| e.kind == "runs")
.collect();
assert_eq!(refunds.len() as i64, cycles);
assert_eq!(refunds[0].from_value.as_deref(), Some("1"));
assert_eq!(refunds[0].to_value.as_deref(), Some("0"));
}

#[test]
fn crashes_after_a_timed_wait_still_hit_max_runs() {
let d = tempfile::tempdir().unwrap();
let (mut c, id, mut node) = setup(d.path());
for n in 1..=MAX_RUNS {
let run = node.start(&c, id).expect("under budget");
// Waited, then the process crashed: counted.
wait_a_day(&mut c, id);
node.finish(&c, run, 1);
assert_eq!(db::get_task(&c, id).unwrap().runs, n);
wake(&c, id);
}
assert_eq!(node.start(&c, id), None);
let t = db::get_task(&c, id).unwrap();
assert_eq!((t.state.as_str(), t.runs), ("escalated", MAX_RUNS));
}

#[test]
fn runs_ending_without_a_timed_wait_still_count() {
let d = tempfile::tempdir().unwrap();
let (mut c, id, mut node) = setup(d.path());
for n in 1..=MAX_RUNS {
let run = node.start(&c, id).expect("under budget");
// The session hands the task back without a wake time.
let back = Changes {
state: Some("pending".into()),
..Default::default()
};
db::set_task(&mut c, &Actor::new("session"), id, &back).unwrap();
node.finish(&c, run, 0);
assert_eq!(db::get_task(&c, id).unwrap().runs, n);
}
assert_eq!(node.start(&c, id), None);
assert_eq!(db::get_task(&c, id).unwrap().state, "escalated");
}
4 changes: 4 additions & 0 deletions docs/user/concepts/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ SIGTERM. Each gets a block note. A run that a quota, prepaid credit, login
or provider failure ended goes back to `pending` with a timed retry instead,
its run refunded and the class named in its note (`failure.rs`, read by the
harness row's log parser, `log_format.rs`).
A run that exits cleanly after its own timed wait (`axe task wait --until`
or `--for`) is refunded too, so a task that waits daily never reaches
`max_runs`; crashes and runs that end any other way still count
(`task_policy.rs`).

**Admission.** A task session starts only when a pool slot is free, the
optional resource gate is open, and no admission hold is set
Expand Down
Loading