Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions pkgs/fleet/crates/fleet-queue/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1022,6 +1022,31 @@ pub(crate) fn list_rows(resp: &Value) -> Result<Vec<Value>, String> {
})
}

/// The total in a PostgREST `Content-Range` header (#10376):
/// `0-49/237` -> 237, `*/0` -> 0. A `*` total (no count was
/// requested) or an unparseable header yields None — unknown,
/// never a fabricated zero.
pub(crate) fn content_range_total(content_range: &str) -> Option<i64> {
content_range.rsplit('/').next()?.trim().parse::<i64>().ok()
}

/// The /list reply envelope (#10376; contract #6622 rule 3 —
/// complete, bounded, or say so): alongside the rows, the total
/// number of matching tasks when the backend knows it (null when
/// it does not) and whether this window is a strict prefix of the
/// matching set. Additive: existing consumers read only `rows`.
pub(crate) fn list_envelope(rows: Value, total: Option<i64>, offset: i64) -> Value {
let returned = rows.as_array().map(|a| a.len() as i64).unwrap_or(0);
let truncated = total.map(|t| offset + returned < t).unwrap_or(false);
json!({"rows": rows, "total": total, "truncated": truncated})
}

/// The total a /list reply carries (#10376), when the broker
/// reported one. Absent on replies from a pre-#10376 broker.
pub(crate) fn list_total(resp: &Value) -> Option<i64> {
resp.get("total").and_then(|t| t.as_i64())
}

