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
251 changes: 8 additions & 243 deletions pkgs/fleet/crates/fleet-queue/src/placement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -570,249 +570,14 @@ fn find_surface<'a>(registry: &'a Value, id: &str) -> Option<&'a Value> {

// ------------------------------------------------------------ session store

fn state_dir() -> String {
std::env::var("FLEET_PLACE_STATE")
.unwrap_or_else(|_| format!("{}/.local/state/fleet-place", home_dir()))
}

fn state_file() -> String {
format!("{}/sessions.json", state_dir())
}

/// Interprocess lock for the session store: a lock directory
/// created with create_dir (atomic) next to the store file.
/// Holders write pid+epoch into it; a lock older than 120s is
/// stale (crashed holder) and is broken. This serializes the
/// store's read-modify-write transactions so concurrent
/// dispatches/status calls cannot drop each other's sessions
/// (Codex P1 on PR #8325).
struct StoreLock {
dir: String,
}

impl StoreLock {
fn acquire() -> R<StoreLock> {
let dir = format!("{}/sessions.lockdir", state_dir());
std::fs::create_dir_all(state_dir())
.map_err(|e| Die(format!("cannot create state dir: {e}")))?;
let deadline = std::time::Instant::now() + Duration::from_secs(15);
loop {
match std::fs::create_dir(&dir) {
Ok(()) => {
let _ = std::fs::write(
format!("{dir}/owner"),
format!("{} {}", std::process::id(), now_epoch()),
);
return Ok(StoreLock { dir });
}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
let stale = std::fs::metadata(&dir)
.and_then(|m| m.modified())
.map(|t| t.elapsed().map(|d| d.as_secs() > 120).unwrap_or(false))
.unwrap_or(false);
if stale {
let _ = std::fs::remove_dir_all(&dir);
continue;
}
if std::time::Instant::now() > deadline {
return die(format!(
"session store is locked by another fleet-place process ({dir}); retry shortly"
));
}
std::thread::sleep(Duration::from_millis(50));
}
Err(e) => {
return die(format!("cannot lock session store {dir}: {e}"));
}
}
}
}
}

impl Drop for StoreLock {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.dir);
}
}

fn with_store_lock<T>(f: impl FnOnce() -> R<T>) -> R<T> {
let _guard = StoreLock::acquire()?;
f()
}

/// A clone of the registry with the named surfaces removed — the
/// dispatch-failure fall-through re-decide (#16824 item 1): a
/// surface whose dispatch just failed (e.g. the fleet-forks 403)
/// must not be re-picked for the retry.
pub(crate) fn registry_without_surfaces(registry: &Value, ids: &[String]) -> Value {
let mut reg = registry.clone();
if let Some(surfaces) = reg.get_mut("surfaces").and_then(|s| s.as_array_mut()) {
surfaces.retain(|s| {
let id = s.get("id").and_then(|i| i.as_str()).unwrap_or("");
!ids.iter().any(|x| x == id)
});
}
reg
}

/// The session record for a dispatch whose eligible surfaces all
/// failed (#16824 item 1): built from the attempt's base record,
/// terminated `failed`, carrying every attempt (surface + error)
/// and the full decision reasoning — a failed placement is visible
/// in `session list` with why each surface was tried and refused,
/// instead of leaving no record at all.
pub fn failed_session_record(
mut rec: Map<String, Value>,
surface_id: &str,
attempts: &[Value],
reasoning: &[String],
) -> Value {
rec.insert("surface".into(), json!(surface_id));
rec.insert("run_id".into(), Value::Null);
rec.insert("run_url".into(), Value::Null);
rec.insert("state".into(), json!("failed"));
rec.insert("dispatch_attempts".into(), json!(attempts));
rec.insert("decision_reasoning".into(), json!(reasoning));
Value::Object(rec)
}

