GeezerVison is showing github.com — fleet-queue: tasks.labels cache, label sweep and list --label (#14170… · developing-today/code@d79e4af
File treeExpand file treeCollapse file tree Open diff view settings pkgs/fleet/crates/fleet-queue/src
Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: pkgs/fleet/crates/fleet-queue/src/client/commands_query.rs +4Lines changed: 4 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -254,6 +254,7 @@ pub(super) fn cmd_list(rest: &[String]) -> i32 { | 254 | 254 | "lane", | 255 | 255 | "worker", | 256 | 256 | "task", | | 257 | + "label", | 257 | 258 | ], | 258 | 259 | &["json"], | 259 | 260 | ); | @@ -304,6 +305,7 @@ pub(super) fn cmd_list(rest: &[String]) -> i32 { | 304 | 305 | "lane": args.get("lane"), | 305 | 306 | "worker": args.get("worker"), | 306 | 307 | "task": args.get_i64("task"), | | 308 | + "label": args.get("label"), | 307 | 309 | }), | 308 | 310 | ); | 309 | 311 | let resp = unwrap_ok(resp); | @@ -450,6 +452,8 @@ pub(super) fn cmd_show(rest: &[String]) -> i32 { | 450 | 452 | "claim_session_id", | 451 | 453 | "issue", | 452 | 454 | "pr", | | 455 | + "labels", | | 456 | + "labels_synced_at", | 453 | 457 | "progress", | 454 | 458 | ] { | 455 | 459 | let payload = task.get("payload"); | |
Collapse file Copy file name to clipboardExpand all lines: pkgs/fleet/crates/fleet-queue/src/client/support.rs +2-2Lines changed: 2 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -189,7 +189,7 @@ usage: repo-queue <verb> ...\n\ | 189 | 189 | Run `repo-queue <verb> --help` for flags:\n\ | 190 | 190 | validate <packet-path>\n\ | 191 | 191 | enqueue <packet-path> [--queue <name>] [--platform <p>] [--dry-run] [--shadow-intent]\n\ | 192 | | - list [--queue <name>] [--status <s>] [--limit <n>] [--not-before <ts>] [--lane <l>] [--worker <w>] [--task <id>] [--json]\n\ | | 192 | + list [--queue <name>] [--status <s>] [--limit <n>] [--not-before <ts>] [--lane <l>] [--worker <w>] [--task <id>] [--label <name|prefix*>] [--json]\n\ | 193 | 193 | claim [--queue <name>] [--worker <id>] [--lease-seconds <n>] [--lane <l>] [--task <id>] [--count <n>] [--from-session <id>] [--platform <p>] [--session-id <id>] [--model-provider <p>] [--model-id <id>] [--model-variant <v>] [--filter <f>] [--pool <p>] [--launched-by <who>] [--remaining-budget-minutes <n>] [--handoff] [--bind]\n\ | 194 | 194 | release <task-id> [--worker <id>] [--lane <id>] --reason <text>\n\ | 195 | 195 | lane <task-id> [--worker <id>] [--exclusion-reason <text>] [--opencode-reason <text>] [--limit-platform <p>] [--limit-reason <text>] [--clear-platform-limit]\n\ | @@ -232,7 +232,7 @@ pub(crate) fn usage(verb: &str) -> &'static str { | 232 | 232 | "usage: repo-queue enqueue <packet-path> [--queue <name>] [--platform <p>] [--dry-run] [--shadow-intent]\n\nEnqueues a task packet." | 233 | 233 | } | 234 | 234 | "list" => { | 235 | | - "usage: repo-queue list [--queue <name>] [--status <s>] [--limit <n>] [--not-before <ts>] [--lane <l>] [--worker <w>] [--task <id>] [--json]\n\nLists tasks; a bare `list` shows one queue in the broker's default ordering (newest terminal rows first) — pass --status queued|parked|claimed|blocked for actionable work. With --json, --queue and --task are required together: one scoped broker read printed as a single JSON record (result found / not_found / partial / unknown, with the mode and route used); no other list flag applies in that form." | | 235 | + "usage: repo-queue list [--queue <name>] [--status <s>] [--limit <n>] [--not-before <ts>] [--lane <l>] [--worker <w>] [--task <id>] [--label <name|prefix*>] [--json]\n\nLists tasks; a bare `list` shows one queue in the broker's default ordering (newest terminal rows first) — pass --status queued|parked|claimed|blocked for actionable work. --label filters on the task's cached GitHub labels (a trailing * matches a prefix, e.g. user/*). With --json, --queue and --task are required together: one scoped broker read printed as a single JSON record (result found / not_found / partial / unknown, with the mode and route used); no other list flag applies in that form." | 236 | 236 | } | 237 | 237 | "claim" => { | 238 | 238 | "usage: repo-queue claim [--queue <name>] [--worker <id>] [--lease-seconds <n>] [--lane <l>] [--task <id>] [--count <n>] [--from-session <id>] [--platform <p>] [--session-id <id>] [--model-provider <p>] [--model-id <id>] [--model-variant <v>] [--filter <f>] [--pool <p>] [--launched-by <who>] [--remaining-budget-minutes <n>] [--handoff] [--bind]\n\nClaims the highest-priority eligible task." | |
Collapse file Copy file name to clipboardExpand all lines: pkgs/fleet/crates/fleet-queue/src/turso_queue/admin.rs +11-2Lines changed: 11 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -1432,7 +1432,7 @@ pub(crate) fn verb_list(t: &TursoBackend, req: &Value) -> Value { | 1432 | 1432 | "id, queue, title, priority, status, dedupe_key, created_at, not_before, \ | 1433 | 1433 | worker_id, claimed_at, lease_until, lane_id, platform, attempts, max_attempts, \ | 1434 | 1434 | claim_provider, claim_model, claim_variant, claim_session_id, progress, payload, \ | 1435 | | - blocked_deps, dep_next_recheck_at, dep_blocked_until" | | 1435 | + blocked_deps, dep_next_recheck_at, dep_blocked_until, labels, labels_synced_at" | 1436 | 1436 | } else { | 1437 | 1437 | "id, queue, title, priority, status, dedupe_key, created_at, not_before, platform" | 1438 | 1438 | }; | @@ -1477,12 +1477,21 @@ pub(crate) fn verb_list(t: &TursoBackend, req: &Value) -> Value { | 1477 | 1477 | conds += " AND dedupe_key = ?"; | 1478 | 1478 | args.push(Arg::Text(d.to_string())); | 1479 | 1479 | } | | 1480 | + // #14170 Q5: --label narrows to tasks whose cached label set | | 1481 | + // holds that label; a trailing `*` matches a prefix (`user/*`). | | 1482 | + // The cache is refreshed at every transition and by the hourly | | 1483 | + // sweep; `labels_synced_at` on the rich row shows its age. | | 1484 | + if let Some(l) = req_str(req, "label").filter(|l| !l.is_empty()) { | | 1485 | + let (cond, arg) = label_filter_cond(l); | | 1486 | + conds += cond; | | 1487 | + args.push(arg); | | 1488 | + } | 1480 | 1489 | let offset = crate::client::list_offset_or_default(req_i64(req, "offset")); | 1481 | 1490 | let sql = format!( | 1482 | 1491 | "SELECT {select} FROM tasks{conds} ORDER BY (priority IS NULL), priority ASC, created_at ASC, id ASC LIMIT {limit} OFFSET {offset}" | 1483 | 1492 | ); | 1484 | 1493 | let json_cols: &[&str] = if rich { | 1485 | | - &["progress", "payload", "blocked_deps"] | | 1494 | + &["progress", "payload", "blocked_deps", "labels"] | 1486 | 1495 | } else { | 1487 | 1496 | &[] | 1488 | 1497 | }; | |
Collapse file Copy file name to clipboardExpand all lines: pkgs/fleet/crates/fleet-queue/src/turso_queue/core.rs +27-1Lines changed: 27 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -907,6 +907,12 @@ impl TursoBackend { | 907 | 907 | ("dep_blocked_until", "TEXT"), | 908 | 908 | ("dep_recheck_seconds", "INTEGER"), | 909 | 909 | ("required_budget_minutes", "INTEGER"), | | 910 | + // #14170 Q5: the label cache (mirror's JSON array of | | 911 | + // names) and its sync stamp. Existing rows read `[]` and | | 912 | + // NULL — "never synced" — until a transition or the | | 913 | + // label sweep copies them from the mirror. | | 914 | + ("labels", "TEXT NOT NULL DEFAULT '[]'"), | | 915 | + ("labels_synced_at", "TEXT"), | 910 | 916 | ] { | 911 | 917 | let has = cols | 912 | 918 | .iter() | @@ -1039,7 +1045,8 @@ pub(crate) const SCHEMA: [&str; 34] = [ | 1039 | 1045 | created_at TEXT NOT NULL, updated_at TEXT NOT NULL, \ | 1040 | 1046 | completed_at TEXT, \ | 1041 | 1047 | blocked_deps TEXT, dep_next_recheck_at TEXT, dep_blocked_until TEXT, \ | 1042 | | - dep_recheck_seconds INTEGER)", | | 1048 | + dep_recheck_seconds INTEGER, \ | | 1049 | + labels TEXT NOT NULL DEFAULT '[]', labels_synced_at TEXT)", | 1043 | 1050 | // NOT unique: the PG data itself carries duplicate (queue, dedupe_key) | 1044 | 1051 | // pairs from before dedupe was enforced, and the backup load must | 1045 | 1052 | // accept them as-is; enqueue dedupe is a read-then-insert check. | @@ -1422,6 +1429,13 @@ pub(crate) fn event( | 1422 | 1429 | ), | 1423 | 1430 | ("COMMIT", vec![]), | 1424 | 1431 | ])?; | | 1432 | + // #14170 Q5: every transition refreshes the task's label cache | | 1433 | + // from the mirror, after the transition has committed. Fail-open: | | 1434 | + // the mirror never gates work (#8575), so a missing mirror table | | 1435 | + // or a failed read leaves the cache as it was. | | 1436 | + if let Some(id) = task_id { | | 1437 | + let _ = refresh_task_labels(t, id); | | 1438 | + } | 1425 | 1439 | Ok(()) | 1426 | 1440 | } | 1427 | 1441 |
| @@ -1930,6 +1944,18 @@ pub(crate) fn verb_sweep(t: &TursoBackend, req: &Value) -> Value { | 1930 | 1944 | if let Some(s) = closed_bound_summary { | 1931 | 1945 | out["closed_bound"] = s; | 1932 | 1946 | } | | 1947 | + // #14170 Q5: the label cache sweep rides the sweep, at most | | 1948 | + // hourly (a checkpoint records the last pass), over | | 1949 | + // actionable statuses only. It never fails the sweep. Opt | | 1950 | + // out per call: labels_sync=false; labels_sync_force=true | | 1951 | + // runs it regardless of the interval. | | 1952 | + if req_bool(req, "labels_sync").unwrap_or(true) { | | 1953 | + if let Some(s) = | | 1954 | + sweep_task_labels(t, req_bool(req, "labels_sync_force").unwrap_or(false)) | | 1955 | + { | | 1956 | + out["labels_sync"] = s; | | 1957 | + } | | 1958 | + } | 1933 | 1959 | if expired > 0 | 1934 | 1960 | || do_revalidate | 1935 | 1961 | || do_prune | |
Collapse file Copy file name to clipboardExpand all lines: pkgs/fleet/crates/fleet-queue/src/turso_queue/label_enrich.rs +218Lines changed: 218 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -168,3 +168,221 @@ pub(crate) fn enrich_payload_labels( | 168 | 168 | pub(crate) fn band_or_inherited(payload: &Value, inherited: Option<i64>) -> Option<i64> { | 169 | 169 | crate::validate::label_band_priority(payload).or(inherited) | 170 | 170 | } | | 171 | + | | 172 | +// --------------------------------------------------------------------------- | | 173 | +// #14170 Q5 — the task-row label cache (`tasks.labels`) | | 174 | +// --------------------------------------------------------------------------- | | 175 | +// | | 176 | +// The mirror stays the source of truth for an issue's current GitHub | | 177 | +// labels; `tasks.labels` is a cache for the readers that cannot join | | 178 | +// per row (list filtering, held-set audits). It holds the mirror's | | 179 | +// exact shape (a JSON array of names) and `labels_synced_at` stamps | | 180 | +// the moment it was copied, so a reader sees staleness instead of | | 181 | +// trusting silently. A task whose issue has no mirror row keeps its | | 182 | +// `[]` and a NULL stamp, which reads honestly as "never synced". | | 183 | +// | | 184 | +// Refresh moments: every lifecycle transition (core::event, which | | 185 | +// covers enqueue and claim), plus the hourly actionable-only sweep | | 186 | +// that rides /sweep, plus /labels-sync on demand (`all: true` is | | 187 | +// the one-off backfill over every task). Every refresh is fail-open: | | 188 | +// the mirror is a read model and never gates work (#8575). | | 189 | + | | 190 | +/// Statuses the hourly sweep keeps fresh: the items a reader is about | | 191 | +/// to act on. Terminal rows are refreshed only by `/labels-sync` with | | 192 | +/// `all: true`. | | 193 | +pub(crate) const LABEL_SYNC_STATUSES: [&str; 4] = ["queued", "claimed", "parked", "blocked"]; | | 194 | + | | 195 | +/// How long the sweep waits between label passes (seconds). | | 196 | +pub(crate) const LABEL_SYNC_INTERVAL_SECONDS: i64 = 3600; | | 197 | + | | 198 | +/// One task's cache refresh from the mirror. Binds: repo, number, | | 199 | +/// synced_at, task id, repo, number. Writes nothing (and leaves the | | 200 | +/// stamp alone) when the mirror has no row for the issue; a mirror | | 201 | +/// row whose labels are absent or not a JSON array caches `[]`. | | 202 | +pub(crate) const LABELS_REFRESH_SQL: &str = "UPDATE tasks SET \ | | 203 | + labels = COALESCE((SELECT CASE WHEN json_valid(m.labels) AND json_type(m.labels) = 'array' \ | | 204 | + THEN m.labels ELSE '[]' END FROM github_mirror_issues m WHERE m.repo = ? AND m.number = ?), '[]'), \ | | 205 | + labels_synced_at = ? \ | | 206 | + WHERE id = ? AND EXISTS (SELECT 1 FROM github_mirror_issues m WHERE m.repo = ? AND m.number = ?)"; | | 207 | + | | 208 | +/// The bound arguments for LABELS_REFRESH_SQL. | | 209 | +pub(crate) fn labels_refresh_args(task_id: i64, repo: &str, number: i64, synced_at: &str) -> Vec<Arg> { | | 210 | + vec![ | | 211 | + Arg::Text(repo.to_string()), | | 212 | + Arg::Int(number), | | 213 | + Arg::Text(synced_at.to_string()), | | 214 | + Arg::Int(task_id), | | 215 | + Arg::Text(repo.to_string()), | | 216 | + Arg::Int(number), | | 217 | + ] | | 218 | +} | | 219 | + | | 220 | +/// The issue ref of a stored task row (payload + dedupe_key), by the | | 221 | +/// same rule enqueue enrichment uses. | | 222 | +fn row_issue_ref(row: &Value) -> Option<(String, i64)> { | | 223 | + let payload = match row.get("payload") { | | 224 | + Some(Value::String(s)) => serde_json::from_str::<Value>(s).unwrap_or(Value::Null), | | 225 | + Some(v) => v.clone(), | | 226 | + None => Value::Null, | | 227 | + }; | | 228 | + payload_issue_ref(&payload, row.get("dedupe_key").and_then(|v| v.as_str())) | | 229 | +} | | 230 | + | | 231 | +/// Refresh one task's label cache from the mirror. Ok(false) when the | | 232 | +/// task has no issue ref (nothing to look up); Ok(true) when the | | 233 | +/// refresh ran (the row is stamped only if the mirror has the issue). | | 234 | +/// Err when the store or the mirror table could not be read — the | | 235 | +/// caller ignores it (fail-open). | | 236 | +pub(crate) fn refresh_task_labels(t: &TursoBackend, task_id: i64) -> Result<bool, TErr> { | | 237 | + let rows = t.query_objs( | | 238 | + "SELECT payload, dedupe_key FROM tasks WHERE id = ?", | | 239 | + &[Arg::Int(task_id)], | | 240 | + &[], | | 241 | + )?; | | 242 | + let Some((repo, number)) = rows.first().and_then(row_issue_ref) else { | | 243 | + return Ok(false); | | 244 | + }; | | 245 | + t.exec(LABELS_REFRESH_SQL, &labels_refresh_args(task_id, &repo, number, &now_iso()))?; | | 246 | + Ok(true) | | 247 | +} | | 248 | + | | 249 | +/// Refresh the label cache for many tasks: every actionable task, or | | 250 | +/// every task with `all`. Rows are read in id pages and refreshed in | | 251 | +/// one pipeline per page. Reports what it scanned, how many rows had | | 252 | +/// an issue ref, and how many the mirror actually stamped. | | 253 | +pub(crate) fn sync_task_labels(t: &TursoBackend, all: bool, page_size: i64) -> Result<Value, TErr> { | | 254 | + let page_size = page_size.clamp(1, 1000); | | 255 | + let synced_at = now_iso(); | | 256 | + let status_cond = if all { | | 257 | + String::new() | | 258 | + } else { | | 259 | + let list = LABEL_SYNC_STATUSES | | 260 | + .iter() | | 261 | + .map(|s| format!("'{s}'")) | | 262 | + .collect::<Vec<_>>() | | 263 | + .join(", "); | | 264 | + format!(" AND status IN ({list})") | | 265 | + }; | | 266 | + let (mut scanned, mut with_ref, mut after) = (0i64, 0i64, 0i64); | | 267 | + loop { | | 268 | + let rows = t.query_objs( | | 269 | + &format!( | | 270 | + "SELECT id, payload, dedupe_key FROM tasks WHERE id > ?{status_cond} \ | | 271 | + ORDER BY id LIMIT {page_size}" | | 272 | + ), | | 273 | + &[Arg::Int(after)], | | 274 | + &[], | | 275 | + )?; | | 276 | + let Some(last) = rows.last().and_then(|r| r.get("id")).and_then(|v| v.as_i64()) else { | | 277 | + break; | | 278 | + }; | | 279 | + after = last; | | 280 | + scanned += rows.len() as i64; | | 281 | + let stmts: Vec<(&str, Vec<Arg>)> = rows | | 282 | + .iter() | | 283 | + .filter_map(|r| { | | 284 | + let id = r.get("id").and_then(|v| v.as_i64())?; | | 285 | + let (repo, number) = row_issue_ref(r)?; | | 286 | + Some((LABELS_REFRESH_SQL, labels_refresh_args(id, &repo, number, &synced_at))) | | 287 | + }) | | 288 | + .collect(); | | 289 | + with_ref += stmts.len() as i64; | | 290 | + if !stmts.is_empty() { | | 291 | + t.exec_batch(&stmts)?; | | 292 | + } | | 293 | + if (rows.len() as i64) < page_size { | | 294 | + break; | | 295 | + } | | 296 | + } | | 297 | + let stamped = t | | 298 | + .query_objs( | | 299 | + "SELECT COUNT(*) AS n FROM tasks WHERE labels_synced_at = ?", | | 300 | + &[Arg::Text(synced_at.clone())], | | 301 | + &[], | | 302 | + )? | | 303 | + .first() | | 304 | + .and_then(|r| r.get("n")) | | 305 | + .and_then(|v| v.as_i64()) | | 306 | + .unwrap_or(0); | | 307 | + Ok(json!({ | | 308 | + "scope": if all { "all" } else { "actionable" }, | | 309 | + "scanned": scanned, | | 310 | + "with_issue_ref": with_ref, | | 311 | + "stamped": stamped, | | 312 | + "synced_at": synced_at, | | 313 | + })) | | 314 | +} | | 315 | + | | 316 | +/// The sweep's hourly label pass: runs when the last pass is older | | 317 | +/// than LABEL_SYNC_INTERVAL_SECONDS (or never ran), records the pass | | 318 | +/// in checkpoints, and never fails the sweep — its error is reported | | 319 | +/// inside its own summary. Ok(None) when the interval has not passed. | | 320 | +pub(crate) fn sweep_task_labels(t: &TursoBackend, force: bool) -> Option<Value> { | | 321 | + let work = || -> Result<Option<Value>, TErr> { | | 322 | + if !force { | | 323 | + let last = t | | 324 | + .query_objs( | | 325 | + "SELECT updated_at FROM checkpoints \ | | 326 | + WHERE worker_id = 'fleet-sweeper' AND key = 'labels_sync'", | | 327 | + &[], | | 328 | + &[], | | 329 | + )? | | 330 | + .first() | | 331 | + .and_then(|r| r.get("updated_at")) | | 332 | + .and_then(|v| v.as_str()) | | 333 | + .map(str::to_string); | | 334 | + let due_before = iso(now_unix() - LABEL_SYNC_INTERVAL_SECONDS); | | 335 | + if last.is_some_and(|l| l > due_before) { | | 336 | + return Ok(None); | | 337 | + } | | 338 | + } | | 339 | + let summary = sync_task_labels(t, false, 500)?; | | 340 | + t.exec( | | 341 | + "INSERT INTO checkpoints (worker_id, key, value, updated_at) \ | | 342 | + VALUES ('fleet-sweeper', 'labels_sync', ?, ?) \ | | 343 | + ON CONFLICT(worker_id, key) DO UPDATE SET \ | | 344 | + value = excluded.value, updated_at = excluded.updated_at", | | 345 | + &[Arg::Text(summary.to_string()), Arg::Text(now_iso())], | | 346 | + )?; | | 347 | + Ok(Some(summary)) | | 348 | + }; | | 349 | + match work() { | | 350 | + Ok(v) => v, | | 351 | + Err(e) => Some(json!({"error": e})), | | 352 | + } | | 353 | +} | | 354 | + | | 355 | +/// `/labels-sync` (#14170 Q5): refresh the task label cache now. | | 356 | +/// `all: true` covers every task (the one-off backfill); otherwise | | 357 | +/// only actionable statuses. `page_size` bounds each read page. | | 358 | +pub(crate) fn verb_labels_sync(t: &TursoBackend, req: &Value) -> Value { | | 359 | + let all = req_bool(req, "all").unwrap_or(false); | | 360 | + let page = req_i64(req, "page_size").unwrap_or(500); | | 361 | + match sync_task_labels(t, all, page) { | | 362 | + Ok(v) => ok(json!({"row": v})), | | 363 | + Err(e) => terr(e), | | 364 | + } | | 365 | +} | | 366 | + | | 367 | +/// The list filter for one `--label` value: an exact label name, or | | 368 | +/// a prefix glob ending in `*` (`user/*`). Returns the SQL condition | | 369 | +/// and its bound argument. | | 370 | +pub(crate) fn label_filter_cond(label: &str) -> (&'static str, Arg) { | | 371 | + match label.strip_suffix('*') { | | 372 | + Some(prefix) => { | | 373 | + let escaped = prefix | | 374 | + .replace('\\', "\\\\") | | 375 | + .replace('%', "\\%") | | 376 | + .replace('_', "\\_"); | | 377 | + ( | | 378 | + " AND EXISTS (SELECT 1 FROM json_each(tasks.labels) \ | | 379 | + WHERE json_each.value LIKE ? ESCAPE '\\')", | | 380 | + Arg::Text(format!("{escaped}%")), | | 381 | + ) | | 382 | + } | | 383 | + None => ( | | 384 | + " AND EXISTS (SELECT 1 FROM json_each(tasks.labels) WHERE json_each.value = ?)", | | 385 | + Arg::Text(label.to_string()), | | 386 | + ), | | 387 | + } | | 388 | +} |
|