diff --git a/pkgs/fleet/crates/fleet-queue/src/client/transport.rs b/pkgs/fleet/crates/fleet-queue/src/client/transport.rs index ffbd8551dd..9deb83c9dc 100644 --- a/pkgs/fleet/crates/fleet-queue/src/client/transport.rs +++ b/pkgs/fleet/crates/fleet-queue/src/client/transport.rs @@ -404,6 +404,168 @@ pub(super) fn unix_roundtrip(data: &[u8]) -> Result { serde_json::from_slice(&buf).map_err(|e| format!("session proxy bad reply: {e}")) } +/// #13146: the bounded, never-dying sibling of [`broker_roundtrip`] +/// for best-effort callers (the placement session mirror). Same +/// route selection, but: every timeout is the caller's budget, HTTP +/// error statuses come back as Err instead of dying with exit 3, +/// a malformed configured broker URL degrades to Err instead of +/// dying, and the session broker is never auto-spawned — a caller +/// that can proceed without the broker must never be able to fail +/// or stall on it. +pub(crate) fn broker_roundtrip_bounded( + path: &str, + body: &Value, + budget: Duration, +) -> Result { + if let Some(url) = direct_broker_url() { + return match route_from_configured_url(&url)? { + DirectRoute::Tcp(u) => bounded_tcp_roundtrip(&u, path, body, budget), + DirectRoute::Unix(s) => bounded_uds_roundtrip(&s, path, body, budget), + }; + } + let cfg = fleet_config::Config::load().unwrap_or_default(); + if let Some(fleet_config::RoleTransport::Socket(socket)) = + cfg.role_transport_choice("queue-broker") + { + // Mirror broker_roundtrip: a failed socket attempt falls + // back to the session-proxy route within the same call. + if let Ok(v) = bounded_uds_roundtrip(&socket, path, body, budget) { + return Ok(v); + } + } + bounded_proxy_roundtrip(path, body, budget) +} + +/// The direct HTTP exchange with caller-bounded timeouts, shared +/// by the bounded TCP and UDS legs. +fn bounded_direct_exchange( + mut s: S, + host: &str, + path: &str, + body: &Value, + token: &str, +) -> Result { + let payload = serde_json::to_vec(body).unwrap(); + let head = format!( + "POST {path} HTTP/1.1\r\nHost: {host}\r\nX-Agent-Token: {token}\r\n\ + Content-Type: application/json\r\nContent-Length: {}\r\n\ + Connection: close\r\n\r\n", + payload.len() + ); + s.write_all(head.as_bytes()) + .and_then(|_| s.write_all(&payload)) + .map_err(|e| format!("queue-broker write failed: {e}"))?; + let mut raw = Vec::new(); + s.read_to_end(&mut raw) + .map_err(|e| format!("queue-broker read failed: {e}"))?; + finish_bounded_response(&raw) +} + +/// Status handling for the bounded legs: an HTTP error status is +/// an Err here, never a die — [`finish_direct_response`] (which +/// dies on >= 400) only ever sees success statuses. +fn finish_bounded_response(raw: &[u8]) -> Result { + let split = raw + .windows(4) + .position(|w| w == b"\r\n\r\n") + .ok_or("queue-broker bad reply")?; + let head_txt = String::from_utf8_lossy(&raw[..split]).to_string(); + let status: u64 = head_txt + .split_whitespace() + .nth(1) + .and_then(|c| c.parse().ok()) + .ok_or_else(|| "queue-broker answered with a malformed status line".to_string())?; + if status >= 400 { + return Err(format!("queue-broker answered HTTP {status}")); + } + finish_direct_response(raw) +} + +fn bounded_tcp_roundtrip( + url: &str, + path: &str, + body: &Value, + budget: Duration, +) -> Result { + use std::net::ToSocketAddrs as _; + let rest = url + .strip_prefix("http://") + .ok_or("broker URL must be http://host:port")?; + let hostport = rest.trim_end_matches('/'); + if hostport.is_empty() || hostport.contains('/') { + return Err(format!("bad broker URL {url:?}")); + } + let token = direct_token()?; + let addr = hostport + .to_socket_addrs() + .map_err(|e| format!("cannot resolve queue-broker at {hostport}: {e}"))? + .next() + .ok_or_else(|| format!("cannot resolve queue-broker at {hostport}"))?; + let mut s = TcpStream::connect_timeout(&addr, budget) + .map_err(|e| format!("cannot connect to queue-broker at {hostport}: {e}"))?; + s.set_read_timeout(Some(budget)).ok(); + s.set_write_timeout(Some(budget)).ok(); + bounded_direct_exchange(&mut s, hostport, path, body, &token) +} + +fn bounded_uds_roundtrip( + socket: &std::path::Path, + path: &str, + body: &Value, + budget: Duration, +) -> Result { + let token = direct_token()?; + let mut s = UnixStream::connect(socket).map_err(|e| { + format!( + "cannot connect to queue-broker at unix://{}: {e}", + socket.display() + ) + })?; + s.set_read_timeout(Some(budget)).ok(); + s.set_write_timeout(Some(budget)).ok(); + bounded_direct_exchange(&mut s, "localhost", path, body, &token) +} + +/// The session-proxy leg, bounded: one attempt, no broker spawn, +/// and a proxy HTTP error is an Err (the unbounded leg dies on it). +fn bounded_proxy_roundtrip(path: &str, body: &Value, budget: Duration) -> Result { + let payload = json!({ + "method": "POST", + "path": path, + "body": body, + "port": QUEUE_BROKER_PORT, + "token_file": format!("{}/tools/queue-broker-token", home()), + }); + let data = serde_json::to_vec(&payload).unwrap(); + let mut s = UnixStream::connect(broker_sock()) + .map_err(|e| format!("cannot connect to session proxy: {e}"))?; + s.set_read_timeout(Some(budget)).ok(); + s.set_write_timeout(Some(budget)).ok(); + s.write_all(&(data.len() as u64).to_be_bytes()) + .and_then(|_| s.write_all(&data)) + .map_err(|e| format!("session proxy write failed: {e}"))?; + let mut hdr = [0u8; 8]; + s.read_exact(&mut hdr) + .map_err(|e| format!("session proxy read failed: {e}"))?; + let n = u64::from_be_bytes(hdr) as usize; + let mut buf = vec![0u8; n]; + s.read_exact(&mut buf) + .map_err(|e| format!("session proxy read failed: {e}"))?; + let resp: Value = + serde_json::from_slice(&buf).map_err(|e| format!("session proxy bad reply: {e}"))?; + let status = resp.get("status").and_then(|s| s.as_u64()).unwrap_or(0); + let resp_body = resp.get("body").cloned().unwrap_or(Value::Null); + if status >= 400 { + let msg = resp_body + .get("error") + .and_then(|e| e.as_str()) + .unwrap_or("session proxy error") + .to_string(); + return Err(msg); + } + Ok(resp_body) +} + /// Which broker program to auto-start: a sibling `fleet` binary /// next to the running one wins (step 3, #5431 — `fleet proxy /// serve` is the Python broker's successor); the standalone @@ -644,3 +806,53 @@ pub(super) fn row_or_ledger(resp: &Value, fn_name: &str) { } } } + +#[cfg(test)] +mod bounded_tests { + use super::*; + + #[test] + fn bounded_exchange_times_out_on_a_silent_peer() { + // Oracle (#13146): the bounded leg gives up within its + // budget when the peer accepts but never answers — the + // unbounded legs would wait out their 300s read timeout, + // and the session-proxy leg would die(3) on an error. + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + std::thread::spawn(move || { + let (_sock, _) = listener.accept().unwrap(); + std::thread::sleep(Duration::from_secs(2)); + }); + let mut s = TcpStream::connect(addr).unwrap(); + s.set_read_timeout(Some(Duration::from_millis(300))).ok(); + s.set_write_timeout(Some(Duration::from_millis(300))).ok(); + let started = std::time::Instant::now(); + let out = bounded_direct_exchange( + &mut s, + "127.0.0.1", + "/placement-get", + &json!({"handle": "fp_x"}), + "test-token", + ); + assert!(out.is_err(), "{out:?}"); + assert!( + started.elapsed() < Duration::from_millis(1500), + "bounded leg took {:?}", + started.elapsed() + ); + } + + #[test] + fn bounded_response_maps_http_error_to_err_not_death() { + // Oracle: an HTTP error status is data (Err) for the + // bounded caller; a success status parses as usual. + let raw = b"HTTP/1.1 401 Unauthorized\r\nContent-Type: application/json\r\n\ + Content-Length: 24\r\n\r\n{\"error\": \"unauthorized\"}"; + let out = finish_bounded_response(raw); + assert!(matches!(out, Err(ref e) if e.contains("401")), "{out:?}"); + let raw = b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\ + Content-Length: 7\r\n\r\n{\"a\":1}"; + let out = finish_bounded_response(raw).unwrap(); + assert_eq!(out, json!({"a": 1})); + } +} diff --git a/pkgs/fleet/crates/fleet-queue/src/placement.rs b/pkgs/fleet/crates/fleet-queue/src/placement.rs index c330eec5c3..583fe35d7e 100644 --- a/pkgs/fleet/crates/fleet-queue/src/placement.rs +++ b/pkgs/fleet/crates/fleet-queue/src/placement.rs @@ -17,12 +17,15 @@ //! //! Sessions are server-side records keyed by an unguessable handle //! (`fp_` + 128-bit random), so any client can reconnect: -//! `repo-queue session status|result|list`. STOPGAP (labeled, per -//! the spec): records live in a local JSON store at -//! `~/.local/state/fleet-place/sessions.json` — the same path and -//! record shape the reference implementation used, so records -//! migrate rather than being redesigned when the designed -//! `agent.placement_sessions` table lands in the queue backend. +//! `repo-queue session status|result|list`. Records live in the +//! local JSON store at `~/.local/state/fleet-place/sessions.json` +//! — the same path and record shape the reference implementation +//! used — and mirror best-effort to the queue backend's +//! `placement_sessions` table (#13146; the designed home the intake +//! spec pointed at), so a handle resolves from any seat. The local +//! store remains the always-available fallback and the only input +//! to placement decisions: the mirror can neither fail nor stall a +//! dispatch, and `FLEET_PLACE_REMOTE=off` disables it. //! //! Client interface (frozen v1): //! repo-queue dispatch --repo --command '' @@ -707,8 +710,14 @@ fn with_store_lock(f: impl FnOnce() -> R) -> R { /// Commit one new session record (and optionally its Blacksmith /// ledger entry) under the store lock, merging into the CURRENT /// store on disk — records written by other processes since this -/// process loaded its snapshot are preserved. -fn commit_new_session(rec: &Value, blacksmith_entry: Option<&Value>) -> R<()> { +/// process loaded its snapshot are preserved. The local commit is +/// the commit: afterwards the record mirrors best-effort to the +/// queue backend (#13146), where a failure changes nothing locally. +fn commit_new_session( + rec: &Value, + blacksmith_entry: Option<&Value>, + remote: &dyn remote::SessionRemote, +) -> R<()> { let handle = rec .get("handle") .and_then(|h| h.as_str()) @@ -730,7 +739,9 @@ fn commit_new_session(rec: &Value, blacksmith_entry: Option<&Value>) -> R<()> { } } save_store(&store) - }) + })?; + let _ = remote.put(rec); + Ok(()) } fn load_store() -> Value { @@ -837,6 +848,7 @@ fn submitted_by() -> String { // ---------------------------------------------------------------- adapters mod adapters; +mod remote; use adapters::adapter_for; #[cfg(test)] use adapters::correlate_run; @@ -1594,6 +1606,9 @@ fn run_dispatch(args: &[String]) -> R { }; let registry = registry_value(&cli)?; let gh = RealGh::new(); + // #13146: the session mirror to the queue backend. Best-effort + // throughout — nothing below may fail because it did. + let remote = remote::session_remote(); // Reconcile outstanding Blacksmith sessions BEFORE the // placement decision (Codex P2 on PR #8325), so the budget // figure build_ctx sums reflects real run durations rather @@ -1622,13 +1637,18 @@ fn run_dispatch(args: &[String]) -> R { Ok(previous) })? } else { - load_store() + // #13146: the previous session may live only in the + // backend mirror (dispatched from another seat) — take + // the newer of the local and backend copies. + let local = load_store() .get("sessions") .and_then(Value::as_object) .and_then(|sessions| sessions.get(handle)) - .cloned() + .cloned(); + let mirrored = remote.get(handle).ok().flatten(); + remote::pick_session(local, mirrored) .ok_or_else(|| Die(format!( - "--followup {handle}: no session with this handle in the local Fleet placement store" + "--followup {handle}: no session with this handle in the local or backend Fleet placement store" )))? }; let state = previous @@ -1730,7 +1750,7 @@ fn run_dispatch(args: &[String]) -> R { "created_at": now_iso(), "updated_at": now_iso(), }); - commit_new_session(&rec, None)?; + commit_new_session(&rec, None, &*remote)?; out.insert("handle".into(), json!(handle)); out.insert("state".into(), json!("queued")); } @@ -1805,7 +1825,7 @@ fn run_dispatch(args: &[String]) -> R { } else { None }; - commit_new_session(&Value::Object(rec), blacksmith_entry.as_ref())?; + commit_new_session(&Value::Object(rec), blacksmith_entry.as_ref(), &*remote)?; out.insert("handle".into(), json!(handle)); if let Some(run_id) = result.run_id { if !runner_repo.is_empty() { @@ -1826,6 +1846,9 @@ fn run_dispatch(args: &[String]) -> R { ); } } + // #13146: opportunistic migration — push any local records the + // backend still lacks (insert-or-ignore there; idempotent). + remote::sync_local_sessions(&*remote, &load_store()); print_out(&Value::Object(out), cli.json, render_decision); Ok(0) } @@ -1837,6 +1860,8 @@ fn run_session(args: &[String]) -> R { let (cli, rest) = extract_common(args)?; let sub = rest.first().map(|s| s.as_str()).unwrap_or(""); let gh = RealGh::new(); + // #13146: the session mirror to the queue backend (best-effort). + let remote = remote::session_remote(); match sub { "status" | "result" => { let handle = rest @@ -1847,12 +1872,32 @@ fn run_session(args: &[String]) -> R { let rec = if parse_portable_run_reference(&handle).is_some() { resolve_portable_run_reference(&handle, ®istry, &gh)? } else { - with_store_lock(|| { + // #13146: seed the local store from the backend + // mirror when it holds the newer copy (or the only + // copy — a session dispatched from another seat), + // refresh as usual, and mirror the refreshed record + // back. Any mirror failure leaves today's local-only + // behavior untouched. + let mirrored = remote.get(&handle).ok().flatten(); + let rec = with_store_lock(|| { let mut store = load_store(); + if let Some(m) = &mirrored { + let local = store + .get("sessions") + .and_then(|s| s.get(&handle)) + .cloned(); + if let Some(winner) = remote::pick_session(local, Some(m.clone())) { + if let Some(sessions) = store["sessions"].as_object_mut() { + sessions.insert(handle.clone(), winner); + } + } + } let rec = refresh_session(&mut store, &handle, ®istry, &gh)?; save_store(&store)?; Ok(rec) - })? + })?; + let _ = remote.put(&rec); + rec }; if sub == "status" { print_out(&rec, cli.json, |r| { @@ -1893,11 +1938,19 @@ fn run_session(args: &[String]) -> R { let mine = rest.iter().any(|a| a == "--mine"); let store = load_store(); let me = submitted_by(); - let mut sessions: Vec = store + let local_sessions: Vec = store .get("sessions") .and_then(|s| s.as_object()) .map(|m| m.values().cloned().collect()) .unwrap_or_default(); + // #13146: union in the backend mirror's records (a + // failed mirror read lists local-only, as before), then + // take the chance to migrate local records upward. + let mirrored_sessions = remote + .list(if mine { Some(me.as_str()) } else { None }, 200) + .unwrap_or_default(); + let mut sessions = remote::merge_session_records(local_sessions, mirrored_sessions); + remote::sync_local_sessions(&*remote, &store); sessions.sort_by(|a, b| { b.get("created_at") .and_then(|v| v.as_str()) @@ -2755,6 +2808,7 @@ mod tests { commit_new_session( &json!({ "handle": "fp_mine", "state": "queued" }), Some(&json!({ "handle": "fp_mine", "month": current_month(), "minutes": 0.0 })), + &remote::NullRemote, ) .unwrap(); let back = load_store(); @@ -2765,6 +2819,67 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// A placement-mirror fake for the commit wiring tests: + /// records puts, and can be told to fail (the backend-down + /// case). + struct RecordingRemote { + puts: RefCell>, + fail: bool, + } + + impl remote::SessionRemote for RecordingRemote { + fn put(&self, rec: &Value) -> Result<(), String> { + if self.fail { + return Err("backend down".to_string()); + } + self.puts.borrow_mut().push(rec.clone()); + Ok(()) + } + fn get(&self, _handle: &str) -> Result, String> { + Err("not used by commit".to_string()) + } + fn list(&self, _who: Option<&str>, _limit: usize) -> Result, String> { + Err("not used by commit".to_string()) + } + fn sync(&self, _records: &[Value]) -> Result { + Err("not used by commit".to_string()) + } + } + + #[test] + fn commit_new_session_mirrors_and_survives_remote_failure() { + // Oracle (#13146): the local commit lands identically + // whether the mirror accepts the record or is down; when + // the mirror is up it receives exactly the committed + // record — the local store is the commit, the mirror is a + // mirror. + let _store_env_guard = STORE_ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner()); + let dir = + std::env::temp_dir().join(format!("fleet-place-test-mirror-{}", std::process::id())); + unsafe { std::env::set_var("FLEET_PLACE_STATE", &dir) }; + let rec = json!({ "handle": "fp_mirror", "state": "queued" }); + let up = RecordingRemote { + puts: RefCell::new(Vec::new()), + fail: false, + }; + commit_new_session(&rec, None, &up).unwrap(); + assert_eq!(up.puts.borrow().as_slice(), &[rec.clone()]); + assert_eq!(load_store()["sessions"]["fp_mirror"]["state"], json!("queued")); + let down = RecordingRemote { + puts: RefCell::new(Vec::new()), + fail: true, + }; + commit_new_session( + &json!({ "handle": "fp_offline", "state": "queued" }), + None, + &down, + ) + .unwrap(); + assert_eq!(load_store()["sessions"]["fp_offline"]["state"], json!("queued")); + unsafe { std::env::remove_var("FLEET_PLACE_STATE") }; + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn embedded_registry_parses_and_has_org_run() { let reg = load_embedded_registry().unwrap(); diff --git a/pkgs/fleet/crates/fleet-queue/src/placement/remote.rs b/pkgs/fleet/crates/fleet-queue/src/placement/remote.rs new file mode 100644 index 0000000000..9eb373580c --- /dev/null +++ b/pkgs/fleet/crates/fleet-queue/src/placement/remote.rs @@ -0,0 +1,338 @@ +//! Placement session mirror to the queue backend (#13146). +//! +//! The local JSON store stays the always-available store and the +//! ONLY input to placement decisions; this module is the +//! best-effort mirror that makes session records visible from +//! every seat. Every operation is allowed to fail — callers treat +//! an Err as "backend unreachable" and proceed exactly as the +//! pre-mirror client did. The transport is the queue client's +//! bounded roundtrip (see client::transport): short budget, errors +//! returned, never a process exit, never a broker auto-spawn, so a +//! dispatch can neither fail nor stall on the mirror. + +use serde_json::{Value, json}; +use std::time::Duration; + +/// One mirror roundtrip's budget. The broker is on the tailnet or +/// the same host; five seconds is generous for four small SQL +/// statements and far below the queue client's 300s legs. +pub const REMOTE_BUDGET: Duration = Duration::from_secs(5); + +/// How many local records one migration sweep pushes. The backend +/// caps /placement-sync at 500; 100 keeps each sweep's body small +/// and bounds the work a single dispatch/list call can do. +pub const SYNC_BATCH: usize = 100; + +/// The queue-backend half of the placement session store. The +/// production implementation is [`BrokerRemote`]; tests substitute +/// a fake. All methods are best-effort by contract. +pub trait SessionRemote { + /// Upsert one session record (state refreshes included). + fn put(&self, rec: &Value) -> Result<(), String>; + /// The backend's record for a handle, if it holds one. + fn get(&self, handle: &str) -> Result, String>; + /// Newest-first session records, optionally one submitter's. + fn list(&self, submitted_by: Option<&str>, limit: usize) -> Result, String>; + /// Insert-or-ignore a batch of local records (migration); + /// returns how many were newly inserted. + fn sync(&self, records: &[Value]) -> Result; +} + +/// The production remote: the queue broker's /placement-* verbs +/// over the bounded transport. +pub struct BrokerRemote; + +impl BrokerRemote { + fn call(&self, path: &str, body: &Value) -> Result { + let resp = crate::client::broker_roundtrip_bounded(path, body, REMOTE_BUDGET)?; + if resp.get("ok").and_then(|o| o.as_bool()) == Some(true) { + Ok(resp) + } else { + Err(resp + .get("error") + .and_then(|e| e.as_str()) + .unwrap_or("queue backend refused the placement mirror call") + .to_string()) + } + } +} + +impl SessionRemote for BrokerRemote { + fn put(&self, rec: &Value) -> Result<(), String> { + self.call("/placement-put", &json!({"record": rec}))?; + Ok(()) + } + + fn get(&self, handle: &str) -> Result, String> { + let resp = self.call("/placement-get", &json!({"handle": handle}))?; + match resp.get("record") { + Some(Value::Null) | None => Ok(None), + Some(rec) => Ok(Some(rec.clone())), + } + } + + fn list(&self, submitted_by: Option<&str>, limit: usize) -> Result, String> { + let mut body = json!({"limit": limit}); + if let Some(who) = submitted_by { + body["submitted_by"] = json!(who); + } + let resp = self.call("/placement-list", &body)?; + Ok(resp + .get("sessions") + .and_then(|s| s.as_array()) + .cloned() + .unwrap_or_default()) + } + + fn sync(&self, records: &[Value]) -> Result { + let resp = self.call("/placement-sync", &json!({"records": records}))?; + Ok(resp.get("inserted").and_then(|i| i.as_i64()).unwrap_or(0)) + } +} + +/// The disabled remote (`FLEET_PLACE_REMOTE=off`): every call +/// fails, which callers already treat as "backend unreachable" — +/// local-only behavior, identical to the pre-#13146 client. +pub struct NullRemote; + +impl SessionRemote for NullRemote { + fn put(&self, _rec: &Value) -> Result<(), String> { + Err("placement remote disabled".to_string()) + } + fn get(&self, _handle: &str) -> Result, String> { + Err("placement remote disabled".to_string()) + } + fn list(&self, _submitted_by: Option<&str>, _limit: usize) -> Result, String> { + Err("placement remote disabled".to_string()) + } + fn sync(&self, _records: &[Value]) -> Result { + Err("placement remote disabled".to_string()) + } +} + +/// The remote for this process: the broker mirror unless the +/// operator escape hatch `FLEET_PLACE_REMOTE=off` is set. +pub fn session_remote() -> Box { + match std::env::var("FLEET_PLACE_REMOTE") { + Ok(v) if v == "off" => Box::new(NullRemote), + _ => Box::new(BrokerRemote), + } +} + +fn updated_at(rec: &Value) -> &str { + rec.get("updated_at").and_then(|v| v.as_str()).unwrap_or("") +} + +fn created_at(rec: &Value) -> &str { + rec.get("created_at").and_then(|v| v.as_str()).unwrap_or("") +} + +fn handle_of(rec: &Value) -> &str { + rec.get("handle").and_then(|v| v.as_str()).unwrap_or("") +} + +/// Pick between the local and backend copies of one session: the +/// record with the newer `updated_at` wins; a tie goes to the +/// backend copy (it is the shared record other seats converge on). +pub fn pick_session(local: Option, remote: Option) -> Option { + match (local, remote) { + (Some(l), Some(r)) => { + if updated_at(&r) >= updated_at(&l) { + Some(r) + } else { + Some(l) + } + } + (Some(l), None) => Some(l), + (None, Some(r)) => Some(r), + (None, None) => None, + } +} + +/// Union two session lists by handle (per-handle winner by +/// [`pick_session`]), newest first — the `session list` view across +/// the local store and the backend. No record present in either +/// input is dropped. +pub fn merge_session_records(local: Vec, remote: Vec) -> Vec { + let mut by_handle: std::collections::HashMap = std::collections::HashMap::new(); + for rec in local { + by_handle.insert(handle_of(&rec).to_string(), rec); + } + for rec in remote { + let key = handle_of(&rec).to_string(); + let cur = by_handle.remove(&key); + if let Some(winner) = pick_session(cur, Some(rec)) { + by_handle.insert(key, winner); + } + } + let mut out: Vec = by_handle.into_values().collect(); + out.sort_by(|a, b| created_at(b).cmp(created_at(a))); + out +} + +/// Best-effort migration sweep: push the local store's most recent +/// records to the backend, which inserts-or-ignores them — a +/// record the backend already holds is never overwritten, so the +/// sweep is idempotent and safe to run on every dispatch and list. +/// Failures are the caller's signal to stay local-only; nothing +/// here is allowed to surface as an error. +pub fn sync_local_sessions(remote: &dyn SessionRemote, store: &Value) { + let mut recs: Vec = store + .get("sessions") + .and_then(|s| s.as_object()) + .map(|m| m.values().cloned().collect()) + .unwrap_or_default(); + if recs.is_empty() { + return; + } + recs.sort_by(|a, b| created_at(b).cmp(created_at(a))); + recs.truncate(SYNC_BATCH); + let _ = remote.sync(&recs); +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::RefCell; + + fn rec(handle: &str, created: &str, updated: &str, state: &str) -> Value { + json!({ + "handle": handle, + "state": state, + "created_at": created, + "updated_at": updated, + "submitted_by": "archer@test", + }) + } + + /// In-memory remote: records calls, serves stored records, + /// and can be switched to failing (the backend-down case). + struct FakeRemote { + stored: RefCell>, + fail: RefCell, + syncs: RefCell>>, + } + + impl FakeRemote { + fn new() -> Self { + FakeRemote { + stored: RefCell::new(std::collections::HashMap::new()), + fail: RefCell::new(false), + syncs: RefCell::new(Vec::new()), + } + } + } + + impl SessionRemote for FakeRemote { + fn put(&self, rec: &Value) -> Result<(), String> { + if *self.fail.borrow() { + return Err("backend down".to_string()); + } + self.stored + .borrow_mut() + .insert(handle_of(rec).to_string(), rec.clone()); + Ok(()) + } + fn get(&self, handle: &str) -> Result, String> { + if *self.fail.borrow() { + return Err("backend down".to_string()); + } + Ok(self.stored.borrow().get(handle).cloned()) + } + fn list(&self, _who: Option<&str>, _limit: usize) -> Result, String> { + if *self.fail.borrow() { + return Err("backend down".to_string()); + } + Ok(self.stored.borrow().values().cloned().collect()) + } + fn sync(&self, records: &[Value]) -> Result { + if *self.fail.borrow() { + return Err("backend down".to_string()); + } + self.syncs.borrow_mut().push(records.to_vec()); + let mut stored = self.stored.borrow_mut(); + let mut inserted = 0; + for rec in records { + let key = handle_of(rec).to_string(); + if !stored.contains_key(&key) { + stored.insert(key, rec.clone()); + inserted += 1; + } + } + Ok(inserted) + } + } + + #[test] + fn pick_session_prefers_the_newer_record() { + // Oracle: updated_at decides; ties go to the backend copy. + let older = rec("fp_a", "2026-11-23T08:00:00Z", "2026-11-23T08:01:00Z", "running"); + let newer = rec("fp_a", "2026-11-23T08:00:00Z", "2026-11-23T08:02:00Z", "succeeded"); + assert_eq!( + pick_session(Some(older.clone()), Some(newer.clone())).unwrap(), + newer + ); + assert_eq!( + pick_session(Some(newer.clone()), Some(older.clone())).unwrap(), + newer + ); + let tied_remote = rec("fp_a", "2026-11-23T08:00:00Z", "2026-11-23T08:02:00Z", "failed"); + assert_eq!( + pick_session(Some(newer), Some(tied_remote.clone())).unwrap(), + tied_remote + ); + assert!(pick_session(None, None).is_none()); + } + + #[test] + fn merge_unions_without_dropping_local_only_records() { + // Oracle: list shows every record from either store, the + // newer copy of a shared handle wins, newest first. + let local_only = rec("fp_local", "2026-11-23T08:00:00Z", "2026-11-23T08:00:00Z", "queued"); + let shared_old = rec("fp_shared", "2026-11-23T07:00:00Z", "2026-11-23T07:30:00Z", "running"); + let shared_new = rec("fp_shared", "2026-11-23T07:00:00Z", "2026-11-23T07:45:00Z", "succeeded"); + let remote_only = rec("fp_remote", "2026-11-23T09:00:00Z", "2026-11-23T09:00:00Z", "running"); + let merged = merge_session_records( + vec![local_only.clone(), shared_old], + vec![shared_new.clone(), remote_only.clone()], + ); + assert_eq!(merged.len(), 3); + assert_eq!(merged[0], remote_only); + assert_eq!(merged[1], local_only); + assert_eq!(merged[2], shared_new); + } + + #[test] + fn sync_sweeps_local_records_and_tolerates_failure() { + // Oracle: the sweep offers the local store's records to the + // backend insert-or-ignore; with the backend down it is a + // silent no-op (the caller proceeds local-only). + let store = json!({"sessions": { + "fp_a": rec("fp_a", "2026-11-23T08:00:00Z", "2026-11-23T08:00:00Z", "queued"), + "fp_b": rec("fp_b", "2026-11-23T08:01:00Z", "2026-11-23T08:01:00Z", "running"), + }}); + let remote = FakeRemote::new(); + sync_local_sessions(&remote, &store); + assert_eq!(remote.syncs.borrow().len(), 1); + assert_eq!(remote.stored.borrow().len(), 2); + // A second sweep inserts nothing new (idempotent). + sync_local_sessions(&remote, &store); + assert_eq!(remote.stored.borrow().len(), 2); + + let down = FakeRemote::new(); + *down.fail.borrow_mut() = true; + sync_local_sessions(&down, &store); // must not panic or surface + assert!(down.stored.borrow().is_empty()); + } + + #[test] + fn fake_remote_round_trips_a_put_through_get() { + // Harness sanity: the fake the placement wiring tests use + // behaves like the verb contract (put upserts, get reads). + let remote = FakeRemote::new(); + let r = rec("fp_a", "2026-11-23T08:00:00Z", "2026-11-23T08:00:00Z", "queued"); + remote.put(&r).unwrap(); + assert_eq!(remote.get("fp_a").unwrap(), Some(r)); + assert_eq!(remote.get("fp_nope").unwrap(), None); + } +} diff --git a/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs index afbb18cc63..c7b092c91c 100644 --- a/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs +++ b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs @@ -49,6 +49,7 @@ mod closed_bound; mod core; mod label_enrich; mod lifecycle; +mod placement_sessions; mod stacks_outbox; mod staleness; mod work_identity; @@ -59,6 +60,7 @@ pub use claim::*; pub use core::*; pub use label_enrich::*; pub use lifecycle::*; +pub use placement_sessions::*; pub use stacks_outbox::*; pub use staleness::*; pub use work_identity::*; 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 86d8e200b0..fbb508699a 100644 --- a/pkgs/fleet/crates/fleet-queue/src/turso_queue/core.rs +++ b/pkgs/fleet/crates/fleet-queue/src/turso_queue/core.rs @@ -819,6 +819,16 @@ impl TursoBackend { .unwrap()) } + /// #13146: several statements in one pipeline request (the + /// placement-sync batch insert). Same per-statement results as + /// repeated `exec` calls, one round trip. + pub(crate) fn exec_batch( + &self, + stmts: &[(&str, Vec)], + ) -> Result, TErr> { + self.pipeline(stmts) + } + /// Rows of one SELECT as JSON objects, with the given TEXT /// columns parsed back into JSON values. pub(crate) fn query_objs( @@ -976,7 +986,7 @@ impl Clone for Arg { } } -pub(crate) const SCHEMA: [&str; 17] = [ +pub(crate) const SCHEMA: [&str; 19] = [ "CREATE TABLE IF NOT EXISTS tasks (\ id INTEGER PRIMARY KEY AUTOINCREMENT, \ queue TEXT NOT NULL, title TEXT, body TEXT, \ @@ -1050,6 +1060,18 @@ pub(crate) const SCHEMA: [&str; 17] = [ // #8582 increment 2: the merge-intent table, DDL of record in // the pure core module. crate::merge_intent::MERGE_INTENT_DDL, + // #13146: placement session records — the designed home for the + // fleet-place session store (intake DDL in + // doc/placement-intake/placement.md, carried into the Turso + // backend). `record` holds the full session JSON — the client + // record shape is the contract; the scalar columns are + // extractions for list/filter queries. + "CREATE TABLE IF NOT EXISTS placement_sessions (\ + handle TEXT PRIMARY KEY, record TEXT NOT NULL DEFAULT '{}', \ + state TEXT, surface TEXT, submitted_by TEXT, run_id INTEGER, \ + created_at TEXT NOT NULL, updated_at TEXT NOT NULL)", + "CREATE INDEX IF NOT EXISTS placement_sessions_created \ + ON placement_sessions(created_at)", ]; // --------------------------------------------------------------------------- diff --git a/pkgs/fleet/crates/fleet-queue/src/turso_queue/placement_sessions.rs b/pkgs/fleet/crates/fleet-queue/src/turso_queue/placement_sessions.rs new file mode 100644 index 0000000000..691680fd40 --- /dev/null +++ b/pkgs/fleet/crates/fleet-queue/src/turso_queue/placement_sessions.rs @@ -0,0 +1,394 @@ +//! turso_queue::placement_sessions — placement session records +//! (#13146): the queue-backend home for fleet placement sessions. +//! +//! Split as its own module following the #8589 pattern. The client +//! session record JSON is the contract: `record` stores it verbatim +//! and the scalar columns are extractions for list/filter queries, +//! the same shape tasks use for payload/progress/result. +//! +//! The mirror is one-directional per verb: /placement-put upserts +//! (a seat refreshing a session's state is the authority for that +//! update), /placement-sync inserts-or-ignores (the migration path +//! for pre-existing local stores — it can never overwrite a row the +//! backend already holds). + +use super::*; + +const PLACEMENT_PUT_SQL: &str = "INSERT INTO placement_sessions \ + (handle, record, state, surface, submitted_by, run_id, created_at, updated_at) \ + VALUES (?, ?, ?, ?, ?, ?, ?, ?) \ + ON CONFLICT(handle) DO UPDATE SET \ + record = excluded.record, state = excluded.state, \ + surface = excluded.surface, submitted_by = excluded.submitted_by, \ + run_id = excluded.run_id, updated_at = excluded.updated_at"; + +const PLACEMENT_SYNC_SQL: &str = "INSERT OR IGNORE INTO placement_sessions \ + (handle, record, state, surface, submitted_by, run_id, created_at, updated_at) \ + VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; + +/// The most records one /placement-sync call accepts. The client +/// sweeps in batches of 100; 500 leaves headroom without letting a +/// single request grow unbounded (the broker caps bodies at +/// MAX_BODY_BYTES regardless). +const PLACEMENT_SYNC_MAX: usize = 500; + +/// Extract one placement_sessions row from a client session record. +/// The record must be an object carrying a non-empty `fp_` handle +/// and created_at/updated_at stamps — the client always writes all +/// three; anything else is a caller bug, not data to store. +fn session_row(rec: &Value) -> Result, String> { + if !rec.is_object() { + return Err("record must be a JSON object".to_string()); + } + let handle = rec + .get("handle") + .and_then(|h| h.as_str()) + .filter(|h| h.starts_with("fp_") && h.len() > 3) + .ok_or_else(|| "record.handle must be an fp_ session handle".to_string())?; + let created_at = rec + .get("created_at") + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) + .ok_or_else(|| "record.created_at is required".to_string())?; + let updated_at = rec + .get("updated_at") + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) + .ok_or_else(|| "record.updated_at is required".to_string())?; + Ok(vec![ + Arg::Text(handle.to_string()), + Arg::Text(rec.to_string()), + arg_str(rec.get("state").and_then(|v| v.as_str())), + arg_str(rec.get("surface").and_then(|v| v.as_str())), + arg_str(rec.get("submitted_by").and_then(|v| v.as_str())), + rec.get("run_id") + .and_then(|v| v.as_i64()) + .map(Arg::Int) + .unwrap_or(Arg::Null), + Arg::Text(created_at.to_string()), + Arg::Text(updated_at.to_string()), + ]) +} + +/// Column names, for the row-shape assertion in tests. +#[cfg(test)] +const PLACEMENT_COLS: &str = "handle, record, state, surface, submitted_by, \ + run_id, created_at, updated_at"; + +pub(crate) fn verb_placement_put(t: &TursoBackend, req: &Value) -> Value { + let rec = req.get("record").cloned().unwrap_or(Value::Null); + let args = match session_row(&rec) { + Ok(a) => a, + Err(e) => return fail(2, e), + }; + let handle = rec + .get("handle") + .and_then(|h| h.as_str()) + .unwrap_or("") + .to_string(); + let work = (|| -> Result { + t.exec(PLACEMENT_PUT_SQL, &args)?; + Ok(json!({"handle": handle})) + })(); + match work { + Ok(v) => ok(v), + Err(e) => terr(e), + } +} + +pub(crate) fn verb_placement_get(t: &TursoBackend, req: &Value) -> Value { + let Some(handle) = req_str(req, "handle").filter(|h| !h.is_empty()) else { + return fail(2, "handle is required".to_string()); + }; + let handle = handle.to_string(); + let work = (|| -> Result { + let rows = t.query_objs( + "SELECT record FROM placement_sessions WHERE handle = ?", + &[Arg::Text(handle.clone())], + &["record"], + )?; + let record = rows + .into_iter() + .next() + .and_then(|r| r.get("record").cloned()) + .unwrap_or(Value::Null); + Ok(json!({"handle": handle, "record": record})) + })(); + match work { + Ok(v) => ok(v), + Err(e) => terr(e), + } +} + +pub(crate) fn verb_placement_list(t: &TursoBackend, req: &Value) -> Value { + let limit = req_i64(req, "limit").unwrap_or(100).clamp(1, 500); + let mine = req_str(req, "submitted_by").map(str::to_string); + let work = (|| -> Result { + let (sql, args): (&str, Vec) = match &mine { + Some(who) => ( + "SELECT record FROM placement_sessions \ + WHERE submitted_by = ? ORDER BY created_at DESC LIMIT ?", + vec![Arg::Text(who.clone()), Arg::Int(limit)], + ), + None => ( + "SELECT record FROM placement_sessions \ + ORDER BY created_at DESC LIMIT ?", + vec![Arg::Int(limit)], + ), + }; + let rows = t.query_objs(sql, &args, &["record"])?; + let sessions: Vec = rows + .iter() + .filter_map(|r| r.get("record").cloned()) + .filter(|r| !r.is_null()) + .collect(); + Ok(json!({"sessions": sessions})) + })(); + match work { + Ok(v) => ok(v), + Err(e) => terr(e), + } +} + +pub(crate) fn verb_placement_sync(t: &TursoBackend, req: &Value) -> Value { + let Some(records) = req.get("records").and_then(|r| r.as_array()) else { + return fail(2, "records array is required".to_string()); + }; + if records.len() > PLACEMENT_SYNC_MAX { + return fail( + 2, + format!( + "records is capped at {PLACEMENT_SYNC_MAX} per sync call, got {}", + records.len() + ), + ); + } + // Validate every row before any write: a malformed record fails + // the batch whole, and the client (best-effort) retries the + // sweep on a later backend contact. + let mut stmts: Vec<(&str, Vec)> = Vec::with_capacity(records.len()); + for rec in records { + match session_row(rec) { + Ok(args) => stmts.push((PLACEMENT_SYNC_SQL, args)), + Err(e) => return fail(2, e), + } + } + let received = stmts.len(); + let work = (|| -> Result { + let mut inserted: u64 = 0; + for chunk in stmts.chunks(100) { + for result in t.exec_batch(chunk)? { + inserted += result.affected; + } + } + Ok(json!({"inserted": inserted, "received": received})) + })(); + match work { + Ok(v) => ok(v), + Err(e) => terr(e), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::{BufRead, BufReader, Read, Write}; + + fn sample_record(handle: &str, updated_at: &str) -> Value { + json!({ + "handle": handle, + "job": {"repo": "developing-today/code", "command": "cargo test"}, + "surface": "fleet-org", + "surface_kind": "github-actions", + "decision_reasoning": ["test"], + "run_id": 42, + "run_url": "https://example.invalid/runs/42", + "state": "running", + "submitted_by": "archer@test", + "actor": "developing-today[bot] (GitHub App dispatch)", + "created_at": "2026-11-23T08:00:00Z", + "updated_at": updated_at, + }) + } + + /// A stub of the Turso pipeline endpoint in the #12744 shape: + /// captures request bodies and answers each execute statement + /// with a canned result — `select_rows` (record JSON strings) + /// when the batch is a SELECT, affected=1 per statement + /// otherwise. + fn stub_pipeline( + select_rows: Vec, + ) -> (String, std::sync::Arc>>) { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let captured = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let sink = captured.clone(); + std::thread::spawn(move || { + loop { + let Ok((mut sock, _)) = listener.accept() else { + return; + }; + let mut reader = BufReader::new(sock.try_clone().unwrap()); + let mut content_length = 0usize; + loop { + let mut line = String::new(); + if reader.read_line(&mut line).unwrap_or(0) == 0 { + break; + } + 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 text = String::from_utf8_lossy(&body).to_string(); + let executes = text.matches("\"type\":\"execute\"").count(); + let is_select = text.contains("SELECT record FROM placement_sessions"); + sink.lock().unwrap().push(text); + let mut results = Vec::new(); + for i in 0..executes { + let result = if is_select && i == 0 { + let rows: Vec = select_rows + .iter() + .map(|r| json!([{"type": "text", "value": r}])) + .collect(); + json!({"cols": [{"name": "record"}], "rows": rows, + "affected_row_count": 0, "last_insert_rowid": null}) + } else { + json!({"cols": [], "rows": [], + "affected_row_count": 1, "last_insert_rowid": null}) + }; + results.push(json!({"type": "ok", "response": {"type": "execute", "result": result}})); + } + let resp_body = json!({"results": results}).to_string(); + let resp = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\ + Content-Length: {}\r\nConnection: close\r\n\r\n{}", + resp_body.len(), + resp_body + ); + if sock.write_all(resp.as_bytes()).is_err() { + return; + } + } + }); + (format!("http://{addr}"), captured) + } + + fn backend(url: String) -> TursoBackend { + TursoBackend::new(url, "test".to_string(), ureq::agent()) + } + + #[test] + fn session_row_extracts_scalars_and_rejects_bad_records() { + // Oracle: the row shape the schema declares — handle first, + // record verbatim, scalars extracted, run_id as INTEGER. + let rec = sample_record("fp_abc123", "2026-11-23T08:05:00Z"); + let args = session_row(&rec).unwrap(); + assert_eq!(args.len(), PLACEMENT_COLS.split(',').count()); + assert!(matches!(&args[0], Arg::Text(h) if h == "fp_abc123")); + assert!(matches!(&args[1], Arg::Text(r) if r == &rec.to_string())); + assert!(matches!(&args[5], Arg::Int(42))); + // A record without an fp_ handle is a caller bug. + assert!(session_row(&json!({"handle": "xx"})).is_err()); + assert!(session_row(&json!({"handle": "fp_x"})).is_err()); + assert!(session_row(&json!({})).is_err()); + assert!(session_row(&json!("nope")).is_err()); + } + + #[test] + fn placement_put_upserts_the_record() { + // Oracle: one execute carrying the upsert SQL and the full + // record; the reply names the stored handle. + let (url, captured) = stub_pipeline(vec![]); + let out = verb_placement_put( + &backend(url), + &json!({"record": sample_record("fp_abc123", "2026-11-23T08:05:00Z")}), + ); + assert_eq!(out["ok"], true, "{out}"); + assert_eq!(out["handle"], "fp_abc123", "{out}"); + let bodies = captured.lock().unwrap(); + assert_eq!(bodies.len(), 1, "{bodies:?}"); + assert!(bodies[0].contains("INSERT INTO placement_sessions"), "{bodies:?}"); + assert!(bodies[0].contains("ON CONFLICT(handle) DO UPDATE"), "{bodies:?}"); + assert!(bodies[0].contains("fp_abc123"), "{bodies:?}"); + } + + #[test] + fn placement_put_rejects_a_record_without_handle() { + let (url, captured) = stub_pipeline(vec![]); + let out = verb_placement_put(&backend(url), &json!({"record": {"state": "running"}})); + assert_eq!(out["ok"], false, "{out}"); + // Validation happens before any statement is sent. + assert!(captured.lock().unwrap().is_empty()); + } + + #[test] + fn placement_get_returns_the_stored_record_or_null() { + // Oracle: the stored record JSON round-trips through the + // record column; a missing handle reads back as null, not + // an error (a fresh seat has no rows yet). + let rec = sample_record("fp_abc123", "2026-11-23T08:05:00Z"); + let (url, _) = stub_pipeline(vec![rec.to_string()]); + let out = verb_placement_get(&backend(url), &json!({"handle": "fp_abc123"})); + assert_eq!(out["ok"], true, "{out}"); + assert_eq!(out["record"], rec, "{out}"); + + let (url, _) = stub_pipeline(vec![]); + let out = verb_placement_get(&backend(url), &json!({"handle": "fp_missing"})); + assert_eq!(out["ok"], true, "{out}"); + assert_eq!(out["record"], Value::Null, "{out}"); + } + + #[test] + fn placement_list_returns_records_newest_first_shape() { + let a = sample_record("fp_a", "2026-11-23T08:05:00Z"); + let b = sample_record("fp_b", "2026-11-23T08:06:00Z"); + let (url, captured) = stub_pipeline(vec![b.to_string(), a.to_string()]); + let out = verb_placement_list(&backend(url), &json!({"limit": 10})); + assert_eq!(out["ok"], true, "{out}"); + assert_eq!(out["sessions"], json!([b, a]), "{out}"); + let bodies = captured.lock().unwrap(); + assert!(bodies[0].contains("ORDER BY created_at DESC"), "{bodies:?}"); + } + + #[test] + fn placement_sync_inserts_or_ignores_and_counts() { + // Oracle: the migration verb NEVER overwrites — its SQL is + // INSERT OR IGNORE — and the reply counts affected rows + // against received records. + let (url, captured) = stub_pipeline(vec![]); + let out = verb_placement_sync( + &backend(url), + &json!({"records": [ + sample_record("fp_a", "2026-11-23T08:05:00Z"), + sample_record("fp_b", "2026-11-23T08:06:00Z"), + ]}), + ); + assert_eq!(out["ok"], true, "{out}"); + assert_eq!(out["received"], 2, "{out}"); + assert_eq!(out["inserted"], 2, "{out}"); + let bodies = captured.lock().unwrap(); + assert!(bodies[0].contains("INSERT OR IGNORE INTO placement_sessions"), "{bodies:?}"); + assert!(!bodies[0].contains("ON CONFLICT"), "{bodies:?}"); + } + + #[test] + fn placement_sync_rejects_a_bad_record_before_writing() { + let (url, captured) = stub_pipeline(vec![]); + let out = verb_placement_sync( + &backend(url), + &json!({"records": [sample_record("fp_a", "2026-11-23T08:05:00Z"), {"no": "handle"}]}), + ); + assert_eq!(out["ok"], false, "{out}"); + assert!(captured.lock().unwrap().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 4effa52db7..9304b5916b 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 @@ -1039,6 +1039,10 @@ pub fn dispatch(t: &TursoBackend, path: &str, req: &Value) -> Value { "/stack-transition" => verb_stack_transition(t, req), "/stack-restack" => verb_stack_restack(t, req), "/events-append" => verb_events_append(t, req), + "/placement-put" => verb_placement_put(t, req), + "/placement-get" => verb_placement_get(t, req), + "/placement-list" => verb_placement_list(t, req), + "/placement-sync" => verb_placement_sync(t, req), "/events-seen" => verb_events_seen(t, req), "/events-count" => verb_events_count(t, req), "/events-list" => verb_events_list(t, req), diff --git a/pkgs/fleet/doc/agents/remote-build-and-test.md b/pkgs/fleet/doc/agents/remote-build-and-test.md index 7508ab7d9b..bd179addde 100644 --- a/pkgs/fleet/doc/agents/remote-build-and-test.md +++ b/pkgs/fleet/doc/agents/remote-build-and-test.md @@ -92,9 +92,10 @@ For a detached laptop command, add `--detach` and track the returned job ID with ## Portable run IDs -Random `fp_...` handles and their records remain in `~/.local/state/fleet-place/sessions.json`. They work where that local store is available. For a follow-up from another agent or workspace, use the portable `OWNER/REPO#RUN_ID` identifier; Fleet resolves it through GitHub without the local session record. If dispatch has not correlated a run ID yet, keep using the local handle. +Random `fp_...` handles and their records live in `~/.local/state/fleet-place/sessions.json` and mirror best-effort to the queue backend's `placement_sessions` table, so a handle resolves from any seat whose client can reach the broker; the local store remains the offline fallback (and the only input to placement decisions). For a follow-up from another agent or workspace, the portable `OWNER/REPO#RUN_ID` identifier also works; Fleet resolves it through GitHub without the local session record. If dispatch has not correlated a run ID yet, keep using the local handle. ## Other dispatch routes - **`fleet dispatch-test scan|submit|status`** — the explicit-dispatch route for work inside a fleet-umbrella submodule. `scan` lists the execution homes (dezren39/fleet and its fork network) with their live Actions load and picks the first with free capacity; `submit --submodule --ref --commands ''` stores the job in the fleet-dispatch Turso store and dispatches `fleet-dispatch-test.yml` there; `status ` reads the stored result. Linux, GitHub-hosted only; use it when the job is naturally "run inside submodule X at ref Y". - **Raw workflow dispatch** — when no current `fleet` binary is at hand, dispatch the workflows directly: `gh workflow run fleet-command.yml --repo developing-today/fleet -f repo= -f ref= -f command=''` (the same runner the placement route uses; `-f platform=macos` and `-f runner=blacksmith` exist — Blacksmith stays explicit-only), or `gh workflow run fleet-run.yml --repo dezren39/fleet -f repo= -f command=''` for the matrix-capable generic runner. Track with `gh run list` / `gh run view --log` on the hosting repo. Prefer the `fleet` verbs whenever they are available: they add placement, budgets, and session tracking. +- No `queue dispatch` verb? Your binary is stale. Get a current one: in a developing-today/code checkout, run scripts/muse/bootstrap.sh (it downloads the pinned static fleet release and installs ~/tools/fleet), or ask the fleet operator for the current published build. Verify with: fleet queue dispatch --help — it must list --dispatch and --followup. On a machine without the Muse bootstrap: read the pinned release tag from the `FLEET_URL` / `FLEET_SHA256` pin block at the top of scripts/muse/bootstrap.sh on main (the tag is the `fleet-static-` segment of `FLEET_URL`), then `gh release download -R developing-today/code -p fleet-x86_64-linux-musl` and download the matching `fleet-x86_64-linux-musl.sha256` asset the same way; verify the binary against it (`sha256sum -c`) before installing. Verify after install with: fleet queue dispatch --help and fleet queue surfaces.