/// The accepted ranges for the queue duration flags (#6420; design
/// #6448 Phase 3 pin, same as `list --limit`: out-of-range is
/// REJECTED, never clamped, at both the client and the broker).
Expand Down Expand Up @@ -1747,6 +1772,7 @@ fn cmd_list(rest: &[String]) -> i32 {
// verify a just-completed task's status from list output even
// when the done list is thousands of rows long.
let mut rows: Vec<Value> = Vec::new();
let mut total: Option<i64> = None;
for (offset, page_limit) in list_pages(limit) {
let resp = call(
"/list",
Expand All @@ -1762,6 +1788,9 @@ fn cmd_list(rest: &[String]) -> i32 {
}),
);
let resp = unwrap_ok(resp);
if let Some(t) = list_total(&resp) {
total = Some(t);
}
let page = match list_rows(&resp) {
Ok(page) => page,
Err(e) => die(3, &e),
Expand All @@ -1782,6 +1811,19 @@ fn cmd_list(rest: &[String]) -> i32 {
.collect();
let str_rows: Vec<Vec<String>> = rows.iter().map(list_row_cells).collect();
print_table(&cols, &str_rows);
// #10376: name the completeness of the listing — a limited
// window must never read as the whole matching set.
if let Some(t) = total {
if (rows.len() as i64) < t {
println!(
"(truncated: showing {} of {} matching tasks — raise --limit to see more)",
rows.len(),
t
);
} else {
println!("({} matching tasks)", t);
}
}
0
}

Expand Down Expand Up @@ -6248,6 +6290,32 @@ mod tests {
);
}

#[test]
fn list_envelope_reports_total_and_truncation() {
// #10376 oracle (contract #6622 rule 3): a listing whose
// limit is below the matching count says so; an exhaustive
// listing reports completeness; an unknown total is null,
// never a fabricated zero.
assert_eq!(content_range_total("0-49/237"), Some(237));
assert_eq!(content_range_total("*/0"), Some(0));
assert_eq!(content_range_total("0-49/*"), None);
assert_eq!(content_range_total("garbage"), None);
let rows = json!([{"id": 1}, {"id": 2}]);
let limited = list_envelope(rows.clone(), Some(5), 0);
assert_eq!(limited["total"], json!(5));
assert_eq!(limited["truncated"], json!(true));
assert_eq!(list_rows(&limited).map(|r| r.len()), Ok(2));
let exhaustive = list_envelope(rows.clone(), Some(2), 0);
assert_eq!(exhaustive["truncated"], json!(false));
let windowed = list_envelope(rows.clone(), Some(5), 3);
assert_eq!(windowed["truncated"], json!(false));
let unknown = list_envelope(rows, None, 0);
assert_eq!(unknown["total"], Value::Null);
assert_eq!(unknown["truncated"], json!(false));
assert_eq!(list_total(&limited), Some(5));
assert_eq!(list_total(&json!({"rows": []})), None);
}

#[test]
fn duration_flags_range_is_validated() {
// #6420: 0/negative durations corrupt claim state (a lease
Expand Down
13 changes: 11 additions & 2 deletions pkgs/fleet/crates/fleet-queue/src/queue_broker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1218,8 +1218,17 @@ fn dispatch(st: &State, path: &str, req: &Value) -> Value {
if let Some(w) = req.get("worker").and_then(|s| s.as_str()) {
path += &format!("&worker_id=eq.{}", quote(w, ""));
}
match st.postgrest("GET", &path, None, false) {
Ok((rows, _)) => ok(json!({"rows": rows})),
// #10376: request the exact count so the reply can
// name its total — without count=exact the
// Content-Range total is `*` and a limited listing
// reads as complete.
match st.postgrest("GET", &path, None, true) {
Ok((rows, content_range)) => {
let total = content_range
.as_deref()
.and_then(crate::client::content_range_total);
ok(crate::client::list_envelope(rows, total, offset))
}
Err(e) => fail(e.exit, e.msg),
}
}
Expand Down
33 changes: 22 additions & 11 deletions pkgs/fleet/crates/fleet-queue/src/turso_queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6430,54 +6430,65 @@ fn verb_list(t: &TursoBackend, req: &Value) -> Value {
// an unnamed queue must not become `queue = ''`, which by
// construction returns zero rows and breaks exact-task readback
// ({"task": id} / {"dedupe_key": key} with no queue).
let mut sql = format!("SELECT {select} FROM tasks WHERE 1 = 1");
let mut conds = String::from(" WHERE 1 = 1");
let mut args: Vec<Arg> = vec![];
if !queue.is_empty() {
sql += " AND queue = ?";
conds += " AND queue = ?";
args.push(Arg::Text(queue));
}
if let Some(s) = req_str(req, "status") {
sql += " AND status = ?";
conds += " AND status = ?";
args.push(Arg::Text(s.to_string()));
}
// #5444: recover a lane's or worker's live claims before lease
// expiry — list filters end-to-end (client -> broker -> here).
if let Some(l) = req_str(req, "lane") {
sql += " AND lane_id = ?";
conds += " AND lane_id = ?";
args.push(Arg::Text(l.to_string()));
}
if let Some(w) = req_str(req, "worker") {
sql += " AND worker_id = ?";
conds += " AND worker_id = ?";
args.push(Arg::Text(w.to_string()));
}
if let Some(nb) = req_str(req, "not_before") {
sql += " AND (not_before IS NULL OR not_before <= ?)";
conds += " AND (not_before IS NULL OR not_before <= ?)";
args.push(Arg::Text(nb.to_string()));
}
// #7871: --task narrows to one task id (the PostgREST /list
// path applies the same filter), and the client's paged fetch
// advances OFFSET page by page.
if let Some(id) = req_i64(req, "task") {
sql += " AND id = ?";
conds += " AND id = ?";
args.push(Arg::Int(id));
}
// #9420: dedupe_key narrows to the task carrying that key (the
// delivery publisher's enqueue readback verifies by dedupe key).
if let Some(d) = req_str(req, "dedupe_key") {
sql += " AND dedupe_key = ?";
conds += " AND dedupe_key = ?";
args.push(Arg::Text(d.to_string()));
}
let offset = crate::client::list_offset_or_default(req_i64(req, "offset"));
sql += &format!(
" ORDER BY (priority IS NULL), priority ASC, created_at ASC, id ASC LIMIT {limit} OFFSET {offset}"
let sql = format!(
"SELECT {select} FROM tasks{conds} ORDER BY (priority IS NULL), priority ASC, created_at ASC, id ASC LIMIT {limit} OFFSET {offset}"
);
let json_cols: &[&str] = if rich {
&["progress", "payload", "blocked_deps"]
} else {
&[]
};
match t.query_objs(&sql, &args, json_cols) {
Ok(rows) => ok(json!({"rows": rows})),
Ok(rows) => {
// #10376 parity with the PostgREST /list: name the
// total matching count so a limited listing cannot
// read as complete. A failed count leaves the total
// unknown (null), never a fabricated number.
let count_sql = format!("SELECT COUNT(*) AS n FROM tasks{conds}");
let total = t
.query_objs(&count_sql, &args, &[])
.ok()
.and_then(|rs| rs.first().and_then(|r| r.get("n")).and_then(|v| v.as_i64()));
ok(crate::client::list_envelope(json!(rows), total, offset))
}
Err(e) => terr(e),
}
}
Expand Down