diff --git a/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs index 6cfdd65030..fe4528b542 100644 --- a/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs +++ b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs @@ -2330,6 +2330,90 @@ mod tests { assert_eq!(e.get("handed_off"), Some(&json!(0))); } + #[test] + fn health_entry_defaults_failed_events_to_zero() { + // #1233 criterion 1 ("zero dead-in-queue over a rolling 7 + // days") is unmeasured today: health lumps failed terminal + // events into terminal_events_24h/7d together with completed + // ones, so a queue can show 2846 terminal events in 7d with + // no way to tell whether any were failures. The failed-only + // counters default to zero here and are filled by the + // terminal-events fold. + let e = health_entry("repo-health-code-pilot"); + assert_eq!(e.get("failed_events_24h"), Some(&json!(0))); + assert_eq!(e.get("failed_events_7d"), Some(&json!(0))); + } + + #[test] + fn terminal_events_fold_splits_failed_from_completed() { + // Fixture for #1233: queue-mixed had 5 terminal events in + // 7d (3 in 24h), of which 2 were failures (1 in 24h); + // queue-clean had terminal events but zero failures; + // queue-quiet had none. + let mut by_queue: Map = Map::new(); + for q in ["queue-mixed", "queue-clean", "queue-quiet"] { + by_queue.insert(q.to_string(), health_entry(q)); + } + let rows = vec![ + json!({"queue": "queue-mixed", "n24": 3, "n7": 5, "f24": 1, "f7": 2}), + json!({"queue": "queue-clean", "n24": 4, "n7": 9, "f24": 0, "f7": 0}), + ]; + apply_terminal_events(&mut by_queue, &rows); + let mixed = &by_queue["queue-mixed"]; + assert_eq!(mixed.get("terminal_events_24h"), Some(&json!(3))); + assert_eq!(mixed.get("terminal_events_7d"), Some(&json!(5))); + assert_eq!(mixed.get("failed_events_24h"), Some(&json!(1))); + assert_eq!(mixed.get("failed_events_7d"), Some(&json!(2))); + // Completed-only rows leave the failed counters at zero, + // and a queue with no terminal events at all keeps every + // default. + assert_eq!( + by_queue["queue-clean"].get("failed_events_7d"), + Some(&json!(0)) + ); + assert_eq!( + by_queue["queue-quiet"].get("failed_events_7d"), + Some(&json!(0)) + ); + assert_eq!( + by_queue["queue-quiet"].get("terminal_events_7d"), + Some(&json!(0)) + ); + } + + #[test] + fn health_failed_events_count_terminal_failures_only() { + // Codex review on #12682 (discussion 4660035001): the + // failed-only sums counted every 'failed' event, so a + // transient requeue or a block read as a dead-in-queue + // failure, while a terminal lease expiry at cap read as + // zero. The terminal-events query must distinguish + // dispositions: requeued and blocked 'failed' events are + // live retries, lease_expired_at_cap is a terminal failure. + let src = &test_source(); + let seg = seg8217(src, "fn verb_health(", "Merge-intent stack storage"); + assert!( + seg.contains("'lease_expired_at_cap'"), + "the kind filter includes terminal lease-expiry events" + ); + assert!( + seg.contains("json_extract(e.detail, '$.requeued')"), + "the failed sums read the requeued disposition from the event detail" + ); + assert!( + seg.contains("json_extract(e.detail, '$.reason_class')"), + "the failed sums read the reason_class disposition from the event detail" + ); + assert!( + seg.contains("'blocked'"), + "blocked failures are excluded from the terminal failed sums" + ); + assert!( + !seg.contains("e.kind = 'failed' THEN 1"), + "the failed sums no longer count every 'failed' event" + ); + } + #[test] fn at_cap_fold_covers_zero_claimable_and_partial_queues() { // Fixture for #6528 criterion 3: queue-dead has queued > 0 diff --git a/pkgs/fleet/crates/fleet-queue/src/turso_queue/admin.rs b/pkgs/fleet/crates/fleet-queue/src/turso_queue/admin.rs index cca200e2c4..4344a3f466 100644 --- a/pkgs/fleet/crates/fleet-queue/src/turso_queue/admin.rs +++ b/pkgs/fleet/crates/fleet-queue/src/turso_queue/admin.rs @@ -1374,6 +1374,7 @@ pub(crate) fn health_entry(queue: &str) -> Value { "parked": 0, "malformed_parked": 0, "handed_off": 0, "blocked": 0, "dep_blocked": 0, "done": 0, "cancelled": 0, "failed": 0, "total": 0, "oldest_queued_at": Value::Null, "terminal_events_24h": 0, "terminal_events_7d": 0, + "failed_events_24h": 0, "failed_events_7d": 0, }) } @@ -1409,6 +1410,42 @@ pub(crate) fn apply_dep_blocked(by_queue: &mut Map, rows: &[Value } } +/// Fold per-queue terminal-event counts (#1233) into health entries: +/// the terminal-events query counts completed AND failed events +/// together, so a queue could show thousands of terminal events in +/// 7d with no way to tell whether any were failures — and the epic's +/// "zero dead-in-queue over a rolling 7 days" criterion stayed +/// unmeasured. The failed-only sums (f24/f7) name the dead-in-queue +/// count for each window; queues with no failed events keep the zero +/// default from health_entry. The failed sums count terminal +/// failures only: a requeued or blocked 'failed' event is a live +/// retry, not a death, and lease expiry at cap counts as a failure +/// (see the terminal predicate in verb_health's query). Rows arrive +/// as {queue, n24, n7, f24, f7}. +pub(crate) fn apply_terminal_events(by_queue: &mut Map, rows: &[Value]) { + for r in rows { + let q = r.get("queue").and_then(|v| v.as_str()).unwrap_or(""); + if let Some(obj) = by_queue.get_mut(q).and_then(|e| e.as_object_mut()) { + obj.insert( + "terminal_events_24h".to_string(), + r.get("n24").cloned().unwrap_or(json!(0)), + ); + obj.insert( + "terminal_events_7d".to_string(), + r.get("n7").cloned().unwrap_or(json!(0)), + ); + obj.insert( + "failed_events_24h".to_string(), + r.get("f24").cloned().unwrap_or(json!(0)), + ); + obj.insert( + "failed_events_7d".to_string(), + r.get("f7").cloned().unwrap_or(json!(0)), + ); + } + } +} + /// The storage-layer not_before rule (#9179, closing the #6426 /// bypass): every value a verb stores in a row's not_before must /// satisfy the same rule the client flag validator and the broker @@ -1531,13 +1568,35 @@ pub(crate) fn verb_health(t: &TursoBackend, req: &Value) -> Value { // Terminal-event counters, the agent.repo_queue_health // view's terminal_events_24h/7d (#5690): events and tasks // share this database, so the JOIN the PG view did is a - // local query here — no cross-database problem. - let mut tsql = "SELECT t.queue AS queue, COUNT(*) AS n7, \ - SUM(CASE WHEN e.created_at > ? THEN 1 ELSE 0 END) AS n24 \ + // local query here — no cross-database problem. The failed- + // only sums (f24/f7, #1233) split dead-in-queue out of the + // completed+failed totals, so the epic's "zero dead-in- + // queue over a rolling 7 days" criterion reads off health. + // A 'failed' event is terminal only when the task actually + // died: verb_fail stamps detail.requeued=true on a transient + // retry and detail.reason_class='blocked' on a block, and + // both still emit kind='failed' — counting every 'failed' + // event would count live retries as dead-in-queue (#12682 + // Codex review). Lease expiry at cap is the other terminal + // failure, but it emits kind='lease_expired_at_cap', so it + // belongs in the filter set and in the failed sums. A + // 'failed' event with no disposition in its detail + // (externally appended) counts as terminal: an explicit + // failure with nothing recorded is a death, not a retry. + // Placeholder order: n24's 24h cutoff, f24's 24h cutoff, + // the 7d window floor, then the optional queue filter. + let failed_terminal = "(e.kind = 'lease_expired_at_cap' OR \ + (e.kind = 'failed' \ + AND COALESCE(json_extract(e.detail, '$.requeued'), 0) = 0 \ + AND COALESCE(json_extract(e.detail, '$.reason_class'), '') <> 'blocked'))"; + let mut tsql = format!("SELECT t.queue AS queue, COUNT(*) AS n7, \ + SUM(CASE WHEN e.created_at > ? THEN 1 ELSE 0 END) AS n24, \ + SUM(CASE WHEN {failed_terminal} THEN 1 ELSE 0 END) AS f7, \ + SUM(CASE WHEN {failed_terminal} AND e.created_at > ? THEN 1 ELSE 0 END) AS f24 \ FROM events e JOIN tasks t ON t.id = e.task_id \ - WHERE e.kind IN ('completed', 'failed') AND e.created_at > ?" - .to_string(); + WHERE e.kind IN ('completed', 'failed', 'lease_expired_at_cap') AND e.created_at > ?"); let mut targs: Vec = vec![ + Arg::Text(iso(now_unix() - 86_400)), Arg::Text(iso(now_unix() - 86_400)), Arg::Text(iso(now_unix() - 7 * 86_400)), ]; @@ -1547,26 +1606,7 @@ pub(crate) fn verb_health(t: &TursoBackend, req: &Value) -> Value { } tsql += " GROUP BY t.queue"; let trows = t.query_objs(&tsql, &targs, &[])?; - for r in &trows { - let q = r - .get("queue") - .and_then(|v| v.as_str()) - .unwrap_or("") - .to_string(); - let entry = by_queue - .entry(q.clone()) - .or_insert_with(|| health_entry(&q)); - if let Some(obj) = entry.as_object_mut() { - obj.insert( - "terminal_events_24h".to_string(), - r.get("n24").cloned().unwrap_or(json!(0)), - ); - obj.insert( - "terminal_events_7d".to_string(), - r.get("n7").cloned().unwrap_or(json!(0)), - ); - } - } + apply_terminal_events(&mut by_queue, &trows); Ok(Value::Array(by_queue.into_iter().map(|(_, v)| v).collect())) })(); match work {