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
25 changes: 14 additions & 11 deletions crates/comma-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use anyhow::Result;
use clap::{Parser, Subcommand};
use comma_common::state_dir;
use comma_common::{
FileKind, cutoff_secs, missing_route_paths, priority_for_rank, resolve_route_name,
FileKind, cutoff_secs, missing_route_paths, priorities_for_sorted_paths, resolve_route_name,
upload_order_key,
};
use comma_connect_api::Client;
Expand Down Expand Up @@ -568,16 +568,17 @@ async fn cmd_upload_files(
));
}

let priorities = priorities_for_sorted_paths(&paths);
let requests: Vec<UploadFileRequest> = paths
.into_iter()
.zip(urls)
.enumerate()
.map(|(rank, (fn_, u))| UploadFileRequest {
.zip(priorities)
.map(|((fn_, u), priority)| UploadFileRequest {
file_name: fn_,
url: u.url,
headers: u.headers.unwrap_or_default(),
allow_cellular: false,
priority: priority_for_rank(rank),
priority,
})
.collect();

Expand Down Expand Up @@ -647,16 +648,17 @@ async fn cmd_upload_route(name: String, dongle: Option<String>, limit: Option<u3
));
}

let priorities = priorities_for_sorted_paths(&paths);
let requests: Vec<UploadFileRequest> = paths
.into_iter()
.zip(urls)
.enumerate()
.map(|(rank, (fn_, u))| UploadFileRequest {
.zip(priorities)
.map(|((fn_, u), priority)| UploadFileRequest {
file_name: fn_,
url: u.url,
headers: u.headers.unwrap_or_default(),
allow_cellular: false,
priority: priority_for_rank(rank),
priority,
})
.collect();

Expand All @@ -683,16 +685,17 @@ async fn enqueue_paths(
paths.len()
));
}
let priorities = priorities_for_sorted_paths(&paths);
let requests: Vec<UploadFileRequest> = paths
.into_iter()
.zip(urls)
.enumerate()
.map(|(rank, (fn_, u))| UploadFileRequest {
.zip(priorities)
.map(|((fn_, u), priority)| UploadFileRequest {
file_name: fn_,
url: u.url,
headers: u.headers.unwrap_or_default(),
allow_cellular: false,
priority: priority_for_rank(rank),
priority,
})
.collect();
Ok(client
Expand Down Expand Up @@ -752,7 +755,7 @@ async fn cmd_upload_recent_routes(
if all_paths.is_empty() {
println!("Nothing to upload.");
} else {
// Sorted by route name, segment, log type; sequential priorities.
// Sorted by route name, segment, log type; per-route priorities.
let result = enqueue_paths(&client, &id, all_paths.clone()).await?;
let n = result
.get("result")
Expand Down
64 changes: 56 additions & 8 deletions crates/comma-common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,30 @@ pub fn upload_order_key(path: &str) -> (String, i32, u8) {
)
}

/// Athena priority for the `rank`-th item in a batch already sorted by
/// `upload_order_key`. Lower number = sooner; clamped to 1..=99.
/// Athena priorities for a batch of paths already sorted by `upload_order_key`.
///
/// All files of the same route receive the same priority (the route's rank,
/// starting at 1). Lower number = higher priority. Athena therefore finishes
/// an entire route before starting the next one. Within a route the order of
/// insertion (segment number, then log type) is preserved via created_at.
/// Priorities are clamped to 1..=99.
pub fn priorities_for_sorted_paths(paths: &[String]) -> Vec<i32> {
let mut priorities = Vec::with_capacity(paths.len());
let mut current_route = String::new();
let mut route_rank = 0i32;
for path in paths {
let route = route_from_path(path);
if route != current_route {
current_route = route;
route_rank = (route_rank + 1).clamp(1, 99);
}
priorities.push(route_rank);
}
priorities
}

/// Legacy: sequential priority by rank. Prefer `priorities_for_sorted_paths`
/// so that whole routes stay together.
pub fn priority_for_rank(rank: usize) -> i32 {
(1 + rank as i32).clamp(1, 99)
}
Expand Down Expand Up @@ -161,9 +183,14 @@ pub fn missing_route_paths(
let mut paths = Vec::new();
for n in 0..segments {
for kind in kinds {
// Include only when the uploaded array is shorter than this segment
// (arrays are ordered by segment number; length > n means uploaded).
if (n as usize) < kind.uploaded(files).len() {
// Official logic (new-connect generateMissingFilePaths): a segment+kind
// is uploaded if any returned path contains the storage key
// `{route_ts}/{n}/{filename}` (signed URLs are of the form
// .../dongle/{route_ts}/{n}/{filename}?...).
// Length-based checks are incorrect when there are gaps or the
// arrays are not dense prefixes from segment 0.
let needle = format!("{route_ts}/{n}/{}", kind.filename());
if kind.uploaded(files).iter().any(|p| p.contains(&needle)) {
continue;
}
paths.push(format!("{route_ts}--{n}/{}", kind.filename()));
Expand Down Expand Up @@ -211,11 +238,18 @@ mod tests {

#[test]
fn route_paths_are_zipped_by_segment_and_skip_uploaded() {
// Paths that look like real signed URLs containing the storage key.
let files = RouteFiles {
cameras: vec!["a".into(), "b".into()],
dcameras: vec!["a".into()],
cameras: vec![
"https://example/dongle/ts/0/fcamera.hevc?sig=1".into(),
"https://example/dongle/ts/1/fcamera.hevc?sig=2".into(),
],
dcameras: vec!["https://example/dongle/ts/0/dcamera.hevc?sig=3".into()],
ecameras: vec![],
logs: vec!["a".into(), "b".into()],
logs: vec![
"https://example/dongle/ts/0/rlog.zst?sig=4".into(),
"https://example/dongle/ts/1/rlog.zst?sig=5".into(),
],
..Default::default()
};
let paths = missing_route_paths("ts", 2, &files, None);
Expand Down Expand Up @@ -249,4 +283,18 @@ mod tests {
let cutoff = cutoff_secs(1792022400, 14);
assert_eq!(cutoff, 1792022400 - 14 * 24 * 60 * 60);
}

#[test]
fn priorities_group_by_route() {
let paths = vec![
"r1--0/rlog.zst".into(),
"r1--0/fcamera.hevc".into(),
"r1--1/rlog.zst".into(),
"r2--0/rlog.zst".into(),
"r2--0/fcamera.hevc".into(),
"r3--5/dcamera.hevc".into(),
];
let prio = priorities_for_sorted_paths(&paths);
assert_eq!(prio, vec![1, 1, 1, 2, 2, 3]);
}
}
26 changes: 23 additions & 3 deletions crates/comma-tui/docs/TDR-007-upload-queue-polling.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,32 @@ Accepted (2026-11-29)

## Upload request ordering

Athena's upload queue is a priority queue. Lower `priority` number is processed first; the allowed range is 0–99. When priorities are equal the relative order is undefined, which is why higher-numbered segments previously appeared first.
Athena's upload queue is a priority queue. Lower `priority` number is processed first; the allowed range is 0–99. When priorities are equal, items are ordered by `created_at` (insertion time).

Upload batches are sorted by **route name**, then **segment number**, then **log type**
(log → fcamera → ecamera → dcamera). Sequential priorities (`priority_for_rank`)
are then assigned so the device processes them in that order.
(log → fcamera → ecamera → dcamera). Priorities are then assigned **per route**:
every file of the first route receives priority 1, every file of the second route
receives priority 2, and so on (clamped to 99).

Because all files of a route share the same priority, Athena finishes an entire
route before starting the next one, even when a route contains more files than
the 99-level limit. Within a route the sorted insertion order is preserved via
`created_at`.

Values stay in 1..=99 so interactive uploads remain ahead of the device's default / firehose priority (99).
Multi-route requests (TUI "upload all listed", CLI `upload recent-routes`) collect all missing
paths first, sort once, and enqueue in a single Athena call.

**Note:** uploading routes one-by-one (TUI `u` / CLI per-route) still assigns priorities starting at 1 for each batch. To obtain strict route-then-segment order across many routes, use the all-listed / recent-routes commands.

## Upload status detection (lcLFWD)

Route file arrays from `/v1/route/{name}/files` are lists of signed URLs that contain the storage key, not dense prefix lengths. Presence is detected the same way comma Connect does:

```
{route_ts}/{segment}/{filename}
```

appears in any returned path. Length-based checks (`n < array.len()`) are incorrect when there are gaps and cause already-uploaded segments to be re-queued and status indicators to stay partial.

When the Athena queue transitions from non-empty to empty, the TUI automatically re-fetches route files so the Routes tab indicators update without a manual Ctrl-r.
37 changes: 31 additions & 6 deletions crates/comma-tui/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,9 @@ pub struct App {
pub fully_uploaded: HashSet<String>,
/// When set, the main loop should trigger a fresh files query for this route.
pub refresh_requested: Option<String>,
/// When true, the main loop should refresh files for all currently listed routes
/// (used after the upload queue becomes empty so status indicators update).
pub refresh_all_files: bool,
/// When set, the main loop should perform this upload/cancel operation.
pub pending_op: Option<PendingOp>,
pub queue: Vec<UploadQueueItem>,
Expand Down Expand Up @@ -106,6 +109,7 @@ impl App {
route_files: HashMap::new(),
fully_uploaded: load_fully_uploaded(),
refresh_requested: None,
refresh_all_files: false,
pending_op: None,
queue: Vec::new(),
devices: Vec::new(),
Expand Down Expand Up @@ -233,13 +237,28 @@ impl App {
.and_then(|r| r.maxqlog)
.map(|m| m + 1)
.unwrap_or(0);
let route_ts = name
.split_once('|')
.map(|(_, ts)| ts)
.unwrap_or(name.as_str());
let present = |uploaded: &[String], filename: &str| -> i32 {
if segs <= 0 {
return 0;
}
(0..segs)
.filter(|&n| {
let needle = format!("{route_ts}/{n}/{filename}");
uploaded.iter().any(|p| p.contains(&needle))
})
.count() as i32
};
let fully = segs > 0
&& (files.qlogs.len() as i32) >= segs
&& (files.qcameras.len() as i32) >= segs
&& (files.logs.len() as i32) >= segs
&& (files.cameras.len() as i32) >= segs
&& (files.ecameras.len() as i32) >= segs
&& (files.dcameras.len() as i32) >= segs;
&& present(&files.qlogs, "qlog.zst") >= segs
&& present(&files.qcameras, "qcamera.ts") >= segs
&& present(&files.logs, "rlog.zst") >= segs
&& present(&files.cameras, "fcamera.hevc") >= segs
&& present(&files.ecameras, "ecamera.hevc") >= segs
&& present(&files.dcameras, "dcamera.hevc") >= segs;
if fully {
if self.fully_uploaded.insert(name.clone()) {
let _ = store_fully_uploaded(&self.fully_uploaded);
Expand All @@ -256,13 +275,19 @@ impl App {
// ignore individual file fetch errors for now
}
DataMsg::Queue(Ok(q)) => {
let was_nonempty = !self.queue.is_empty();
self.queue = q;
self.online = Some(true);
self.queue_status = if self.queue.is_empty() {
"queue empty".into()
} else {
String::new()
};
// After uploads finish (queue goes empty), refresh route files so
// the Routes tab status indicators update without a manual Ctrl-r.
if was_nonempty && self.queue.is_empty() && !self.routes.is_empty() {
self.refresh_all_files = true;
}
self.clamp_selection();
}
DataMsg::Queue(Err(e)) => {
Expand Down
13 changes: 7 additions & 6 deletions crates/comma-tui/src/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
//! so the UI loop stays responsive.

use anyhow::Result;
use comma_common::{FileKind, missing_route_paths, priority_for_rank, upload_order_key};
use comma_common::{FileKind, missing_route_paths, priorities_for_sorted_paths, upload_order_key};
use comma_connect_api::{Client, Device, Route, RouteFiles, UploadFileRequest, UploadQueueItem};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{
Expand Down Expand Up @@ -166,7 +166,7 @@ impl Loader {
///
/// Collects missing paths from all routes, sorts them by route name then
/// segment then log type, and enqueues them in one Athena call with
/// sequential priorities so the device processes them in that order.
/// per-route priorities so the device finishes one route before the next.
/// Tracked in `inflight_uploads` so graceful quit can wait.
pub fn request_upload_all(&self, dongle_id: String, routes: Vec<String>) {
let client = self.client.clone();
Expand Down Expand Up @@ -242,7 +242,7 @@ async fn refresh_queue(client: &Client, dongle_id: &str, tx: &Sender<DataMsg>) {
let _ = tx.send(DataMsg::Queue(res));
}

/// Sort paths by route name, segment, log type; assign sequential priorities;
/// Sort paths by route name, segment, log type; assign per-route priorities;
/// request URLs and enqueue.
async fn do_upload_paths(
client: &Client,
Expand All @@ -257,16 +257,17 @@ async fn do_upload_paths(
if urls.len() != paths.len() {
return Err(anyhow::anyhow!("url count mismatch"));
}
let priorities = priorities_for_sorted_paths(&paths);
let requests: Vec<UploadFileRequest> = paths
.into_iter()
.zip(urls)
.enumerate()
.map(|(rank, (fn_, u))| UploadFileRequest {
.zip(priorities)
.map(|((fn_, u), priority)| UploadFileRequest {
file_name: fn_,
url: u.url,
headers: u.headers.unwrap_or_default(),
allow_cellular: false,
priority: priority_for_rank(rank),
priority,
})
.collect();
client
Expand Down
13 changes: 13 additions & 0 deletions crates/comma-tui/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,19 @@ fn loop_tui(
while let Ok(msg) = rx.try_recv() {
app.apply_msg(msg);
}
// After the upload queue becomes empty, refresh route files so the
// Routes tab status indicators reflect the newly uploaded segments.
if app.refresh_all_files {
app.refresh_all_files = false;
let names: Vec<_> = app.routes.iter().map(|r| r.fullname.clone()).collect();
info!(
count = names.len(),
"refreshing route files after queue emptied"
);
for name in names {
loader.load_route_files(name);
}
}

// If the user switched dongle, reload its data
if app.active_dongle != *last_dongle {
Expand Down
Loading
Loading