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
2 changes: 2 additions & 0 deletions pkgs/fleet/crates/fleet-queue/src/turso_queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ pub mod ctx_scope;
#[cfg(all(test, feature = "queue-broker"))]
mod hrana_double;
mod label_enrich;
mod lane_share;
mod lifecycle;
mod lifecycle_limits;
mod lifecycle_park;
Expand All @@ -74,6 +75,7 @@ pub use claim_filter::*;
pub use closed_bound::*;
pub use core::*;
pub use label_enrich::*;
pub use lane_share::*;
pub use lifecycle::*;
pub use lifecycle_limits::*;
pub use lifecycle_park::*;
Expand Down
50 changes: 50 additions & 0 deletions pkgs/fleet/crates/fleet-queue/src/turso_queue/hrana_double.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
//! repair design run against real transaction state.

use super::core::TursoBackend;
use super::dispatch;
use super::repair::verb_repair;
use rusqlite::{Connection, params_from_iter, types::Value as SqlValue, types::ValueRef};
use serde_json::{Value, json};
Expand Down Expand Up @@ -273,6 +274,55 @@ fn repair_req(id: i64, dry_run: bool) -> Value {
json!({"task_id": id, "worker": "operator", "reason": "13579 test", "dry_run": dry_run})
}

#[test]
fn lane_share_rows_include_terminal_tasks_without_ledger_records() {
// Oracle: the task table is authoritative for terminal membership;
// the ledger is optional enrichment and cannot hide unrecorded rows.
let d = start("lane-share-rows", Fault::None);
schema(&d);
let conn = direct(&d);
conn.execute_batch(
"INSERT INTO tasks (id, queue, status, created_at, updated_at, completed_at) VALUES
(1, 'code', 'done', '2026-11-27T00:00:00Z', '2026-11-28T12:00:00Z', '2026-11-28T12:00:00Z'),
(2, 'code', 'done', '2026-11-27T00:00:00Z', '2026-11-28T13:00:00Z', '2026-11-28T13:00:00Z'),
(3, 'code', 'failed', '2026-11-27T00:00:00Z', '2026-11-28T14:00:00Z', NULL),
(4, 'code', 'queued', '2026-11-27T00:00:00Z', '2026-11-28T14:00:00Z', NULL);
INSERT INTO repo_task_lane_ledger (queue, task_id, executed_lane, updated_at)
VALUES ('code', 1, 'opencode', '2026-11-28T12:00:00Z'),
('code', 3, 'opencode', '2026-11-28T14:00:00Z');",
)
.expect("seed terminal tasks and partial lane ledger");

let response = dispatch(
&backend(&d),
"/lane-share-rows",
&json!({"from": "2026-11-28", "through": "2026-11-28"}),
);
assert_eq!(response["ok"], true);
let rows = response["rows"].as_array().expect("rows array");
assert_eq!(rows.len(), 3, "all and only terminal tasks in range");
assert_eq!(rows[0]["executed_lane"], "opencode");
assert_eq!(rows[1]["exclusion_reason"], "unrecorded");
assert_eq!(rows[2]["executed_lane"], Value::Null);
assert_eq!(rows[2]["exclusion_reason"], "terminal-failed");
}

#[test]
fn lane_share_rows_reject_invalid_or_reversed_date_ranges() {
// Oracle: malformed or reversed ranges are usage errors, not silent empty data.
let d = start("lane-share-dates", Fault::None);
schema(&d);
let backend = backend(&d);
for request in [
json!({"from": "2026-02-29", "through": "2026-03-01"}),
json!({"from": "2026-11-29", "through": "2026-11-28"}),
] {
let response = dispatch(&backend, "/lane-share-rows", &request);
assert_eq!(response["ok"], false);
assert_eq!(response["exit"], 2);
}
}