/// 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. 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())
.unwrap_or("")
.to_string();
with_store_lock(|| {
let mut store = load_store();
if let Some(sessions) = store["sessions"].as_object_mut() {
sessions.insert(handle.clone(), rec.clone());
}
if let Some(entry) = blacksmith_entry {
if let Some(arr) = store["blacksmith_dispatches"].as_array_mut() {
let exists = arr
.iter()
.any(|d| d.get("handle").and_then(|h| h.as_str()) == Some(handle.as_str()));
if !exists {
arr.push(entry.clone());
}
}
}
save_store(&store)
})?;
let _ = remote.put(rec);
Ok(())
}

fn load_store() -> Value {
let path = state_file();
if let Ok(text) = std::fs::read_to_string(&path) {
if let Ok(v) = serde_json::from_str::<Value>(&text) {
return v;
}
}
json!({ "sessions": {}, "blacksmith_dispatches": [] })
}

fn save_store(store: &Value) -> R<()> {
let dir = state_dir();
std::fs::create_dir_all(&dir)
.map_err(|e| Die(format!("cannot create state dir {dir}: {e}")))?;
let path = state_file();
let tmp = format!("{path}.tmp{}", std::process::id());
let mut text = serde_json::to_string_pretty(store).unwrap_or_default();
text.push('\n');
// Keys sorted for a stable store file, as the reference wrote it.
let text = sort_json_keys(&text);
std::fs::write(&tmp, text)
.and_then(|_| std::fs::rename(&tmp, &path))
.map_err(|e| Die(format!("cannot write session store {path}: {e}")))
}

fn sort_json_keys(text: &str) -> String {
fn sort(v: &Value) -> Value {
match v {
Value::Object(m) => {
let mut keys: Vec<&String> = m.keys().collect();
keys.sort();
let mut out = Map::new();
for k in keys {
out.insert(k.clone(), sort(&m[k]));
}
Value::Object(out)
}
Value::Array(a) => Value::Array(a.iter().map(sort).collect()),
other => other.clone(),
}
}
match serde_json::from_str::<Value>(text) {
Ok(v) => serde_json::to_string_pretty(&sort(&v)).unwrap_or_else(|_| text.to_string()),
Err(_) => text.to_string(),
}
}

fn new_handle<Src: rand_source::RandSource>(rng: &Src) -> String {
let bytes = rng.bytes16();
let mut out = String::with_capacity(35);
out.push_str("fp_");
for b in bytes {
out.push_str(&format!("{b:02x}"));
}
out
}

/// Randomness for handles, behind a tiny seam so tests are
/// deterministic. Production reads /dev/urandom.
mod rand_source {
pub trait RandSource {
fn bytes16(&self) -> [u8; 16];
}
pub struct URandom;
impl RandSource for URandom {
fn bytes16(&self) -> [u8; 16] {
use std::io::Read;
let mut buf = [0u8; 16];
// Read exactly 16 bytes: /dev/urandom is an endless
// stream, so a read-to-end here would never return.
if let Ok(mut f) = std::fs::File::open("/dev/urandom") {
if f.read_exact(&mut buf).is_ok() {
return buf;
}
}
// Fallback: time + pid mixing (never expected on Linux).
let seed = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos() as u64)
.unwrap_or(0)
^ (std::process::id() as u64) << 32;
let mut x = seed | 1;
for b in buf.iter_mut() {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
*b = (x >> 32) as u8;
}
buf
}
}
}

fn submitted_by() -> String {
let user = std::env::var("USER").unwrap_or_else(|_| "unknown".to_string());
let host = std::fs::read_to_string("/proc/sys/kernel/hostname")
.map(|s| s.trim().to_string())
.unwrap_or_else(|_| "unknown".to_string());
format!("{user}@{host}")
}
mod store;
pub(crate) use store::{
commit_new_session, failed_session_record, load_store, new_handle, save_store,
submitted_by, with_store_lock,
};
pub(crate) use store::rand_source;
pub(crate) use store::state_file;
pub use store::registry_without_surfaces;

// ---------------------------------------------------------------- adapters

Expand Down
Loading