From f7f45d67925e37149416b4a04d72be01475a80d5 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 09:07:14 +0000 Subject: [PATCH] fix(queue): broker never re-serves condition parks or completed work (#13091) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two serve-path holes let the broker hand out work that was already dispositioned, five times on 2026-11-23: - verb_park stamps a (possibly default) not_before on every park, and the default pick released every park on that timer — including parks whose recorded term is a broker-owned condition (task_terminal/task_status/event_seen, released by the park-revalidation sweeper) or a person's answer (person_answer, released by /wake). Lanes receiving those rows could only re-park them. The pick predicate now ANDs PARKED_TERM_EXCLUSION into the parked branch (mirrored in the budget-skip and no-claim-count diagnostics); all other parks keep timer release, and expired-claim re-serve is untouched. - A done row is unservable, but a re-filing for the same work manufactured a fresh servable row: revive-on-enqueue fired for any terminal predecessor, and the #10627 work-identity rule ignored terminal holders, leaving detection to the fail-open claim-time staleness probe. Enqueue now treats a completed predecessor (same key) and a completed identity holder (any key) as dedupe hits, exactly like live ones. Failed/cancelled predecessors still revive, and dedupe_override still files a deliberate parallel. Regression tests pin both halves: enqueue after completion on the same key and under a dispatch key files no new task, the override and failed-predecessor controls still file, and the pick predicate evaluated per-row never serves broker/person condition parks or a completed row. --- .../crates/fleet-queue/src/turso_queue.rs | 448 ++++++++++++++++++ .../fleet-queue/src/turso_queue/claim.rs | 61 ++- .../fleet-queue/src/turso_queue/lifecycle.rs | 4 +- .../src/turso_queue/work_identity.rs | 55 ++- 4 files changed, 557 insertions(+), 11 deletions(-) diff --git a/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs index afbb18cc63..60b5dc97fd 100644 --- a/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs +++ b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs @@ -484,6 +484,454 @@ mod tests { ); } + // ---- #13091: the broker must not re-serve parked or completed + // work. The incidents (2026-11-23): a parked task whose recorded + // term was a condition/stand-down was timer-served to lanes that + // could only re-park it, and a fresh filing for already-completed + // work created a new servable task that a lane completed a + // second time. The tests below pin both halves at the verb/SQL + // surface the serve path actually runs. + + /// A content-routed stub of the Turso pipeline endpoint for the + /// #13091 tests: each request is answered by the first route + /// whose needle appears in its body; unmatched requests get a + /// bare ok execute reply. Captures every request body. + fn stub_pipeline_routed_13091( + routes: Vec<(&'static str, String)>, + ) -> (String, std::sync::Arc>>) { + use std::io::{BufRead, BufReader, Read, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let captured = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let sink = captured.clone(); + let routes = std::sync::Arc::new(routes); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut sock) = stream else { break }; + let mut reader = BufReader::new(sock.try_clone().unwrap()); + let mut content_length = 0usize; + loop { + let mut line = String::new(); + if reader.read_line(&mut line).unwrap_or(0) == 0 { + break; + } + if line.trim().is_empty() { + break; + } + if let Some((name, value)) = line.split_once(':') { + if name.trim().eq_ignore_ascii_case("content-length") { + content_length = value.trim().parse().unwrap_or(0); + } + } + } + let mut body = vec![0u8; content_length]; + if reader.read_exact(&mut body).is_err() { + break; + } + let body = String::from_utf8_lossy(&body).to_string(); + sink.lock().unwrap().push(body.clone()); + let resp = routes + .iter() + .find(|(needle, _)| body.contains(needle)) + .map(|(_, reply)| reply.clone()) + .unwrap_or_else(|| { + json!({"results": [ + {"type": "ok", "response": {"type": "execute", "result": { + "cols": [], "rows": [], + "affected_row_count": 0, + "last_insert_rowid": null}}}, + {"type": "ok", "response": {"type": "close"}} + ]}) + .to_string() + }); + let out = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\ + Content-Length: {}\r\nConnection: close\r\n\r\n{}", + resp.len(), + resp + ); + if sock.write_all(out.as_bytes()).is_err() { + break; + } + } + }); + (format!("http://{addr}"), captured) + } + + /// A SELECT reply carrying full task rows (TASK_COLS order). + fn task_select_reply_13091(rows: Vec) -> String { + let cols: Vec = TASK_COLS + .split(", ") + .map(|c| json!({"name": c.trim()})) + .collect(); + json!({"results": [ + {"type": "ok", "response": {"type": "execute", "result": { + "cols": cols, "rows": rows, + "affected_row_count": 0, "last_insert_rowid": null}}}, + {"type": "ok", "response": {"type": "close"}} + ]}) + .to_string() + } + + /// One task row in TASK_COLS order for the #13091 stub replies. + fn task_row_13091(id: i64, status: &str, payload: &Value, dedupe_key: &str) -> Value { + let text = |v: &str| json!({"type": "text", "value": v}); + let int = |v: i64| json!({"type": "integer", "value": v.to_string()}); + let null = json!({"type": "null"}); + json!([ + int(id), + text("repo-health-code-pilot"), + text("probe"), + null, + text(&payload.to_string()), + text(dedupe_key), + int(30), + text(status), + null, + null, + null, + null, + null, + null, + int(1), + int(1000), + null, + null, + null, + null, + text("{}"), + text("{}"), + null, + null, + null, + null, + null, + null, + null, + text("2026-11-20T00:00:00Z"), + text("2026-11-21T00:00:00Z"), + text("2026-11-21T00:00:00Z"), + null, + null, + null, + null + ]) + } + + fn insert_ok_13091(id: i64) -> String { + json!({"results": [ + {"type": "ok", "response": {"type": "execute", "result": { + "cols": [], "rows": [], + "affected_row_count": 1, + "last_insert_rowid": id.to_string()}}}, + {"type": "ok", "response": {"type": "close"}} + ]}) + .to_string() + } + + /// A #12744-shaped packet whose payload carries labels, so the + /// mirror enrichment (and its backend call) is skipped and the + /// first backend call is the dedupe read. + fn packet_13091(issue: i64) -> Value { + let mut p = packet_12744(issue, 30); + p["payload"]["labels"] = json!([]); + p + } + + /// The full valid packet payload: a holder row only absorbs + /// when it is not quarantined, and the claim guard validates + /// the holder's payload — a minimal payload would (correctly) + /// read as invalid and absorb nothing. + fn payload_13091(issue: i64) -> Value { + packet_12744(issue, 30)["payload"].clone() + } + + #[test] + fn enqueue_after_completion_on_the_same_key_files_no_new_task_13091() { + // Incident shape: the task for this dedupe key completed + // with a verified disposition; a generator re-files the same + // packet. The broker must answer with the completed task — + // never a fresh servable row. + let done = task_row_13091( + 4242, + "done", + &payload_13091(10283), + "repo-health:v1:fix:developing-today/code:issue:10283", + ); + let fresh = task_row_13091( + 4243, + "queued", + &payload_13091(10283), + "repo-health:v1:fix:developing-today/code:issue:10283", + ); + let (url, captured) = stub_pipeline_routed_13091(vec![ + ("dedupe_key = ?", task_select_reply_13091(vec![done])), + ("status IN (", task_select_reply_13091(vec![])), + ("status = 'done'", task_select_reply_13091(vec![])), + ("INSERT INTO tasks", insert_ok_13091(4243)), + ( + "FROM tasks WHERE id = ?", + task_select_reply_13091(vec![fresh]), + ), + ]); + let backend = TursoBackend::new(url, "test".to_string(), ureq::agent()); + let req = json!({"queue": "repo-health-code-pilot", "packet": packet_13091(10283)}); + let out = verb_enqueue(&backend, &req); + assert_eq!(out["ok"], true, "{out}"); + assert_eq!(out["row"]["id"], 4242, "{out}"); + assert_eq!(out["row"]["status"], "done", "{out}"); + let bodies = captured.lock().unwrap(); + assert_eq!(bodies.len(), 1, "only the dedupe read may run: {bodies:?}"); + assert!( + !bodies.iter().any(|b| b.contains("INSERT INTO tasks")), + "no new task may be filed: {bodies:?}" + ); + } + + #[test] + fn enqueue_after_completion_under_another_key_files_no_new_task_13091() { + // Incident 21296's shape: the completed task sits under a + // DIFFERENT dedupe key (generators key the same work + // differently), so only the work identity can see it. A done + // holder of the identity absorbs the filing the same way. + let done = task_row_13091( + 4242, + "done", + &payload_13091(10283), + "repo-health:v1:fix:developing-today/code:issue:10283", + ); + let fresh = task_row_13091( + 4243, + "queued", + &payload_13091(10283), + "repo-health:v1:fix:developing-today/code:issue:10283:dispatch:0123abcd", + ); + let (url, captured) = stub_pipeline_routed_13091(vec![ + ("dedupe_key = ?", task_select_reply_13091(vec![])), + ("status IN (", task_select_reply_13091(vec![])), + ("status = 'done'", task_select_reply_13091(vec![done])), + ("INSERT INTO tasks", insert_ok_13091(4243)), + ( + "FROM tasks WHERE id = ?", + task_select_reply_13091(vec![fresh]), + ), + ]); + let backend = TursoBackend::new(url, "test".to_string(), ureq::agent()); + let mut packet = packet_13091(10283); + packet["dedupe_key"] = + json!("repo-health:v1:fix:developing-today/code:issue:10283:dispatch:0123abcd"); + let req = json!({"queue": "repo-health-code-pilot", "packet": packet}); + let out = verb_enqueue(&backend, &req); + assert_eq!(out["ok"], true, "{out}"); + assert_eq!(out["row"]["id"], 4242, "{out}"); + assert_eq!(out["work_identity_collision"]["status"], "done", "{out}"); + let bodies = captured.lock().unwrap(); + assert!( + !bodies.iter().any(|b| b.contains("INSERT INTO tasks")), + "no new task may be filed: {bodies:?}" + ); + } + + #[test] + fn enqueue_done_predecessor_with_override_files_a_deliberate_parallel_13091() { + // The escape hatch stands: a packet that declares + // dedupe_override files a deliberate parallel even over a + // completed predecessor (the revive-on-enqueue path). + let done = task_row_13091( + 4242, + "done", + &payload_13091(10283), + "repo-health:v1:fix:developing-today/code:issue:10283", + ); + let fresh = task_row_13091( + 4243, + "queued", + &payload_13091(10283), + "repo-health:v1:fix:developing-today/code:issue:10283", + ); + let (url, captured) = stub_pipeline_routed_13091(vec![ + ("dedupe_key = ?", task_select_reply_13091(vec![done])), + ("INSERT INTO tasks", insert_ok_13091(4243)), + ( + "FROM tasks WHERE id = ?", + task_select_reply_13091(vec![fresh]), + ), + ]); + let backend = TursoBackend::new(url, "test".to_string(), ureq::agent()); + let mut packet = packet_13091(10283); + packet["payload"]["dedupe_override"] = json!("deliberate parallel after a regression"); + let req = json!({"queue": "repo-health-code-pilot", "packet": packet}); + let out = verb_enqueue(&backend, &req); + assert_eq!(out["ok"], true, "{out}"); + assert_eq!(out["row"]["id"], 4243, "{out}"); + let bodies = captured.lock().unwrap(); + assert!( + bodies.iter().any(|b| b.contains("INSERT INTO tasks")), + "the override must file: {bodies:?}" + ); + } + + #[test] + fn enqueue_failed_predecessor_still_revives_13091() { + // Only completion is terminal for a filing: a FAILED + // predecessor keeps the #6838 revive-on-enqueue behavior. + let failed = task_row_13091( + 4242, + "failed", + &payload_13091(10283), + "repo-health:v1:fix:developing-today/code:issue:10283", + ); + let fresh = task_row_13091( + 4243, + "queued", + &payload_13091(10283), + "repo-health:v1:fix:developing-today/code:issue:10283", + ); + let (url, captured) = stub_pipeline_routed_13091(vec![ + ("dedupe_key = ?", task_select_reply_13091(vec![failed])), + ("status IN (", task_select_reply_13091(vec![])), + ("status = 'done'", task_select_reply_13091(vec![])), + ("INSERT INTO tasks", insert_ok_13091(4243)), + ( + "FROM tasks WHERE id = ?", + task_select_reply_13091(vec![fresh]), + ), + ]); + let backend = TursoBackend::new(url, "test".to_string(), ureq::agent()); + let req = json!({"queue": "repo-health-code-pilot", "packet": packet_13091(10283)}); + let out = verb_enqueue(&backend, &req); + assert_eq!(out["ok"], true, "{out}"); + assert_eq!(out["row"]["id"], 4243, "{out}"); + let bodies = captured.lock().unwrap(); + assert!( + bodies.iter().any(|b| b.contains("INSERT INTO tasks")), + "a failed predecessor must still revive: {bodies:?}" + ); + } + + #[test] + fn claim_pick_never_serves_broker_or_person_condition_parks_13091() { + // The parked half, at the exact SQL the serve path runs: + // the default pick predicate (shared verbatim by the pick + // SELECT and the claim UPDATE re-check) evaluated per row. + // A park whose recorded term is a broker-owned condition + // (task_terminal / task_status / event_seen — released by + // the park-revalidation sweeper) or a person's answer + // (person_answer — released by /wake when the person acts) + // is NOT the pick's to timer-serve; every other park keeps + // its timer release, and a completed row is never servable. + let conn = rusqlite::Connection::open_in_memory().unwrap(); + conn.execute_batch( + "CREATE TABLE tasks (id INTEGER PRIMARY KEY, queue TEXT, payload TEXT, + status TEXT, attempts INTEGER, max_attempts INTEGER, not_before TEXT, + wait_kind TEXT, ready_condition TEXT, required_budget_minutes INTEGER, + priority INTEGER, created_at TEXT, progress TEXT); + CREATE TABLE repo_task_lane_ledger (task_id INTEGER, platform_limit TEXT, + platform_limit_reason TEXT);", + ) + .unwrap(); + let now = "2026-11-23T12:00:00Z"; + let past = "2026-11-23T11:00:00Z"; + let rows: [(i64, &str, Option<&str>, Option<&str>); 8] = [ + (1, "queued", None, None), + (2, "parked", Some(past), Some("{\"kind\":\"time\"}")), + (3, "parked", Some(past), Some("{\"kind\":\"pr_merged\"}")), + ( + 4, + "parked", + Some(past), + Some("{\"kind\":\"task_terminal\",\"task_id\":99}"), + ), + ( + 5, + "parked", + Some(past), + Some("{\"kind\":\"person_answer\"}"), + ), + ( + 6, + "parked", + Some(past), + Some("{\"kind\":\"event_seen\",\"event_kind\":\"x\"}"), + ), + (7, "done", None, None), + (8, "parked", Some(past), None), + ]; + for (id, status, nb, rc) in rows { + conn.execute( + "INSERT INTO tasks (id, queue, payload, status, attempts, max_attempts, \ + not_before, wait_kind, ready_condition, required_budget_minutes, \ + priority, created_at) \ + VALUES (?, 'repo-health-code-pilot', '{\"kind\":\"small_fix\"}', ?, \ + 0, 1000, ?, NULL, ?, NULL, 30, '2026-11-20T00:00:00Z')", + rusqlite::params![id, status, nb, rc], + ) + .unwrap(); + } + let pred = default_pick_predicate(); + let scope = claim_scope(None, None, &ClaimerCtx::default()); + let mut args: Vec = vec![ + rusqlite::types::Value::Text(now.to_string()), + rusqlite::types::Value::Text(now.to_string()), + rusqlite::types::Value::Null, + rusqlite::types::Value::Null, + rusqlite::types::Value::Null, + rusqlite::types::Value::Null, + ]; + for a in &scope.args { + args.push(match a { + Arg::Text(s) => rusqlite::types::Value::Text(s.clone()), + Arg::Int(i) => rusqlite::types::Value::Integer(*i), + Arg::Null => rusqlite::types::Value::Null, + }); + } + let servable = |id: i64| -> bool { + let sql = format!( + "SELECT COUNT(*) FROM tasks WHERE id = ? AND payload IS NOT NULL \ + AND payload <> '' AND payload <> '{{}}' AND ( {pred} ) \ + {PLATFORM_LIMIT_PICK_CLAUSE}{}", + scope.sql + ); + let mut all: Vec = vec![rusqlite::types::Value::Integer(id)]; + all.extend(args.iter().cloned()); + conn.query_row(&sql, rusqlite::params_from_iter(all), |r| { + r.get::<_, i64>(0) + }) + .unwrap() + > 0 + }; + assert!(servable(1), "a due queued row stays servable"); + assert!(servable(2), "a timed park keeps its timer release"); + assert!( + servable(3), + "a lane-recheck condition park keeps its timer release" + ); + assert!( + !servable(4), + "a task_terminal park is the sweeper's to release, not the pick's" + ); + assert!( + !servable(5), + "a person_answer park waits on a person, not on a timer" + ); + assert!( + !servable(6), + "an event_seen park is the sweeper's to release, not the pick's" + ); + assert!(!servable(7), "a completed task is never served"); + assert!( + servable(8), + "a legacy park with no recorded condition keeps its timer release" + ); + // The claim UPDATE re-check embeds the same predicate, so a + // row the pick cannot select cannot be claimed by racing it. + let upd = claim_update_sql(&pred); + assert!( + upd.contains("person_answer"), + "the claim re-check carries the same exclusion: {upd}" + ); + } + #[test] fn payload_issue_ref_shapes_12744() { // The identity the enrichment keys on: the payload's own diff --git a/pkgs/fleet/crates/fleet-queue/src/turso_queue/claim.rs b/pkgs/fleet/crates/fleet-queue/src/turso_queue/claim.rs index dc42eada6f..3e05893519 100644 --- a/pkgs/fleet/crates/fleet-queue/src/turso_queue/claim.rs +++ b/pkgs/fleet/crates/fleet-queue/src/turso_queue/claim.rs @@ -101,6 +101,23 @@ pub(crate) fn verb_enqueue(t: &TursoBackend, req: &Value) -> Value { if let Some(row) = live { return Ok((row, None, None)); } + // #13091: a COMPLETED predecessor is terminal for the + // key. The work was done and dispositioned; a re-filing + // (a generator re-scanning, a stale snapshot) must not + // manufacture a fresh servable task out of it — the + // completed row is the dedupe hit, exactly like a live + // one. Failed and cancelled predecessors keep + // revive-on-enqueue (#6838), and a declared + // dedupe_override still files its deliberate parallel + // below, revive bookkeeping included. + if override_reason.is_none() { + if let Some(row) = terminal + .as_ref() + .filter(|r| r.get("status").and_then(|v| v.as_str()) == Some("done")) + { + return Ok((row.clone(), None, None)); + } + } predecessor = terminal; } // #10627: open-collision rule. A live task in any queue that @@ -117,6 +134,26 @@ pub(crate) fn verb_enqueue(t: &TursoBackend, req: &Value) -> Value { let detail = collision_detail(&holder, ident); return Ok((holder, None, Some(detail))); } + // #13091: a COMPLETED holder of the identity absorbs + // the filing the same way. #10627 left terminal rows + // out so failures could re-queue, and left already-done + // detection to the claim-time staleness probe — which + // fails open by standing rule, so while a probe was + // degraded, completed work was served again and + // completed a second time (2026-11-23 incidents). The + // broker knows its own completions locally; no probe + // is involved. Failed and cancelled holders still + // never block a filing. + if let Some(holder) = done_identity_holder(t, ident, kind)? { + let mut detail = collision_detail(&holder, ident); + detail["rule"] = json!("done_work_identity"); + detail["hint"] = json!( + "this work already completed under another task; a completed \ + task is never re-served (#13091) — file with \ + payload.dedupe_override=\"\" for a deliberate parallel" + ); + return Ok((holder, None, Some(detail))); + } } let ins = t.exec( "INSERT INTO tasks (queue, title, body, payload, dedupe_key, priority, \ @@ -2126,7 +2163,10 @@ pub(crate) fn claim_update_sql(pick_predicate: &str) -> String { /// handoff pick and by-id claim keep working unchanged. Since /// #8234 a sink row is never 'parked', so the timed parked branch /// needs no sink exclusion — genuine wait parks release through -/// claim at not_before, and only there. The sink branch carries +/// claim at not_before, and only there. #13091 narrows "genuine +/// wait": a park whose recorded term is a broker-owned condition +/// or a person's answer (PARKED_TERM_EXCLUSION) is not the pick's +/// to release — the revalidation sweeper and /wake own those. The sink branch carries /// no `?` placeholder, so the pick SELECT and the claim UPDATE /// re-check keep their four leading arguments: the two `now`s of /// the queued/parked branches, then the claimer's declared @@ -2158,6 +2198,23 @@ pub(crate) fn budget_bypass_sql() -> String { format!("({REQUIRED_BUDGET_EXPR} IS NOT NULL AND COALESCE(?, -1) >= {REQUIRED_BUDGET_EXPR})") } +/// #13091: the park terms the default pick may NOT release on its +/// timer. A park whose recorded ready condition is a broker-owned +/// condition (`task_terminal`, `task_status`, `event_seen`) is +/// released by the park-revalidation sweeper when the broker +/// itself observes the condition — never by a lane claiming the +/// row on the clock. A `person_answer` park waits on a person and +/// releases through /wake when the person acts. Serving either +/// kind to a lane on the park's (possibly default) timer hands +/// work to a lane that can only re-park it — the double-serve +/// incidents of 2026-11-23. Every other park (time, ci, review, +/// capacity, triage, external, or a legacy row with no recorded +/// condition) keeps its timer release: for those, claim-at- +/// not_before IS the designed release path (FDR-0008). Literals +/// only — the predicate's placeholder count is pinned. +pub(crate) const PARKED_TERM_EXCLUSION: &str = "COALESCE(json_extract(ready_condition, '$.kind'), 'time') \ + NOT IN ('task_terminal', 'task_status', 'event_seen', 'person_answer')"; + pub(crate) fn default_pick_predicate() -> String { let gate = budget_gate_sql(); let bypass = budget_bypass_sql(); @@ -2165,7 +2222,7 @@ pub(crate) fn default_pick_predicate() -> String { "(((status = 'queued' AND attempts < max_attempts \ AND (not_before IS NULL OR not_before <= ?)) \ OR (status = 'parked' AND ((not_before IS NOT NULL AND not_before <= ?) \ - OR (wait_kind = 'capacity' AND {bypass})))) \ + OR (wait_kind = 'capacity' AND {bypass})) AND {PARKED_TERM_EXCLUSION})) \ AND {gate}) \ OR ({HANDOFF_SQL})" ) diff --git a/pkgs/fleet/crates/fleet-queue/src/turso_queue/lifecycle.rs b/pkgs/fleet/crates/fleet-queue/src/turso_queue/lifecycle.rs index 3f3d950300..ac512f3fe6 100644 --- a/pkgs/fleet/crates/fleet-queue/src/turso_queue/lifecycle.rs +++ b/pkgs/fleet/crates/fleet-queue/src/turso_queue/lifecycle.rs @@ -874,7 +874,7 @@ pub(crate) fn budget_skip_sql(scope_sql: &str) -> String { AND (((status = 'queued' AND attempts < max_attempts \ AND (not_before IS NULL OR not_before <= ?)) \ OR (status = 'parked' AND ((not_before IS NOT NULL AND not_before <= ?) \ - OR wait_kind = 'capacity'))) \ + OR wait_kind = 'capacity') AND {PARKED_TERM_EXCLUSION})) \ AND {req_expr} IS NOT NULL \ AND {req_expr} > COALESCE(?, -1)){scope_sql}" ) @@ -935,7 +935,7 @@ pub(crate) fn no_claim_counts_sql(scope_sql: &str) -> String { COALESCE(SUM(CASE WHEN status = 'queued' AND attempts < max_attempts \ AND not_before IS NOT NULL AND not_before > ? THEN 1 ELSE 0 END), 0) AS queued_not_yet_due, \ COALESCE(SUM(CASE WHEN status = 'parked' AND ((not_before IS NOT NULL AND not_before <= ?) \ - OR wait_kind = 'capacity') THEN 1 ELSE 0 END), 0) AS parked_due \ + OR wait_kind = 'capacity') AND {PARKED_TERM_EXCLUSION} THEN 1 ELSE 0 END), 0) AS parked_due \ FROM tasks \ WHERE payload IS NOT NULL AND payload <> '' AND payload <> '{{}}'{scope_sql}" ) diff --git a/pkgs/fleet/crates/fleet-queue/src/turso_queue/work_identity.rs b/pkgs/fleet/crates/fleet-queue/src/turso_queue/work_identity.rs index ece0d970e3..84f6c57499 100644 --- a/pkgs/fleet/crates/fleet-queue/src/turso_queue/work_identity.rs +++ b/pkgs/fleet/crates/fleet-queue/src/turso_queue/work_identity.rs @@ -15,9 +15,13 @@ //! in any queue, files no new row: the reply carries the existing //! task (like a dedupe_key hit) plus a `work_identity_collision` //! naming its id, state and identity, so a generator can route its -//! follow-up onto it. Terminal tasks never block a new filing -//! (re-queue after failure is unaffected; a fresh already-done -//! verdict is the claim-time staleness check's job, #10626). +//! follow-up onto it. Failed and cancelled tasks never block a new +//! filing (re-queue after failure is unaffected). A COMPLETED task +//! does block (#13091): the claim-time staleness check (#10626) +//! fails open by standing rule, so during a probe degradation +//! completed work was served again and completed a second time; +//! the broker knows its own verified completions locally and +//! absorbs the re-filing itself, no probe involved. //! //! Only kinds that work one issue one way take part: small_fix, //! triage, and pr_shepherd (per PR set). ci_investigation, @@ -129,11 +133,12 @@ pub fn dedupe_override(packet: &Value) -> Option { .map(str::to_string) } -/// Whether a live row holds `identity` and may absorb a new filing: -/// same identity, and not a quarantined (invalid) row. -pub fn holds_identity(row: &Value, identity: &WorkIdentity) -> bool { +/// Whether a row in one of `statuses` holds `identity` and may +/// absorb a new filing: same identity, and not a quarantined +/// (invalid) row. +fn holds_identity_in(row: &Value, identity: &WorkIdentity, statuses: &[&str]) -> bool { let status = row.get("status").and_then(|v| v.as_str()).unwrap_or(""); - if !LIVE_STATUSES.contains(&status) { + if !statuses.contains(&status) { return false; } if work_identity(row).as_ref() != Some(identity) { @@ -142,6 +147,17 @@ pub fn holds_identity(row: &Value, identity: &WorkIdentity) -> bool { claim_guard_reason(row).is_none() } +/// Whether a live row holds `identity` and may absorb a new filing: +/// same identity, and not a quarantined (invalid) row. +pub fn holds_identity(row: &Value, identity: &WorkIdentity) -> bool { + holds_identity_in(row, identity, &LIVE_STATUSES) +} + +/// Whether a completed row holds `identity` (#13091). +fn holds_completed_identity(row: &Value, identity: &WorkIdentity) -> bool { + holds_identity_in(row, identity, &["done"]) +} + /// The live task already holding `identity`, oldest first, in any /// queue. pub(crate) fn live_identity_holder( @@ -163,6 +179,31 @@ pub(crate) fn live_identity_holder( Ok(rows.into_iter().find(|row| holds_identity(row, identity))) } +/// The completed task already holding `identity`, oldest first, in +/// any queue (#13091): the same match as live_identity_holder over +/// done rows. Only completion absorbs — failed and cancelled rows +/// are re-queueable by design (#10627). +pub(crate) fn done_identity_holder( + t: &TursoBackend, + identity: &WorkIdentity, + kind: &str, +) -> Result, TErr> { + let rows = t.query_objs( + &format!( + "SELECT {TASK_COLS} FROM tasks \ + WHERE status = 'done' \ + AND json_extract(payload, '$.kind') = ? \ + AND CAST(json_extract(payload, '$.issue.number') AS INTEGER) = ? \ + ORDER BY id ASC" + ), + &[Arg::Text(kind.to_string()), Arg::Int(identity.issue)], + &TASK_JSON_COLS, + )?; + Ok(rows + .into_iter() + .find(|row| holds_completed_identity(row, identity))) +} + /// The machine-readable collision a deduped enqueue reports. pub fn collision_detail(holder: &Value, identity: &WorkIdentity) -> Value { json!({