#[test]
fn event_rejection_rolls_back_13579() {
// Fault row 6: the repaired-event insert is rejected after the
Expand Down
98 changes: 98 additions & 0 deletions pkgs/fleet/crates/fleet-queue/src/turso_queue/lane_share.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
//! Broker read surface for daily lane-share measurement (#1657).
//!
//! Keep the terminal task set authoritative: start from `tasks`, then
//! LEFT JOIN the lane ledger so missing assignment records remain visible
//! to the tally as explicit `unrecorded` exclusions.

use super::core::{Arg, TErr, TursoBackend, fail, ok};
use serde_json::{Value, json};

fn valid_day(value: &str) -> bool {
let bytes = value.as_bytes();
if bytes.len() != 10
|| bytes[4] != b'-'
|| bytes[7] != b'-'
|| !bytes.iter().enumerate().all(|(i, byte)| {
matches!(i, 4 | 7) && *byte == b'-' || !matches!(i, 4 | 7) && byte.is_ascii_digit()
})
{
return false;
}
let Ok(year) = value[0..4].parse::<i32>() else {
return false;
};
let Ok(month) = value[5..7].parse::<u32>() else {
return false;
};
let Ok(day) = value[8..10].parse::<u32>() else {
return false;
};
let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
let days_in_month = match month {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 if leap => 29,
2 => 28,
_ => return false,
};
(1..=days_in_month).contains(&day)
}

/// Read all terminal tasks in an inclusive UTC date range, retaining rows
/// without a lane-ledger record. The response's `rows` can be fed to the
/// pure lane-share tally after mapping `executed_lane`, `exclusion_reason`
/// and `fallback_reason`.
pub(crate) fn verb_lane_share_rows(t: &TursoBackend, req: &Value) -> Value {
let from = req.get("from").and_then(Value::as_str).unwrap_or("");
let through = req.get("through").and_then(Value::as_str).unwrap_or("");
if !valid_day(from) || !valid_day(through) || from > through {
return fail(
2,
"lane-share-rows: from and through must be ordered YYYY-MM-DD dates",
);
}

let sql = "SELECT t.id AS task_id, t.queue, t.status, \
substr(COALESCE(NULLIF(t.completed_at, ''), NULLIF(t.resolved_at, ''), t.updated_at), 1, 10) AS completed_on, \
CASE WHEN t.status = 'done' THEN l.executed_lane ELSE NULL END AS executed_lane, \
CASE WHEN t.status IN ('cancelled', 'failed') THEN 'terminal-' || t.status \
WHEN l.task_id IS NULL THEN 'unrecorded' \
WHEN l.exclusion_reason IS NOT NULL THEN l.exclusion_reason \
WHEN l.executed_lane IS NULL THEN 'unrecorded' \
WHEN l.executed_lane NOT IN ('opencode', 'direct') THEN 'unknown-lane:' || l.executed_lane \
ELSE NULL END AS exclusion_reason, \
l.fallback_reason \
FROM tasks AS t LEFT JOIN repo_task_lane_ledger AS l ON l.task_id = t.id \
WHERE t.status IN ('done', 'cancelled', 'failed') \
AND substr(COALESCE(NULLIF(t.completed_at, ''), NULLIF(t.resolved_at, ''), t.updated_at), 1, 10) >= ? \
AND substr(COALESCE(NULLIF(t.completed_at, ''), NULLIF(t.resolved_at, ''), t.updated_at), 1, 10) <= ? \
ORDER BY completed_on, t.queue, t.id";
match t.query_objs(
sql,
&[Arg::Text(from.into()), Arg::Text(through.into())],
&[],
) {
Ok(rows) => ok(json!({"rows": rows, "from": from, "through": through})),
Err(error) => queue_error(error),
}
}

fn queue_error(error: TErr) -> Value {
super::core::terr(error)
}

#[cfg(test)]
mod tests {
use super::valid_day;

#[test]
fn lane_share_date_range_uses_calendar_dates() {
// Oracle: Gregorian calendar validity, including leap-year boundaries.
assert!(valid_day("2024-02-29"));
assert!(valid_day("2000-02-29"));
assert!(!valid_day("1900-02-29"));
assert!(!valid_day("2026-02-29"));
assert!(!valid_day("2026-13-01"));
assert!(!valid_day("2026-11-1"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1066,6 +1066,7 @@ pub fn dispatch(t: &TursoBackend, path: &str, req: &Value) -> Value {
"/needs-user" => verb_needs_user(t, req),
"/meta" => verb_meta(t, req),
"/labels-sync" => verb_labels_sync(t, req),
"/lane-share-rows" => verb_lane_share_rows(t, req),
"/note-add" => verb_note_add(t, req),
"/note-list" => verb_note_list(t, req),
"/note-edit" => verb_note_edit(t, req),
Expand Down