diff --git a/pkgs/fleet/crates/fleet-queue/src/client.rs b/pkgs/fleet/crates/fleet-queue/src/client.rs index 6c145067dd..5897aa146f 100644 --- a/pkgs/fleet/crates/fleet-queue/src/client.rs +++ b/pkgs/fleet/crates/fleet-queue/src/client.rs @@ -72,6 +72,7 @@ pub fn run(args: &[String]) -> i32 { "heartbeat" => cmd_heartbeat(rest), "checkpoint" => cmd_checkpoint(rest), "park" => cmd_park(rest), + "reprioritize" => cmd_reprioritize(rest), "wake" => cmd_wake(rest), "block" => cmd_block(rest), "unblock" => cmd_unblock(rest), diff --git a/pkgs/fleet/crates/fleet-queue/src/client/commands_lifecycle.rs b/pkgs/fleet/crates/fleet-queue/src/client/commands_lifecycle.rs index efca939026..ed5cafd7fe 100644 --- a/pkgs/fleet/crates/fleet-queue/src/client/commands_lifecycle.rs +++ b/pkgs/fleet/crates/fleet-queue/src/client/commands_lifecycle.rs @@ -933,6 +933,36 @@ pub(super) fn cmd_park(rest: &[String]) -> i32 { 0 } +/// Change a task's queue priority and request the broker's linked +/// GitHub synchronization. +pub(super) fn cmd_reprioritize(rest: &[String]) -> i32 { + let args = parse_verb_args("reprioritize", rest, &["worker", "reason"], &[]); + reject_extra_pos("reprioritize", &args, 2); + let id = args.pos_i64(0, "task_id"); + let raw = args + .pos(1) + .unwrap_or_else(|| die(2, "reprioritize: priority is required")); + let v: Value = match raw.parse::() { + Ok(n) => json!(n), + Err(_) => json!(raw), + }; + let to = match crate::validate::resolve_priority(&v, "priority") { + Ok(n) => n, + Err(e) => die(2, &e), + }; + // The actor is the authenticated caller identity: the worker id + // presented over the broker's X-Agent-Token channel (opt_worker + // default), exactly like the other lifecycle verbs. No free-form + // actor string is accepted — it would be spoofable. + let body = json!({"task_id": id, "priority": to, "worker": opt_worker(&args), "reason": args.get("reason")}); + let resp = unwrap_ok(call("/reprioritize", &body)); + print_json(&served_row( + require_row(&resp, "reprioritize_task"), + "reprioritize", + )); + 0 +} + /// wake (#8184): release a broker-held parked wait now that /// its condition is satisfied (e.g. the triage step finished /// triaging the item). The broker flips it back to queued. diff --git a/pkgs/fleet/crates/fleet-queue/src/client/commands_query.rs b/pkgs/fleet/crates/fleet-queue/src/client/commands_query.rs index 50acf6f002..cf768488c7 100644 --- a/pkgs/fleet/crates/fleet-queue/src/client/commands_query.rs +++ b/pkgs/fleet/crates/fleet-queue/src/client/commands_query.rs @@ -387,6 +387,8 @@ pub(super) fn cmd_show(rest: &[String]) -> i32 { "claim_refused", "released", "parked", + "reprioritized", + "reprioritize_sync_pending", "failed", "cancelled", ] { @@ -946,6 +948,8 @@ pub(super) fn cmd_timeline(verb: &str, rest: &[String]) -> i32 { "claim_refused", "released", "parked", + "reprioritized", + "reprioritize_sync_pending", "failed", "cancelled", ] { diff --git a/pkgs/fleet/crates/fleet-queue/src/client/support.rs b/pkgs/fleet/crates/fleet-queue/src/client/support.rs index 567415bfa3..fe753022a1 100644 --- a/pkgs/fleet/crates/fleet-queue/src/client/support.rs +++ b/pkgs/fleet/crates/fleet-queue/src/client/support.rs @@ -196,6 +196,7 @@ Run `repo-queue --help` for flags:\n\ bind [--worker ] --session-id [--launched-by ] [--model-provider

] [--model-id ] [--model-variant ]\n\ heartbeat [--worker ] [--lane ] [--extend-seconds ] [--progress

] [--progress-file ]\n\ checkpoint [--worker ] [--lane ] --stage [--progress

] [--progress-file ]\n\ + reprioritize [--worker ] [--reason ]\n\ park [--worker ] [--lane ] --reason [--delay-seconds ] [--not-before ] [--progress

] [--progress-file ] [--ready-condition ] [--execution ] [--required-budget-minutes ] [--hands --action ]\n\ wake [--worker ] [--reason ]\n\ block [--worker ] [--lane ] --reason-class --blocker [--progress

] [--progress-file ] [--ledger-id ] [--question ] [--context ] [--options-json ] [--links-json ] [--blocked-by-pr ] [--blocked-by-issue ] [--blocked-by-task ] [--blocked-by-ci ] [--dep-recheck-seconds ] [--dep-max-ttl-seconds ] [--hands --action ]\n\ @@ -251,6 +252,9 @@ pub(crate) fn usage(verb: &str) -> &'static str { "checkpoint" => { "usage: repo-queue checkpoint [--worker ] [--lane ] --stage [--progress

] [--progress-file ]\n\nRecords a progress checkpoint." } + "reprioritize" => { + "usage: repo-queue reprioritize [--worker ] [--reason ]\n\nChanges a live task priority (one of 10, 20, 30, 40, 50, 70, 90) and synchronizes its linked issue category." + } "park" => { "usage: repo-queue park [--worker ] [--lane ] --reason [--delay-seconds ] [--not-before ] [--progress

] [--progress-file ] [--ready-condition ] [--execution ] [--required-budget-minutes ] [--hands --action ]\n\nParks a task. A park that waits on a person is refused unless it is a hands item (FDR-0013): --hands physical|interactive-login|payment|signature with --action, one sentence a person can do in five minutes." } @@ -459,6 +463,9 @@ pub(super) fn parse_args_inner( } impl Args { + pub(super) fn pos(&self, idx: usize) -> Option { + self.pos.get(idx).cloned() + } pub(super) fn get(&self, name: &str) -> Option { self.opts .get(name) diff --git a/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs b/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs index 0be9837760..64e3ad3772 100644 --- a/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs +++ b/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs @@ -247,6 +247,11 @@ fn validate_durations(path: &str, req: &Value) -> Result<(), String> { "/claim" | "/claim-flow" => lease_seconds(req).map(|_| ()), "/heartbeat" => extend_seconds(req).map(|_| ()), "/park" => delay_seconds(req).map(|_| ()), + "/reprioritize" => crate::validate::resolve_priority( + req.get("priority").unwrap_or(&Value::Null), + "priority", + ) + .map(|_| ()), _ => Ok(()), } } @@ -661,6 +666,181 @@ fn maybe_raise_actions_exec_extension(st: &State, resp: &Value) { }); } +/// Broker-owned GitHub synchronization for a committed reprioritize. +/// Queue state is never rolled back on an API failure; the durable +/// retry row and task event are written instead. Only `priority/*` +/// labels are edited, so expedite/next-up and unrelated labels are +/// outside this operation's write set. +fn sync_reprioritized(st: &State, t: &crate::turso_queue::TursoBackend, resp: &Value) { + let Some(row) = resp.get("row") else { return }; + let id = row.get("id").and_then(Value::as_i64).unwrap_or(0); + let payload = row.get("payload").unwrap_or(&Value::Null); + let Some(number) = payload.pointer("/issue/number").and_then(Value::as_i64) else { + return; // queue-only task; no linked issue + }; + let Some(repo) = payload.get("repo").and_then(Value::as_str) else { + return; + }; + let Some(priority) = row.get("priority").and_then(Value::as_i64) else { + return; + }; + let Some(label) = crate::validate::label_for_priority(priority) else { + return; + }; + let category = crate::validate::category_for_priority(priority).unwrap_or("unknown"); + let attempt = (|| -> Result<(), String> { + let resolver = Resolver::new(vec![Box::new(DirectSecrets { + url: st.secrets_url.clone(), + token: st.secrets_token.clone(), + agent: st.agent.clone(), + })]); + let token = resolver + .resolve(GH_DEP_TOKEN_SECRET) + .map_err(|e| e.to_string())?; + let base = format!("https://api.github.com/repos/{repo}/issues/{number}"); + let get = st + .agent + .get(&base) + .header("Authorization", &format!("Bearer {}", token.expose())) + .header("Accept", "application/vnd.github+json") + .header("User-Agent", "fleet-queue-broker") + .call() + .map_err(|e| format!("github_read_failed: {e}"))?; + let issue: Value = get + .into_body() + .read_json() + .map_err(|e| format!("github_read_failed: {e}"))?; + let names: Vec = issue + .get("labels") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|l| l.get("name").and_then(Value::as_str).map(str::to_owned)) + .collect(); + for old in names + .iter() + .filter(|n| n.starts_with("priority/") && n.as_str() != label) + { + let url = format!("{base}/labels/{}", old.replace('/', "%2F")); + st.agent + .delete(&url) + .header("Authorization", &format!("Bearer {}", token.expose())) + .header("Accept", "application/vnd.github+json") + .header("User-Agent", "fleet-queue-broker") + .call() + .map_err(|e| format!("github_label_remove_failed: {e}"))?; + } + if !names.iter().any(|n| n == label) { + st.agent + .post(&format!("{base}/labels")) + .header("Authorization", &format!("Bearer {}", token.expose())) + .header("Accept", "application/vnd.github+json") + .header("User-Agent", "fleet-queue-broker") + .send_json(json!({"labels": [label]})) + .map_err(|e| format!("github_label_add_failed: {e}"))?; + } + // Update lineage.priority only inside an existing metadata block. + if let Some(body) = issue.get("body").and_then(Value::as_str) { + if let (Some(start), Some(end)) = ( + body.find(""), + body.find(""), + ) { + if end > start { + let block = &body[start..end]; + if let Some(open) = block.find("```json") { + let json_start = open + "```json".len(); + if let Some(relative_close) = block[json_start..].find("```") { + let close = json_start + relative_close; + let mut metadata: Value = + serde_json::from_str(block[json_start..close].trim()) + .map_err(|e| format!("pm_metadata_parse_failed: {e}"))?; + if metadata.get("lineage").is_some_and(Value::is_object) { + metadata["lineage"]["priority"] = json!(category); + let replacement = format!( + "```json\n{}\n```", + serde_json::to_string_pretty(&metadata).unwrap_or_default() + ); + let patched = format!( + "{}{}{}", + &body[..start], + block.replacen(&block[open..close + 3], &replacement, 1), + &body[end..] + ); + st.agent + .patch(&base) + .header("Authorization", &format!("Bearer {}", token.expose())) + .header("Accept", "application/vnd.github+json") + .header("User-Agent", "fleet-queue-broker") + .send_json(json!({"body": patched})) + .map_err(|e| format!("github_metadata_update_failed: {e}"))?; + } + } + } + } + } + } + Ok(()) + })(); + // Do not acknowledge an older sync if another reprioritize landed + // while the GitHub request was in flight. The durable intent for + // the newer category remains pending and will reconcile from the + // current task row on the next broker request. + let still_current = crate::turso_queue::get_task(t, id) + .ok() + .flatten() + .and_then(|current| current.get("priority").and_then(Value::as_i64)) + == Some(priority); + if attempt.is_ok() && still_current { + let _ = t.exec("UPDATE tasks SET progress = json_set(COALESCE(progress, '{}'), '$.reprioritize_sync_pending', false) WHERE id = ?", &[ + crate::turso_queue::Arg::Int(id), + ]); + let _ = t.exec("UPDATE reprioritize_sync_outbox SET state = 'done', updated_at = ? WHERE task_id = ? AND issue = ? AND state = 'pending'", &[ + crate::turso_queue::Arg::Text(crate::turso_queue::now_iso()), crate::turso_queue::Arg::Int(id), crate::turso_queue::Arg::Int(number), + ]); + } + if let Err(error) = attempt { + let now = crate::turso_queue::now_iso(); + let error_class = error.split(':').next().unwrap_or("github_sync_failed"); + let pending = t.query_objs("SELECT id FROM reprioritize_sync_outbox WHERE task_id = ? AND issue = ? AND state = 'pending' LIMIT 1", &[ + crate::turso_queue::Arg::Int(id), crate::turso_queue::Arg::Int(number), + ], &[]).unwrap_or_default(); + if pending.is_empty() { + let _ = t.exec("INSERT INTO reprioritize_sync_outbox (task_id, repo, issue, category, label, state, attempts, available_at, last_error_class, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 'pending', 0, ?, ?, ?, ?)", &[ + crate::turso_queue::Arg::Int(id), crate::turso_queue::Arg::Text(repo.to_owned()), crate::turso_queue::Arg::Int(number), + crate::turso_queue::Arg::Text(category.to_owned()), crate::turso_queue::Arg::Text(label.to_owned()), crate::turso_queue::Arg::Text(now.clone()), + crate::turso_queue::Arg::Text(error_class.to_owned()), crate::turso_queue::Arg::Text(now.clone()), crate::turso_queue::Arg::Text(now.clone()), + ]); + } else { + let _ = t.exec("UPDATE reprioritize_sync_outbox SET attempts = attempts + 1, available_at = ?, last_error_class = ?, updated_at = ? WHERE task_id = ? AND issue = ? AND state = 'pending'", &[ + crate::turso_queue::Arg::Text(crate::turso_queue::iso(crate::turso_queue::now_unix() + 30)), crate::turso_queue::Arg::Text(error_class.to_owned()), crate::turso_queue::Arg::Text(now.clone()), crate::turso_queue::Arg::Int(id), crate::turso_queue::Arg::Int(number), + ]); + } + let detail = json!({"error_class": error_class, "issue": number, "category": category}); + let _ = t.exec("INSERT INTO events (worker_id, task_id, kind, detail, created_at) VALUES ('queue-broker', ?, 'reprioritize_sync_pending', ?, ?)", &[ + crate::turso_queue::Arg::Int(id), crate::turso_queue::Arg::Text(detail.to_string()), crate::turso_queue::Arg::Text(now), + ]); + let _ = crate::log::info( + "queue-broker", + &format!("reprioritize GitHub sync pending for task {id}: {error_class}"), + ); + } +} + +/// Retry due sync intents before serving the next broker call. A +/// retry uses the latest task row (if it still exists), so a newer +/// reprioritize supersedes an older pending category cleanly. +fn retry_reprioritize_sync(st: &State, t: &crate::turso_queue::TursoBackend) { + let Ok(rows) = t.query_objs("SELECT task_id FROM reprioritize_sync_outbox WHERE state = 'pending' AND available_at <= ? ORDER BY id LIMIT 20", &[ + crate::turso_queue::Arg::Text(crate::turso_queue::now_iso()), + ], &[]) else { return }; + for r in rows { + let id = r.get("task_id").and_then(Value::as_i64).unwrap_or(0); + if let Ok(Some(row)) = crate::turso_queue::get_task(t, id) { + sync_reprioritized(st, t, &json!({"row": row})); + } + } +} + fn dispatch(st: &State, path: &str, req: &Value) -> Value { if let Err(e) = validate_durations(path, req) { return fail(2, e); @@ -684,7 +864,35 @@ fn dispatch(st: &State, path: &str, req: &Value) -> Value { .unwrap_or_default(); return fail(3, format!("queue backend not ready: {why}")); }; - let resp = crate::turso_queue::dispatch(turso, path, req); + retry_reprioritize_sync(st, turso); + // The worker id arrives over the broker's authenticated + // (X-Agent-Token) channel, like every other lifecycle + // verb — that is the authenticated caller identity the + // reprioritized event records as actor. A legacy `actor` + // string without a worker is promoted for back-compat; + // a caller-provided actor never overrides the worker. + let mut effective_req = req.clone(); + if path == "/reprioritize" { + let has_worker = effective_req + .get("worker") + .and_then(Value::as_str) + .is_some_and(|s| !s.trim().is_empty()); + if !has_worker { + if let Some(a) = effective_req + .get("actor") + .and_then(Value::as_str) + .map(str::to_owned) + { + if !a.trim().is_empty() { + effective_req["worker"] = json!(a); + } + } + } + } + let resp = crate::turso_queue::dispatch(turso, path, &effective_req); + if path == "/reprioritize" && resp.get("ok").and_then(Value::as_bool) == Some(true) { + sync_reprioritized(st, turso, &resp); + } // #8568: the broker-side needs-drew raise for an // escalated block (fire-and-forget). if path == "/block" { @@ -1457,3 +1665,72 @@ mod startup_retry_tests { assert!(start.elapsed() < Duration::from_secs(5)); } } + +#[cfg(test)] +mod reprioritize_sync_tests { + /// T3/T4 contract pins (#14100): the GitHub sync leg runs after + /// the queue commit, touches only priority/* labels, sets + /// lineage.priority only inside an existing pm-metadata block, + /// and records failures as pending + outbox without rolling + /// back the queue change. + const SRC: &str = include_str!("queue_broker.rs"); + + fn sync_fn() -> &'static str { + let start = SRC + .find("fn sync_reprioritized") + .expect("sync_reprioritized must exist"); + let rest = &SRC[start..]; + let end = rest + .find("\nfn retry_reprioritize_sync") + .expect("retry fn follows"); + &rest[..end] + } + + #[test] + fn sync_touches_only_priority_labels() { + let f = sync_fn(); + // Removal is scoped to priority/* labels, add is the mapped one. + assert!(f.contains("starts_with(\"priority/\")"), "{f}"); + // expedite/next-up are never in the sync write set. + assert!(!f.contains("expedite"), "must not touch expedite"); + assert!(!f.contains("next-up"), "must not touch next-up"); + } + + #[test] + fn sync_sets_lineage_only_inside_an_existing_block() { + let f = sync_fn(); + assert!(f.contains("pm-metadata:start"), "reads existing block"); + assert!( + f.contains("[\"lineage\"][\"priority\"]"), + "sets lineage.priority" + ); + assert!( + f.contains("get(\"lineage\").is_some_and(Value::is_object)"), + "never creates a block speculatively" + ); + } + + #[test] + fn queue_change_never_rolls_back_and_failure_is_recorded() { + // The sync runs only after a committed queue write. + assert!( + SRC.contains("if path == \"/reprioritize\" && resp.get(\"ok\")"), + "sync is post-commit only" + ); + let f = sync_fn(); + // Failure path: pending event + durable outbox row, and the + // success path clears the visible marker only when no newer + // reprioritize landed meanwhile. + assert!(f.contains("reprioritize_sync_pending"), "pending event"); + assert!( + f.contains("INSERT INTO reprioritize_sync_outbox"), + "durable intent" + ); + assert!( + f.contains("still_current"), + "no stale clear of a newer intent" + ); + // The retry runs ahead of serving, from the latest task row. + assert!(SRC.contains("retry_reprioritize_sync(st, turso)")); + } +} diff --git a/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs index 9e8ba47f9d..2b5a71dc88 100644 --- a/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs +++ b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs @@ -74,11 +74,11 @@ mod tests { /// The full backend source, concatenated across the #8589 /// module split (parent file last, so the cfg(test) marker - /// still terminates the production text). Production-only - /// modules come first; modules with inline test mods - /// (staleness, work_identity, closed_bound) come after, so - /// the first `#[cfg(test)]` in the concat stays behind every - /// production module the source-content tests read. + /// still terminates the production text). Each file is + /// truncated at its own first `#[cfg(test)]` so inline test + /// modules (staleness, work_identity, closed_bound, lifecycle + /// reprioritize_tests) never hide a later file's production + /// text from the source-content oracles. fn test_source() -> String { [ include_str!("turso_queue/core.rs"), @@ -92,6 +92,9 @@ mod tests { include_str!("turso_queue/closed_bound.rs"), include_str!("turso_queue.rs"), ] + .iter() + .map(|s| s.split("#[cfg(test)]").next().unwrap_or("")) + .collect::>() .concat() } use super::*; diff --git a/pkgs/fleet/crates/fleet-queue/src/turso_queue/core.rs b/pkgs/fleet/crates/fleet-queue/src/turso_queue/core.rs index 881cd05115..a04ee073ea 100644 --- a/pkgs/fleet/crates/fleet-queue/src/turso_queue/core.rs +++ b/pkgs/fleet/crates/fleet-queue/src/turso_queue/core.rs @@ -1015,7 +1015,7 @@ impl Clone for Arg { } } -pub(crate) const SCHEMA: [&str; 25] = [ +pub(crate) const SCHEMA: [&str; 27] = [ "CREATE TABLE IF NOT EXISTS tasks (\ id INTEGER PRIMARY KEY AUTOINCREMENT, \ queue TEXT NOT NULL, title TEXT, body TEXT, \ @@ -1087,6 +1087,17 @@ pub(crate) const SCHEMA: [&str; 25] = [ id INTEGER PRIMARY KEY CHECK (id = 1), \ consecutive_rate_limits INTEGER NOT NULL DEFAULT 0, \ open_until TEXT, last_error_class TEXT, updated_at TEXT NOT NULL)", + // #14100: durable retry for priority-category synchronization. + // This is intentionally separate from creation_outbox: reprioritize + // edits an existing issue and is not an issue-creation intent. + "CREATE TABLE IF NOT EXISTS reprioritize_sync_outbox (\ + id INTEGER PRIMARY KEY AUTOINCREMENT, task_id INTEGER NOT NULL, \ + repo TEXT NOT NULL, issue INTEGER NOT NULL, category TEXT NOT NULL, \ + label TEXT NOT NULL, state TEXT NOT NULL DEFAULT 'pending', \ + attempts INTEGER NOT NULL DEFAULT 0, available_at TEXT NOT NULL, \ + last_error_class TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL)", + "CREATE INDEX IF NOT EXISTS reprioritize_sync_due \ + ON reprioritize_sync_outbox(state, available_at)", // #8582 increment 2: the merge-intent table, DDL of record in // the pure core module. crate::merge_intent::MERGE_INTENT_DDL, 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 47e3dce1bb..8d4424712f 100644 --- a/pkgs/fleet/crates/fleet-queue/src/turso_queue/lifecycle.rs +++ b/pkgs/fleet/crates/fleet-queue/src/turso_queue/lifecycle.rs @@ -7,6 +7,107 @@ use super::*; +/// Change a live task's priority without changing any lifecycle/claim +/// fields. The row priority is authoritative; the packet mirror is +/// updated in the same SQL statement when it exists, and the event +/// records the snapshot used by the compare-and-swap guard. +pub(crate) fn verb_reprioritize(t: &TursoBackend, req: &Value) -> Value { + let id = req_i64(req, "task_id") + .or_else(|| req_i64(req, "id")) + .unwrap_or(0); + // Authenticated caller identity (#14100: the event's actor): the + // worker id presented over the broker's authenticated channel, + // exactly like the other lifecycle verbs. A legacy `actor` + // string is honored only when no worker is present (old + // clients); it is never trusted over the worker. + let actor = req_str(req, "worker") + .filter(|s| !s.trim().is_empty()) + .or_else(|| req_str(req, "actor")) + .unwrap_or("fleet-queue-cli"); + let reason = req_str(req, "reason") + .map(str::trim) + .filter(|s| !s.is_empty()); + let raw = req.get("priority").cloned().unwrap_or(Value::Null); + let to = match crate::validate::resolve_priority(&raw, "priority") { + Ok(n) => n, + Err(e) => return fail(2, e), + }; + let work = (|| -> Result { + let row = get_task(t, id) + .map_err(|e| e)? + .ok_or_else(|| format!("reprioritize_task: task {id} does not exist"))?; + let status = row.get("status").and_then(Value::as_str).unwrap_or(""); + if !["queued", "claimed", "parked", "blocked"].contains(&status) { + return Err(format!( + "reprioritize_task: task {id} is terminal ({status})" + )); + } + let from = row.get("priority").and_then(Value::as_i64).unwrap_or(90); + if from == to { + return Ok(row); + } + let payload = row.get("payload").cloned().unwrap_or(json!({})); + let payload_text = if payload.get("priority").is_some() { + let mut p = payload; + p["priority"] = json!(to); + Some(p.to_string()) + } else { + None + }; + let category = crate::validate::category_for_priority(to).unwrap_or("unknown"); + let issue = row + .get("payload") + .and_then(|p| p.get("issue")) + .cloned() + .unwrap_or(Value::Null); + let repo = row + .get("payload") + .and_then(|p| p.get("repo")) + .and_then(Value::as_str) + .filter(|r| !r.is_empty()); + let issue_number = issue + .get("number") + .and_then(Value::as_i64) + .filter(|n| *n > 0); + // Queue-only tasks (no linked issue) note that explicitly; + // linked tasks note the sync intent the broker will fulfill. + let sync_note = if repo.is_some() && issue_number.is_some() { + "github-pending" + } else { + "no issue linked" + }; + let detail = with_marks( + &json!({"from": from, "to": to, "category": category, "issue": issue, "actor": actor, "reason": reason, "sync": sync_note}), + &row, + ); + // One Turso pipeline transaction couples the guarded task + // mutation, packet mirror, and history event. The conditional + // event insert is gated by changes() from the CAS UPDATE. + let update = t.exec_batch(&[ + ("BEGIN IMMEDIATE", vec![]), + ("UPDATE tasks SET priority = ?, payload = CASE WHEN ? IS NULL THEN payload ELSE ? END, progress = CASE WHEN ? IS NOT NULL AND ? > 0 THEN json_set(COALESCE(progress, '{}'), '$.reprioritize_sync_pending', true) ELSE progress END, updated_at = ? WHERE id = ? AND priority = ? AND status IN ('queued','claimed','parked','blocked')", vec![Arg::Int(to), payload_text.clone().map(Arg::Text).unwrap_or(Arg::Null), payload_text.map(Arg::Text).unwrap_or(Arg::Null), repo.map(|s| Arg::Text(s.to_owned())).unwrap_or(Arg::Null), issue_number.map(Arg::Int).unwrap_or(Arg::Null), Arg::Text(now_iso()), Arg::Int(id), Arg::Int(from)]), + ("INSERT INTO events (worker_id, task_id, kind, detail, created_at) SELECT ?, ?, 'reprioritized', ?, ? WHERE changes() = 1", vec![Arg::Text(actor.to_string()), Arg::Int(id), Arg::Text(detail.to_string()), Arg::Text(now_iso())]), + // Persist the external side-effect intent in the same + // transaction. Queue-only tasks have no linked issue and + // intentionally produce no sync row. + ("INSERT INTO reprioritize_sync_outbox (task_id, repo, issue, category, label, state, attempts, available_at, created_at, updated_at) SELECT ?, ?, ?, ?, ?, 'pending', 0, ?, ?, ? WHERE changes() = 1 AND ? IS NOT NULL AND ? > 0", vec![Arg::Int(id), repo.map(|s| Arg::Text(s.to_owned())).unwrap_or(Arg::Null), issue_number.map(Arg::Int).unwrap_or(Arg::Null), Arg::Text(category.to_owned()), Arg::Text(crate::validate::label_for_priority(to).unwrap_or("priority/unknown").to_owned()), Arg::Text(now_iso()), Arg::Text(now_iso()), Arg::Text(now_iso()), repo.map(|s| Arg::Text(s.to_owned())).unwrap_or(Arg::Null), issue_number.map(Arg::Int).unwrap_or(Arg::Null)]), + ("COMMIT", vec![]), + ]).map_err(|e| e)?; + if update.get(1).map(|r| r.affected).unwrap_or(0) != 1 { + return Err(format!( + "reprioritize_task: task {id} priority changed concurrently; retry" + )); + } + get_task(t, id) + .map_err(|e| e)? + .ok_or_else(|| format!("reprioritize_task: task {id} disappeared")) + })(); + match work { + Ok(row) => ok(json!({"row": row})), + Err(e) => fail(2, e), + } +} + /// The session a lane row is *live*-bound to (#8368): the ledger /// session_id, unless the broker itself cleared that exact binding /// (progress.session_cleared.session_id, stamped by clear_binding @@ -2080,3 +2181,469 @@ pub(crate) fn verb_wake(t: &TursoBackend, req: &Value) -> Value { Err(e) => terr(e), } } + +// --------------------------------------------------------------------------- +// Tests (#14100): reprioritize T1–T7 against a rusqlite-backed fake of +// the Turso pipeline endpoint (the actions_exec proof-bar pattern — +// real SQL semantics, so the guarded CAS UPDATE, the claim order, +// and the lease/worker/attempts invariance are exercised, not +// mimicked). GitHub itself is not touched: the sync leg's contract +// (queue-first, priority/*-only labels, durable outbox + visible +// pending marker) is covered through the rows the verb commits +// atomically and the broker source pins in queue_broker.rs. +// --------------------------------------------------------------------------- + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod reprioritize_tests { + use super::*; + use std::io::{BufRead, BufReader, Read, Write}; + use std::sync::{Arc, Mutex}; + + fn fake_backend() -> (TursoBackend, Arc>) { + let conn = rusqlite::Connection::open_in_memory().unwrap(); + for ddl in SCHEMA { + conn.execute_batch(ddl).unwrap(); + } + let db = Arc::new(Mutex::new(conn)); + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let base = format!("http://{addr}"); + let db_thread = db.clone(); + std::thread::spawn(move || { + for sock in listener.incoming() { + let Ok(sock) = sock else { return }; + let db_conn = db_thread.clone(); + std::thread::spawn(move || handle_conn(sock, db_conn)); + } + }); + ( + TursoBackend::new(base, "test".to_string(), ureq::agent()), + db, + ) + } + + fn handle_conn(mut sock: std::net::TcpStream, db: Arc>) { + let mut reader = BufReader::new(sock.try_clone().unwrap()); + loop { + let mut request_line = String::new(); + if reader.read_line(&mut request_line).unwrap_or(0) == 0 { + return; + } + let mut content_length = 0usize; + loop { + let mut line = String::new(); + if reader.read_line(&mut line).unwrap_or(0) == 0 { + return; + } + let trimmed = line.trim(); + if trimmed.is_empty() { + break; + } + if let Some((name, value)) = trimmed.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() { + return; + } + let payload = run_pipeline(&db, &body); + let text = payload.to_string(); + let resp = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\ + Content-Length: {}\r\n\r\n{}", + text.len(), + text + ); + if sock.write_all(resp.as_bytes()).is_err() { + return; + } + } + } + + fn run_pipeline(db: &Arc>, body: &[u8]) -> Value { + let req: Value = serde_json::from_slice(body).unwrap_or(Value::Null); + let conn = db.lock().unwrap(); + let mut results = Vec::new(); + for r in req + .get("requests") + .and_then(|v| v.as_array()) + .cloned() + .unwrap_or_default() + { + match r.get("type").and_then(|v| v.as_str()) { + Some("close") => { + results.push(json!({"type": "ok", "response": {"type": "close"}})); + } + Some("execute") => { + let stmt = r.get("stmt").cloned().unwrap_or(Value::Null); + let sql = stmt.get("sql").and_then(|v| v.as_str()).unwrap_or(""); + let mut params: Vec = Vec::new(); + if let Some(args) = stmt.get("args").and_then(|v| v.as_array()) { + for a in args { + params.push(match a.get("type").and_then(|v| v.as_str()) { + Some("text") => rusqlite::types::Value::Text( + a.get("value") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(), + ), + Some("integer") => rusqlite::types::Value::Integer( + a.get("value") + .and_then(|v| v.as_str()) + .and_then(|s| s.parse().ok()) + .unwrap_or(0), + ), + _ => rusqlite::types::Value::Null, + }); + } + } + results.push(execute_sql(&conn, sql, ¶ms)); + } + _ => {} + } + } + json!({"results": results, "baton": null}) + } + + fn cell_json(v: rusqlite::types::ValueRef) -> Value { + use rusqlite::types::ValueRef::*; + match v { + Null => json!({"type": "null"}), + Integer(i) => json!({"type": "integer", "value": i.to_string()}), + Real(f) => json!({"type": "float", "value": f}), + Text(s) => json!({"type": "text", "value": String::from_utf8_lossy(s)}), + Blob(b) => json!({"type": "blob", "value": hex_encode(b)}), + } + } + + fn hex_encode(data: &[u8]) -> String { + data.iter().map(|b| format!("{b:02x}")).collect() + } + + fn execute_sql( + conn: &rusqlite::Connection, + sql: &str, + params: &[rusqlite::types::Value], + ) -> Value { + let is_query = sql.trim_start().to_ascii_uppercase().starts_with("SELECT"); + // BEGIN/COMMIT are connection state, not preparable statements. + if !is_query { + let head = sql.trim_start().to_ascii_uppercase(); + if head.starts_with("BEGIN") { + return match conn.execute_batch(sql) { + Ok(()) => json!({"type": "ok", "response": {"type": "execute", "result": { + "cols": [], "rows": [], "affected_row_count": 0, "last_insert_rowid": null}}}), + Err(e) => { + json!({"type": "error", "error": {"message": e.to_string(), "code": "SQLITE"}}) + } + }; + } + if head.starts_with("COMMIT") || head.starts_with("ROLLBACK") { + return match conn.execute_batch(sql) { + Ok(()) => json!({"type": "ok", "response": {"type": "execute", "result": { + "cols": [], "rows": [], "affected_row_count": 0, "last_insert_rowid": null}}}), + Err(e) => { + json!({"type": "error", "error": {"message": e.to_string(), "code": "SQLITE"}}) + } + }; + } + } + let mut stmt = match conn.prepare(sql) { + Ok(s) => s, + Err(e) => { + return json!({"type": "error", "error": {"message": e.to_string(), "code": "SQLITE"}}); + } + }; + if is_query { + let cols: Vec = stmt.column_names().map(|s| s.to_string()).collect(); + let mut rows_out = Vec::new(); + match stmt.query(rusqlite::params_from_iter(params.iter())) { + Ok(mut rows) => loop { + match rows.next() { + Ok(Some(row)) => { + let mut cells = Vec::new(); + for i in 0..cols.len() { + cells.push(cell_json(row.get_ref(i).unwrap())); + } + rows_out.push(Value::Array(cells)); + } + Ok(None) => break, + Err(e) => { + return json!({"type": "error", "error": {"message": e.to_string(), "code": "SQLITE"}}); + } + } + }, + Err(e) => { + return json!({"type": "error", "error": {"message": e.to_string(), "code": "SQLITE"}}); + } + } + json!({"type": "ok", "response": {"type": "execute", "result": { + "cols": cols.iter().map(|c| json!({"name": c, "decltype": null})).collect::>(), + "rows": rows_out, "affected_row_count": 0, "last_insert_rowid": null}}}) + } else { + match stmt.execute(rusqlite::params_from_iter(params.iter())) { + Ok(changed) => json!({"type": "ok", "response": {"type": "execute", "result": { + "cols": [], "rows": [], "affected_row_count": changed, + "last_insert_rowid": conn.last_insert_rowid().to_string()}}}), + Err(e) => { + json!({"type": "error", "error": {"message": e.to_string(), "code": "SQLITE"}}) + } + } + } + } + + /// Seed one live task row; returns its id. + fn seed_task( + t: &TursoBackend, + status: &str, + priority: i64, + payload: Value, + worker: Option<&str>, + ) -> i64 { + let payload_text = payload.to_string(); + let r = t + .exec( + "INSERT INTO tasks (queue, title, payload, priority, status, worker_id, lease_until, attempts, progress, created_at, updated_at) \ + VALUES ('repo-health-code-pilot', 't', ?, ?, ?, ?, ?, 0, '{}', ?, ?)", + &[ + Arg::Text(payload_text), + Arg::Int(priority), + Arg::Text(status.to_string()), + worker.map(|w| Arg::Text(w.to_string())).unwrap_or(Arg::Null), + if worker.is_some() { + Arg::Text("2026-11-24T02:00:00Z".to_string()) + } else { + Arg::Null + }, + Arg::Text("2026-11-24T01:00:00Z".to_string()), + Arg::Text("2026-11-24T01:00:00Z".to_string()), + ], + ) + .unwrap(); + r.last_insert_rowid.unwrap() + } + + fn events_for(t: &TursoBackend, task_id: i64, kind: &str) -> Vec { + t.query_objs( + "SELECT id, worker_id, task_id, kind, detail, created_at FROM events WHERE task_id = ? AND kind = ? ORDER BY id", + &[Arg::Int(task_id), Arg::Text(kind.to_string())], + &[], + ) + .unwrap() + } + + /// T6a: terminal states are refused. + #[test] + fn terminal_tasks_are_refused() { + let (t, _) = fake_backend(); + for status in ["done", "failed", "cancelled"] { + let id = seed_task(&t, status, 90, json!({}), None); + let out = verb_reprioritize(&t, &json!({"task_id": id, "priority": 20, "worker": "w"})); + assert_eq!(out["ok"], false, "{status}: {out}"); + assert!( + out["error"].as_str().unwrap_or("").contains("terminal"), + "{status}: {out}" + ); + assert!(events_for(&t, id, "reprioritized").is_empty()); + } + } + + /// T6b: off-scale targets are refused with the scale error. + #[test] + fn off_scale_targets_are_refused() { + let (t, _) = fake_backend(); + let id = seed_task(&t, "queued", 90, json!({}), None); + for bad in [json!(15), json!(25), json!(5), json!(99), json!("high")] { + let out = + verb_reprioritize(&t, &json!({"task_id": id, "priority": bad, "worker": "w"})); + assert_eq!(out["ok"], false, "{bad}: {out}"); + assert!( + out["error"].as_str().unwrap_or("").contains("design scale"), + "{bad}: {out}" + ); + } + // The row is untouched by every refusal. + let row = get_task(&t, id).unwrap().unwrap(); + assert_eq!(row["priority"], 90); + assert!(events_for(&t, id, "reprioritized").is_empty()); + } + + /// T2: the reprioritized event carries from/to/category/actor and + /// lands in the same transaction as the row change. + #[test] + fn history_event_carries_from_to_category_actor() { + let (t, _) = fake_backend(); + let id = seed_task( + &t, + "queued", + 90, + json!({"repo": "developing-today/code", "issue": {"number": 1}}), + None, + ); + let out = verb_reprioritize( + &t, + &json!({"task_id": id, "priority": 20, "worker": "conductor", "reason": "hot"}), + ); + assert_eq!(out["ok"], true, "{out}"); + let evs = events_for(&t, id, "reprioritized"); + assert_eq!(evs.len(), 1, "{evs:?}"); + let detail: Value = serde_json::from_str(evs[0]["detail"].as_str().unwrap()).unwrap(); + assert_eq!(detail["from"], 90); + assert_eq!(detail["to"], 20); + assert_eq!(detail["category"], "high"); + assert_eq!(detail["actor"], "conductor"); + assert_eq!(detail["reason"], "hot"); + assert_eq!(detail["task_id"], id); + assert_eq!(detail["sync"], "github-pending"); + } + + /// T5: a claimed task changes priority only — lease, worker and + /// attempts are byte-identical before and after. + #[test] + fn claimed_task_changes_priority_only() { + let (t, _) = fake_backend(); + let id = seed_task(&t, "claimed", 90, json!({}), Some("holder-1")); + t.exec( + "UPDATE tasks SET attempts = 3 WHERE id = ?", + &[Arg::Int(id)], + ) + .unwrap(); + let before = get_task(&t, id).unwrap().unwrap(); + let out = verb_reprioritize( + &t, + &json!({"task_id": id, "priority": 30, "worker": "conductor"}), + ); + assert_eq!(out["ok"], true, "{out}"); + let after = get_task(&t, id).unwrap().unwrap(); + assert_eq!(after["priority"], 30); + for k in ["worker_id", "lease_until", "attempts", "status"] { + assert_eq!(after[k], before[k], "column {k} moved"); + } + } + + /// T7: the stored packet's payload.priority copy moves with the + /// row, and the row still passes claim-guard revalidation. + #[test] + fn packet_copy_moves_with_row() { + let (t, _) = fake_backend(); + let id = seed_task( + &t, + "queued", + 90, + json!({"priority": 90, "repo": "developing-today/code", "issue": {"number": 2}}), + None, + ); + let out = verb_reprioritize(&t, &json!({"task_id": id, "priority": 40, "worker": "w"})); + assert_eq!(out["ok"], true, "{out}"); + let row = get_task(&t, id).unwrap().unwrap(); + assert_eq!(row["priority"], 40); + assert_eq!(row["payload"]["priority"], 40); + // Claim-guard revalidation: the row priority is on-scale and + // the packet mirror agrees. + assert!(crate::validate::PRIORITY_SCALE.contains(&row["priority"].as_i64().unwrap())); + // A task without a stored priority copy leaves payload alone. + let bare = seed_task( + &t, + "parked", + 90, + json!({"repo": "developing-today/code"}), + None, + ); + let out = verb_reprioritize(&t, &json!({"task_id": bare, "priority": 20, "worker": "w"})); + assert_eq!(out["ok"], true, "{out}"); + let row = get_task(&t, bare).unwrap().unwrap(); + assert_eq!(row["priority"], 20); + assert!(row["payload"].get("priority").is_none()); + // Queue-only change notes that no issue is linked. + let evs = events_for(&t, bare, "reprioritized"); + assert_eq!(evs.len(), 1); + let detail: Value = serde_json::from_str(evs[0]["detail"].as_str().unwrap()).unwrap(); + assert_eq!(detail["sync"], "no issue linked"); + } + + /// T1: reprioritizing the later task above the earlier one flips + /// the next-claim order (claims read priority ASC). + #[test] + fn reprioritize_flips_claim_order() { + let (t, _) = fake_backend(); + let early = seed_task(&t, "queued", 70, json!({}), None); + let late = seed_task(&t, "queued", 90, json!({}), None); + let first_before: Vec = t + .query_objs( + "SELECT id FROM tasks WHERE status = 'queued' ORDER BY priority ASC, id ASC LIMIT 1", + &[], + &[], + ) + .unwrap(); + assert_eq!(first_before[0]["id"], early); + let out = verb_reprioritize(&t, &json!({"task_id": late, "priority": 20, "worker": "w"})); + assert_eq!(out["ok"], true, "{out}"); + let first_after: Vec = t + .query_objs( + "SELECT id FROM tasks WHERE status = 'queued' ORDER BY priority ASC, id ASC LIMIT 1", + &[], + &[], + ) + .unwrap(); + assert_eq!(first_after[0]["id"], late); + } + + /// T4: the queue change commits its durable sync intent in the + /// same transaction and marks the row visibly pending — so a + /// GitHub-leg failure can never silently drop the sync. + #[test] + fn sync_intent_is_atomic_and_visible() { + let (t, _) = fake_backend(); + let id = seed_task( + &t, + "blocked", + 90, + json!({"priority": 90, "repo": "developing-today/code", "issue": {"number": 14100}}), + None, + ); + let out = verb_reprioritize(&t, &json!({"task_id": id, "priority": 10, "worker": "w"})); + assert_eq!(out["ok"], true, "{out}"); + // The row carries the visible pending marker fleet queue show reads. + // (json_set stores the boolean as 1 — the production readback shape.) + let row = get_task(&t, id).unwrap().unwrap(); + assert_eq!(row["priority"], 10); + assert!( + row["progress"]["reprioritize_sync_pending"] == json!(1) + || row["progress"]["reprioritize_sync_pending"] == json!(true), + "pending marker missing: {}", + row["progress"] + ); + // The durable outbox intent for the mapped category+label. + let rows = t + .query_objs( + "SELECT task_id, repo, issue, category, label, state FROM reprioritize_sync_outbox WHERE task_id = ?", + &[Arg::Int(id)], + &[], + ) + .unwrap(); + assert_eq!(rows.len(), 1, "{rows:?}"); + assert_eq!(rows[0]["repo"], "developing-today/code"); + assert_eq!(rows[0]["issue"], 14100); + assert_eq!(rows[0]["category"], "critical"); + assert_eq!(rows[0]["label"], "priority/critical"); + assert_eq!(rows[0]["state"], "pending"); + // Queue-only tasks produce no sync row and no pending marker. + let bare = seed_task(&t, "queued", 90, json!({}), None); + let out = verb_reprioritize(&t, &json!({"task_id": bare, "priority": 20, "worker": "w"})); + assert_eq!(out["ok"], true, "{out}"); + let row = get_task(&t, bare).unwrap().unwrap(); + assert!(row["progress"].get("reprioritize_sync_pending").is_none()); + let rows = t + .query_objs( + "SELECT task_id FROM reprioritize_sync_outbox WHERE task_id = ?", + &[Arg::Int(bare)], + &[], + ) + .unwrap(); + assert!(rows.is_empty()); + } +} diff --git a/pkgs/fleet/crates/fleet-queue/src/turso_queue/stacks_outbox.rs b/pkgs/fleet/crates/fleet-queue/src/turso_queue/stacks_outbox.rs index e1202aae91..2480844351 100644 --- a/pkgs/fleet/crates/fleet-queue/src/turso_queue/stacks_outbox.rs +++ b/pkgs/fleet/crates/fleet-queue/src/turso_queue/stacks_outbox.rs @@ -1024,6 +1024,7 @@ pub fn dispatch(t: &TursoBackend, path: &str, req: &Value) -> Value { "/park" => verb_park(t, req), "/release" => verb_release(t, req), "/wake" => verb_wake(t, req), + "/reprioritize" => verb_reprioritize(t, req), "/block" => verb_block(t, req), "/unblock" => verb_unblock(t, req), "/dep-recheck" => verb_dep_recheck(t, req), diff --git a/pkgs/fleet/crates/fleet-queue/src/validate.rs b/pkgs/fleet/crates/fleet-queue/src/validate.rs index 9ec839c6d5..586465340b 100644 --- a/pkgs/fleet/crates/fleet-queue/src/validate.rs +++ b/pkgs/fleet/crates/fleet-queue/src/validate.rs @@ -68,6 +68,63 @@ use serde_json::{Value, json}; use std::time::{SystemTime, UNIX_EPOCH}; pub const PRIORITY_SCALE: [i64; 7] = [10, 20, 30, 40, 50, 70, 90]; +/// The numeric→category mapping for #14100 (from the issue spec's +/// table, derived from the scale, the label descriptions, and the +/// 2026-11-12 census bands): 10 → critical; 20/30 (and stored +/// 15/25 from #7030) → high; 40/50 → normal; 70/90 → low. +/// Defined over ranges so any stored value resolves +/// deterministically: ≤10 critical · 11–30 high · 31–50 normal · +/// ≥51 low. `expedite` and `next-up` are separate labels with +/// their own enqueue-time derivations, never priority categories. +pub fn category_for_priority(n: i64) -> Option<&'static str> { + if n <= 10 { + Some("critical") + } else if n <= 30 { + Some("high") + } else if n <= 50 { + Some("normal") + } else { + Some("low") + } +} + +/// GitHub label for a queue priority number (#14100): the mapped +/// category rendered as `priority/`. Total over the same +/// range domain as `category_for_priority`, so stored off-scale +/// values (15/25) resolve to their band label. +pub fn label_for_priority(n: i64) -> Option<&'static str> { + match category_for_priority(n) { + Some("critical") => Some("priority/critical"), + Some("high") => Some("priority/high"), + Some("normal") => Some("priority/normal"), + Some("low") => Some("priority/low"), + _ => None, + } +} + +/// Resolve a user-supplied reprioritize target (#14100): an integer +/// on PRIORITY_SCALE (numeric strings are accepted and parsed). +/// Off-scale is rejected with the existing scale error; category +/// names are not accepted — the CLI takes a number, and the +/// category is derived from it. +pub fn resolve_priority(input: &serde_json::Value, field: &str) -> Result { + let n = match input { + serde_json::Value::Number(n) => n.as_i64(), + serde_json::Value::String(s) => s.trim().parse::().ok(), + _ => None, + }; + match n { + Some(v) if PRIORITY_SCALE.contains(&v) => Ok(v), + Some(v) => Err(format!( + "{field}: {v} is not on the design scale {:?}", + PRIORITY_SCALE + )), + None => Err(format!( + "{field}: must be an integer on the design scale {:?} (10, 20, 30, 40, 50, 70, 90)", + PRIORITY_SCALE + )), + } +} /// #7030: Drew's ratified label bands (ratified 2026-11-07): an issue /// carrying the `expedite` label queues at priority 15 (the 10–20 /// band) and one carrying `next-up` at 25 (the 20–30 band). These are @@ -1370,6 +1427,49 @@ pub fn task_from_packet(packet: &Value, queue: &str) -> Value { #[cfg(test)] mod tests { + use super::*; + #[test] + fn reprioritize_scale_and_category_mapping() { + // #14100: the design scale is exactly these seven numbers. + assert_eq!(PRIORITY_SCALE, [10, 20, 30, 40, 50, 70, 90]); + // Spec table: 10 critical; 20/30 high; 40/50 normal; 70/90 low. + assert_eq!(category_for_priority(10), Some("critical")); + assert_eq!(label_for_priority(10), Some("priority/critical")); + for n in [20, 30] { + assert_eq!(category_for_priority(n), Some("high"), "{n}"); + assert_eq!(label_for_priority(n), Some("priority/high"), "{n}"); + } + for n in [40, 50] { + assert_eq!(category_for_priority(n), Some("normal"), "{n}"); + assert_eq!(label_for_priority(n), Some("priority/normal"), "{n}"); + } + for n in [70, 90] { + assert_eq!(category_for_priority(n), Some("low"), "{n}"); + assert_eq!(label_for_priority(n), Some("priority/low"), "{n}"); + } + // Stored off-scale values resolve to their band (high). + for n in [15, 25] { + assert_eq!(category_for_priority(n), Some("high"), "{n}"); + assert_eq!(label_for_priority(n), Some("priority/high"), "{n}"); + assert!( + resolve_priority(&json!(n), "priority").is_err(), + "{n} is stored-only, never a valid target" + ); + } + // Every scale number resolves; off-scale numbers are refused + // with the scale error; non-numeric input is refused. + for n in PRIORITY_SCALE { + assert_eq!(resolve_priority(&json!(n), "priority").unwrap(), n); + assert_eq!( + resolve_priority(&json!(n.to_string()), "priority").unwrap(), + n + ); + } + for bad in [5, 15, 25, 60, 80, 100] { + assert!(resolve_priority(&json!(bad), "priority").is_err(), "{bad}"); + } + assert!(resolve_priority(&json!("high"), "priority").is_err()); + } /// #13177: the published packet schema (pkgs/fleet/repo-task-v1.schema.json) /// and this validator must agree on the kind and repo enums. The /// validator is canonical: KINDS carries second_pass/feature_slice