Skip to main content

agentmux_srv_core/backend/storage/
job_events.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! Which events a job has heard of (docs/specs/SPEC_DRONE_REAL_WORLD_JOBS_2026_11_11.md ยง3.7): delivery is at least
5//! once, so a source may name the same event twice, and the job's `(job_id, event_id)` here is what turns the second
6//! into nothing. It sits beside the run ledger, in the identity store every channel and version on this computer
7//! shares, so two instances sharing a job don't both start a run for one event.
8//!
9//! The id table keeps only the id. The event's data is kept apart, per run, in `db_job_event_inputs`, for as long as
10//! the run may still need it: while it waits out a delay or its turn, and across a retry. The run's end (or [`KEEP_MS`])
11//! lets it go. A job forgets an id after [`KEEP_MS`]: a source that repeats an id after that is a new event.
12
13use rusqlite::{params, OptionalExtension};
14
15use super::store::Store;
16use super::StoreError;
17
18/// The table, created on every open of the identity store, with no schema version bump.
19pub(crate) const SCHEMA: &str = "
20    CREATE TABLE IF NOT EXISTS db_job_trigger_events (
21        job_id    TEXT NOT NULL,
22        event_id  TEXT NOT NULL,
23        run_id    TEXT NOT NULL DEFAULT '',
24        at_ms     INTEGER NOT NULL,
25        PRIMARY KEY (job_id, event_id)
26    );
27    CREATE INDEX IF NOT EXISTS idx_ids_job_trigger_events_at ON db_job_trigger_events(at_ms);
28    CREATE TABLE IF NOT EXISTS db_job_event_inputs (
29        run_id  TEXT PRIMARY KEY,
30        job_id  TEXT NOT NULL,
31        input   TEXT NOT NULL,
32        at_ms   INTEGER NOT NULL
33    );
34    CREATE INDEX IF NOT EXISTS idx_ids_job_event_inputs_at ON db_job_event_inputs(at_ms);";
35
36/// Columns added to `db_job_trigger_events` after its first shape, run on every open with [`SCHEMA`] (a table an earlier
37/// build created gains them; a default needs no schema version bump). `seen_ms` is the last time a look saw the event
38/// again ([`Store::job_event_touch`]): the sweep keeps an id until a week after the later of `at_ms` and `seen_ms`, while
39/// `at_ms` stays the time the job heard it, which is what the hourly limit counts.
40pub(crate) const COLUMNS: [&str; 1] = ["ALTER TABLE db_job_trigger_events ADD COLUMN seen_ms INTEGER NOT NULL DEFAULT 0"];
41
42/// How long a job remembers an event id.
43pub const KEEP_MS: i64 = 7 * 24 * 3600 * 1000;
44/// How long a run's input is kept, from the event: a run may be held back by a delay of up to a week and then wait
45/// further for its turn, so its input outlives the id by that week.
46pub const INPUT_KEEP_MS: i64 = 2 * KEEP_MS;
47
48impl Store {
49    /// Record that `job_id` heard of `event_id` now, for run `run_id`. `Ok(true)` the first time, `Ok(false)` when it
50    /// already had: another delivery of the same event, here or in another instance.
51    pub fn job_event_claim(&self, job_id: &str, event_id: &str, run_id: &str, now_ms: i64) -> Result<bool, StoreError> {
52        let conn = self.conn().lock().unwrap();
53        let n = conn.execute(
54            "INSERT OR IGNORE INTO db_job_trigger_events (job_id, event_id, run_id, at_ms) VALUES (?1, ?2, ?3, ?4)",
55            params![job_id, event_id, run_id, now_ms],
56        )?;
57        Ok(n > 0)
58    }
59
60    /// Claim `marker` and every id in `ids` for `job_id` in one transaction, with no run (they are noted, not started).
61    /// `Ok(true)` when the marker was new: all of them are claimed, and nobody sees the marker without them.
62    /// `Ok(false)` when the marker was already there: nothing is written, so a half-finished first look elsewhere
63    /// (another instance, or a crash) is not completed here as if it were this one's.
64    pub fn job_event_claim_baseline(&self, job_id: &str, marker: &str, ids: &[String], now_ms: i64) -> Result<bool, StoreError> {
65        let mut conn = self.conn().lock().unwrap();
66        let tx = conn.transaction()?;
67        let first = tx.execute("INSERT OR IGNORE INTO db_job_trigger_events (job_id, event_id, run_id, at_ms) VALUES (?1, ?2, '', ?3)", params![job_id, marker, now_ms])? > 0;
68        if !first {
69            return Ok(false);
70        }
71        for id in ids {
72            tx.execute("INSERT OR IGNORE INTO db_job_trigger_events (job_id, event_id, run_id, at_ms) VALUES (?1, ?2, '', ?3)", params![job_id, id, now_ms])?;
73        }
74        tx.commit()?;
75        Ok(true)
76    }
77
78    /// Note that `job_id` saw `event_id` again at `now_ms`, so the retention sweep keeps it a week from now. The time
79    /// the job heard it (`at_ms`) is left alone, so a touch neither makes the row an event the job admitted nor counts it
80    /// again toward the hourly limit. `Ok(true)` when it moved.
81    pub fn job_event_touch(&self, job_id: &str, event_id: &str, now_ms: i64) -> Result<bool, StoreError> {
82        let conn = self.conn().lock().unwrap();
83        let n = conn.execute(
84            "UPDATE db_job_trigger_events SET seen_ms = ?3 WHERE job_id = ?1 AND event_id = ?2 AND MAX(at_ms, seen_ms) < ?3",
85            params![job_id, event_id, now_ms],
86        )?;
87        Ok(n > 0)
88    }
89
90    /// Forget the ids neither heard nor seen again since `before_ms`. How many went.
91    pub fn job_events_forget_before(&self, before_ms: i64) -> Result<usize, StoreError> {
92        let conn = self.conn().lock().unwrap();
93        Ok(conn.execute("DELETE FROM db_job_trigger_events WHERE MAX(at_ms, seen_ms) < ?1", params![before_ms])?)
94    }
95
96    /// Let go of the inputs kept before `before_ms` (event time). How many went. A run still waiting that long after
97    /// its event has lost its input, and says so when it starts.
98    pub fn job_event_inputs_forget_before(&self, before_ms: i64) -> Result<usize, StoreError> {
99        let conn = self.conn().lock().unwrap();
100        Ok(conn.execute("DELETE FROM db_job_event_inputs WHERE at_ms < ?1", params![before_ms])?)
101    }
102
103    /// Keep `input` (what the graph reads as `{{trigger.*}}`) for run `run_id`.
104    pub fn job_event_input_put(&self, run_id: &str, job_id: &str, input: &serde_json::Value, now_ms: i64) -> Result<(), StoreError> {
105        let conn = self.conn().lock().unwrap();
106        conn.execute(
107            "INSERT OR REPLACE INTO db_job_event_inputs (run_id, job_id, input, at_ms) VALUES (?1, ?2, ?3, ?4)",
108            params![run_id, job_id, input.to_string(), now_ms],
109        )?;
110        Ok(())
111    }
112
113    /// The input kept for run `run_id`, if any.
114    pub fn job_event_input_get(&self, run_id: &str) -> Result<Option<serde_json::Value>, StoreError> {
115        let conn = self.conn().lock().unwrap();
116        let text: Option<String> =
117            conn.query_row("SELECT input FROM db_job_event_inputs WHERE run_id = ?1", params![run_id], |r| r.get(0)).optional()?;
118        Ok(text.and_then(|t| serde_json::from_str(&t).ok()))
119    }
120
121    /// Let go of the input of run `run_id`.
122    pub fn job_event_input_drop(&self, run_id: &str) -> Result<(), StoreError> {
123        let conn = self.conn().lock().unwrap();
124        conn.execute("DELETE FROM db_job_event_inputs WHERE run_id = ?1", params![run_id])?;
125        Ok(())
126    }
127
128    /// Hand the input of run `from` to run `to` (a retry takes over the event of the attempt before it).
129    pub fn job_event_input_carry(&self, from: &str, to: &str) -> Result<(), StoreError> {
130        let conn = self.conn().lock().unwrap();
131        conn.execute("UPDATE db_job_event_inputs SET run_id = ?2 WHERE run_id = ?1", params![from, to])?;
132        Ok(())
133    }
134
135    /// An event the job heard of but did not start a run for (a skip, a cap, the rate limit): it stays heard, so a
136    /// repeat of it is nothing, but it no longer counts as one the job admitted.
137    pub fn job_event_unadmit(&self, job_id: &str, event_id: &str) -> Result<(), StoreError> {
138        let conn = self.conn().lock().unwrap();
139        conn.execute("UPDATE db_job_trigger_events SET run_id = '' WHERE job_id = ?1 AND event_id = ?2", params![job_id, event_id])?;
140        Ok(())
141    }
142
143    /// How many events `job_id` admitted (started or queued a run for) since `since_ms`.
144    pub fn job_events_since(&self, job_id: &str, since_ms: i64) -> Result<i64, StoreError> {
145        let conn = self.conn().lock().unwrap();
146        Ok(conn.query_row(
147            "SELECT COUNT(*) FROM db_job_trigger_events WHERE job_id = ?1 AND at_ms >= ?2 AND run_id != ''",
148            params![job_id, since_ms],
149            |r| r.get(0),
150        )?)
151    }
152}
153
154#[cfg(test)]
155mod tests {
156    use super::*;
157
158    fn store() -> Store {
159        let store = Store::open_in_memory().unwrap();
160        let conn = store.conn().lock().unwrap();
161        conn.execute_batch(SCHEMA).unwrap();
162        crate::backend::storage::migrations::apply_additive_columns(&conn, COLUMNS).unwrap();
163        drop(conn);
164        store
165    }
166
167    #[test]
168    fn an_event_id_is_new_once_per_job() {
169        let s = store();
170        assert!(s.job_event_claim("job-a", "e1", "run-1", 100).unwrap());
171        assert!(!s.job_event_claim("job-a", "e1", "run-2", 200).unwrap(), "the same event again is nothing");
172        assert!(s.job_event_claim("job-a", "e2", "run-3", 300).unwrap());
173        assert!(s.job_event_claim("job-b", "e1", "run-4", 400).unwrap(), "another job hears the same id as new");
174    }
175
176    #[test]
177    fn a_baseline_claims_the_marker_and_every_id_together_or_nothing() {
178        let s = store();
179        let ids: Vec<String> = ["a", "b", "c"].iter().map(|x| x.to_string()).collect();
180        assert!(s.job_event_claim_baseline("job-a", "marker", &ids, 100).unwrap());
181        for id in &ids {
182            assert!(!s.job_event_claim("job-a", id, "", 200).unwrap(), "{id} was claimed with the marker");
183        }
184        assert_eq!(s.job_events_since("job-a", 0).unwrap(), 0, "noted, not started: none count as admitted");
185        assert!(!s.job_event_claim_baseline("job-a", "marker", &ids, 300).unwrap(), "the second first look is not one");
186
187        // A marker with items unclaimed (another instance mid-way, or a crash): this one writes nothing.
188        assert!(s.job_event_claim("job-b", "marker", "", 100).unwrap());
189        assert!(!s.job_event_claim_baseline("job-b", "marker", &ids, 200).unwrap());
190        for id in &ids {
191            assert!(s.job_event_claim("job-b", id, "run-x", 300).unwrap(), "{id} is still unclaimed: a baseline that did not run wrote nothing");
192        }
193    }
194
195    #[test]
196    fn touching_an_id_keeps_it_through_the_sweep_without_making_it_an_admitted_event() {
197        let s = store();
198        assert!(s.job_event_claim("job-a", "marker", "", 100).unwrap());
199        assert!(s.job_event_touch("job-a", "marker", 500).unwrap());
200        assert!(!s.job_event_touch("job-a", "marker", 400).unwrap(), "never backwards");
201        assert!(!s.job_event_touch("job-a", "nothing", 500).unwrap());
202        assert_eq!(s.job_events_forget_before(300).unwrap(), 0, "it was touched, so it is not old");
203        assert_eq!(s.job_events_since("job-a", 0).unwrap(), 0, "a marker with no run is not an admitted event");
204        assert!(!s.job_event_claim("job-a", "marker", "", 600).unwrap());
205    }
206
207    #[test]
208    fn touching_an_old_admitted_event_does_not_count_it_again_toward_the_hour() {
209        // An expect's gap, heard days ago and admitted (it started a run), is seen again now and touched to keep it.
210        let s = store();
211        let hour = 3_600_000;
212        let day = 24 * hour;
213        let now = 10 * day;
214        assert!(s.job_event_claim("job-a", "gap-old", "run-1", now - 3 * day).unwrap());
215        assert!(s.job_event_touch("job-a", "gap-old", now).unwrap());
216        assert_eq!(s.job_events_since("job-a", now - hour).unwrap(), 0, "the touch is not an event admitted this hour");
217
218        // The watched job recovers, then a new gap opens within the hour: with a limit of one an hour it is the first.
219        assert!(s.job_event_claim("job-a", "gap-new", "run-2", now + 20 * 60_000).unwrap());
220        assert_eq!(s.job_events_since("job-a", now + 20 * 60_000 - hour).unwrap(), 1, "only the new gap counts");
221
222        // The touch still keeps the old gap's id past the week from when it was heard.
223        assert_eq!(s.job_events_forget_before(now - 1).unwrap(), 0);
224        assert!(!s.job_event_claim("job-a", "gap-old", "run-3", now + hour).unwrap(), "still heard: the same gap is nothing");
225        assert_eq!(s.job_events_forget_before(now + 1).unwrap(), 1, "a week after the last look it goes");
226    }
227
228    #[test]
229    fn the_seen_column_is_added_to_a_table_an_earlier_build_made() {
230        let store = Store::open_in_memory().unwrap();
231        let conn = store.conn().lock().unwrap();
232        conn.execute_batch(
233            "CREATE TABLE db_job_trigger_events (job_id TEXT NOT NULL, event_id TEXT NOT NULL, run_id TEXT NOT NULL DEFAULT '', \
234             at_ms INTEGER NOT NULL, PRIMARY KEY (job_id, event_id));
235             INSERT INTO db_job_trigger_events VALUES ('job-a', 'e1', 'run-1', 100);",
236        )
237        .unwrap();
238        conn.execute_batch(SCHEMA).unwrap();
239        crate::backend::storage::migrations::apply_additive_columns(&conn, COLUMNS).unwrap();
240        crate::backend::storage::migrations::apply_additive_columns(&conn, COLUMNS).unwrap();
241        drop(conn);
242        assert!(store.job_event_touch("job-a", "e1", 500).unwrap());
243        assert_eq!(store.job_events_since("job-a", 200).unwrap(), 0, "the old row keeps its own time");
244        assert_eq!(store.job_events_forget_before(300).unwrap(), 0);
245    }
246
247    #[test]
248    fn a_job_forgets_old_ids_and_counts_recent_ones() {
249        let s = store();
250        for (i, at) in [100, 200, 300].into_iter().enumerate() {
251            assert!(s.job_event_claim("job-a", &format!("e{i}"), "r", at).unwrap());
252        }
253        assert_eq!(s.job_events_since("job-a", 200).unwrap(), 2);
254        assert_eq!(s.job_events_forget_before(250).unwrap(), 2);
255        assert_eq!(s.job_events_since("job-a", 0).unwrap(), 1);
256        assert!(s.job_event_claim("job-a", "e0", "r", 400).unwrap(), "a forgotten id is a new event");
257    }
258
259    #[test]
260    fn an_unadmitted_event_stays_heard_but_is_not_counted() {
261        let s = store();
262        assert!(s.job_event_claim("job-a", "e1", "run-1", 100).unwrap());
263        assert!(s.job_event_claim("job-a", "e2", "run-2", 110).unwrap());
264        s.job_event_unadmit("job-a", "e2").unwrap();
265        assert_eq!(s.job_events_since("job-a", 0).unwrap(), 1, "only the admitted one counts");
266        assert!(!s.job_event_claim("job-a", "e2", "run-3", 120).unwrap(), "but it is still heard: a repeat is nothing");
267    }
268
269    #[test]
270    fn an_input_is_kept_per_run_carried_dropped_and_forgotten_with_age() {
271        let s = store();
272        let input = serde_json::json!({ "outcome": "failed", "n": 3 });
273        s.job_event_input_put("run-1", "job-a", &input, 100).unwrap();
274        assert_eq!(s.job_event_input_get("run-1").unwrap(), Some(input.clone()));
275        assert_eq!(s.job_event_input_get("run-2").unwrap(), None);
276
277        s.job_event_input_carry("run-1", "run-2").unwrap();
278        assert_eq!((s.job_event_input_get("run-1").unwrap(), s.job_event_input_get("run-2").unwrap()), (None, Some(input)));
279
280        s.job_event_input_drop("run-2").unwrap();
281        assert_eq!(s.job_event_input_get("run-2").unwrap(), None);
282
283        s.job_event_input_put("old", "job-a", &serde_json::json!({}), 100).unwrap();
284        s.job_event_input_put("new", "job-a", &serde_json::json!({}), 900).unwrap();
285        s.job_events_forget_before(500).unwrap();
286        assert_eq!(s.job_event_input_get("old").unwrap().is_some(), true, "forgetting ids does not take an input a run may still need");
287        s.job_event_inputs_forget_before(500).unwrap();
288        assert_eq!((s.job_event_input_get("old").unwrap(), s.job_event_input_get("new").unwrap().is_some()), (None, true));
289    }
290}