From f3709882c5e32bb0ade84d19d86ced9451d6fd7d Mon Sep 17 00:00:00 2001 From: i2cjak Date: Sun, 22 Nov 2026 13:21:36 -0500 Subject: [PATCH] kicad: invalidate exited IPC servers and bound BeginCommit / snapguard hangs Clear stale server socket/PID and readiness on process exit or connection drop, gate server events by launch generation, bound pipe draining and pre-write snapguard snapshots, and probe/invalidate stalled BeginCommit calls. Fixes #1588 --- native/host/src/agents/snapguard.rs | 80 +- native/host/src/agents/tests/snapguard.rs | 83 ++ native/host/src/kicad/embed.rs | 187 +++- native/host/src/kicad/ipc.rs | 1228 +++++++++++++++++++-- native/host/src/kicad/kipc.rs | 201 +++- native/host/src/kicad/kserve.rs | 38 +- 6 files changed, 1679 insertions(+), 138 deletions(-) diff --git a/native/host/src/agents/snapguard.rs b/native/host/src/agents/snapguard.rs index e95d9a3fde..42357ca1d6 100644 --- a/native/host/src/agents/snapguard.rs +++ b/native/host/src/agents/snapguard.rs @@ -28,10 +28,15 @@ pub fn is_guard_event(e: &Value) -> bool { (e["$"] == "ActivityLogged" && e["kind"] == "git" && e["act"].as_str().is_some_and(|a| a.starts_with("sg"))) || (e["$"] == "SettingSet" && e["key"].as_str().is_some_and(|k| k.starts_with("review.ro.") || k.starts_with("restore.ask."))) } +/// Timeout for the git availability probe before write_guard / turn_guard_start. +pub const GIT_PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); +/// Timeout for the pre-write snapshot inside `write_guard` so a stalled git/repo_lock never hangs BeginCommit for 300s. +pub const WRITE_SNAP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30); + /// Whether git runs here (Windows: one installed since this hub started is put on its PATH first). pub async fn git_runs() -> bool { crate::settings::tools_install::git_pick_up(); - crate::files::git::proc_ro("git", &["--version"], "/", &[]).await.code == 0 + crate::files::git::read_within(GIT_PROBE_TIMEOUT, "git", &["--version"], "/", &[]).await.code == 0 } /// The ask a mass deletion waits on. pub const MASS_TOOL: &str = "mass_delete"; @@ -130,6 +135,11 @@ impl Agents { /// `turn_guard_start`; `new_turn` false for a guard taken late, at a write of a turn that has none (an earlier turn's restore ask stays open). async fn guard_begin(self: &Arc, th: &str, cwd: &str, text: Option<&str>, new_turn: bool) { if crate::copy::on() || cwd.is_empty() { return } + let g = self.compute_guard(th, cwd, text, new_turn).await; + self.turn_guards.lock().unwrap().insert(th.to_string(), g); + } + /// Compute the snapshot and review state without mutating `self.turn_guards` (used so a timed-out detached call cannot overwrite a newer turn). + async fn compute_guard(self: &Arc, th: &str, cwd: &str, text: Option<&str>, new_turn: bool) -> TurnGuard { let cur = self.world().await.setting(&review_key(th)).to_string(); let prev = cur == "1"; let review = text.map_or(prev, |t| review_next(prev, t)); // a new message decides afresh; the person's "off" ("0") lasts until it, a late guard (no text) keeps what is set @@ -138,7 +148,7 @@ impl Agents { if review && !prev { self.guard_say(th, "info", format!("{REVIEW_WHY} Allow edits (over the message box) switches it off, or ask for a change in a message.")).await } if new_turn { self.close_restore_asks(th).await } let root = kc::design_root(cwd); - if !std::path::Path::new(&root).is_dir() { self.turn_guards.lock().unwrap().insert(th.to_string(), TurnGuard { review, ..Default::default() }); return } // no folder: nothing to snapshot (the turn says why it cannot run there) + if !std::path::Path::new(&root).is_dir() { return TurnGuard { review, ..Default::default() } } // no folder: nothing to snapshot (the turn says why it cannot run there) let mut g = TurnGuard { review, ..Default::default() }; // The agent gets the turn only once the snapshot is taken: it must hold the state before the turn, whatever the agent's own tools write // (#1233, #1246). The snapshot is incremental (files/snapshot.rs keeps its index between turns), so it is quick after the first; a slow one @@ -148,7 +158,7 @@ impl Agents { let r = self.take_snapshot(th, &root).await; say.abort(); if let Some((top, turn, reference)) = r { g = TurnGuard { top, turn, reference, ..g } } - self.turn_guards.lock().unwrap().insert(th.to_string(), g); + g } /// The folder `root` made a repository if it is in none, and its work tree snapshotted for `th`'s next turn: (top, turn, reference), None when @@ -168,24 +178,82 @@ impl Agents { } } + /// Run a future on a detached task bounded by `limit` so a caller timeout never drops the spawned task's guards (such as `repo_lock`) + /// while an underlying non-abortable write subprocess is still finishing. + pub(crate) async fn await_detached( + limit: std::time::Duration, + fut: impl std::future::Future + Send + 'static, + ) -> Result { + let (tx, rx) = tokio::sync::oneshot::channel(); + tokio::spawn(async move { + let res = fut.await; + let _ = tx.send(res); + }); + match tokio::time::timeout(limit, rx).await { + Ok(Ok(v)) => Ok(v), + _ => Err(()), + } + } + /// Before a write through the hub to `path` (absolute): a review refuses it when it is a design file; the turn's first write snapshots /// first (again, when the person or the agent changed something since the turn's snapshot). pub async fn write_guard(self: &Arc, th: &str, path: &str) -> Result<(), String> { + self.write_guard_within(th, path, WRITE_SNAP_TIMEOUT).await + } + pub(crate) async fn write_guard_within(self: &Arc, th: &str, path: &str, limit: std::time::Duration) -> Result<(), String> { if crate::copy::on() { return Ok(()) } let rel = path.rsplit_once("/.backplane/worktrees/").map(|x| x.1.split_once('/').map_or("", |y| y.1).to_string()).unwrap_or_else(|| path.to_string()); let design = kc::is_design(&rel) || kc::is_document(path) || path.ends_with(".kicad_pro"); if design && self.in_review(th).await { return Err(sn::review_refusal(path.rsplit('/').next().unwrap_or(path))) } let g = self.turn_guard(th); if g.as_ref().is_some_and(|g| g.wrote) { return Ok(()) } + let timed_out = || { + let secs = limit.as_secs_f64(); + let secs_str = if secs >= 1.0 && secs.fract() == 0.0 { format!("{} s", secs as u64) } else { format!("{secs:.2} s") }; + ( + format!("No snapshot before this turn's first edit: pre-write git snapshot timed out after {secs_str}"), + format!("KiCad write blocked: pre-write git snapshot timed out after {secs_str} (git or the project repository lock did not finish). Retry once git is idle."), + ) + }; match g { Some(g) if !g.top.is_empty() => { let title = self.thread_title(th).await; - let r = sn::snapshot(&g.top, th, &format!("{}-edit", g.reference), &sn::snap_msg(th, g.turn, &title, "before its first edit"), self.off_branch().await).await; - if let Err(e) = r { self.guard_say(th, "warn", format!("No snapshot before this turn's first edit: {e}")).await } + let off_branch = self.off_branch().await; + let top = g.top.clone(); + let reference = format!("{}-edit", g.reference); + let msg = sn::snap_msg(th, g.turn, &title, "before its first edit"); + let th_s = th.to_string(); + match Self::await_detached(limit, async move { sn::snapshot(&top, &th_s, &reference, &msg, off_branch).await }).await { + Ok(Ok(_)) => {} + Ok(Err(e)) => self.guard_say(th, "warn", format!("No snapshot before this turn's first edit: {e}")).await, + Err(()) => { + let (say_msg, err_msg) = timed_out(); + self.guard_say(th, "warn", say_msg).await; + return Err(err_msg); + } + } } // no snapshot of this turn yet (a turn that started before this hub did): take it now _ if !git_runs().await => { self.git_missing(th).await; return Err(GIT_MISSING.into()) } - _ => { let cwd = self.world().await.cwd(th); let review = self.in_review(th).await; self.guard_begin(th, &cwd, None, false).await; if let Some(x) = self.turn_guards.lock().unwrap().get_mut(th) { x.review = review } } + _ => { + let cwd = self.world().await.cwd(th); + if !crate::copy::on() && !cwd.is_empty() { + let me = self.clone(); + let th_s = th.to_string(); + match Self::await_detached(limit, async move { me.compute_guard(&th_s, &cwd, None, false).await }).await { + Ok(mut computed) => { + computed.wrote = true; + self.turn_guards.lock().unwrap().insert(th.to_string(), computed); + return Ok(()); + } + Err(()) => { + let (say_msg, err_msg) = timed_out(); + self.guard_say(th, "warn", say_msg).await; + return Err(err_msg); + } + } + } + } } if let Some(x) = self.turn_guards.lock().unwrap().get_mut(th) { x.wrote = true } Ok(()) diff --git a/native/host/src/agents/tests/snapguard.rs b/native/host/src/agents/tests/snapguard.rs index d62e56d68a..b9627cc2b0 100644 --- a/native/host/src/agents/tests/snapguard.rs +++ b/native/host/src/agents/tests/snapguard.rs @@ -329,3 +329,86 @@ done assert_eq!(ag.world().await.setting(&sg::review_key(T1)), ""); ag.shutdown(); } + +#[tokio::test(flavor = "multi_thread")] async fn write_guard_bounds_stalled_snapshot_so_begin_commit_never_hangs() { + let bin = dir("sg-wg-bin"); script(&bin, "claude", HOLDER); + let (hub, ag, _home, work) = start("sg-wg-tmo", |w| { + std::fs::write(w.join("board.kicad_pcb"), board(10)).unwrap(); + std::fs::write(w.join("board.kicad_pro"), "{}").unwrap(); + base_log(w, 1, "") + }, |_| Cli::standin(&bin)).await; + let from = len(&hub).await; + assert_eq!(rpc(&hub, "turn.start", json!({"thread":T1,"text":"edit the board, hold"})).await["ok"], true); + wait_file(&work.join("seen.log")).await; + let top = sn::top_of(&work.to_string_lossy()).await.unwrap(); + let b = work.join("board.kicad_pcb").to_string_lossy().into_owned(); + let lock = sn::repo_lock(&top).await; + let t0 = Instant::now(); + let err = ag.write_guard_within(T1, &b, Duration::from_millis(250)).await.unwrap_err(); + assert!(t0.elapsed() < Duration::from_secs(3), "write_guard_within must bound stalled snapshot, took {:?}", t0.elapsed()); + assert!(err.contains("timed out"), "unexpected error: {err}"); + assert!(!ag.turn_guard(T1).unwrap().wrote, "wrote flag must stay false after timed-out write_guard"); + drop(lock); + ag.write_guard_within(T1, &b, Duration::from_secs(10)).await.expect("write_guard succeeds once lock is released"); + assert!(ag.turn_guard(T1).unwrap().wrote); + std::fs::write(work.join("go"), "").unwrap(); + until(&hub, from, 30, |ev| ev.iter().any(|e| turn_is(e, "completed") || turn_is(e, "failed"))).await; + ag.shutdown(); +} + +#[tokio::test(flavor = "multi_thread")] async fn await_detached_keeps_repo_lock_held_until_in_flight_work_finishes() { + let top = crate::plat::tmp::short_dir_str("sg-lock"); + let top_s = top.to_string(); + let (done_tx, done_rx) = tokio::sync::oneshot::channel::<()>(); + let release = Arc::new(tokio::sync::Notify::new()); + let release_task = release.clone(); + // Acquire repo_lock inside the detached future and hold it past the caller timeout. + let res = Agents::await_detached(Duration::from_millis(80), async move { + let _guard = sn::repo_lock(&top_s).await; + let _ = done_tx.send(()); + release_task.notified().await; + }).await; + assert!(res.is_err(), "caller must time out cleanly"); + done_rx.await.unwrap(); + assert!( + tokio::time::timeout(Duration::from_millis(80), sn::repo_lock(&top)).await.is_err(), + "repo_lock must stay held by the in-flight detached task after caller timeout" + ); + release.notify_one(); + tokio::time::timeout(Duration::from_secs(2), sn::repo_lock(&top)) + .await + .expect("repo_lock must become available once in-flight task finishes"); +} + +#[tokio::test(flavor = "multi_thread")] async fn timed_out_late_guard_never_overwrites_next_turns_guard() { + let bin = dir("sg-late-bin"); script(&bin, "claude", HOLDER); + let (hub, ag, _home, work) = start("sg-late-tmo", |w| { + std::fs::write(w.join("board.kicad_pcb"), board(5)).unwrap(); + std::fs::write(w.join("board.kicad_pro"), "{}").unwrap(); + base_log(w, 1, "") + }, |_| Cli::standin(&bin)).await; + // Start & finish turn 1 quickly so repo exists. + let from = len(&hub).await; + assert_eq!(rpc(&hub, "turn.start", json!({"thread":T1,"text":"hello"})).await["ok"], true); + until(&hub, from, 30, |ev| ev.iter().any(|e| turn_is(e, "completed") || turn_is(e, "failed"))).await; + tokio::time::sleep(Duration::from_millis(300)).await; + assert!(ag.turn_guard(T1).is_none()); + + // Hold repo_lock so the late-guard path (`None` turn_guard) times out while its detached task awaits the lock. + let top = sn::top_of(&work.to_string_lossy()).await.unwrap(); + let lock = sn::repo_lock(&top).await; + let b = work.join("board.kicad_pcb").to_string_lossy().into_owned(); + let err = ag.write_guard_within(T1, &b, Duration::from_millis(120)).await.unwrap_err(); + assert!(err.contains("timed out"), "{err}"); + + // Install a newer turn's guard, then release lock so the stale detached snapshot completes. + let sentinel = super::super::snapguard::TurnGuard { top: top.clone(), turn: 99, reference: "refs/backplane/new-turn".into(), review: true, wrote: false, ..Default::default() }; + ag.turn_guards.lock().unwrap().insert(T1.into(), sentinel.clone()); + drop(lock); + tokio::time::sleep(Duration::from_millis(400)).await; + let after = ag.turn_guard(T1).unwrap(); + assert_eq!(after.turn, 99, "late timed-out guard must never overwrite next turn's turn number"); + assert_eq!(after.reference, "refs/backplane/new-turn"); + assert!(!after.wrote && after.review); + ag.shutdown(); +} diff --git a/native/host/src/kicad/embed.rs b/native/host/src/kicad/embed.rs index a035b8721d..de8425fd64 100644 --- a/native/host/src/kicad/embed.rs +++ b/native/host/src/kicad/embed.rs @@ -52,6 +52,8 @@ impl Frame { } } +const SYNTHETIC_EXIT_HOW: &str = "process exited (detected by liveness check)"; + #[derive(Clone, Debug, PartialEq, Eq)] pub struct Session { pub pro: String, @@ -172,6 +174,8 @@ pub struct Session { pub opening: Option, /// the library editor KiCad last opened (its ET_FRAME_OPENED) and when: only a show request just after it is an opening pub lib_opened: Option<(String, std::time::Instant)>, + /// True when the latest transition out of live state came from a synthetic `CheckAlive` fallback rather than the real child watcher. + pub synthetic_exit: bool, } /// How long after KiCad opens a library editor (ET_FRAME_OPENED) its show request counts as that open's (an `Opening`). pub const LIB_FRESH: Duration = Duration::from_secs(2); @@ -218,7 +222,7 @@ impl Session { container: 0, toplevel: 0, holder: 0, display: String::new(), start_phase: String::new(), start_at: 0, lock_ask: Value::Null, sock: String::new(), events_sock: String::new(), sock_dir: String::new(), argv: String::new(), cli: String::new(), version: String::new(), desc: String::new(), - caps: vec![], frames: vec![], missed_pings: 0, dialogs: vec![], notices: vec![], drawn: vec![], keys: vec![], rss_mb: 0, peak_mb: 0, mem_pub: (0, 0), peak_logged: false, stop_reason: String::new(), stopped_at: 0, closed_frames: vec![], pane_cid: String::new(), active_by: Value::Null, task_wait: String::new(), parked: false, left: String::new(), holder_gone_at: 0, last_pid: 0, busy: false, gone_kinds: vec![], closing_ask: String::new(), close_answered: false, killed_by_hub: false, close_pending: false, close_asked_as: String::new(), close_overtaken: false, reopen: false, touched_at: now, closing: false, lost_parent: false, editor_req: (String::new(), String::new(), None), opening: None, lib_opened: None, + caps: vec![], frames: vec![], missed_pings: 0, dialogs: vec![], notices: vec![], drawn: vec![], keys: vec![], rss_mb: 0, peak_mb: 0, mem_pub: (0, 0), peak_logged: false, stop_reason: String::new(), stopped_at: 0, closed_frames: vec![], pane_cid: String::new(), active_by: Value::Null, task_wait: String::new(), parked: false, left: String::new(), holder_gone_at: 0, last_pid: 0, busy: false, gone_kinds: vec![], closing_ask: String::new(), close_answered: false, killed_by_hub: false, close_pending: false, close_asked_as: String::new(), close_overtaken: false, reopen: false, touched_at: now, closing: false, lost_parent: false, editor_req: (String::new(), String::new(), None), opening: None, lib_opened: None, synthetic_exit: false, } } pub fn spawned(mut self, pid: u32) -> Self { self.pid = pid; self } @@ -1587,6 +1591,13 @@ pub fn gui_route(pro: &str) -> Option { routes().lock().unwrap().get(&norm_pro_key(pro)).cloned() } +/// If the project's GUI KiCad process has already exited before the actor recorded it, notify the embed actor at once. +pub fn check_exited(pro: &str) { + if let Some(r) = gui_route(pro) { + let _ = r.tx.send(Msg::CheckAlive { pro: r.pro }); + } +} + // The person's unsaved edits (the person's rule, Nov 11): an agent's save never writes what the person has open and unsaved. Per project: // whether a document is modified (from each publish: GetFrames in fork mode, the client's titles in stock mode), whether the agent's own // commits changed it since the last save, and whether the person changed it. A co-editing runtime (`coedit`, bp.11+) says who made each @@ -1806,6 +1817,27 @@ pub async fn gui_call_patient(route: &GuiRoute, ty: &str, msg: Value, client: &s pub fn busy_words(what: &str, waited: Duration) -> String { format!("KiCad is busy with {what} and answers only some reads until it ends; it was still running after {} s. Nothing was done: ask again in a moment.", waited.as_secs()) } +async fn send_gui_raw(route: &GuiRoute, ty: &str, msg: Value, client: &str, timeout_ms: u64) -> Value { + let (t, r) = oneshot::channel(); + let deadline = tokio::time::Instant::now() + Duration::from_millis(timeout_ms); + if route.tx.send(Msg::Raw { + sock: route.sock.clone(), + desc: route.desc.clone(), + ty: ty.into(), + msg, + timeout: timeout_ms, + deadline: Some(deadline), + client: client.into(), + reply: t, + }).is_err() { + return json!({"ok":false,"error":"no reply","why":"no reply","fallback":true}) + } + match tokio::time::timeout_at(deadline + Duration::from_millis(1_000), r).await { + Ok(Ok(v)) => v, + Ok(Err(_)) => json!({"ok":false,"error":"no reply","why":"no reply","fallback":true}), + Err(_) => json!({"ok":false,"error":format!("KiCad did not answer in {} s", timeout_ms as f64 / 1000.0),"why":"timeout","fallback":true}), + } +} async fn gui_call_in(route: &GuiRoute, ty: &str, msg: Value, client: &str, patient: Option) -> Value { // every request but the checks' own is counted, so an in-editor check never starts while another client waits (kicad/checkrun.rs) // a named client's (an agent, the person's edit from a panel or a phone) also holds checks a moment after it ends; the hub's own @@ -1816,13 +1848,15 @@ async fn gui_call_in(route: &GuiRoute, ty: &str, msg: Value, client: &str, patie if !super::ipc::is_read(ty) && !NEVER_SELECTS.iter().any(|n| ty.rsplit('.').next() == Some(*n)) { super::coedit::hub_command(&route.pro) } let named = !client.is_empty(); let _use = (client != CHECKS_CLIENT).then(|| { let mut m = gui_use().lock().unwrap(); let e = m.entry(route.sock.clone()).or_default(); e.0 += 1; if named { e.1 = crate::hub::now_ms() } Use(route.sock.clone(), named) }); - if TASK_GATED.iter().any(|g| ty.rsplit('.').next() == Some(*g)) && has_task_gate(&route.sock) { return raw_gated(&route.tx, &route.sock, &route.desc, ty, msg, 30000, client, None).await } - if let Some(max) = patient { return raw_gated_for(&route.tx, &route.sock, &route.desc, ty, msg, 30000, client, None, true, max, false).await } - let (t, r) = oneshot::channel(); - if route.tx.send(Msg::Raw { sock: route.sock.clone(), desc: route.desc.clone(), ty: ty.into(), msg, timeout: 30000, client: client.into(), reply: t }).is_err() { - return json!({"ok":false,"error":"no reply","why":"no reply","fallback":true}) - } - r.await.unwrap_or_else(|_| json!({"ok":false,"error":"no reply","why":"no reply","fallback":true})) + let timeout = super::ipc::timeout_ms_for(ty); + if TASK_GATED.iter().any(|g| ty.rsplit('.').next() == Some(*g)) && has_task_gate(&route.sock) { return raw_gated(&route.tx, &route.sock, &route.desc, ty, msg, timeout, client, None).await } + if let Some(max) = patient { return raw_gated_for(&route.tx, &route.sock, &route.desc, ty, msg, timeout, client, None, true, max, false).await } + send_gui_raw(route, ty, msg, client, timeout).await +} + +/// Send one command directly with an explicit timeout in ms (e.g. a quick Ping probe after BeginCommit times out). +pub async fn gui_call_timeout(route: &GuiRoute, ty: &str, msg: Value, client: &str, timeout_ms: u64) -> Value { + send_gui_raw(route, ty, msg, client, timeout_ms).await } /// One commit of item updates in the open editor as `client` (`coedit::client_name`): BeginCommit, UpdateItems, EndCommit, every one @@ -2053,7 +2087,7 @@ enum Msg { client: u64, pro: String, frames: Vec, reply: oneshot::Sender>, }, Raw { - sock: String, desc: String, ty: String, msg: Value, timeout: u64, client: String, reply: oneshot::Sender, + sock: String, desc: String, ty: String, msg: Value, timeout: u64, deadline: Option, client: String, reply: oneshot::Sender, }, TransportLine(u64, Value), Spawned { pro: String, gen: u64, pid: u32 }, @@ -2094,6 +2128,7 @@ enum Msg { HealthResult { pro: String, gen: u64, ok: bool, modified_docs: Option> }, /// `pid`: the process that ended (0 for a made-up exit): whatever the session's generation is now, its `last_pid` is forgotten ChildExited { pro: String, gen: u64, pid: u32, code: i32, how: String, tail: String, reply: Option>> }, + CheckAlive { pro: String }, Tick, } @@ -3163,7 +3198,19 @@ impl Actor { if s.task_wait != what { s.task_wait = what; let snap = s.clone(); self.publish(&snap, None); } } } - Msg::Raw { sock, desc, ty, msg, timeout, client, reply } => { + Msg::Raw { sock, desc, ty, msg, timeout, deadline, client, reply } => { + if reply.is_closed() { return } + let eff_timeout = match deadline { + Some(dl) => { + let rem = dl.saturating_duration_since(tokio::time::Instant::now()).as_millis() as u64; + if rem == 0 { + let _ = reply.send(json!({"ok":false,"error":format!("KiCad did not answer in {} s", timeout as f64 / 1000.0),"why":"timeout","fallback":true})); + return; + } + timeout.min(rem).max(1) + } + None => timeout, + }; // BACKPLANE_KICAD_DEBUG: every request the hub sends the embedded KiCad, in order, with the time, its kind and KiCad's memory // then (what is loaded at open, and which request separates a 4.8 GB open from a 5.5 GB one) if std::env::var_os("BACKPLANE_KICAD_DEBUG").is_some() && !ty.ends_with("NextEvents") && !ty.ends_with("Ping") { @@ -3179,7 +3226,7 @@ impl Actor { let _ = reply.send(json!({"ok": false, "error": "KiCad is closing: no request is sent to it", "closing": true})); return } - self.raw_call(&sock, &desc, &ty, msg, timeout, &client, reply) + self.raw_call(&sock, &desc, &ty, msg, eff_timeout, &client, reply) } Msg::TransportLine(g, o) => { if self.helper.as_ref().map(|(_, hg)| *hg) != Some(g) { return } @@ -3441,6 +3488,7 @@ impl Actor { } Msg::HealthResult { pro, gen, ok, modified_docs } => { let Some(s) = self.sessions.get_mut(&pro).filter(|s| s.gen == gen && matches!(s.state.as_str(), "ready" | "unresponsive")) else { return }; + if s.pid > 0 && !crate::plat::proc::alive(s.pid) { return; } let was_unresponsive = s.state == "unresponsive"; let prev = s.clone(); *s = s.clone().ping_result(ok); @@ -3473,7 +3521,21 @@ impl Actor { return; }; if matches!(s.state.as_str(), "stopped" | "failed" | CLOSED) { - // the real exit of a KiCad whose session stopped before it (a close's made-up exit): gone now, nothing to wait for + // the real exit of a KiCad whose session stopped before it (a close's made-up exit, or CheckAlive's synthetic timeout): + // if the synthetic exit preempted a real code 3 `windows_lost`, still run its automatic recovery once. + let late_windows_lost = reply.is_none() && s.synthetic_exit && windows_lost(code, &tail); + if late_windows_lost { + s.synthetic_exit = false; + s.last_pid = 0; + s.container = 0; + s.reason = "KiCad lost its window and is starting again to offer back the unsaved changes".into(); + let snap = s.clone(); + self.publish(&snap, None); + eprintln!("kicad embed: {pro}: KiCad lost its windows (code 3, after liveness exit): starting it again"); + let (me, hub) = (self.me.clone(), self.hub.clone()); + tokio::spawn(async move { let env = ipc::runtime(&hub).await; let (tx, _rx) = oneshot::channel(); let _ = me.send(Msg::Restart { client: 0, pro, env, reply: tx }); }); + return; + } if reply.is_none() { s.last_pid = 0; } if let Some(tx) = reply { let _ = tx.send(Ok(json!({"closed":true}))); } return; @@ -3481,6 +3543,7 @@ impl Actor { let was_starting = s.state == "starting"; let old = s.clone(); *s = s.clone().exited_how(code, &how, &tail); + s.synthetic_exit = reply.is_none() && how == SYNTHETIC_EXIT_HOW; if reply.is_none() { s.last_pid = 0; } // ended by a Close a pane had overtaken: the pane on show opens KiCad again (a fresh one), never a pane on a KiCad closed under it s.reopen = old.close_overtaken && !s.is_live(); // its real exit: gone (a pid used again later is never waited on or killed) @@ -3511,6 +3574,37 @@ impl Actor { tokio::spawn(async move { let env = ipc::runtime(&hub).await; let (tx, _rx) = oneshot::channel(); let _ = me.send(Msg::Restart { client: 0, pro, env, reply: tx }); }); } } + Msg::CheckAlive { pro } => { + const EXITING_WHY: &str = "KiCad process exited; waiting for exit status"; + let dead = self.sessions.get_mut(&pro) + .filter(|s| s.is_live() && s.pid > 0 && !crate::plat::proc::alive(s.pid)); + if let Some(s) = dead { + if s.state == "unresponsive" && s.reason == EXITING_WHY { + return; + } + let gen = s.gen; + let pid = s.pid; + let old_sock = s.sock.clone(); + let old_events = s.events_sock.clone(); + let was_ready = s.state == "ready"; + if matches!(s.state.as_str(), "ready" | "unresponsive") { + s.state = "unresponsive".into(); + s.reason = EXITING_WHY.into(); + } + let snap = s.clone(); + self.close_sock(&old_sock); + self.close_sock(&old_events); + if was_ready { + self.publish(&snap, None); + } + // Let the real child watcher deliver its exit code (e.g. code 3 windows_lost recovery); fall back after its 1.5 s pipe-drain window. + let me = self.me.clone(); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(2500)).await; + let _ = me.send(Msg::ChildExited { pro, gen, pid, code: -1, how: SYNTHETIC_EXIT_HOW.into(), tail: String::new(), reply: None }); + }); + } + } Msg::Tick => { // the app closed (no desktop client that used KiCad is connected any more): its KiCads close with it let hub = self.hub.clone(); @@ -3581,10 +3675,14 @@ async fn raw_on(me: &mpsc::UnboundedSender, sock: &str, desc: &str, ty: &st } async fn raw_once(me: &mpsc::UnboundedSender, sock: &str, desc: &str, ty: &str, msg: Value, timeout: u64, client: &str) -> Value { let (t, r) = oneshot::channel(); - if me.send(Msg::Raw { sock: sock.into(), desc: desc.into(), ty: ty.into(), msg, timeout, client: client.into(), reply: t }).is_err() { + let deadline = tokio::time::Instant::now() + Duration::from_millis(timeout); + if me.send(Msg::Raw { sock: sock.into(), desc: desc.into(), ty: ty.into(), msg, timeout, deadline: Some(deadline), client: client.into(), reply: t }).is_err() { return json!({"ok":false,"error":"embed actor stopped"}) } - r.await.unwrap_or_else(|_| json!({"ok":false,"error":"no reply"})) + match tokio::time::timeout_at(deadline + Duration::from_millis(1_000), r).await { + Ok(Ok(v)) => v, + _ => json!({"ok":false,"error":"no reply"}), + } } /// The hub's own drive of the editor's frames, which KiCad with `task-gate-reads` (lane P, 56ef479828) refuses AS_BUSY while a check or a @@ -6228,7 +6326,7 @@ mod tests { let mut child = sleep_child(); let pid = child.id(); let (mut a, _h) = test_actor().await; let mut s = seq_session(pid); s.events_sock = "/no/sock.events".into(); assert!(s.close_sent("agentClosed")); a.sessions.insert(s.pro.clone(), s); - let send = |a: &mut Actor, sock: &str, ty: &str| { let (tx, rx) = oneshot::channel(); a.handle(Msg::Raw { sock: sock.into(), desc: String::new(), ty: ty.into(), msg: json!({}), timeout: 500, client: String::new(), reply: tx }); rx }; + let send = |a: &mut Actor, sock: &str, ty: &str| { let (tx, rx) = oneshot::channel(); a.handle(Msg::Raw { sock: sock.into(), desc: String::new(), ty: ty.into(), msg: json!({}), timeout: 500, deadline: None, client: String::new(), reply: tx }); rx }; // before the answer (pending, not closing): requests go as usual (quiet_for says nothing holds them back) assert!(quiet_for(&a.sessions, "/no/sock").is_none() && quiet_for(&a.sessions, "/no/sock.events").is_none()); a.handle(Msg::CloseAnswered { pro: "/p/a.kicad_pro".into(), gen: 3, pid, answered: true, reply: None }); @@ -6244,6 +6342,65 @@ mod tests { let mut q = seq_session(77); q.gone_kinds = vec!["PCB".into()]; assert!(socket_gone(&mut q)); let m: HashMap = [(q.pro.clone(), q)].into_iter().collect(); assert!(quiet_for(&m, "/no/sock").is_some()); } + #[tokio::test] async fn check_alive_clears_route_without_suppressing_windows_lost_recovery() { + let mut child = std::process::Command::new("sleep").arg("30").spawn().unwrap(); + let pid = child.id(); + let _ = child.kill(); + let _ = child.wait(); + assert!(!crate::plat::proc::alive(pid)); + + let pro = "/p/check-alive-1588.kicad_pro".to_string(); + let (mut a, _h) = test_actor().await; + let mut s = Session::new(&pro, "/p", "fork", "PCB", 3, 0).ready("/no/sock-1588", "", 0).spawned(pid); + s.container = 9001; + a.publish(&s, None); + a.sessions.insert(pro.clone(), s); + assert!(gui_route(&pro).is_some(), "ready session must publish gui_route"); + + a.handle(Msg::CheckAlive { pro: pro.clone() }); + { + let cur = &a.sessions[&pro]; + assert_eq!(cur.state, "unresponsive"); + assert!(gui_route(&pro).is_none(), "CheckAlive must remove gui_route immediately once pid is dead"); + } + + // Queued HealthResult { ok: true } for the dead PID must NOT restore "ready" or gui_route. + a.handle(Msg::HealthResult { pro: pro.clone(), gen: 3, ok: true, modified_docs: None }); + { + let cur = &a.sessions[&pro]; + assert_eq!(cur.state, "unresponsive"); + assert!(gui_route(&pro).is_none(), "queued HealthResult must not restore route for dead PID"); + } + + // Even if the synthetic liveness exit arrives BEFORE the real code 3 `windows lost` event, recovery must still run. + a.handle(Msg::ChildExited { + pro: pro.clone(), + gen: 3, + pid, + code: -1, + how: SYNTHETIC_EXIT_HOW.into(), + tail: String::new(), + reply: None, + }); + assert!(a.sessions[&pro].synthetic_exit); + assert_eq!(a.sessions[&pro].state, CLOSED); + + // Subsequent real exit with code 3 (`windows lost`) must still run automatic recovery instead of returning early. + a.handle(Msg::ChildExited { + pro: pro.clone(), + gen: 3, + pid, + code: 3, + how: "code 3".into(), + tail: "kicad embed: windows lost\n".into(), + reply: None, + }); + let ended = &a.sessions[&pro]; + assert_eq!(ended.state, CLOSED); + assert!(!ended.synthetic_exit); + assert!(ended.reason.contains("lost its window"), "expected windows_lost recovery reason, got: {}", ended.reason); + assert!(gui_route(&pro).is_none()); + } #[test] fn a_start_held_for_the_previous_kicad_is_one_session_that_every_attach_joins() { let prev = Session::new("/p/a.kicad_pro", "/p", "fork", "PCB", 7, 0).ready("/s", "", 0).spawned(41).stopped(""); assert_eq!(previous_alive(&prev, |p| p == 41), Some(41), "its KiCad still there: the start is held"); diff --git a/native/host/src/kicad/ipc.rs b/native/host/src/kicad/ipc.rs index bcba1a6822..13e59aa4fe 100644 --- a/native/host/src/kicad/ipc.rs +++ b/native/host/src/kicad/ipc.rs @@ -37,34 +37,95 @@ pub struct Env { pub cli: String, pub root: String, pub caps: Vec, pub v fn failed(text: &str) -> Value { json!({"ok":false,"error":text,"why":text,"fallback":true}) } // KServe.failed +pub const REQUEST_TIMEOUT_MS: u64 = 30_000; +pub const BEGIN_COMMIT_TIMEOUT_MS: u64 = 15_000; +pub const ASK_TIMEOUT: Duration = Duration::from_secs(90); +const PROBE_PING_TIMEOUT_MS: u64 = 3_000; + +/// Timeout in milliseconds for an IPC command (`BeginCommit` is an in-memory sub-millisecond op and gets a tighter bound). +pub fn timeout_ms_for(ty: &str) -> u64 { + if ty.rsplit('.').next() == Some("BeginCommit") { BEGIN_COMMIT_TIMEOUT_MS } else { REQUEST_TIMEOUT_MS } +} + +/// True when `reply` is a transport/dial connection error (not a KiCad API status refusal). +pub fn is_conn_error(reply: &Value) -> bool { + if reply["ok"] == true || !reply["status"].is_null() { return false } + reply["error"].as_str().is_some_and(|e| { + e.starts_with("dial ipc://") + || e.contains(super::nng::CLOSED) + || e.contains("KiCad IPC connection failed") + || e == kipc::CONN_CLOSED + }) +} + +/// True when `reply` failed on `dial ipc://...` before any bytes reached KiCad (safe to invalidate and retry). +pub fn is_dial_refused(reply: &Value) -> bool { + reply["ok"] != true + && reply["status"].is_null() + && reply["error"].as_str().is_some_and(|e| e.starts_with("dial ipc://")) +} + +/// True when `reply` is a client-side IPC timeout (`KiCad did not answer in ... s`). +pub fn is_timeout_error(reply: &Value) -> bool { + reply["ok"] != true + && reply["status"].is_null() + && reply["error"].as_str().is_some_and(|e| e.starts_with("KiCad did not answer in ")) +} + +struct AskOutcome { reply: Value, sock: String, launch_gen: u64, dead_invalidated: bool } +enum PendingReply { Ask(oneshot::Sender), Raw(oneshot::Sender) } + +fn send_pending(reply: PendingReply, sock: &str, launch_gen: u64, val: Value, dead_invalidated: bool) { + match reply { + PendingReply::Ask(tx) => { + let _ = tx.send(AskOutcome { reply: val, sock: sock.into(), launch_gen, dead_invalidated }); + } + PendingReply::Raw(tx) => { + let _ = tx.send(val); + } + } +} + enum Msg { - Ask { project: String, env: Env, ty: String, msg: Value, reply: oneshot::Sender }, - Raw { sock: String, env: Env, ty: String, msg: Value, reply: oneshot::Sender }, + Ask { project: String, env: Env, ty: String, msg: Value, deadline: std::time::Instant, reply: oneshot::Sender }, + Raw { sock: String, env: Env, ty: String, msg: Value, timeout_ms: Option, fence: Option<(String, u64)>, reply: oneshot::Sender }, Retire { project: String, reply: oneshot::Sender }, - Retired { project: String, ok: bool, why: String, reply: oneshot::Sender }, + Retired { project: String, launch_gen: u64, ok: bool, why: String, reply: oneshot::Sender }, Info(oneshot::Sender), Argv { project: String, env: Env, reply: oneshot::Sender }, + ReadySock { project: String, reply: oneshot::Sender> }, + Invalidate { project: String, launch_gen: u64, why: String, reply: oneshot::Sender }, Clear, Line(u64, Value), - Up { project: String, version: String }, - Bad { project: String, why: String }, - Late { project: String, born: u64 }, - Go { project: String }, - Evicted { victim: String, project: String, ok: bool, why: String }, + Up { project: String, version: String, launch_gen: u64 }, + Bad { project: String, why: String, launch_gen: u64 }, + Late { project: String, born: u64, launch_gen: u64 }, + Go { project: String, launch_gen: u64 }, + Evicted { victim: String, victim_gen: u64, project: String, project_gen: u64, ok: bool, why: String }, } -struct Wt { project: String, ty: String, msg: Value, env: Env, reply: oneshot::Sender } +struct Wt { project: String, ty: String, msg: Value, env: Env, deadline: std::time::Instant, reply: oneshot::Sender } /// What carries the actor's requests. It takes request objects and answers, through the actor's mailbox, with /// the objects it writes (`Msg::Line`): replies by id, and `{"event":"line"|"exit"}` for a server. -trait Transport: Send { fn send(&mut self, fields: Value) -> bool; } // false: it is gone, and nothing will answer +trait Transport: Send { + fn send(&mut self, fields: Value) -> bool; // false: it is gone, and nothing will answer + fn process_alive(&self, _key: &str) -> Option { None } + fn pid_of(&self, _key: &str) -> u32 { 0 } +} /// The hub's own: the default. -impl Transport for kipc::Native { fn send(&mut self, fields: Value) -> bool { self.handle(fields); true } } +impl Transport for kipc::Native { + fn send(&mut self, fields: Value) -> bool { self.handle(fields); true } + fn process_alive(&self, key: &str) -> Option { kipc::Native::process_alive(self, key) } + fn pid_of(&self, key: &str) -> u32 { kipc::Native::pid_of(self, key) } +} struct Helper { link: Box, gen: u64 } +struct Pending { project: Option, sock: String, launch_gen: u64, reply: PendingReply } struct Actor { me: mpsc::UnboundedSender, home: String, rt: String, hub_pid: u32, - helper: Option, gen: u64, pend: HashMap>, next: u64, - srvs: Vec, wait: Vec, shown: String, env: Env, lines: Arc>, + helper: Option, gen: u64, pend: HashMap, next: u64, + srvs: Vec, srv_gen: HashMap, wait: Vec, shown: String, env: Env, + lines: Arc>, timeout_override_ms: Option, } pub fn now_s() -> u64 { std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0) } @@ -75,15 +136,79 @@ impl Actor { fn put(&mut self, s: Srv) { match self.srvs.iter_mut().find(|x| x.project == s.project) { Some(x) => *x = s, None => self.srvs.push(s) } } // KServe.put fn emit(&mut self) { let t = ks::lines(&self.srvs); if t != self.shown { *self.lines.lock().unwrap() = t.clone(); self.shown = t } } // KServe.emit fn later(&self, secs: f64, m: Msg) { let me = self.me.clone(); tokio::spawn(async move { tokio::time::sleep(Duration::from_secs_f64(secs)).await; let _ = me.send(m); }); } + fn launch_gen(&self, project: &str) -> u64 { self.srv_gen.get(project).copied().unwrap_or(0) } + fn bump_gen(&mut self, project: &str) -> u64 { let g = self.launch_gen(project) + 1; self.srv_gen.insert(project.to_string(), g); g } + fn process_alive(&self, project: &str) -> Option { self.helper.as_ref().and_then(|h| h.link.process_alive(project)) } + fn pid_of(&self, project: &str) -> u32 { self.helper.as_ref().map_or(0, |h| h.link.pid_of(project)) } + + fn remove_stale_sock(&self, project: &str, sock: &str) { + #[cfg(unix)] + if !sock.is_empty() { + let expected_dir = ks::dir(&self.rt, &self.home, project); + if Path::new(sock).parent() == Some(Path::new(&expected_dir)) { + let _ = std::fs::remove_file(sock); + } + } + #[cfg(not(unix))] + let _ = (project, sock); + } + + fn invalidate_server(&mut self, project: &str, expected_gen: Option, why: &str, remove_sock_file: bool) { + if expected_gen.is_some_and(|g| self.launch_gen(project) != g) { return } + let before = self.srv(project); + let old_sock = before.sock.clone(); + if !old_sock.is_empty() { + self.close(&old_sock); + if remove_sock_file { self.remove_stale_sock(project, &old_sock); } + } + if ks::active(&before.state) { + let s = before.disconnected(why); + self.put(s); + self.fail_project(project, why); + self.emit(); + } + } + + fn mark_unresponsive(&mut self, project: &str, expected_gen: u64, why: &str) { + if self.launch_gen(project) != expected_gen { return } + let before = self.srv(project); + if !before.sock.is_empty() { + self.close(&before.sock); + } + if matches!(before.state.as_str(), "ready" | "unresponsive") { + let s = before.unresponsive(why); + self.put(s); + self.fail_project(project, why); + self.emit(); + } + } + + fn reap_dead(&mut self) { + let candidates: Vec<(String, u32)> = self.srvs.iter() + .filter(|s| matches!(s.state.as_str(), "ready" | "unresponsive") || (s.state == "starting" && !s.sock.is_empty())) + .map(|s| (s.project.clone(), s.pid)) + .collect(); + for (project, pid) in candidates { + if self.process_alive(&project) == Some(false) { + self.invalidate_server(&project, None, "the headless KiCad process exited", true); + } else if pid == 0 { + let live_pid = self.pid_of(&project); + if live_pid > 0 { + if let Some(s) = self.srvs.iter_mut().find(|x| x.project == project) { s.pid = live_pid; } + } + } + } + } /// A request line registered for its reply (KServe.call). The helper is started on first use. - fn call(&mut self, mut fields: Value, reply: oneshot::Sender) { + fn call(&mut self, fields: Value, reply: oneshot::Sender) { self.call_for(None, "", 0, fields, PendingReply::Raw(reply)) } + fn call_for(&mut self, project: Option<&str>, sock: &str, launch_gen: u64, mut fields: Value, reply: PendingReply) { if self.helper.is_none() { self.start_helper() } - let Some(h) = &mut self.helper else { let _ = reply.send(failed("the KiCad IPC transport could not start")); return }; + let Some(h) = &mut self.helper else { send_pending(reply, sock, launch_gen, failed("the KiCad IPC transport could not start"), false); return }; self.next += 1; let id = self.next.to_string(); fields["id"] = json!(self.next); - if !h.link.send(fields) { let _ = reply.send(failed("the KiCad IPC helper exited")); return } - self.pend.insert(id, reply); + if !h.link.send(fields) { send_pending(reply, sock, launch_gen, failed("the KiCad IPC helper exited"), false); return } + self.pend.insert(id, Pending { project: project.map(String::from), sock: sock.into(), launch_gen, reply }); } fn start_helper(&mut self) { self.gen += 1; let gen = self.gen; @@ -92,74 +217,123 @@ impl Actor { } fn sink(&mut self, fields: Value) { let (t, _r) = oneshot::channel(); self.call(fields, t) } - fn forward(&mut self, project: &str, env: &Env, ty: &str, msg: Value, reply: oneshot::Sender) { // KServe.forward - let srv = self.srv(project).touch(now_s()); - let f = self.call_fields(&srv.sock, env, ty, msg); self.put(srv); self.call(f, reply) + fn forward(&mut self, w: Wt) { // KServe.forward + if w.reply.is_closed() { return } + let srv = self.srv(&w.project).touch(now_s()); + let launch_gen = self.launch_gen(&w.project); + let sock = srv.sock.clone(); + let rem_ms = w.deadline.saturating_duration_since(std::time::Instant::now()).as_millis() as u64; + if rem_ms == 0 { + let short = w.ty.rsplit('.').next().unwrap_or(&w.ty); + let _ = w.reply.send(AskOutcome { + reply: failed(&format!("KiCad IPC request {short} timed out after {} s waiting on the headless server", ASK_TIMEOUT.as_secs())), + sock, + launch_gen, + dead_invalidated: false, + }); + return; + } + let req_timeout = self.timeout_override_ms.unwrap_or_else(|| timeout_ms_for(&w.ty)).min(rem_ms).max(1); + let f = self.call_fields(&sock, &w.env, &w.ty, w.msg, Some(req_timeout)); + self.put(srv); + self.call_for(Some(&w.project), &sock, launch_gen, f, PendingReply::Ask(w.reply)); } - fn call_fields(&self, sock: &str, env: &Env, ty: &str, msg: Value) -> Value { // KServe.call.fields - json!({"sock":sock,"type":ty,"message":msg,"desc":ks::desc(&env.root, &env.caps),"lib":format!("{}/lib", env.root),"timeout":30000}) + fn call_fields(&self, sock: &str, env: &Env, ty: &str, msg: Value, timeout_ms: Option) -> Value { // KServe.call.fields + let timeout = timeout_ms.unwrap_or_else(|| self.timeout_override_ms.unwrap_or_else(|| timeout_ms_for(ty))); + json!({"sock":sock,"type":ty,"message":msg,"desc":ks::desc(&env.root, &env.caps),"lib":format!("{}/lib", env.root),"timeout":timeout}) } fn fail_project(&mut self, project: &str, text: &str) { // KServe.fail.project let (mine, rest): (Vec, Vec) = std::mem::take(&mut self.wait).into_iter().partition(|w| w.project == project); self.wait = rest; - for w in mine { let _ = w.reply.send(failed(&ks::unavailable(text, &w.env.cli))); } + let launch_gen = self.launch_gen(project); + for w in mine { + let _ = w.reply.send(AskOutcome { reply: failed(&ks::unavailable(text, &w.env.cli)), sock: String::new(), launch_gen, dead_invalidated: false }); + } } fn launch(&mut self, project: &str) { // KServe.launch: helper present, then the server is started and gets 30 s to say it listens let now = now_s(); + let launch_gen = self.bump_gen(project); let dir = ks::dir(&self.rt, &self.home, project); { use crate::plat::fs::DirBuilderExt; let _ = std::fs::DirBuilder::new().recursive(true).mode(0o700).create(&dir); } let argv = ks::argv(&self.env.cli, project, &dir, self.hub_pid, &self.env.caps); let envv: Map = ["BACKPLANE_KICAD_LIBRARY", "KICAD_CONFIG_HOME"].iter().map(|k| (k.to_string(), json!(std::env::var(k).unwrap_or_default()))).collect(); - self.sink(json!({"op":"spawn","key":project,"argv":argv,"memory":"1536M","env":envv})); + self.sink(json!({"op":"spawn","key":project,"gen":launch_gen,"argv":argv,"memory":"1536M","env":envv})); let s = self.srv(project).starting(now); self.put(s); - if self.helper.is_some() { self.later(30.0, Msg::Late { project: project.into(), born: now }) } + if self.helper.is_some() { self.later(30.0, Msg::Late { project: project.into(), born: now, launch_gen }) } self.emit(); } fn close(&mut self, sock: &str) { if !sock.is_empty() { self.sink(json!({"op":"close","sock":sock})) } } // KServe.close fn ask(&mut self, w: Wt) { + if w.reply.is_closed() { return } + if std::time::Instant::now() >= w.deadline { + let short = w.ty.rsplit('.').next().unwrap_or(&w.ty); + let launch_gen = self.launch_gen(&w.project); + let _ = w.reply.send(AskOutcome { + reply: failed(&format!("KiCad IPC request {short} timed out after {} s waiting on the headless server", ASK_TIMEOUT.as_secs())), + sock: String::new(), + launch_gen, + dead_invalidated: false, + }); + return; + } let plan = ks::plan(&self.srvs, &w.project, &self.env.caps); + let cur_gen = self.launch_gen(&w.project); match plan.as_str() { - "ready" => self.forward(&w.project.clone(), &w.env.clone(), &w.ty.clone(), w.msg, w.reply), + "ready" => self.forward(w), + "unresponsive" => { + if self.srv(&w.project).sock.is_empty() { + let _ = w.reply.send(AskOutcome { + reply: failed(&ks::unavailable("the headless KiCad process is unresponsive", &w.env.cli)), + sock: String::new(), + launch_gen: cur_gen, + dead_invalidated: false, + }); + } else { + self.forward(w); + } + } "wait" => self.wait.insert(0, w), - "failed" => { let why = format!("the headless KiCad for {} stopped: {}", ks::name(&w.project), self.srv(&w.project).why); let _ = w.reply.send(failed(&ks::unavailable(&why, &w.env.cli))); } - "busy" => { let _ = w.reply.send(failed(&ks::unavailable(ks::BUSY, &w.env.cli))); } + "failed" => { let why = format!("the headless KiCad for {} stopped: {}", ks::name(&w.project), self.srv(&w.project).why); let _ = w.reply.send(AskOutcome { reply: failed(&ks::unavailable(&why, &w.env.cli)), sock: String::new(), launch_gen: cur_gen, dead_invalidated: false }); } + "busy" => { let _ = w.reply.send(AskOutcome { reply: failed(&ks::unavailable(ks::BUSY, &w.env.cli)), sock: String::new(), launch_gen: cur_gen, dead_invalidated: false }); } "start" => { let p = w.project.clone(); self.wait.insert(0, w); self.launch(&p) } p => { // "evict:": the least recently used server is asked to stop (it does so itself); the new one starts when it has let victim = p.trim_start_matches("evict:").to_string(); let project = w.project.clone(); - self.evicting(&victim, &project); + let victim_gen = self.launch_gen(&victim); + let project_gen = self.bump_gen(&project); + self.evicting(&victim, victim_gen, &project, project_gen); let s = Srv::new(&project, now_s()); self.put(s); self.wait.insert(0, w); self.emit(); } } } - fn evicting(&mut self, victim: &str, project: &str) { // KServe.evicting: kiapi.backplane.Shutdown, never a signal + fn evicting(&mut self, victim: &str, victim_gen: u64, project: &str, project_gen: u64) { // KServe.evicting: kiapi.backplane.Shutdown, never a signal let sock = self.srv(victim).sock; let env = self.env.clone(); let me = self.me.clone(); let (victim, project) = (victim.to_string(), project.to_string()); tokio::spawn(async move { - let (t, r) = oneshot::channel(); let _ = me.send(Msg::Raw { sock, env, ty: "kiapi.backplane.Shutdown".into(), msg: json!({}), reply: t }); + let (t, r) = oneshot::channel(); let _ = me.send(Msg::Raw { sock, env, ty: "kiapi.backplane.Shutdown".into(), msg: json!({}), timeout_ms: None, fence: Some((victim.clone(), victim_gen)), reply: t }); let o = r.await.unwrap_or_else(|_| failed("no reply")); - let _ = me.send(Msg::Evicted { victim, project, ok: o["ok"].as_bool().unwrap_or(false), why: o["error"].as_str().unwrap_or("").into() }); + let _ = me.send(Msg::Evicted { victim, victim_gen, project, project_gen, ok: o["ok"].as_bool().unwrap_or(false), why: o["error"].as_str().unwrap_or("").into() }); }); } /// A server that is listening answers Ping and GetVersion, and is the build the manifest names, before any request goes to it (KServe.hand). - fn hand(&self, project: String, env: Env, sock: String) { + fn hand(&self, project: String, env: Env, sock: String, launch_gen: u64) { let me = self.me.clone(); tokio::spawn(async move { - let ask = |ty: &str| { let (t, r) = oneshot::channel(); let _ = me.send(Msg::Raw { sock: sock.clone(), env: env.clone(), ty: ty.into(), msg: json!({}), reply: t }); r }; + let ask = |ty: &str| { let (t, r) = oneshot::channel(); let _ = me.send(Msg::Raw { sock: sock.clone(), env: env.clone(), ty: ty.into(), msg: json!({}), timeout_ms: None, fence: Some((project.clone(), launch_gen)), reply: t }); r }; // KiCad listens before it has finished loading and says so ("KiCad is not ready to reply", AS_NOT_READY): that is asked again for // up to READY_WAIT, never taken as a failed server (which stays failed until the person retries it) let mut p = ask("kiapi.common.commands.Ping").await.unwrap_or_else(|_| failed("no reply")); let until = std::time::Instant::now() + READY_WAIT; while not_ready(&p) && std::time::Instant::now() < until { tokio::time::sleep(Duration::from_millis(250)).await; p = ask("kiapi.common.commands.Ping").await.unwrap_or_else(|_| failed("no reply")); } - if !p["ok"].as_bool().unwrap_or(false) { let _ = me.send(Msg::Bad { project, why: format!("it did not answer Ping: {}", p["error"].as_str().unwrap_or("")) }); return } + if !p["ok"].as_bool().unwrap_or(false) { let _ = me.send(Msg::Bad { project, why: format!("it did not answer Ping: {}", p["error"].as_str().unwrap_or("")), launch_gen }); return } let o = ask("kiapi.common.commands.GetVersion").await.unwrap_or_else(|_| failed("no reply")); let full = o["message"]["version"]["full_version"].as_str().unwrap_or("").to_string(); // status says the manifest's version (a test build's GetVersion is a describe name, "...-dirty-bp.13"); KiCad's own string is logged if o["ok"].as_bool().unwrap_or(false) && ks::version_ok(&full, &env.version) { // (written so that a closed stderr cannot stop the handshake: eprintln! panics there, and the server would never be handed its requests) { use std::io::Write; let _ = writeln!(std::io::stderr(), "kicad ipc: {project} up, KiCad says {full} (manifest {})", env.version); } - let _ = me.send(Msg::Up { project, version: shown_version(&env.version, &full) }); } - else { let err = o["error"].as_str().unwrap_or(""); let _ = me.send(Msg::Bad { project, why: if err.is_empty() { format!("this KiCad is {full}, not the {} Backplane installed", env.version) } else { format!("it did not answer GetVersion: {err}") } }); } + let _ = me.send(Msg::Up { project, version: shown_version(&env.version, &full), launch_gen }); } + else { let err = o["error"].as_str().unwrap_or(""); let _ = me.send(Msg::Bad { project, why: if err.is_empty() { format!("this KiCad is {full}, not the {} Backplane installed", env.version) } else { format!("it did not answer GetVersion: {err}") }, launch_gen }); } }); } @@ -167,64 +341,204 @@ impl Actor { match o["event"].as_str() { Some("line") => { let project = o["key"].as_str().unwrap_or("").to_string(); + let ev_gen = o.get("gen").and_then(Value::as_u64); + let cur_gen = self.launch_gen(&project); + if ev_gen.is_some_and(|g| g != cur_gen) { return } if let Some(path) = ks::ready(o["text"].as_str().unwrap_or("")) { let s = self.srv(&project); - if s.state == "starting" && s.sock.is_empty() { self.hand(project.clone(), self.env.clone(), path.clone()); let s = s.listening(&path); self.put(s) } + if s.state == "starting" && s.sock.is_empty() { + self.hand(project.clone(), self.env.clone(), path.clone(), cur_gen); + let mut s = s.listening(&path); + s.pid = self.pid_of(&project); + self.put(s); + } + } + } + Some("exit") => { + let project = o["key"].as_str().unwrap_or("").to_string(); + let ev_gen = o.get("gen").and_then(Value::as_u64); + let cur_gen = self.launch_gen(&project); + if ev_gen.is_some_and(|g| g != cur_gen) { return } + self.exited(project, o["code"].as_i64().unwrap_or(1) as i32, o["tail"].as_str().unwrap_or("").to_string(), cur_gen); + } + _ => { + let id = match &o["id"] { Value::String(s) => s.clone(), v => v.to_string() }; + if let Some(p) = self.pend.remove(&id) { + let mut dead_invalidated = false; + if let Some(project) = &p.project { + if self.launch_gen(project) == p.launch_gen { + if o["ok"].as_bool().unwrap_or(false) { + if let Some(s) = self.srvs.iter_mut().find(|x| x.project == *project && x.state == "unresponsive" && x.sock == p.sock) { + s.state = "ready".into(); + s.why.clear(); + s.last = now_s(); + self.emit(); + } + } else if is_conn_error(&o) { + if self.process_alive(project) == Some(false) { + self.invalidate_server(project, Some(p.launch_gen), "the headless KiCad process exited", true); + dead_invalidated = true; + } else { + self.mark_unresponsive(project, p.launch_gen, "KiCad IPC connection dropped"); + } + } else if is_timeout_error(&o) && self.process_alive(project) == Some(false) { + self.invalidate_server(project, Some(p.launch_gen), "the headless KiCad process exited", true); + dead_invalidated = true; + } + } + } + send_pending(p.reply, &p.sock, p.launch_gen, o, dead_invalidated); } } - Some("exit") => self.exited(o["key"].as_str().unwrap_or("").to_string(), o["code"].as_i64().unwrap_or(1) as i32, o["tail"].as_str().unwrap_or("").to_string()), - _ => { let id = match &o["id"] { Value::String(s) => s.clone(), v => v.to_string() }; if let Some(r) = self.pend.remove(&id) { let _ = r.send(o); } } } } - fn exited(&mut self, project: String, code: i32, tail: String) { // the server's process ended: the record says what that means + fn exited(&mut self, project: String, code: i32, tail: String, launch_gen: u64) { // the server's process ended: the record says what that means + if self.launch_gen(&project) != launch_gen { return } let now = now_s(); let before = self.srv(&project); - if before.state == "stopped" { self.close(&before.sock); return } - let srv = before.exited(code, now, &tail); self.put(srv.clone()); self.close(&srv.sock); + let old_sock = before.sock.clone(); + self.close(&old_sock); + self.remove_stale_sock(&project, &old_sock); + if before.state == "stopped" { + if code == 0 { + if !before.why.is_empty() { self.put(before.set("stopped", "")); self.emit(); } + } else { + let fails = ks::fails_add(code, &before.fails, now); + let mut srv = before; + srv.fails = fails; + if ks::retry(&srv.fails, now).is_none() { + srv = srv.set("failed", &format!("stopped four times in five minutes: {tail}")); + } + self.put(srv); + self.emit(); + } + return + } + let srv = before.exited(code, now, &tail); self.put(srv.clone()); let name = ks::name(&project); match srv.state.as_str() { - "starting" => if let Some(s) = ks::retry(&srv.fails, now) { self.later(s as f64, Msg::Go { project }) }, + "starting" => if let Some(s) = ks::retry(&srv.fails, now) { self.later(s as f64, Msg::Go { project, launch_gen }) }, "failed" => self.fail_project(&project, &format!("the headless KiCad for {name} stopped: {}", srv.why)), _ => self.fail_project(&project, &format!("the headless KiCad for {name} exited")), } self.emit(); } - fn up(&mut self, project: String, version: String) { // it answered Ping and GetVersion as the right build: ready, and what waited goes out - let s = self.srv(&project); if s.state != "starting" { return } - let sock = s.sock.clone(); self.put(s.up(&sock, &version, now_s())); + fn up(&mut self, project: String, version: String, launch_gen: u64) { // it answered Ping and GetVersion as the right build: ready, and what waited goes out + if self.launch_gen(&project) != launch_gen { return } + let s = self.srv(&project); if s.state != "starting" || s.sock.is_empty() { return } + if self.process_alive(&project) == Some(false) { + self.invalidate_server(&project, Some(launch_gen), "the headless KiCad process exited", true); + return + } + let sock = s.sock.clone(); + let mut up_srv = s.up(&sock, &version, now_s()); + up_srv.pid = self.pid_of(&project); + self.put(up_srv); let (mine, rest): (Vec, Vec) = std::mem::take(&mut self.wait).into_iter().partition(|w| w.project == project); self.wait = rest; - for w in mine { self.forward(&w.project.clone(), &w.env.clone(), &w.ty.clone(), w.msg, w.reply) } + for w in mine { self.forward(w) } self.emit(); } - fn bad(&mut self, project: String, why: String) { // it failed the handshake or never listened - if self.srv(&project).state != "starting" { return } - let s = self.srv(&project).set("failed", &why); self.put(s); + fn bad(&mut self, project: String, why: String, launch_gen: u64) { // it failed the handshake or never listened + if self.launch_gen(&project) != launch_gen { return } + let before = self.srv(&project); + if before.state != "starting" { return } + let old_sock = before.sock.clone(); + self.close(&old_sock); + if self.process_alive(&project) == Some(false) { + self.remove_stale_sock(&project, &old_sock); + } + let s = before.set("failed", &why); self.put(s); self.fail_project(&project, &format!("the headless KiCad for {} {why}", ks::name(&project))); self.emit(); } - fn evicted(&mut self, victim: String, project: String, ok: bool, why: String) { - if ok { let s = self.srv(&victim).set("stopped", ""); self.put(s); self.launch(&project); return } - let s = self.srv(&victim).hold(); self.put(s); // Shutdown refused (unsaved changes): held, never forced; the next least recently used is asked + fn evicted(&mut self, victim: String, victim_gen: u64, project: String, project_gen: u64, ok: bool, why: String) { + if ok { + if self.launch_gen(&victim) == victim_gen { + let before = self.srv(&victim); + let old_sock = before.sock.clone(); + self.close(&old_sock); + self.remove_stale_sock(&victim, &old_sock); + self.bump_gen(&victim); + let s = before.set("stopped", ""); self.put(s); + self.emit(); + } + if self.launch_gen(&project) == project_gen && self.srv(&project).state == "starting" { + let live_others = self.srvs.iter().filter(|x| x.project != project && ks::active(&x.state)).count(); + if live_others < 2 { + self.launch(&project); + } else { + let other = ks::evict(&self.srvs); + if other.is_empty() { + self.bump_gen(&project); + let s = self.srv(&project).set("stopped", ""); self.put(s); + self.fail_project(&project, &format!("{} ({} was busy)", ks::BUSY, ks::name(&victim))); self.emit(); + } else { + let other_gen = self.launch_gen(&other); + self.evicting(&other, other_gen, &project, project_gen); + } + } + } + return + } + if self.launch_gen(&victim) == victim_gen && ks::active(&self.srv(&victim).state) { + let s = self.srv(&victim).hold(); self.put(s); // Shutdown refused (unsaved changes): held, never forced; the next least recently used is asked + } + if self.launch_gen(&project) != project_gen || self.srv(&project).state != "starting" { return } let other = ks::evict(&self.srvs); if other.is_empty() { - let s = self.srv(&project).set("stopped", ""); self.put(s); + let before = self.srv(&project); + let old_sock = before.sock.clone(); + self.close(&old_sock); + self.remove_stale_sock(&project, &old_sock); + self.bump_gen(&project); + let s = before.set("stopped", ""); self.put(s); self.fail_project(&project, &format!("{} ({} would not stop: {why})", ks::BUSY, ks::name(&victim))); self.emit(); - } else { self.evicting(&other, &project) } + } else { + let other_gen = self.launch_gen(&other); + self.evicting(&other, other_gen, &project, project_gen); + } } fn retire(&mut self, project: String, reply: oneshot::Sender) { let s = self.srv(&project); + let launch_gen = self.launch_gen(&project); + if s.state == "starting" && s.sock.is_empty() && self.process_alive(&project) != Some(false) { + let _ = reply.send(json!({"ok":false,"error":"the headless KiCad server is still starting"})); + return; + } + if s.state == "failed" && self.process_alive(&project) == Some(true) { + let _ = reply.send(json!({"ok":false,"error":"the failed headless KiCad process is still running"})); + return; + } if s.sock.is_empty() || matches!(s.state.as_str(), "none" | "stopped" | "failed") { + let old_sock = s.sock.clone(); + self.close(&old_sock); + self.remove_stale_sock(&project, &old_sock); + self.bump_gen(&project); self.put(s.set("stopped", "")); self.fail_project(&project, "the GUI KiCad took over this project"); self.emit(); let _ = reply.send(json!({"ok":true,"retired":false})); return } let sock = s.sock.clone(); let env = self.env.clone(); let me = self.me.clone(); tokio::spawn(async move { - let (t, r) = oneshot::channel(); let _ = me.send(Msg::Raw { sock, env, ty: "kiapi.backplane.Shutdown".into(), msg: json!({}), reply: t }); + let (t, r) = oneshot::channel(); let _ = me.send(Msg::Raw { sock, env, ty: "kiapi.backplane.Shutdown".into(), msg: json!({}), timeout_ms: None, fence: Some((project.clone(), launch_gen)), reply: t }); let o = r.await.unwrap_or_else(|_| failed("no reply")); - let _ = me.send(Msg::Retired { project, ok: o["ok"].as_bool().unwrap_or(false), why: o["error"].as_str().unwrap_or("").into(), reply }); + let _ = me.send(Msg::Retired { project, launch_gen, ok: o["ok"].as_bool().unwrap_or(false), why: o["error"].as_str().unwrap_or("").into(), reply }); }); } - fn retired(&mut self, project: String, ok: bool, why: String, reply: oneshot::Sender) { + fn retired(&mut self, project: String, launch_gen: u64, ok: bool, why: String, reply: oneshot::Sender) { + if self.launch_gen(&project) != launch_gen { + let cur = self.srv(&project); + if !ks::active(&cur.state) { + let _ = reply.send(json!({"ok":true,"retired":false})); + } else { + let _ = reply.send(json!({"ok":false,"error":"a newer headless KiCad server replaced the retired one"})); + } + return; + } if ok { - let s = self.srv(&project).set("stopped", ""); self.put(s); + let before = self.srv(&project); + let old_sock = before.sock.clone(); + self.close(&old_sock); + self.remove_stale_sock(&project, &old_sock); + self.bump_gen(&project); + let s = before.set("stopped", ""); self.put(s); self.fail_project(&project, "the GUI KiCad took over this project"); self.emit(); let _ = reply.send(json!({"ok":true,"retired":true})); } else { @@ -234,19 +548,64 @@ impl Actor { } fn handle(&mut self, m: Msg) { match m { - Msg::Ask { project, env, ty, msg, reply } => { self.env = env.clone(); self.ask(Wt { project, ty, msg, env, reply }) } - Msg::Raw { sock, env, ty, msg, reply } => { let f = self.call_fields(&sock, &env, &ty, msg); self.call(f, reply) } + Msg::Ask { project, env, ty, msg, deadline, reply } => { self.env = env.clone(); self.reap_dead(); self.ask(Wt { project, ty, msg, env, deadline, reply }) } + Msg::Raw { sock, env, ty, msg, timeout_ms, fence, reply } => { + if reply.is_closed() { return } + if let Some((proj, expected_gen)) = fence { + if self.launch_gen(&proj) != expected_gen || self.srv(&proj).sock != sock { + let _ = reply.send(failed("stale KiCad server generation")); + return; + } + } + let f = self.call_fields(&sock, &env, &ty, msg, timeout_ms); + self.call(f, reply) + } Msg::Retire { project, reply } => self.retire(project, reply), - Msg::Retired { project, ok, why, reply } => self.retired(project, ok, why, reply), - Msg::Info(r) => { let _ = r.send(ks::lines(&self.srvs)); } + Msg::Retired { project, launch_gen, ok, why, reply } => self.retired(project, launch_gen, ok, why, reply), + Msg::Info(r) => { self.reap_dead(); let _ = r.send(ks::lines(&self.srvs)); } Msg::Argv { project, env, reply } => { let d = ks::dir(&self.rt, &self.home, &project); let _ = reply.send(ks::argv(&env.cli, &project, &d, self.hub_pid, &env.caps).join(" ")); } - Msg::Clear => { for s in self.srvs.iter_mut().filter(|s| s.state == "failed") { *s = s.clone().cleared() } self.emit() } + Msg::ReadySock { project, reply } => { + self.reap_dead(); + let s = self.srv(&project); + let out = (matches!(s.state.as_str(), "ready" | "unresponsive") && !s.sock.is_empty()).then(|| (s.sock, self.launch_gen(&project))); + let _ = reply.send(out); + } + Msg::Invalidate { project, launch_gen, why, reply } => { + if self.launch_gen(&project) != launch_gen { + let _ = reply.send(false); + } else if self.process_alive(&project) == Some(false) { + self.invalidate_server(&project, Some(launch_gen), &why, true); + self.bump_gen(&project); + let _ = reply.send(true); + } else { + self.mark_unresponsive(&project, launch_gen, &why); + let _ = reply.send(false); + } + } + Msg::Clear => { + let projects: Vec = self.srvs.iter() + .filter(|s| s.state == "failed" && self.process_alive(&s.project) != Some(true)) + .map(|s| s.project.clone()) + .collect(); + for p in &projects { + if let Some(s) = self.srvs.iter_mut().find(|x| x.project == *p) { + *s = s.clone().cleared(); + } + self.bump_gen(p); + } + self.emit() + } Msg::Line(gen, t) => if self.helper.as_ref().map(|h| h.gen) == Some(gen) { self.line(t) }, - Msg::Up { project, version } => self.up(project, version), - Msg::Bad { project, why } => self.bad(project, why), - Msg::Late { project, born } => { let s = self.srv(&project); if s.state == "starting" && s.started == born && s.sock.is_empty() { self.bad(project, "did not say it was listening within 30 s".into()) } } - Msg::Go { project } => if self.srv(&project).state == "starting" { self.launch(&project) }, - Msg::Evicted { victim, project, ok, why } => self.evicted(victim, project, ok, why), + Msg::Up { project, version, launch_gen } => self.up(project, version, launch_gen), + Msg::Bad { project, why, launch_gen } => self.bad(project, why, launch_gen), + Msg::Late { project, born, launch_gen } => { + let s = self.srv(&project); + if s.state == "starting" && s.started == born && s.sock.is_empty() && self.launch_gen(&project) == launch_gen { + self.bad(project, "did not say it was listening within 30 s".into(), launch_gen) + } + } + Msg::Go { project, launch_gen } => if self.srv(&project).state == "starting" && self.launch_gen(&project) == launch_gen { self.launch(&project) }, + Msg::Evicted { victim, victim_gen, project, project_gen, ok, why } => self.evicted(victim, victim_gen, project, project_gen, ok, why), } } } @@ -260,7 +619,7 @@ pub fn start(hub: &Arc) { let lines = Arc::new(std::sync::Mutex::new(String::new())); let home = hub.cfg.home.to_string_lossy().to_string(); let mut a = Actor { me: tx.clone(), home, rt: std::env::var("XDG_RUNTIME_DIR").unwrap_or_default(), hub_pid: std::process::id(), helper: None, gen: 0, pend: HashMap::new(), next: 0, - srvs: vec![], wait: vec![], shown: String::new(), env: Env::default(), lines: lines.clone() }; + srvs: vec![], srv_gen: HashMap::new(), wait: vec![], shown: String::new(), env: Env::default(), lines: lines.clone(), timeout_override_ms: None }; tokio::spawn(async move { while let Some(m) = rx.recv().await { a.handle(m) } }); if IPC.set(Ipc { tx, lines }).is_ok() { hub.register_rpc(Arc::new(IpcRpc)) } // Settings > CAD reads kicad.* and freecad from the hub's info: say what is found now, and again whenever the path field changes @@ -398,13 +757,147 @@ pub fn read_runtime(cli: &Path) -> Env { // What the hub asks --------------------------------------------------------------------------------------------------------- -async fn ask(i: &Ipc, project: &str, env: &Env, ty: &str, msg: Value) -> Value { +async fn ask_detailed(i: &Ipc, project: &str, env: &Env, ty: &str, msg: Value) -> AskOutcome { + let deadline = std::time::Instant::now() + ASK_TIMEOUT; let (t, r) = oneshot::channel(); - if i.tx.send(Msg::Ask { project: project.into(), env: env.clone(), ty: ty.into(), msg, reply: t }).is_err() { return failed("no reply") } - r.await.unwrap_or_else(|_| failed("no reply")) + if i.tx.send(Msg::Ask { project: project.into(), env: env.clone(), ty: ty.into(), msg, deadline, reply: t }).is_err() { + return AskOutcome { reply: failed("no reply"), sock: String::new(), launch_gen: 0, dead_invalidated: false }; + } + match tokio::time::timeout(ASK_TIMEOUT, r).await { + Ok(Ok(o)) => o, + Ok(Err(_)) => AskOutcome { reply: failed("no reply"), sock: String::new(), launch_gen: 0, dead_invalidated: false }, + Err(_) => { + let short = ty.rsplit('.').next().unwrap_or(ty); + let suffix = if short == "BeginCommit" { "; request outcome unknown if it had already reached KiCad" } else { "" }; + AskOutcome { + reply: failed(&format!("KiCad IPC request {short} timed out after {} s waiting on the headless server{suffix}", ASK_TIMEOUT.as_secs())), + sock: String::new(), + launch_gen: 0, + dead_invalidated: false, + } + } + } +} +#[cfg_attr(not(test), allow(dead_code))] +async fn ask(i: &Ipc, project: &str, env: &Env, ty: &str, msg: Value) -> Value { ask_detailed(i, project, env, ty, msg).await.reply } +async fn explain_begin_commit_timeout_headless(i: &Ipc, pro: &str, env: &Env, orig: &Value, orig_sock: &str, orig_gen: u64) -> String { + let name = ks::name(pro); + let unknown = "request outcome unknown if bytes reached KiCad"; + if orig_gen == 0 || orig_sock.is_empty() { + return format!( + "BeginCommit timed out ({}); {unknown} — the headless KiCad server for {name} is no longer active", + err_of(orig) + ); + } + let diag_wait = Duration::from_millis(PROBE_PING_TIMEOUT_MS + 1_000); + let (rt, rx) = oneshot::channel(); + if i.tx.send(Msg::ReadySock { project: pro.into(), reply: rt }).is_err() { + return format!("BeginCommit timed out ({}; {unknown}), and the KiCad IPC actor is not running", err_of(orig)); + } + let ready = match tokio::time::timeout(diag_wait, rx).await { + Ok(Ok(v)) => v, + Ok(Err(_)) | Err(_) => { + return format!( + "BeginCommit timed out ({}; {unknown}), and the KiCad IPC actor did not answer readiness check in time", + err_of(orig) + ); + } + }; + let Some((sock, launch_gen)) = ready else { + return format!( + "BeginCommit timed out ({}; {unknown}) — the headless KiCad server for {name} is no longer running (stale state was cleared; retry to start a fresh server)", + err_of(orig) + ); + }; + if launch_gen != orig_gen || sock != orig_sock { + return format!( + "BeginCommit timed out ({}; {unknown}) — the original KiCad server generation has since been replaced (not probing the newer server)", + err_of(orig) + ); + } + let (pt, pr) = oneshot::channel(); + if i.tx.send(Msg::Raw { + sock, + env: env.clone(), + ty: "kiapi.common.commands.Ping".into(), + msg: json!({}), + timeout_ms: Some(PROBE_PING_TIMEOUT_MS), + fence: Some((pro.into(), launch_gen)), + reply: pt, + }).is_err() { + return format!("BeginCommit timed out ({}; {unknown}), and the KiCad IPC actor stopped before probing health", err_of(orig)); + } + let ping = match tokio::time::timeout(diag_wait, pr).await { + Ok(Ok(v)) => v, + Ok(Err(_)) => failed("no reply"), + Err(_) => failed("follow-up Ping probe timed out waiting on transport queue"), + }; + if ping["ok"].as_bool().unwrap_or(false) { + format!( + "BeginCommit timed out ({}; {unknown}) while KiCad still answers reads/Ping — a modal dialog, busy task, or stale open commit may be blocking writes; check kicad_ipc_status, drop any open commit with EndCommit (CMA_DROP), or restart KiCad", + err_of(orig) + ) + } else { + let ping_err = err_of(&ping); + let (itx, irx) = oneshot::channel(); + let dead = if i.tx.send(Msg::Invalidate { + project: pro.into(), + launch_gen, + why: format!("KiCad stopped responding after BeginCommit timed out ({ping_err})"), + reply: itx, + }).is_ok() { + tokio::time::timeout(diag_wait, irx).await.ok().and_then(|r| r.ok()).unwrap_or(false) + } else { + false + }; + if dead { + format!( + "BeginCommit timed out ({}; {unknown}) and a follow-up Ping failed ({ping_err}); the headless KiCad process for {name} exited and its stale session was invalidated — retry to start a fresh server", + err_of(orig) + ) + } else { + format!( + "BeginCommit timed out ({}; {unknown}) and a follow-up Ping failed ({ping_err}); the headless KiCad process for {name} is still running and was marked unresponsive (not starting a duplicate server) — check kicad_ipc_status or restart KiCad", + err_of(orig) + ) + } + } +} +async fn explain_begin_commit_timeout_gui(gui: &super::embed::GuiRoute, pro: &str, orig: &Value) -> String { + let st = super::embed::session_state(pro); + let dialogs: Vec<&str> = st["dialogs"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); + if !dialogs.is_empty() { + return format!( + "BeginCommit timed out ({}; request outcome unknown if bytes reached KiCad) while KiCad has dialog(s) open ({}); close or answer the dialog in KiCad, then retry", + err_of(orig), + dialogs.join(", ") + ); + } + let ping = super::embed::gui_call_timeout(gui, "kiapi.common.commands.Ping", json!({}), "", PROBE_PING_TIMEOUT_MS).await; + if ping["ok"].as_bool().unwrap_or(false) { + format!( + "BeginCommit timed out ({}; request outcome unknown if bytes reached KiCad) while KiCad still answers reads/Ping — an unreported modal dialog, busy task, or stale open commit may be blocking writes; check kicad_ipc_status, drop any open commit with EndCommit (CMA_DROP), or restart KiCad", + err_of(orig) + ) + } else { + super::embed::check_exited(pro); + format!( + "BeginCommit timed out ({}; request outcome unknown if bytes reached KiCad) and a follow-up Ping failed ({}); KiCad may have exited or hung — check kicad_ipc_status or reopen KiCad", + err_of(orig), + err_of(&ping) + ) + } +} +async fn info_on(i: &Ipc) -> String { + let (t, r) = oneshot::channel(); + if i.tx.send(Msg::Info(t)).is_err() { return String::new() } + tokio::time::timeout(Duration::from_millis(PROBE_PING_TIMEOUT_MS + 1_000), r).await.ok().and_then(|res| res.ok()).unwrap_or_default() +} +async fn argv_on(i: &Ipc, project: &str, env: &Env) -> String { + let (t, r) = oneshot::channel(); + if i.tx.send(Msg::Argv { project: project.into(), env: env.clone(), reply: t }).is_err() { return String::new() } + tokio::time::timeout(Duration::from_millis(PROBE_PING_TIMEOUT_MS + 1_000), r).await.ok().and_then(|res| res.ok()).unwrap_or_default() } -async fn info_on(i: &Ipc) -> String { let (t, r) = oneshot::channel(); if i.tx.send(Msg::Info(t)).is_err() { return String::new() } r.await.unwrap_or_default() } -async fn argv_on(i: &Ipc, project: &str, env: &Env) -> String { let (t, r) = oneshot::channel(); if i.tx.send(Msg::Argv { project: project.into(), env: env.clone(), reply: t }).is_err() { return String::new() } r.await.unwrap_or_default() } /// Ask a running headless KiCad for `project` to shut down cleanly (`kiapi.backplane.Shutdown`, never a signal) before a GUI KiCad takes over. pub async fn retire(project: &str) -> Value { @@ -580,14 +1073,19 @@ async fn run_on(hub: &Arc, thread: Option<&str>, path: &str, ty: &str, msg: if o["ok"].as_bool().unwrap_or(false) && thread.is_some_and(|t| !t.is_empty()) && writes_items(short, &msg_doc, commits) { super::embed::agent_changed(&pro, &doc_file(path, &pro)) } let ok = o["ok"].as_bool().unwrap_or(false); if !ok && short == "BeginCommit" { unpin() } + if !ok && is_conn_error(&o) { super::embed::check_exited(&pro); } if o["fallback"].as_bool().unwrap_or(false) { log_fallback(hub, thread, o["why"].as_str().unwrap_or("")).await; return Err(o["error"].as_str().unwrap_or("").into()) } - let servers = format!("{pro}|ready|gui ({})", gui.mode); + let live = super::embed::gui_route(&pro).is_some() && !is_conn_error(&o); + let servers = format!("{pro}|{}|gui ({})", if live { "ready" } else { "stopped" }, gui.mode); if status { // KiCad's open dialogs and its notices (embed-notice: "Could not use OpenGL, falling back to software rendering"): the agent says them let st = super::embed::session_state(&pro); return Ok(json!({"server":format!("gui ({})", gui.mode),"servers":servers,"argv":gui.argv,"version":gui.version,"capabilities":o["message"].clone(),"detail":if ok { String::new() } else { err_of(&o) }, "dialogs":st["dialogs"].clone(),"dialogs_reported":st["dialogs_reported"].clone(),"notices":st["notices"].clone()})) } + if !ok && short == "BeginCommit" && is_timeout_error(&o) { + return Err(explain_begin_commit_timeout_gui(&gui, &pro, &o).await); + } if !ok { return Err(if short == "SaveDocument" { super::savegate::explain_save_error(&err_of(&o), super::savegate::saves_design(&msg_doc, path)) } else { err_of(&o) }) } let wrote_nothing = short == "SaveDocument" && super::savegate::wrote_nothing(&o); let mut o = o; let mut out = json!({"type":o["type"].as_str().unwrap_or(""),"message":o["message"].take()}); // (taken, not copied: a simulation's vectors) @@ -612,12 +1110,23 @@ async fn run_on(hub: &Arc, thread: Option<&str>, path: &str, ty: &str, msg: let Some(i) = IPC.get() else { let why = "this Backplane has no KiCad IPC helper"; log_fallback(hub, thread, why).await; return Err(ks::unavailable(why, &env.cli)) }; let msg_for_warning = msg.clone(); if !status { dispatch(HEADLESS, ty.rsplit('.').next().unwrap_or(ty))?; } - let o = ask(i, &pro, &env, ty, msg).await; - let lines = info_on(i).await; let argv = argv_on(i, &pro, &env).await; + let mut outcome = ask_detailed(i, &pro, &env, ty, msg.clone()).await; + if !status && outcome.dead_invalidated && is_dial_refused(&outcome.reply) { + outcome = ask_detailed(i, &pro, &env, ty, msg).await; + } + let (o, orig_sock, orig_gen) = (outcome.reply, outcome.sock, outcome.launch_gen); let ok = o["ok"].as_bool().unwrap_or(false); - if !ok && ty.ends_with(".BeginCommit") { unpin() } + let short = ty.rsplit('.').next().unwrap_or(ty); + if !ok && short == "BeginCommit" { unpin() } if o["fallback"].as_bool().unwrap_or(false) { log_fallback(hub, thread, o["why"].as_str().unwrap_or("")).await; return Err(o["error"].as_str().unwrap_or("").into()) } - if status { return Ok(json!({"server":ks::note(&lines),"servers":lines,"argv":argv,"version":env.version,"capabilities":o["message"].clone(),"detail":if ok { String::new() } else { err_of(&o) }})) } + if status { + let lines = info_on(i).await; + let argv = argv_on(i, &pro, &env).await; + return Ok(json!({"server":ks::note(&lines),"servers":lines,"argv":argv,"version":env.version,"capabilities":o["message"].clone(),"detail":if ok { String::new() } else { err_of(&o) }})); + } + if !ok && short == "BeginCommit" && is_timeout_error(&o) { + return Err(explain_begin_commit_timeout_headless(i, &pro, &env, &o, &orig_sock, orig_gen).await); + } if !ok { return Err(err_of(&o)) } let mut o = o; let mut out = json!({"type":o["type"].as_str().unwrap_or(""),"message":o["message"].take()}); // (taken, not copied: a simulation's vectors) // a KiCad Open in KiCad started detached has this project open: it has no API server, so it does not show the agent's change, and @@ -899,12 +1408,12 @@ mod tests { asked }); let (tx, mut rx) = mpsc::unbounded_channel(); let lines = Arc::new(std::sync::Mutex::new(String::new())); - let mut a = Actor { me: tx.clone(), home: String::new(), rt, hub_pid: std::process::id(), helper: None, gen: 0, pend: HashMap::new(), next: 0, srvs: vec![], wait: vec![], shown: String::new(), env: Env::default(), lines: lines.clone() }; + let mut a = Actor { me: tx.clone(), home: String::new(), rt, hub_pid: std::process::id(), helper: None, gen: 0, pend: HashMap::new(), next: 0, srvs: vec![], srv_gen: HashMap::new(), wait: vec![], shown: String::new(), env: Env::default(), lines: lines.clone(), timeout_override_ms: None }; tokio::spawn(async move { while let Some(m) = rx.recv().await { a.handle(m) } }); let env = Env { cli, version: "10.99.0-bp.4".into(), ..Default::default() }; let (t, r) = oneshot::channel(); - tx.send(Msg::Ask { project: project.clone(), env, ty: "kiapi.common.commands.GetVersion".into(), msg: json!({}), reply: t }).unwrap(); - let o = tokio::time::timeout(Duration::from_secs(10), r).await.expect("an answer in time").unwrap(); + tx.send(Msg::Ask { project: project.clone(), env, ty: "kiapi.common.commands.GetVersion".into(), msg: json!({}), deadline: std::time::Instant::now() + ASK_TIMEOUT, reply: t }).unwrap(); + let o = tokio::time::timeout(Duration::from_secs(10), r).await.expect("an answer in time").unwrap().reply; assert_eq!(o["ok"], json!(true), "{o}"); assert_eq!(o["message"]["version"]["full_version"], json!("10.99.0-unknown-bp.4")); let asked = srv.await.unwrap(); assert!(asked[0].ends_with("commands.Ping") && asked[1].ends_with("commands.GetVersion") && asked[2].ends_with("commands.GetVersion"), "{asked:?}"); @@ -927,6 +1436,557 @@ mod tests { for t in ["kiapi.common.commands.SaveDocument", "kiapi.board.commands.CreateItems", "kiapi.board.commands.BeginCommit", "kiapi.board.commands.EndCommit", "kiapi.backplane.Shutdown", "", "GetItemsX.Delete"] { assert!(copy_ipc_refused(true, t).is_some(), "{t}") } assert_eq!(copy_ipc_refused(false, "kiapi.common.commands.SaveDocument"), None); } + + struct MockTransport { + tx: mpsc::UnboundedSender, + alive: Arc>>, + pids: Arc>>, + } + impl super::Transport for MockTransport { + fn send(&mut self, fields: Value) -> bool { let _ = self.tx.send(fields); true } + fn process_alive(&self, key: &str) -> Option { self.alive.lock().unwrap().get(key).copied() } + fn pid_of(&self, key: &str) -> u32 { self.pids.lock().unwrap().get(key).copied().unwrap_or(0) } + } + + fn mock_actor(rt: String) -> ( + Ipc, + mpsc::UnboundedReceiver, + mpsc::UnboundedSender, + Arc>>, + Arc>>, + ) { + let (tx, mut rx) = mpsc::unbounded_channel(); + let (ftx, frx) = mpsc::unbounded_channel(); + let alive = Arc::new(std::sync::Mutex::new(HashMap::new())); + let pids = Arc::new(std::sync::Mutex::new(HashMap::new())); + let lines = Arc::new(std::sync::Mutex::new(String::new())); + let mut a = Actor { + me: tx.clone(), + home: String::new(), + rt, + hub_pid: std::process::id(), + helper: Some(Helper { + link: Box::new(MockTransport { tx: ftx, alive: alive.clone(), pids: pids.clone() }), + gen: 1, + }), + gen: 1, + pend: HashMap::new(), + next: 0, + srvs: vec![], + srv_gen: HashMap::new(), + wait: vec![], + shown: String::new(), + env: Env::default(), + lines: lines.clone(), + timeout_override_ms: None, + }; + tokio::spawn(async move { while let Some(m) = rx.recv().await { a.handle(m) } }); + (Ipc { tx: tx.clone(), lines }, frx, tx, alive, pids) + } + + #[tokio::test] + async fn process_exit_invalidates_ready_state_and_clears_stale_socket() { + let root = crate::plat::tmp::short_dir("ipc-exit"); + let rt = root.to_string_lossy().to_string(); + let project = "/p/exit.kicad_pro".to_string(); + let dir = ks::dir(&rt, "", &project); + std::fs::create_dir_all(&dir).unwrap(); + let sock = format!("{dir}/api.sock"); + std::fs::write(&sock, "stale").unwrap(); + + let (ipc, mut frx, tx, alive, pids) = mock_actor(rt); + alive.lock().unwrap().insert(project.clone(), true); + pids.lock().unwrap().insert(project.clone(), 12345); + let env = Env { cli: "/k/kicad-cli".into(), version: "10.99.0-bp.13".into(), ..Default::default() }; + + let (atx, arx) = oneshot::channel(); + tx.send(Msg::Ask { project: project.clone(), env: env.clone(), ty: "kiapi.common.commands.Ping".into(), msg: json!({}), deadline: std::time::Instant::now() + ASK_TIMEOUT, reply: atx }).unwrap(); + let spawn = frx.recv().await.unwrap(); + assert_eq!(spawn["op"], "spawn"); + let launch_gen = spawn["gen"].as_u64().unwrap(); + tx.send(Msg::Line(1, json!({"event":"line","key":project,"gen":launch_gen,"text":format!("KiCad API server listening at ipc://{sock}")}))).unwrap(); + for _ in 0..2 { + let req = frx.recv().await.unwrap(); + let id = req["id"].clone(); + let msg = if req["type"].as_str().unwrap().ends_with("GetVersion") { json!({"version":{"full_version":"10.99.0-bp.13"}}) } else { json!({}) }; + tx.send(Msg::Line(1, json!({"id":id,"ok":true,"type":"r","message":msg}))).unwrap(); + } + let user_req = frx.recv().await.unwrap(); + tx.send(Msg::Line(1, json!({"id":user_req["id"],"ok":true,"type":"PingResponse","message":{}}))).unwrap(); + assert_eq!(arx.await.unwrap().reply["ok"], json!(true)); + assert_eq!(info_on(&ipc).await, format!("{project}|ready|")); + + // Process dies without delivering an exit event yet -> Info / Ask reaps it immediately. + alive.lock().unwrap().insert(project.clone(), false); + let info = info_on(&ipc).await; + assert!(info.contains("|stopped|") && !info.contains("|ready|"), "got: {info}"); + #[cfg(unix)] + assert!(!std::path::Path::new(&sock).exists(), "stale socket should be removed on process exit"); + + // Next request sees stopped state and launches a fresh server instead of talking to dead socket. + alive.lock().unwrap().insert(project.clone(), true); + let (atx2, _arx2) = oneshot::channel(); + tx.send(Msg::Ask { project: project.clone(), env, ty: "kiapi.common.commands.Ping".into(), msg: json!({}), deadline: std::time::Instant::now() + ASK_TIMEOUT, reply: atx2 }).unwrap(); + let mut saw_spawn = false; + while let Ok(Some(msg)) = tokio::time::timeout(Duration::from_millis(500), frx.recv()).await { + if msg["op"] == "spawn" { saw_spawn = true; break } + } + assert!(saw_spawn, "new request after process exit must spawn fresh server"); + } + + #[tokio::test] + async fn connection_drop_on_ready_server_invalidates_readiness_immediately() { + let root = crate::plat::tmp::short_dir("ipc-drop"); + let rt = root.to_string_lossy().to_string(); + let project = "/p/drop.kicad_pro".to_string(); + let dir = ks::dir(&rt, "", &project); + std::fs::create_dir_all(&dir).unwrap(); + let sock = format!("{dir}/api.sock"); + std::fs::write(&sock, "live").unwrap(); + + let (ipc, mut frx, tx, alive, pids) = mock_actor(rt); + alive.lock().unwrap().insert(project.clone(), true); + pids.lock().unwrap().insert(project.clone(), 4321); + let env = Env { cli: "/k/kicad-cli".into(), version: "10.99.0-bp.13".into(), ..Default::default() }; + + let (atx, arx) = oneshot::channel(); + tx.send(Msg::Ask { project: project.clone(), env: env.clone(), ty: "kiapi.common.commands.Ping".into(), msg: json!({}), deadline: std::time::Instant::now() + ASK_TIMEOUT, reply: atx }).unwrap(); + let spawn = frx.recv().await.unwrap(); + let launch_gen = spawn["gen"].as_u64().unwrap(); + tx.send(Msg::Line(1, json!({"event":"line","key":project,"gen":launch_gen,"text":format!("KiCad API server listening at ipc://{sock}")}))).unwrap(); + for _ in 0..2 { + let req = frx.recv().await.unwrap(); + let msg = if req["type"].as_str().unwrap().ends_with("GetVersion") { json!({"version":{"full_version":"10.99.0-bp.13"}}) } else { json!({}) }; + tx.send(Msg::Line(1, json!({"id":req["id"],"ok":true,"type":"r","message":msg}))).unwrap(); + } + let user_req = frx.recv().await.unwrap(); + tx.send(Msg::Line(1, json!({"id":user_req["id"],"ok":false,"error":format!("dial ipc://{sock}: Connection refused")}))).unwrap(); + let ans = arx.await.unwrap(); + assert_eq!(ans.reply["ok"], json!(false)); + assert!(!ans.dead_invalidated, "live process must not report dead_invalidated"); + let info = info_on(&ipc).await; + assert!(info.contains("|unresponsive|") && !info.contains("|ready|"), "live connection drop must mark unresponsive immediately: {info}"); + #[cfg(unix)] + assert!(std::path::Path::new(&sock).exists(), "live process socket must not be unlinked"); + + // Next call while alive must reconnect on existing generation (NO second spawn!) and promote back to ready on success. + let (atx2, arx2) = oneshot::channel(); + tx.send(Msg::Ask { project: project.clone(), env, ty: "kiapi.common.commands.Ping".into(), msg: json!({}), deadline: std::time::Instant::now() + ASK_TIMEOUT, reply: atx2 }).unwrap(); + let mut msg2 = frx.recv().await.unwrap(); + if msg2["op"] == "close" { msg2 = frx.recv().await.unwrap(); } + assert_ne!(msg2["op"], "spawn", "must never spawn a duplicate KiCad while process is alive"); + assert_eq!(msg2["type"], "kiapi.common.commands.Ping"); + assert_eq!(msg2["sock"], sock); + tx.send(Msg::Line(1, json!({"id":msg2["id"],"ok":true,"type":"PingResponse","message":{}}))).unwrap(); + assert_eq!(arx2.await.unwrap().reply["ok"], json!(true)); + assert!(info_on(&ipc).await.contains("|ready|"), "successful call must promote unresponsive back to ready"); + } + + #[tokio::test] + async fn stale_handshake_up_cannot_resurrect_exited_server() { + let root = crate::plat::tmp::short_dir("ipc-gen"); + let rt = root.to_string_lossy().to_string(); + let project = "/p/gen.kicad_pro".to_string(); + let dir = ks::dir(&rt, "", &project); + std::fs::create_dir_all(&dir).unwrap(); + let sock1 = format!("{dir}/s1.sock"); + let sock2 = format!("{dir}/s2.sock"); + #[cfg(unix)] + let (_l1, _l2) = (crate::plat::ipc::bind(&sock1).unwrap(), crate::plat::ipc::bind(&sock2).unwrap()); + let (ipc, mut frx, tx, alive, _pids) = mock_actor(rt); + alive.lock().unwrap().insert(project.clone(), true); + let env = Env { cli: "/k/kicad-cli".into(), version: "10.99.0-bp.13".into(), ..Default::default() }; + + let (atx, _arx) = oneshot::channel(); + tx.send(Msg::Ask { project: project.clone(), env, ty: "kiapi.common.commands.Ping".into(), msg: json!({}), deadline: std::time::Instant::now() + ASK_TIMEOUT, reply: atx }).unwrap(); + let spawn1 = frx.recv().await.unwrap(); + let g1 = spawn1["gen"].as_u64().unwrap(); + tx.send(Msg::Line(1, json!({"event":"line","key":project,"gen":g1,"text":format!("KiCad API server listening at ipc://{sock1}")}))).unwrap(); + // Process crashes once -> enters "starting" retry state (awaiting Go). + tx.send(Msg::Line(1, json!({"event":"exit","key":project,"gen":g1,"code":1,"tail":"boom"}))).unwrap(); + // Trigger retry -> launches gen 2 and gen 2 is now in "starting" WITH a non-empty socket. + tx.send(Msg::Go { project: project.clone(), launch_gen: g1 }).unwrap(); + let spawn2 = loop { + let msg = frx.recv().await.unwrap(); + if msg["op"] == "spawn" { break msg } + }; + let g2 = spawn2["gen"].as_u64().unwrap(); + assert_ne!(g2, g1); + tx.send(Msg::Line(1, json!({"event":"line","key":project,"gen":g2,"text":format!("KiCad API server listening at ipc://{sock2}")}))).unwrap(); + // Late Up for generation g1 arrives while gen 2 is "starting" with sock2 populated: must be ignored. + tx.send(Msg::Up { project: project.clone(), version: "10.99.0-bp.13".into(), launch_gen: g1 }).unwrap(); + let info = info_on(&ipc).await; + assert!(!info.contains("|ready|"), "stale Up must not mark replacement generation ready: {info}"); + // Genuine Up for gen 2 marks it ready. + tx.send(Msg::Up { project: project.clone(), version: "10.99.0-bp.13".into(), launch_gen: g2 }).unwrap(); + let info2 = info_on(&ipc).await; + assert!(info2.contains("|ready|"), "current generation Up must mark server ready: {info2}"); + } + + #[tokio::test] + async fn dial_refused_recovers_by_starting_fresh_server() { + let root = crate::plat::tmp::short_dir("ipc-retry"); + let rt = root.to_string_lossy().to_string(); + let project = "/p/retry.kicad_pro".to_string(); + let dir = ks::dir(&rt, "", &project); + std::fs::create_dir_all(&dir).unwrap(); + let sock1 = format!("{dir}/s1.sock"); + let sock2 = format!("{dir}/s2.sock"); + #[cfg(unix)] + let (_l1, _l2) = (crate::plat::ipc::bind(&sock1).unwrap(), crate::plat::ipc::bind(&sock2).unwrap()); + let (ipc, mut frx, tx, alive, _pids) = mock_actor(rt); + alive.lock().unwrap().insert(project.clone(), true); + let env = Env { cli: "/k/kicad-cli".into(), version: "10.99.0-bp.13".into(), ..Default::default() }; + + // Start initial ready server (gen 1). + let (atx0, arx0) = oneshot::channel(); + tx.send(Msg::Ask { project: project.clone(), env: env.clone(), ty: "kiapi.common.commands.Ping".into(), msg: json!({}), deadline: std::time::Instant::now() + ASK_TIMEOUT, reply: atx0 }).unwrap(); + let sp1 = frx.recv().await.unwrap(); + let g1 = sp1["gen"].as_u64().unwrap(); + tx.send(Msg::Line(1, json!({"event":"line","key":project,"gen":g1,"text":format!("KiCad API server listening at ipc://{sock1}")}))).unwrap(); + for _ in 0..2 { + let req = frx.recv().await.unwrap(); + let msg = if req["type"].as_str().unwrap().ends_with("GetVersion") { json!({"version":{"full_version":"10.99.0-bp.13"}}) } else { json!({}) }; + tx.send(Msg::Line(1, json!({"id":req["id"],"ok":true,"type":"r","message":msg}))).unwrap(); + } + let u0 = frx.recv().await.unwrap(); + tx.send(Msg::Line(1, json!({"id":u0["id"],"ok":true,"type":"PingResponse","message":{}}))).unwrap(); + assert_eq!(arx0.await.unwrap().reply["ok"], json!(true)); + + // Drive mock responses: + // (1) dial refused while process is alive -> unresponsive (dead_invalidated = false, no duplicate spawn) + // (2) dial refused after process exits -> stopped & dead_invalidated = true -> retry launches gen 2 and succeeds. + let proj_drive = project.clone(); + let alive_drive = alive.clone(); + let s1_clone = sock1.clone(); + let s2_clone = sock2.clone(); + let drive = tokio::spawn(async move { + // (1) Alive process: dial refused marks unresponsive, next ask reuses gen 1 (not spawn). + let u1 = frx.recv().await.unwrap(); + assert_eq!(u1["type"], "kiapi.common.commands.Ping"); + tx.send(Msg::Line(1, json!({"id":u1["id"],"ok":false,"error":format!("dial ipc://{s1_clone}: Connection refused")}))).unwrap(); + + // (2) Next ask hits existing socket without spawning; now simulate dead process before sending dial refused. + let u2 = loop { + let msg = frx.recv().await.unwrap(); + if msg["op"] == "close" { continue } + assert_ne!(msg["op"], "spawn", "alive unresponsive server must never spawn a duplicate KiCad"); + break msg + }; + assert_eq!(u2["type"], "kiapi.common.commands.Ping"); + alive_drive.lock().unwrap().insert(proj_drive.clone(), false); + tx.send(Msg::Line(1, json!({"id":u2["id"],"ok":false,"error":format!("dial ipc://{s1_clone}: Connection refused")}))).unwrap(); + + let sp2 = loop { + let msg = frx.recv().await.unwrap(); + if msg["op"] == "spawn" { break msg } + }; + let g2 = sp2["gen"].as_u64().unwrap(); + assert_ne!(g2, g1); + tx.send(Msg::Line(1, json!({"event":"line","key":proj_drive,"gen":g2,"text":format!("KiCad API server listening at ipc://{s2_clone}")}))).unwrap(); + for _ in 0..2 { + let req = frx.recv().await.unwrap(); + let msg = if req["type"].as_str().unwrap().ends_with("GetVersion") { json!({"version":{"full_version":"10.99.0-bp.13"}}) } else { json!({}) }; + tx.send(Msg::Line(1, json!({"id":req["id"],"ok":true,"type":"r","message":msg}))).unwrap(); + } + let u3 = frx.recv().await.unwrap(); + tx.send(Msg::Line(1, json!({"id":u3["id"],"ok":true,"type":"PingResponse","message":{}}))).unwrap(); + }); + + let o_alive = ask_detailed(&ipc, &project, &env, "kiapi.common.commands.Ping", json!({})).await; + assert!(!o_alive.dead_invalidated && is_dial_refused(&o_alive.reply)); + assert!(info_on(&ipc).await.contains("|unresponsive|")); + + let mut outcome = ask_detailed(&ipc, &project, &env, "kiapi.common.commands.Ping", json!({})).await; + assert!(outcome.dead_invalidated && is_dial_refused(&outcome.reply)); + alive.lock().unwrap().insert(project.clone(), true); + if outcome.dead_invalidated && is_dial_refused(&outcome.reply) { + outcome = ask_detailed(&ipc, &project, &env, "kiapi.common.commands.Ping", json!({})).await; + } + assert_eq!(outcome.reply["ok"], json!(true), "retry after dead server invalidated must succeed: {}", outcome.reply); + drive.await.unwrap(); + } + + #[cfg(unix)] + #[tokio::test] + async fn begin_commit_timeout_while_reads_work_and_when_server_hangs() { + use super::super::nng::tests as stand_in; + use crate::plat::fs::PermissionsExt; + + let version: Vec = { + let h = "0a040a02746b120208011a5c0a3c747970652e676f6f676c65617069732e636f6d2f6b696170692e636f6d6d6f6e2e636f6d6d616e64732e47657456657273696f6e526573706f6e7365121c0a1a080a1063221431302e39392e302d756e6b6e6f776e2d62702e34"; + (0..h.len() / 2).map(|i| u8::from_str_radix(&h[2 * i..2 * i + 2], 16).unwrap()).collect() + }; + let ping_ok: Vec = { + // ApiResponse { header: { kicad_token: "tk" }, status: { status: AS_OK (1) } } + let h = "0a040a02746b12020801"; + (0..h.len() / 2).map(|i| u8::from_str_radix(&h[2 * i..2 * i + 2], 16).unwrap()).collect() + }; + + let root = crate::plat::tmp::short_dir("ipc-bctmo"); + let rt = root.to_string_lossy().to_string(); + let desc_src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .ancestors() + .find(|d| d.join("test/fixtures/kipc/api.desc").is_file()) + .unwrap() + .join("test/fixtures/kipc/api.desc"); + let env_root = root.join("rt"); + std::fs::create_dir_all(env_root.join("share/backplane")).unwrap(); + std::fs::copy(&desc_src, env_root.join("share/backplane/api.desc")).unwrap(); + + let project = "/p/bctmo.kicad_pro".to_string(); + let dir = ks::dir(&rt, "", &project); + std::fs::create_dir_all(&dir).unwrap(); + let sock = format!("{dir}/api.sock"); + let l = crate::plat::ipc::bind(&sock).unwrap(); + let cli = format!("{rt}/kicad-cli"); + std::fs::write(&cli, "#!/bin/sh\necho \"KiCad API server listening at ipc://$4\"\nsleep 15\n").unwrap(); + std::fs::set_permissions(&cli, std::fs::Permissions::from_mode(0o755)).unwrap(); + + let ver_b = version.clone(); + let ping_b = ping_ok.clone(); + let srv = tokio::spawn(async move { + // Conn 1: Ping + GetVersion (handshake), then BeginCommit (silently dropped -> timeout!) + let (mut s1, _) = stand_in::accept(&l).await; + for _ in 0..2 { + let (id, _) = stand_in::read_req(&mut s1).await.unwrap(); + stand_in::write_rep(&mut s1, id, &ver_b).await; + } + let (_id_bc, req_bc) = stand_in::read_req(&mut s1).await.unwrap(); + assert!(String::from_utf8_lossy(&req_bc).contains("BeginCommit")); + // Do NOT reply on s1 -> triggers timeout_override_ms (250 ms) and drops s1. + + // Case (a): Conn 2 (after timeout dropped s1): follow-up Ping SUCCEEDS (reads work while BeginCommit timed out). + let (mut s2, _) = stand_in::accept(&l).await; + let (id_p2, req_p2) = stand_in::read_req(&mut s2).await.unwrap(); + assert!(String::from_utf8_lossy(&req_p2).contains("Ping")); + stand_in::write_rep(&mut s2, id_p2, &ping_b).await; + + // Case (b): Another BeginCommit times out on s2... + let (_id_bc2, req_bc2) = stand_in::read_req(&mut s2).await.unwrap(); + assert!(String::from_utf8_lossy(&req_bc2).contains("BeginCommit")); + // ...and on Conn 3, follow-up Ping ALSO hangs (server wedged)! + let (mut s3, _) = stand_in::accept(&l).await; + let (_id_p3, _) = stand_in::read_req(&mut s3).await.unwrap(); + tokio::time::sleep(Duration::from_secs(6)).await; + drop((s1, s2, s3)); + }); + + let (tx, mut rx) = mpsc::unbounded_channel(); + let lines = Arc::new(std::sync::Mutex::new(String::new())); + let mut a = Actor { + me: tx.clone(), home: String::new(), rt, hub_pid: std::process::id(), + helper: None, gen: 0, pend: HashMap::new(), next: 0, + srvs: vec![], srv_gen: HashMap::new(), wait: vec![], shown: String::new(), + env: Env::default(), lines: lines.clone(), timeout_override_ms: Some(250), + }; + tokio::spawn(async move { while let Some(m) = rx.recv().await { a.handle(m) } }); + let ipc = Ipc { tx, lines }; + let env = Env { + cli, + root: env_root.to_string_lossy().into(), + caps: vec!["api-descriptor".into()], + version: "10.99.0-bp.4".into(), + ..Default::default() + }; + + // Case (a): BeginCommit times out in ~250ms, Ping succeeds -> actionable error saying reads/Ping still work, server stays ready. + let o1 = ask_detailed(&ipc, &project, &env, "kiapi.common.commands.BeginCommit", json!({})).await; + assert!(is_timeout_error(&o1.reply), "expected timeout error, got: {}", o1.reply); + let msg1 = explain_begin_commit_timeout_headless(&ipc, &project, &env, &o1.reply, &o1.sock, o1.launch_gen).await; + assert!(msg1.contains("still answers reads/Ping") && msg1.contains("CMA_DROP"), "unexpected msg1: {msg1}"); + assert!(info_on(&ipc).await.contains("|ready|"), "server should still be ready when Ping succeeded"); + + // Case (b): BeginCommit times out, follow-up Ping fails while process is still alive -> marked unresponsive (no duplicate server spawn). + let o2 = ask_detailed(&ipc, &project, &env, "kiapi.common.commands.BeginCommit", json!({})).await; + assert!(is_timeout_error(&o2.reply), "expected timeout error, got: {}", o2.reply); + let msg2 = explain_begin_commit_timeout_headless(&ipc, &project, &env, &o2.reply, &o2.sock, o2.launch_gen).await; + assert!(msg2.contains("follow-up Ping failed") && msg2.contains("unresponsive"), "unexpected msg2: {msg2}"); + let info_after = info_on(&ipc).await; + assert!(info_after.contains("|unresponsive|") && !info_after.contains("|ready|"), "server must be marked unresponsive while process lives: {info_after}"); + srv.abort(); + } + + #[tokio::test] + async fn expired_or_dropped_waiting_begin_commit_is_never_dispatched() { + let root = crate::plat::tmp::short_dir("ipc-wait-exp"); + let rt = root.to_string_lossy().to_string(); + let project = "/p/waitexp.kicad_pro".to_string(); + let dir = ks::dir(&rt, "", &project); + std::fs::create_dir_all(&dir).unwrap(); + let sock = format!("{dir}/api.sock"); + let (ipc, mut frx, tx, alive, _pids) = mock_actor(rt); + alive.lock().unwrap().insert(project.clone(), true); + let env = Env { cli: "/k/kicad-cli".into(), version: "10.99.0-bp.13".into(), ..Default::default() }; + + // Request 1: short deadline that expires while waiting in "starting". + let (t1, r1) = oneshot::channel(); + tx.send(Msg::Ask { + project: project.clone(), + env: env.clone(), + ty: "kiapi.common.commands.BeginCommit".into(), + msg: json!({}), + deadline: std::time::Instant::now() + Duration::from_millis(40), + reply: t1, + }).unwrap(); + // Request 2: receiver dropped before server becomes ready. + let (t2, r2) = oneshot::channel(); + tx.send(Msg::Ask { + project: project.clone(), + env, + ty: "kiapi.common.commands.BeginCommit".into(), + msg: json!({}), + deadline: std::time::Instant::now() + ASK_TIMEOUT, + reply: t2, + }).unwrap(); + drop(r2); + + let sp = frx.recv().await.unwrap(); + let launch_gen = sp["gen"].as_u64().unwrap(); + tokio::time::sleep(Duration::from_millis(70)).await; + tx.send(Msg::Line(1, json!({"event":"line","key":project,"gen":launch_gen,"text":format!("KiCad API server listening at ipc://{sock}")}))).unwrap(); + tx.send(Msg::Up { project: project.clone(), version: "10.99.0-bp.13".into(), launch_gen }).unwrap(); + + let o1 = r1.await.unwrap(); + assert!(o1.reply["ok"] == json!(false) && o1.reply["error"].as_str().unwrap().contains("timed out"), "{}", o1.reply); + // Actor must still be healthy and never dispatch BeginCommit for either expired/dropped request. + assert!(info_on(&ipc).await.contains("|ready|")); + while let Ok(Some(msg)) = tokio::time::timeout(Duration::from_millis(100), frx.recv()).await { + assert_ne!(msg.get("type").and_then(Value::as_str), Some("kiapi.common.commands.BeginCommit"), "expired/dropped BeginCommit must never be sent: {msg}"); + } + } + + #[tokio::test] + async fn delayed_retire_evict_and_timeout_probe_cannot_affect_replacement_generation() { + let root = crate::plat::tmp::short_dir("ipc-stale-gen"); + let rt = root.to_string_lossy().to_string(); + let proj_a = "/p/a.kicad_pro".to_string(); + let proj_b = "/p/b.kicad_pro".to_string(); + let dir_a = ks::dir(&rt, "", &proj_a); + std::fs::create_dir_all(&dir_a).unwrap(); + let sock_a1 = format!("{dir_a}/a1.sock"); + let sock_a2 = format!("{dir_a}/a2.sock"); + #[cfg(unix)] + let mut _l_a2 = Some(crate::plat::ipc::bind(&sock_a2).unwrap()); + + let (ipc, mut frx, tx, alive, _pids) = mock_actor(rt); + alive.lock().unwrap().insert(proj_a.clone(), true); + let env = Env { cli: "/k/kicad-cli".into(), version: "10.99.0-bp.13".into(), ..Default::default() }; + + // Start proj_a on gen 1 -> crash -> launch gen 2 on sock_a2 and bring it ready. + let (t1, _r1) = oneshot::channel(); + tx.send(Msg::Ask { project: proj_a.clone(), env: env.clone(), ty: "kiapi.common.commands.Ping".into(), msg: json!({}), deadline: std::time::Instant::now() + ASK_TIMEOUT, reply: t1 }).unwrap(); + let sp1 = frx.recv().await.unwrap(); + let g1 = sp1["gen"].as_u64().unwrap(); + tx.send(Msg::Line(1, json!({"event":"line","key":proj_a,"gen":g1,"text":format!("KiCad API server listening at ipc://{sock_a1}")}))).unwrap(); + tx.send(Msg::Line(1, json!({"event":"exit","key":proj_a,"gen":g1,"code":1,"tail":"crash"}))).unwrap(); + tx.send(Msg::Go { project: proj_a.clone(), launch_gen: g1 }).unwrap(); + let sp2 = loop { + let msg = frx.recv().await.unwrap(); + if msg["op"] == "spawn" { break msg } + }; + let g2 = sp2["gen"].as_u64().unwrap(); + assert_ne!(g2, g1); + tx.send(Msg::Line(1, json!({"event":"line","key":proj_a,"gen":g2,"text":format!("KiCad API server listening at ipc://{sock_a2}")}))).unwrap(); + tx.send(Msg::Up { project: proj_a.clone(), version: "10.99.0-bp.13".into(), launch_gen: g2 }).unwrap(); + assert!(info_on(&ipc).await.contains("|ready|")); + + // Stale Retired from gen g1 must not stop/unlink replacement gen g2. + let (rtx, rrx) = oneshot::channel(); + tx.send(Msg::Retired { project: proj_a.clone(), launch_gen: g1, ok: true, why: String::new(), reply: rtx }).unwrap(); + let r_ans = rrx.await.unwrap(); + assert_eq!(r_ans["ok"], json!(false)); + + // Stale Evicted naming victim proj_a @ g1 must not stop/unlink replacement gen g2. + tx.send(Msg::Evicted { victim: proj_a.clone(), victim_gen: g1, project: proj_b, project_gen: 999, ok: true, why: String::new() }).unwrap(); + + // Drain any handshake Ping/GetVersion left from mock spawn, then confirm timeout probe for g1 sends NO Ping. + while tokio::time::timeout(Duration::from_millis(50), frx.recv()).await.ok().flatten().is_some() {} + let explain = explain_begin_commit_timeout_headless(&ipc, &proj_a, &env, &failed("KiCad did not answer in 15 s"), &sock_a1, g1).await; + assert!(explain.contains("replaced"), "unexpected explain: {explain}"); + assert!(tokio::time::timeout(Duration::from_millis(50), frx.recv()).await.is_err(), "stale probe must not touch replacement socket"); + + // Even when gen 3 reuses the exact same socket path as gen 2, a fenced Raw request for g2 must be rejected without reaching transport. + #[cfg(unix)] + { _l_a2 = None; } + tx.send(Msg::Line(1, json!({"event":"exit","key":proj_a,"gen":g2,"code":1,"tail":"crash2"}))).unwrap(); + tx.send(Msg::Go { project: proj_a.clone(), launch_gen: g2 }).unwrap(); + let sp3 = loop { + let msg = frx.recv().await.unwrap(); + if msg["op"] == "spawn" { break msg } + }; + let g3 = sp3["gen"].as_u64().unwrap(); + #[cfg(unix)] + { _l_a2 = Some(crate::plat::ipc::bind(&sock_a2).unwrap()); } + tx.send(Msg::Line(1, json!({"event":"line","key":proj_a,"gen":g3,"text":format!("KiCad API server listening at ipc://{sock_a2}")}))).unwrap(); + tx.send(Msg::Up { project: proj_a.clone(), version: "10.99.0-bp.13".into(), launch_gen: g3 }).unwrap(); + while tokio::time::timeout(Duration::from_millis(50), frx.recv()).await.ok().flatten().is_some() {} + + let (ftx, frx_raw) = oneshot::channel(); + tx.send(Msg::Raw { + sock: sock_a2.clone(), + env, + ty: "kiapi.backplane.Shutdown".into(), + msg: json!({}), + timeout_ms: None, + fence: Some((proj_a.clone(), g2)), + reply: ftx, + }).unwrap(); + let raw_ans = frx_raw.await.unwrap(); + assert_eq!(raw_ans["ok"], json!(false)); + assert!(raw_ans["error"].as_str().unwrap().contains("stale KiCad server generation"), "{raw_ans}"); + assert!(tokio::time::timeout(Duration::from_millis(50), frx.recv()).await.is_err(), "fenced Raw for stale gen must not reach transport even on reused socket path"); + + assert!(info_on(&ipc).await.contains("|ready|"), "replacement generation must remain ready"); + #[cfg(unix)] + assert!(std::path::Path::new(&sock_a2).exists(), "replacement socket must still exist"); + } + + #[tokio::test] + async fn startup_failure_or_retire_does_not_release_live_child_ownership() { + let root = crate::plat::tmp::short_dir("ipc-start-own"); + let rt = root.to_string_lossy().to_string(); + let project = "/p/startown.kicad_pro".to_string(); + let (ipc, mut frx, tx, alive, _pids) = mock_actor(rt); + alive.lock().unwrap().insert(project.clone(), true); + let env = Env { cli: "/k/kicad-cli".into(), version: "10.99.0-bp.13".into(), ..Default::default() }; + + let (atx, arx) = oneshot::channel(); + tx.send(Msg::Ask { + project: project.clone(), + env: env.clone(), + ty: "kiapi.common.commands.Ping".into(), + msg: json!({}), + deadline: std::time::Instant::now() + ASK_TIMEOUT, + reply: atx, + }).unwrap(); + let sp = frx.recv().await.unwrap(); + let g1 = sp["gen"].as_u64().unwrap(); + + // Starting process with empty socket and alive == true must refuse retire(). + let (rtx1, rrx1) = oneshot::channel(); + tx.send(Msg::Retire { project: project.clone(), reply: rtx1 }).unwrap(); + let r1 = rrx1.await.unwrap(); + assert_eq!(r1["ok"], json!(false), "retire while starting child is alive must fail: {r1}"); + + // Handshake fails via Msg::Bad -> state = failed; while process stays alive, both retire and Clear refuse to release ownership. + tx.send(Msg::Bad { project: project.clone(), why: "handshake failed".into(), launch_gen: g1 }).unwrap(); + let _ = arx.await.unwrap(); + assert!(info_on(&ipc).await.contains("|failed|")); + + let (rtx2, rrx2) = oneshot::channel(); + tx.send(Msg::Retire { project: project.clone(), reply: rtx2 }).unwrap(); + let r2 = rrx2.await.unwrap(); + assert_eq!(r2["ok"], json!(false), "retire while failed child is alive must fail: {r2}"); + + tx.send(Msg::Clear).unwrap(); + assert!(info_on(&ipc).await.contains("|failed|"), "Clear must not reset failed state while child is still alive"); + + // Once the child actually exits, Clear succeeds and next request can spawn a fresh server. + alive.lock().unwrap().insert(project.clone(), false); + tx.send(Msg::Clear).unwrap(); + assert!(info_on(&ipc).await.contains("|stopped|")); + } } /// Whether `path`'s project is open in a co-editing KiCad (bp.11 `coedit`): agents write its live documents through IPC at once, diff --git a/native/host/src/kicad/kipc.rs b/native/host/src/kicad/kipc.rs index edc88288fd..22554242cc 100644 --- a/native/host/src/kicad/kipc.rs +++ b/native/host/src/kicad/kipc.rs @@ -11,7 +11,7 @@ use super::{nng, proto::{self, Reply, Schema}}; use serde_json::{json, Value}; use std::{collections::{HashMap, VecDeque}, path::Path, process::Stdio, sync::{atomic::{AtomicBool, Ordering}, Arc, Mutex}, time::Duration}; -use tokio::{io::{AsyncBufReadExt, AsyncRead, BufReader}, process::Command, sync::{mpsc, oneshot}}; +use tokio::{io::{AsyncBufReadExt, AsyncRead, BufReader}, sync::{mpsc, oneshot}}; /// Where answers and events go, as the objects the helper would have written. pub type Sink = Arc; @@ -19,17 +19,52 @@ pub type Sink = Arc; pub const CONN_CLOSED: &str = "KiCad IPC connection closed; request outcome unknown"; const READY: &str = "KiCad API server listening at "; const TIMEOUT_MS: u64 = 30000; +/// How long after child exit we keep draining stdout/stderr before emitting `exit` anyway (so a pipe-holding grandchild never stalls readiness invalidation). +pub const PIPE_DRAIN_GRACE: Duration = Duration::from_millis(1500); fn fail(id: Value, error: &str, status: Option<&str>) -> Value { match status { Some(s) => json!({"id":id,"ok":false,"status":s,"error":error}), None => json!({"id":id,"ok":false,"error":error}) } } -struct Job { id: Value, schema: Arc, ty: String, message: Value, timeout: u64, client: String } +struct Job { id: Value, schema: Arc, ty: String, message: Value, timeout: u64, deadline: tokio::time::Instant, client: String } struct Slot { jobs: mpsc::UnboundedSender, shut: oneshot::Sender<()> } +#[derive(Clone, Copy, Debug)] +struct SpawnState { seq: u64, pid: u32, exited: bool } /// One hub's transport. `handle` never blocks: the work runs on tasks and answers through the sink. Call it on the runtime. -pub struct Native { socks: HashMap, desc: String, client: String, sink: Sink } +pub struct Native { + socks: HashMap, + runs: Arc>>, + next_seq: u64, + pipe_drain_grace: Duration, + desc: String, + client: String, + sink: Sink, +} impl Native { /// `desc`: the descriptor set for requests that name none (the helper's --desc). - pub fn new(desc: &str, sink: Sink) -> Native { Native { socks: HashMap::new(), desc: desc.into(), client: format!("backplane-{}", std::process::id()), sink } } + pub fn new(desc: &str, sink: Sink) -> Native { + Native { + socks: HashMap::new(), + runs: Arc::new(Mutex::new(HashMap::new())), + next_seq: 0, + pipe_drain_grace: PIPE_DRAIN_GRACE, + desc: desc.into(), + client: format!("backplane-{}", std::process::id()), + sink, + } + } + #[cfg(test)] + pub fn set_pipe_drain_grace(&mut self, grace: Duration) { self.pipe_drain_grace = grace; } + /// Active PID of the latest spawned server for `key`, or 0 if unspawned or already exited. + pub fn pid_of(&self, key: &str) -> u32 { + self.runs.lock().unwrap().get(key).filter(|st| !st.exited).map_or(0, |st| st.pid) + } + /// Whether the latest spawned server for `key` is alive (`None` if unknown or still spawning). + pub fn process_alive(&self, key: &str) -> Option { + let st = *self.runs.lock().unwrap().get(key)?; + if st.exited { return Some(false) } + if st.pid == 0 { return None } + Some(crate::plat::proc::alive(st.pid)) + } pub fn handle(&mut self, r: Value) { let id = r.get("id").cloned().unwrap_or(Value::Null); @@ -45,13 +80,18 @@ impl Native { let schema = proto::load(r.get("desc").and_then(Value::as_str).unwrap_or(&self.desc)); if !schema.knows(&ty) { return (self.sink)(fail(id, proto::NO_SCHEMA, None)) } // `client`: the request's actor (the fork's co-editing names undo groups and changes by it); default the hub's own name - let job = Job { id, schema, ty, timeout: r["timeout"].as_u64().unwrap_or(TIMEOUT_MS), message: r.get("message").cloned().unwrap_or(Value::Null), client: r["client"].as_str().unwrap_or("").to_string() }; + let timeout = r["timeout"].as_u64().unwrap_or(TIMEOUT_MS); + let deadline = tokio::time::Instant::now() + Duration::from_millis(timeout); + let job = Job { id, schema, ty, timeout, deadline, message: r.get("message").cloned().unwrap_or(Value::Null), client: r["client"].as_str().unwrap_or("").to_string() }; let slot = self.socks.entry(sock.clone()).or_insert_with(|| { let (jobs, rx) = mpsc::unbounded_channel(); let (shut, down) = oneshot::channel(); - tokio::spawn(worker(sock, rx, down, self.client.clone(), self.sink.clone())); + tokio::spawn(worker(sock.clone(), rx, down, self.client.clone(), self.sink.clone())); Slot { jobs, shut } }); - if let Err(e) = slot.jobs.send(job) { (self.sink)(fail(e.0.id, CONN_CLOSED, None)) } + if let Err(e) = slot.jobs.send(job) { + self.socks.remove(&sock); + (self.sink)(fail(e.0.id, CONN_CLOSED, None)) + } } fn spawn(&mut self, id: Value, r: &Value) { @@ -67,7 +107,11 @@ impl Native { }, Some(_) => return (self.sink)(fail(id, "invalid KiCad environment", None)), } - start_server(key, argv, r["memory"].as_str().map(String::from), env, self.sink.clone()); + let launch_gen = r.get("gen").and_then(Value::as_u64); + self.next_seq += 1; + let seq = self.next_seq; + self.runs.lock().unwrap().insert(key.clone(), SpawnState { seq, pid: 0, exited: false }); + start_server(key, seq, launch_gen, argv, r["memory"].as_str().map(String::from), env, self.runs.clone(), self.pipe_drain_grace, self.sink.clone()); (self.sink)(json!({"id":id,"ok":true})) } } @@ -78,6 +122,10 @@ async fn worker(sock: String, mut rx: mpsc::UnboundedReceiver, mut down: on let (mut conn, mut token) = (None, String::new()); loop { let job = tokio::select! { biased; _ = &mut down => break, j = rx.recv() => match j { Some(j) => j, None => break } }; + if tokio::time::Instant::now() >= job.deadline { + sink(fail(job.id, &format!("KiCad did not answer in {} s", job.timeout as f64 / 1000.0), None)); + continue + } let id = job.id.clone(); tokio::select! { biased; @@ -90,23 +138,30 @@ async fn worker(sock: String, mut rx: mpsc::UnboundedReceiver, mut down: on } /// One request. The codec runs off the runtime's threads: a big board's reply takes a while, and a panic there must answer this request, not lose it. async fn one(sock: &str, job: Job, conn: &mut Option, token: &mut String, client: &str) -> Value { - let Job { id, schema, ty, message, timeout, client: actor } = job; + let Job { id, schema, ty, message, timeout, deadline, client: actor } = job; let (s, t, tok, cl) = (schema.clone(), ty.clone(), token.clone(), if actor.is_empty() { client.to_string() } else { actor }); - let bytes = match tokio::task::spawn_blocking(move || proto::encode_request(&s, &t, &message, &tok, &cl)).await.unwrap_or_else(|e| Err(e.to_string())) { - Ok(b) => b, - Err(e) => return fail(id, &format!("bad message for {ty}: {e}"), Some("AS_BAD_REQUEST")), + let bytes = match tokio::time::timeout_at(deadline, tokio::task::spawn_blocking(move || proto::encode_request(&s, &t, &message, &tok, &cl))).await { + Ok(Ok(Ok(b))) => b, + Ok(Ok(Err(e))) => return fail(id, &format!("bad message for {ty}: {e}"), Some("AS_BAD_REQUEST")), + Ok(Err(e)) => return fail(id, &format!("bad message for {ty}: {e}"), Some("AS_BAD_REQUEST")), + Err(_) => return fail(id, &format!("KiCad did not answer in {} s", timeout as f64 / 1000.0), None), }; - let reply = match tokio::time::timeout(Duration::from_millis(timeout), exchange(sock, conn, &bytes)).await { + if tokio::time::Instant::now() >= deadline { + return fail(id, &format!("KiCad did not answer in {} s", timeout as f64 / 1000.0), None) + } + let reply = match tokio::time::timeout_at(deadline, exchange(sock, conn, &bytes)).await { Ok(Ok(b)) => b, Ok(Err(e)) => { *conn = None; return fail(id, &e, None) } Err(_) => { *conn = None; return fail(id, &format!("KiCad did not answer in {} s", timeout as f64 / 1000.0), None) } }; - match tokio::task::spawn_blocking(move || proto::decode_response(&schema, &reply)).await.unwrap_or_else(|e| Err(e.to_string())) { - Ok(rep) => { + match tokio::time::timeout_at(deadline, tokio::task::spawn_blocking(move || proto::decode_response(&schema, &reply))).await { + Ok(Ok(Ok(rep))) => { if !rep.token().is_empty() { *token = rep.token().to_string() } match rep { Reply::Ok { ty, message, .. } => json!({"id":id,"ok":true,"type":ty,"message":message}), Reply::Err { status, error, .. } => fail(id, &error, Some(&status)) } } - Err(e) => fail(id, &format!("bad reply: {e}"), None), + Ok(Ok(Err(e))) => fail(id, &format!("bad reply: {e}"), None), + Ok(Err(e)) => fail(id, &format!("bad reply: {e}"), None), + Err(_) => fail(id, &format!("KiCad did not answer in {} s", timeout as f64 / 1000.0), None), } } async fn exchange(sock: &str, conn: &mut Option, bytes: &[u8]) -> Result, String> { @@ -155,15 +210,21 @@ pub(super) fn sockets_at(requested: &str) -> HashMap { } fn socket_arg(argv: &[String]) -> String { argv.iter().position(|a| a == "--socket").and_then(|i| argv.get(i + 1)).cloned().unwrap_or_default() } -struct Run { key: String, said: AtomicBool, done: AtomicBool, tail: Mutex>, sink: Sink } +struct Run { key: String, launch_gen: Option, said: AtomicBool, exited: AtomicBool, done: AtomicBool, tail: Mutex>, sink: Sink } impl Run { fn keep(&self, l: &str) { let mut t = self.tail.lock().unwrap(); t.push_back(l.to_string()); if t.len() > 12 { t.pop_front(); } } - fn line(&self, text: String) { (self.sink)(json!({"event":"line","key":self.key,"text":text})) } + fn line(&self, text: String) { + let mut o = json!({"event":"line","key":self.key,"text":text}); + if let Some(g) = self.launch_gen { o["gen"] = json!(g); } + (self.sink)(o) + } fn end(&self, code: i32, extra: Option) { if self.done.swap(true, Ordering::SeqCst) { return } let t: Vec = extra.into_iter().chain(self.tail.lock().unwrap().iter().cloned()).collect(); let t = t.join("\n"); let n = t.chars().count(); - (self.sink)(json!({"event":"exit","key":self.key,"code":code,"tail":t.chars().skip(n.saturating_sub(400)).collect::()})) + let mut o = json!({"event":"exit","key":self.key,"code":code,"tail":t.chars().skip(n.saturating_sub(400)).collect::()}); + if let Some(g) = self.launch_gen { o["gen"] = json!(g); } + (self.sink)(o) } fn out_line(&self, l: String) { // the ready line counts once, whoever saw it first self.keep(&l); @@ -181,12 +242,22 @@ async fn lines(r: R, mut each: impl FnMut(String)) { each(String::from_utf8_lossy(&v).into_owned()); } } -fn start_server(key: String, argv0: Vec, memory: Option, env: Vec<(String, String)>, sink: Sink) { +fn start_server( + key: String, + seq: u64, + launch_gen: Option, + argv0: Vec, + memory: Option, + env: Vec<(String, String)>, + runs: Arc>>, + pipe_drain_grace: Duration, + sink: Sink, +) { let at = socket_arg(&argv0); let before = sockets_at(&at); let argv = wrap(argv0, memory.as_deref()); let mut c = crate::proc::tokio_cmd(crate::proc::Kind::Local, &argv[0]); c.args(&argv[1..]).envs(env).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).current_dir("/").kill_on_drop(false); - let run = Arc::new(Run { key, said: AtomicBool::new(false), done: AtomicBool::new(false), tail: Mutex::new(VecDeque::new()), sink }); + let run = Arc::new(Run { key, launch_gen, said: AtomicBool::new(false), exited: AtomicBool::new(false), done: AtomicBool::new(false), tail: Mutex::new(VecDeque::new()), sink }); tokio::spawn(async move { // "Text file busy": a program written a moment ago is still open for writing in a child another thread just forked (the child holds the descriptor until its own exec); // it passes in a few milliseconds, as for the accounts' CLI (accounts_io) @@ -195,27 +266,40 @@ fn start_server(key: String, argv0: Vec, memory: Option, env: Ve match c.spawn() { Ok(c) => break c, Err(e) if e.raw_os_error() == Some(crate::plat::errno::ETXTBSY) && tries < 40 => { tries += 1; tokio::time::sleep(Duration::from_millis(25)).await } - Err(e) => return run.end(127, Some(e.to_string())), + Err(e) => { + run.exited.store(true, Ordering::SeqCst); + if let Some(st) = runs.lock().unwrap().get_mut(&run.key).filter(|st| st.seq == seq) { st.exited = true; } + return run.end(127, Some(e.to_string())); + } } }; + let pid = child.id().unwrap_or(0); + if let Some(st) = runs.lock().unwrap().get_mut(&run.key).filter(|st| st.seq == seq) { st.pid = pid; } let (out, err) = (child.stdout.take(), child.stderr.take()); if !at.is_empty() { // KiCad buffers stdout on a pipe: report its freshly bound socket; the hub still requires Ping and a matching GetVersion let run = run.clone(); tokio::spawn(async move { - while !run.done.load(Ordering::SeqCst) && !run.said.load(Ordering::SeqCst) { + while !run.done.load(Ordering::SeqCst) && !run.exited.load(Ordering::SeqCst) && !run.said.load(Ordering::SeqCst) { tokio::time::sleep(Duration::from_millis(100)).await; + if run.exited.load(Ordering::SeqCst) { return } if let Some((path, _)) = sockets_at(&at).into_iter().find(|(p, i)| before.get(p) != Some(i)) { - if !run.done.load(Ordering::SeqCst) && !run.said.swap(true, Ordering::SeqCst) { run.line(format!("{READY}{path}")) } + if !run.done.load(Ordering::SeqCst) && !run.exited.load(Ordering::SeqCst) && !run.said.swap(true, Ordering::SeqCst) { run.line(format!("{READY}{path}")) } return } } }); } let (a, b) = (run.clone(), run.clone()); - let so = tokio::spawn(async move { if let Some(o) = out { lines(o, |l| a.out_line(l)).await } }); - let se = tokio::spawn(async move { if let Some(e) = err { lines(e, |l| b.keep(&l)).await } }); + let mut so = tokio::spawn(async move { if let Some(o) = out { lines(o, |l| a.out_line(l)).await } }); + let mut se = tokio::spawn(async move { if let Some(e) = err { lines(e, |l| b.keep(&l)).await } }); let code = child.wait().await.map(|s| s.code().unwrap_or(128)).unwrap_or(1); // no code: a signal ended it, and not one of ours - let _ = so.await; let _ = se.await; + run.exited.store(true, Ordering::SeqCst); + if let Some(st) = runs.lock().unwrap().get_mut(&run.key).filter(|st| st.seq == seq) { st.exited = true; } + let drain = async { let _ = (&mut so).await; let _ = (&mut se).await; }; + if tokio::time::timeout(pipe_drain_grace, drain).await.is_err() { + so.abort(); + se.abort(); + } run.end(code, None); }); } @@ -329,4 +413,67 @@ mod tests { } #[test] fn wrap_only_with_a_memory_cap() { assert_eq!(wrap(vec!["a".into()], None), vec!["a".to_string()]); } #[test] fn socket_argument() { assert_eq!(socket_arg(&["x".into(), "--socket".into(), "/s".into()]), "/s"); assert_eq!(socket_arg(&["x".into()]), ""); } + + #[cfg(unix)] + #[tokio::test] async fn exit_is_reported_even_when_a_grandchild_keeps_pipes_open() { + let d = tmp("pipe-leak"); + let pidf = format!("{d}/grand.pid"); + let f = script(&d, &format!("sleep 30 &\npid=$!\necho $pid > '{pidf}'\necho hi\nexit 0")); + let (mut n, mut r) = native(""); + n.set_pipe_drain_grace(Duration::from_millis(200)); + n.handle(json!({"id":1,"op":"spawn","key":"p","argv":[f]})); + assert_eq!(next(&mut r).await, json!({"id":1,"ok":true})); + let mut exit_ev = None; + let deadline = tokio::time::Instant::now() + Duration::from_secs(5); + while tokio::time::Instant::now() < deadline { + if let Ok(Some(o)) = tokio::time::timeout(Duration::from_secs(3), r.recv()).await { + if o["event"] == "exit" { exit_ev = Some(o); break } + } else { + break + } + } + let exit_ev = exit_ev.expect("exit event must arrive even when grandchild holds pipes open"); + assert_eq!(exit_ev["code"], json!(0)); + assert_eq!(n.process_alive("p"), Some(false)); + if let Ok(s) = std::fs::read_to_string(&pidf) { + if let Ok(gpid) = s.trim().parse::() { + crate::plat::proc::kill(gpid, crate::plat::proc::KILL); + } + } + } + + #[cfg(unix)] + #[tokio::test] async fn queued_request_past_deadline_is_not_sent_to_kicad() { + let (path, l, _d) = stand_in::sock("kipc-deadline"); + let desc = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .ancestors() + .find(|d| d.join("test/fixtures/kipc/api.desc").is_file()) + .unwrap() + .join("test/fixtures/kipc/api.desc") + .to_string_lossy() + .into_owned(); + let reqs_seen = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen_srv = reqs_seen.clone(); + let srv = tokio::spawn(async move { + let (mut s, _) = stand_in::accept(&l).await; + let (id, _) = stand_in::read_req(&mut s).await.unwrap(); + seen_srv.fetch_add(1, Ordering::SeqCst); + // Hold request 1 long enough that queued request 2 expires in the worker queue before dispatch. + tokio::time::sleep(Duration::from_millis(400)).await; + stand_in::write_rep(&mut s, id, &version_reply()).await; + if let Ok(Some(_)) = tokio::time::timeout(Duration::from_millis(300), stand_in::read_req(&mut s)).await { + seen_srv.fetch_add(1, Ordering::SeqCst); + } + }); + let (mut n, mut r) = native(""); + n.handle(json!({"id":1,"sock":path,"type":"kiapi.common.commands.Ping","timeout":2000})); + n.handle(json!({"id":2,"sock":path,"desc":desc,"type":"kiapi.common.commands.BeginCommit","message":{},"timeout":120})); + let mut got = vec![next(&mut r).await, next(&mut r).await]; + got.sort_by_key(|o| o["id"].as_i64()); + assert_eq!(got[0]["ok"], json!(true)); + assert_eq!(got[1]["ok"], json!(false)); + assert!(got[1]["error"].as_str().unwrap().contains("did not answer in 0.12 s"), "{}", got[1]); + srv.await.unwrap(); + assert_eq!(reqs_seen.load(Ordering::SeqCst), 1, "expired queued BeginCommit must never be sent to KiCad"); + } } diff --git a/native/host/src/kicad/kserve.rs b/native/host/src/kicad/kserve.rs index 2e4a9e2e31..1f121c62c1 100644 --- a/native/host/src/kicad/kserve.rs +++ b/native/host/src/kicad/kserve.rs @@ -76,7 +76,10 @@ impl Srv { pub fn new(project: &str, now: u64) -> Srv { Srv { project: project.into(), sock: String::new(), state: "starting".into(), pid: 0, started: now, last: now, fails: vec![], why: String::new(), version: String::new() } } /// A project with no record (KServe.get): stopped. pub fn none(project: &str) -> Srv { Srv::new(project, 0).set("stopped", "") } - pub fn set(mut self, state: &str, why: &str) -> Srv { self.state = state.into(); self.why = why.into(); self } // KS.set + pub fn set(mut self, state: &str, why: &str) -> Srv { + if matches!(state, "stopped" | "failed") { self.sock.clear(); self.pid = 0; } + self.state = state.into(); self.why = why.into(); self + } // KS.set /// KS.touch: asked for again at this time (a held server is released). pub fn touch(mut self, now: u64) -> Srv { self.last = now; if self.why == HELD { self.why.clear() } self } /// KS.hold: it refused Shutdown: keep it, never force it. @@ -84,12 +87,17 @@ impl Srv { /// KS.up: it answered Ping and GetVersion. pub fn up(mut self, sock: &str, version: &str, now: u64) -> Srv { self.sock = sock.into(); self.state = "ready".into(); self.last = now; self.why.clear(); self.version = version.into(); self } /// KS.starting: started again; no socket yet; the failures stay on record. - pub fn starting(mut self, now: u64) -> Srv { self.sock.clear(); self.state = "starting".into(); self.started = now; self.last = now; self.why.clear(); self } + pub fn starting(mut self, now: u64) -> Srv { self.sock.clear(); self.pid = 0; self.state = "starting".into(); self.started = now; self.last = now; self.why.clear(); self } pub fn listening(mut self, sock: &str) -> Srv { self.sock = sock.into(); self } // KS.listening /// KS.cleared: Retry: failures forgotten, left stopped so the next request starts it. - pub fn cleared(mut self) -> Srv { self.state = "stopped".into(); self.fails.clear(); self.why.clear(); self } + pub fn cleared(mut self) -> Srv { self.sock.clear(); self.pid = 0; self.state = "stopped".into(); self.fails.clear(); self.why.clear(); self } + /// The connection dropped or the spawned process ended before its exit event: clear stale socket and pid and leave it stopped so the next request starts fresh. + pub fn disconnected(mut self, why: &str) -> Srv { self.sock.clear(); self.pid = 0; self.state = "stopped".into(); self.why = why.into(); self } + /// The live process still owns the project, so keep its socket and pid, but mark IPC unresponsive until a call succeeds or it exits. + pub fn unresponsive(mut self, why: &str) -> Srv { self.state = "unresponsive".into(); self.why = why.into(); self } /// KS.exited: the process ended with this code: stopped on a clean exit, else the crash is recorded and it waits to start again ("starting") or gives up ("failed"). pub fn exited(mut self, code: i32, now: u64, tail: &str) -> Srv { + self.sock.clear(); self.pid = 0; self.fails = fails_add(code, &self.fails, now); let state = if code == 0 { "stopped" } else if retry(&self.fails, now).is_some() { "starting" } else { "failed" }; self.why = match state { "failed" => format!("stopped four times in five minutes: {tail}"), "starting" => format!("restarting after a crash: {tail}"), _ => String::new() }; @@ -99,7 +107,7 @@ impl Srv { // Room for two --------------------------------------------------------------------------------------------------------- -pub fn active(st: &str) -> bool { st == "starting" || st == "ready" } // KS.active +pub fn active(st: &str) -> bool { matches!(st, "starting" | "ready" | "unresponsive") } // KS.active pub fn count(xs: &[Srv]) -> usize { xs.iter().filter(|s| active(&s.state)).count() } // KS.count /// KS.evict: with two servers starting or ready and a third wanted: the project of the least recently used ready one ("" when none can be retired; a held one never is). pub fn evict(srvs: &[Srv]) -> String { @@ -110,10 +118,10 @@ pub fn evict(srvs: &[Srv]) -> String { } /// KS.state.of: a project's state ("" when no record); the first record wins. pub fn state_of(xs: &[Srv], project: &str) -> String { xs.iter().find(|s| s.project == project).map(|s| s.state.clone()).unwrap_or_default() } -/// KS.plan: "ready", "wait", "failed", "start", "evict:" or "busy". +/// KS.plan: "ready", "unresponsive", "wait", "failed", "start", "evict:" or "busy". pub fn plan(srvs: &[Srv], project: &str, caps: &[String]) -> String { match state_of(srvs, project).as_str() { - "ready" => "ready".into(), "starting" => "wait".into(), "failed" => "failed".into(), + "ready" => "ready".into(), "unresponsive" => "unresponsive".into(), "starting" => "wait".into(), "failed" => "failed".into(), _ => if count(srvs) < 2 { "start".into() } else { let v = evict(srvs); if has(caps, "shutdown") && !v.is_empty() { format!("evict:{v}") } else { "busy".into() } }, } } @@ -295,4 +303,22 @@ mod tests { assert_eq!(desc("/r", &s(&["api-descriptor"])), "/r/share/backplane/api.desc"); assert_eq!(desc("/r", &[]), ""); assert_eq!(caps_safe(&s(&["idle-exit", "shutdown"]), 1), s(&["shutdown"])); assert_eq!(caps_safe(&s(&["idle-exit"]), 2), s(&["idle-exit"])); } + #[test] fn exited_and_disconnected_clear_stale_socket_and_pid() { + let mut s = Srv::new("A", 1).up("/s/A/api.sock", "10.99.0-bp.13", 5); + s.pid = 4242; + let stopped = s.clone().exited(0, 20, ""); + assert_eq!((stopped.state.as_str(), stopped.sock.as_str(), stopped.pid), ("stopped", "", 0)); + let crashed = s.clone().exited(1, 20, "boom"); + assert_eq!((crashed.state.as_str(), crashed.sock.as_str(), crashed.pid), ("starting", "", 0)); + let failed = s.clone().set("failed", "bad"); + assert_eq!((failed.state.as_str(), failed.sock.as_str(), failed.pid), ("failed", "", 0)); + let stopped2 = s.clone().set("stopped", ""); + assert_eq!((stopped2.state.as_str(), stopped2.sock.as_str(), stopped2.pid), ("stopped", "", 0)); + let disc = s.clone().disconnected("connection dropped"); + assert_eq!((disc.state.as_str(), disc.sock.as_str(), disc.pid, disc.why.as_str()), ("stopped", "", 0, "connection dropped")); + let unresp = s.unresponsive("connection dropped"); + assert_eq!((unresp.state.as_str(), unresp.sock.as_str(), unresp.pid, unresp.why.as_str()), ("unresponsive", "/s/A/api.sock", 4242, "connection dropped")); + assert!(active(&unresp.state)); + assert_eq!(plan(&[unresp], "A", &[]), "unresponsive"); + } }