1use rusqlite::{params, OptionalExtension};
13
14use super::job_runs::{reason, row_to_run, state, JobRun, COLS};
15use super::store::Store;
16use super::StoreError;
17
18pub(crate) const SCHEMA: &str = "
21 CREATE TABLE IF NOT EXISTS db_job_events (
22 job_id TEXT NOT NULL,
23 run_id TEXT NOT NULL,
24 event_id TEXT NOT NULL,
25 seen_ms INTEGER NOT NULL,
26 PRIMARY KEY (job_id, run_id, event_id)
27 );
28 CREATE INDEX IF NOT EXISTS idx_ids_job_events_seen ON db_job_events(seen_ms);";
29
30const KEEP_EVENT_IDS_MS: i64 = 8 * 24 * 3600 * 1000;
32
33#[derive(Debug, Clone, Copy)]
36pub struct EventMark<'a> {
37 pub run_id: &'a str,
38 pub event_id: &'a str,
39 pub now_ms: i64,
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum CloudStart {
45 Opened,
47 TookOverMissed,
49 Known,
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum CloudFinish {
56 Closed,
58 Created,
60 Late,
62 Known,
64}
65
66pub fn cloud_run_id(job_id: &str, run_id: &str) -> String {
68 format!("cloud:{job_id}:{run_id}")
69}
70
71fn get(conn: &rusqlite::Connection, id: &str) -> Result<Option<JobRun>, StoreError> {
72 Ok(conn.query_row(&format!("SELECT {COLS} FROM db_job_runs WHERE id = ?1"), params![id], row_to_run).optional()?)
73}
74
75fn given_up_for(conn: &rusqlite::Connection, run: &JobRun, slot: Option<i64>) -> Result<Option<JobRun>, StoreError> {
79 if let Some(slot) = slot {
80 return Ok(conn
81 .query_row(
82 &format!("SELECT {COLS} FROM db_job_runs WHERE job_id = ?1 AND scheduled_for_ms = ?2 AND state IN ('missed','lost')"),
83 params![run.job_id, slot],
84 row_to_run,
85 )
86 .optional()?);
87 }
88 Ok(conn
90 .query_row(
91 &format!(
92 "SELECT {COLS} FROM db_job_runs
93 WHERE job_id = ?1 AND job_source = 'cloud' AND state = 'missed' AND json_valid(links)
94 AND json_extract(links, '$.window_from') <= ?2 AND ?2 < json_extract(links, '$.window_until')
95 ORDER BY scheduled_for_ms LIMIT 1"
96 ),
97 params![run.job_id, run.started_at_ms],
98 row_to_run,
99 )
100 .optional()?)
101}
102
103fn withdraw_failure(tx: &rusqlite::Connection, id: &str) -> Result<(), StoreError> {
107 let incident: Option<String> =
108 tx.query_row("SELECT incident_id FROM db_job_incident_runs WHERE run_id = ?1", params![id], |r| r.get(0)).optional()?;
109 if let Some(incident) = incident {
110 tx.execute("DELETE FROM db_job_incident_runs WHERE run_id = ?1", params![id])?;
111 tx.execute("UPDATE db_job_incidents SET failures = MAX(failures - 1, 0) WHERE id = ?1", params![incident])?;
113 }
114 Ok(())
115}
116
117fn merge_links(old: &serde_json::Value, new: &serde_json::Value) -> serde_json::Value {
118 let mut merged = if old.is_object() { old.clone() } else { serde_json::json!({}) };
119 if let (Some(m), Some(n)) = (merged.as_object_mut(), new.as_object()) {
120 for (k, v) in n {
121 m.insert(k.clone(), v.clone());
122 }
123 }
124 merged
125}
126
127fn record_event(tx: &rusqlite::Connection, mark: &EventMark, job_id: &str) -> Result<bool, StoreError> {
130 tx.execute("DELETE FROM db_job_events WHERE seen_ms < ?1", params![mark.now_ms - KEEP_EVENT_IDS_MS])?;
131 let n = tx.execute(
132 "INSERT OR IGNORE INTO db_job_events (job_id, run_id, event_id, seen_ms) VALUES (?1, ?2, ?3, ?4)",
133 params![job_id, mark.run_id, mark.event_id, mark.now_ms],
134 )?;
135 Ok(n > 0)
136}
137
138fn slot_covered(conn: &rusqlite::Connection, job_id: &str, slot_ms: i64, from_ms: i64, until_ms: i64) -> Result<bool, StoreError> {
141 Ok(conn
142 .query_row(
143 "SELECT 1 FROM db_job_runs
144 WHERE job_id = ?1 AND job_source = 'cloud'
145 AND (scheduled_for_ms = ?2
146 OR (json_valid(links) AND json_extract(links, '$.scheduled_for_ms') = ?2)
147 OR (started_at_ms >= ?3 AND started_at_ms < ?4
148 AND scheduled_for_ms IS NULL
149 AND NOT (json_valid(links) AND json_extract(links, '$.scheduled_for_ms') IS NOT NULL)))
150 LIMIT 1",
151 params![job_id, slot_ms, from_ms, until_ms],
152 |_| Ok(()),
153 )
154 .optional()?
155 .is_some())
156}
157
158impl Store {
159 pub fn job_cloud_slot_covered(&self, job_id: &str, slot_ms: i64, from_ms: i64, until_ms: i64) -> Result<bool, StoreError> {
161 slot_covered(&self.conn().lock().unwrap(), job_id, slot_ms, from_ms, until_ms)
162 }
163
164 pub fn job_cloud_give_up_slot(&self, missed: &JobRun, from_ms: i64, until_ms: i64) -> Result<bool, StoreError> {
168 let mut conn = self.conn().lock().unwrap();
169 let tx = conn.transaction()?;
170 let Some(slot) = missed.scheduled_for_ms else {
171 return Ok(false);
172 };
173 if slot_covered(&tx, &missed.job_id, slot, from_ms, until_ms)? {
174 return Ok(false);
175 }
176 insert(&tx, missed)?;
177 tx.commit()?;
178 Ok(true)
179 }
180
181 pub fn job_cloud_running(&self) -> Result<Vec<JobRun>, StoreError> {
183 let conn = self.conn().lock().unwrap();
184 let mut stmt = conn.prepare(&format!("SELECT {COLS} FROM db_job_runs WHERE job_source = 'cloud' AND state = 'running'"))?;
185 let rows = stmt.query_map([], row_to_run)?;
186 Ok(rows.collect::<Result<Vec<_>, _>>()?)
187 }
188
189 pub fn job_cloud_lose(&self, id: &str, now_ms: i64, max_run_ms: i64) -> Result<bool, StoreError> {
193 let conn = self.conn().lock().unwrap();
194 let n = conn.execute(
195 "UPDATE db_job_runs SET state = 'lost', reason = ?2, ended_at_ms = ?3
196 WHERE id = ?1 AND state = 'running'
197 AND MAX(started_at_ms, CASE WHEN json_valid(links) THEN COALESCE(json_extract(links, '$.heartbeat_ms'), 0) ELSE 0 END) + ?4 < ?3",
198 params![id, reason::NO_REPORT, now_ms, max_run_ms],
199 )?;
200 Ok(n > 0)
201 }
202
203 pub fn job_cloud_start(&self, run: &JobRun, slot: Option<i64>, mark: &EventMark) -> Result<Option<CloudStart>, StoreError> {
206 let mut conn = self.conn().lock().unwrap();
207 let tx = conn.transaction()?;
208 if !record_event(&tx, mark, &run.job_id)? {
209 return Ok(None);
210 }
211 if get(&tx, &run.id)?.is_some() {
212 tx.commit()?;
213 return Ok(Some(CloudStart::Known));
214 }
215 let result = if let Some(given_up) = given_up_for(&tx, run, slot)? {
216 tx.execute(
217 "UPDATE db_job_runs SET id = ?2, state = 'running', reason = ?3, infra = '', ended_at_ms = NULL, started_at_ms = ?4,
218 trigger_kind = ?5, attempt = ?6, links = ?7, reporter = ?8, recorded_by = ?9
219 WHERE id = ?1",
220 params![
221 given_up.id,
222 run.id,
223 reason::LATE,
224 run.started_at_ms,
225 run.trigger,
226 run.attempt,
227 merge_links(&given_up.links, &run.links).to_string(),
228 run.reporter,
229 run.recorded_by
230 ],
231 )?;
232 withdraw_failure(&tx, &given_up.id)?;
233 CloudStart::TookOverMissed
234 } else {
235 insert(&tx, run)?;
236 CloudStart::Opened
237 };
238 tx.commit()?;
239 Ok(Some(result))
240 }
241
242 pub fn job_cloud_heartbeat(&self, job_id: &str, id: &str, at_ms: i64, mark: &EventMark) -> Result<Option<bool>, StoreError> {
245 let mut conn = self.conn().lock().unwrap();
246 let tx = conn.transaction()?;
247 if !record_event(&tx, mark, job_id)? {
248 return Ok(None);
249 }
250 let n = tx.execute(
251 "UPDATE db_job_runs SET links = json_set(CASE WHEN json_valid(links) THEN links ELSE '{}' END, '$.heartbeat_ms', MAX(?2, COALESCE(json_extract(links, '$.heartbeat_ms'), 0)))
252 WHERE id = ?1 AND state = 'running'",
253 params![id, at_ms],
254 )?;
255 tx.commit()?;
256 Ok(Some(n > 0))
257 }
258
259 pub fn job_cloud_finish(&self, run: &JobRun, slot: Option<i64>, mark: &EventMark) -> Result<Option<CloudFinish>, StoreError> {
262 let mut conn = self.conn().lock().unwrap();
263 let tx = conn.transaction()?;
264 if !record_event(&tx, mark, &run.job_id)? {
265 return Ok(None);
266 }
267 let existing = match get(&tx, &run.id)? {
268 Some(row) => Some(row),
269 None => given_up_for(&tx, run, slot)?,
270 };
271 let result = match existing {
272 None => {
273 insert(&tx, run)?;
274 CloudFinish::Created
275 }
276 Some(row) if row.state == state::FINISHED => {
277 tx.commit()?;
278 return Ok(Some(CloudFinish::Known));
279 }
280 Some(row) => {
281 let late = matches!(row.state.as_str(), state::MISSED | state::LOST);
282 let started = if late { run.started_at_ms } else { row.started_at_ms };
284 tx.execute(
285 "UPDATE db_job_runs SET id = ?2, state = 'finished', reason = ?3, infra = ?4, outcome = ?5, summary = ?6,
286 started_at_ms = ?7, ended_at_ms = ?8, cost_usd = ?9, cost_known = ?10, output_tokens = ?11,
287 links = ?12, reporter = ?13, recorded_by = ?14, trigger_kind = ?15, attempt = ?16
288 WHERE id = ?1",
289 params![
290 row.id,
291 run.id,
292 if late || row.reason == reason::LATE { reason::LATE } else { "" },
293 run.infra,
294 run.outcome,
295 run.summary,
296 started,
297 run.ended_at_ms,
298 run.cost_usd,
299 run.cost_known as i64,
300 run.output_tokens,
301 merge_links(&row.links, &run.links).to_string(),
302 run.reporter,
303 run.recorded_by,
304 run.trigger,
305 run.attempt
306 ],
307 )?;
308 if late {
309 withdraw_failure(&tx, &row.id)?;
310 }
311 if late || row.reason == reason::LATE {
312 if let Some(ended) = [row.ended_at_ms, run.ended_at_ms].into_iter().flatten().min() {
316 tx.execute(
317 "UPDATE db_job_incident_cursors SET ended_at_ms = ?2 - 1, run_id = '' WHERE job_id = ?1 AND ended_at_ms >= ?2",
318 params![row.job_id, ended],
319 )?;
320 }
321 }
322 if late {
323 CloudFinish::Late
324 } else {
325 CloudFinish::Closed
326 }
327 }
328 };
329 tx.commit()?;
330 Ok(Some(result))
331 }
332}
333
334fn insert(conn: &rusqlite::Connection, run: &JobRun) -> Result<(), StoreError> {
335 conn.execute(
336 &format!(
337 "INSERT OR IGNORE INTO db_job_runs ({COLS}) VALUES \
338 (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16,?17,?18,?19,?20,?21,?22,?23,?24,?25,?26,?27,?28,?29,?30,?31,?32)"
339 ),
340 params![
341 run.id,
342 run.job_id,
343 run.job_source,
344 run.job_name,
345 run.template_id,
346 run.template_version,
347 run.trigger,
348 run.scheduled_for_ms,
349 run.triggered_by,
350 run.attempt,
351 run.state,
352 run.reason,
353 run.infra,
354 run.outcome,
355 run.summary,
356 run.target_agent_uid,
357 run.block_id,
358 run.turn_id,
359 run.account_id,
360 run.provider,
361 run.started_at_ms,
362 run.ended_at_ms,
363 run.cost_usd,
364 run.cost_known as i64,
365 run.cost_partial as i64,
366 run.output_tokens,
367 run.steps,
368 run.links.to_string(),
369 run.skip_count,
370 run.last_skip_at_ms,
371 run.reporter,
372 run.recorded_by,
373 ],
374 )?;
375 Ok(())
376}