From 5565f18b06300218868ed61622435008941c3fa7 Mon Sep 17 00:00:00 2001 From: abdelrahman fahmy <104788132+Apdelrahman1911@users.noreply.github.com> Date: Sun, 6 Dec 2026 06:52:37 +0000 Subject: [PATCH 1/5] fix(ax/simax): prevent 80ms st.stuck spiral on live cold-launching apps and bind simax socket before .fg --- host/simax/simax.m | 40 ++++++++----- tools/launcher/core/src/ax.rs | 105 ++++++++++++++++++++++++++++++++-- 2 files changed, 127 insertions(+), 18 deletions(-) diff --git a/host/simax/simax.m b/host/simax/simax.m index 3f960d58..a0f68328 100644 --- a/host/simax/simax.m +++ b/host/simax/simax.m @@ -2411,7 +2411,7 @@ static void serve(int fd) { // this runs outside the @try below: a timeout that is no number ("timeout": []) must not raise here id tv = req[@"timeout"]; double timeout = [tv isKindOfClass:[NSNumber class]] ? [tv doubleValue] : 5.0; - if (!(timeout >= 0.1)) timeout = 0.1; + if (!(timeout >= 0.05)) timeout = 0.05; if (timeout > 600) timeout = 600; __block NSData* answer = nil; dispatch_semaphore_t sem = dispatch_semaphore_create(0); @@ -2419,8 +2419,8 @@ static void serve(int fd) { dispatch_async(dispatch_get_main_queue(), ^{ uint64_t t1 = clock_gettime_nsec_np(CLOCK_MONOTONIC); @try { - // Let the socket worker return its timeout if this write is already overdue. - if ([req[@"op"] isEqual:@"insert_bound"] && (t1 - t0) >= timeout * NSEC_PER_SEC) return; + // Drop any queued request whose caller already timed out so cold launches do not accumulate stale tree walks. + if ((t1 - t0) >= (uint64_t)(timeout * (double)NSEC_PER_SEC)) return; handle(req, ^(NSDictionary* r) { NSMutableDictionary* m = [r mutableCopy]; m[@"wait_ms"] = @((t1 - t0) / 1000000); @@ -2447,16 +2447,8 @@ static void serve(int fd) { } static void* listen_thread(void* arg) { - struct sockaddr_un a = { 0 }; - int s = socket(AF_UNIX, SOCK_STREAM, 0); - a.sun_family = AF_UNIX; - strlcpy(a.sun_path, g_path, sizeof(a.sun_path)); - unlink(g_path); - if (bind(s, (struct sockaddr*)&a, sizeof(a)) != 0 || listen(s, 4) != 0) { - alog("cannot listen on %s: errno %d", g_path, errno); - close(s); - return NULL; - } + int s = (int)(intptr_t)arg; + if (s < 0) return NULL; alog("listening on %s", g_path); for (;;) { // Darling's accept() needs an address buffer (simhid listen_thread) @@ -2506,9 +2498,29 @@ static void cleanup(void) { } static void start(void) { + struct sockaddr_un a = { 0 }; + int s = socket(AF_UNIX, SOCK_STREAM, 0); + if (s < 0) { + alog("cannot create socket for %s: errno %d", g_path, errno); + return; + } + a.sun_family = AF_UNIX; + strlcpy(a.sun_path, g_path, sizeof(a.sun_path)); + unlink(g_path); + // Bind and listen synchronously before writing .fg so host snapshots never observe a .fg marker before the socket is accepting. + if (bind(s, (struct sockaddr*)&a, sizeof(a)) != 0 || listen(s, 4) != 0) { + alog("cannot listen on %s: errno %d", g_path, errno); + close(s); + return; + } atexit(cleanup); pthread_t t; - pthread_create(&t, NULL, listen_thread, NULL); + if (pthread_create(&t, NULL, listen_thread, (void*)(intptr_t)s) != 0) { + alog("cannot spawn listen_thread for %s: errno %d", g_path, errno); + close(s); + cleanup(); + return; + } pthread_detach(t); NSNotificationCenter* nc = NSNotificationCenter.defaultCenter; for (NSString* n in @[ UIApplicationWillEnterForegroundNotification, UIApplicationDidBecomeActiveNotification ]) diff --git a/tools/launcher/core/src/ax.rs b/tools/launcher/core/src/ax.rs index 34dba152..06240bdc 100644 --- a/tools/launcher/core/src/ax.rs +++ b/tools/launcher/core/src/ax.rs @@ -523,6 +523,15 @@ enum AskReply { ClosedEmpty, } +fn guest_timeout_secs(timeout: Duration) -> f64 { + let secs = timeout.as_secs_f64(); + if secs > 0.5 { + (secs - 0.3).max(0.2) + } else { + (secs * 0.6).max(0.05) + } +} + fn ask_reply(sock: &Path, req: &Value, timeout: Duration) -> Result { let mut s = match connect_nb(sock) { Ok(s) => s, @@ -534,8 +543,8 @@ fn ask_reply(sock: &Path, req: &Value, timeout: Duration) -> Result { s.set_read_timeout(Some(timeout))?; s.set_write_timeout(Some(Duration::from_secs(1)))?; let mut r = req.clone(); - // the guest answers "busy" a little before we give up - r["timeout"] = json!((timeout.as_secs_f64() - 0.3).max(0.2)); + // the guest answers "busy" strictly before our socket read deadline expires + r["timeout"] = json!(guest_timeout_secs(timeout)); s.write_all(format!("{r}\n").as_bytes())?; let mut line = String::new(); BufReader::new(s).read_line(&mut line).context("no answer")?; @@ -1192,9 +1201,14 @@ fn snapshot_once_with_guest_states( UnresponsiveFg::LiveIncomplete => {} } // no answer at all: hung, or suspended (an extension RunningBoard suspended keeps its .fg: it draws - // nothing either). Said once (the first time), then it gets a short timeout until it answers again. + // nothing either). Keep live non-wallpaper foreground apps out of the 80 ms stuck fast-fail set so a + // slow cold-launching app can recover on the next full-timeout snapshot instead of getting trapped. mark_incomplete(&mut snap, "fg_timeout"); - st.stuck.insert(pid); + let live_fg_app = !is_wallpaper(&fg_b) + && live_guest.as_ref().is_some_and(|states| matches!(states.get(&pid), Some('R' | 'S' | 'D'))); + if !live_fg_app { + st.stuck.insert(pid); + } let who = format!("{fg_b} (pid {pid}: {})", if was_stuck.contains(&pid) { "still no answer".to_string() } else { format!("no answer in {:.1} s", timeout.as_secs_f64()) }); if std::env::var_os("X86SIM_AX_DEBUG").is_some() { @@ -3447,4 +3461,87 @@ mod tests { let _ = server.join(); let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn live_slow_foreground_app_recovers_after_timeout() { + use std::io::{BufRead, BufReader, Write}; + use std::os::unix::net::UnixListener; + + assert!(guest_timeout_secs(Duration::from_millis(80)) < 0.08); + assert!(guest_timeout_secs(Duration::from_millis(400)) < 0.4); + assert!(guest_timeout_secs(Duration::from_secs(6)) < 6.0); + + let dir = std::env::temp_dir().join(format!("x86sim-ax-slow-fg-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let inst = Instance { + id: "fixture-slowfg".into(), + dir: dir.clone(), + name: "test".into(), + model: String::new(), + model_id: String::new(), + runtime_dir: String::new(), + runtime_root: dir.clone(), + runtime_present: true, + unavailable: None, + ios: String::new(), + platform: "ios".into(), + build: String::new(), + screen: (390, 844), + scale: 3.0, + corner: 0.0, + ring: dir.join("simfb.ring"), + inner: None, + sock: dir.join("simhid.sock"), + state_dir: dir.clone(), + prefix: dir.clone(), + log_dir: dir.clone(), + is_default: false, + udid: "fixture-slowfg".into(), + created: 0, + }; + + let slow_sock = dir.join("x86sim-ax-fixture-slowfg-200.sock"); + let slow_fg = dir.join("x86sim-ax-fixture-slowfg-200.fg"); + std::fs::write(&slow_fg, "com.example.slow\n").unwrap(); + let listener = UnixListener::bind(&slow_sock).unwrap(); + let server = std::thread::spawn(move || { + for (idx, stream) in listener.incoming().take(2).enumerate() { + let mut stream = stream.unwrap(); + let mut line = String::new(); + let _ = BufReader::new(&stream).read_line(&mut line); + if idx == 0 { + // Exceeds snapshot #1 timeout (350 ms) to simulate slow cold launch. + std::thread::sleep(Duration::from_millis(550)); + continue; + } + // Exceeds old 80 ms stuck timeout, well below 350 ms snapshot #2 timeout. + std::thread::sleep(Duration::from_millis(140)); + let reply = json!({ + "pid": 200, + "bundle": "com.example.slow", + "state": "active", + "partial": false, + "screen": [390.0, 844.0, 3.0], + "windows": [{"class": "UIWindow", "frame": [0.0, 0.0, 390.0, 844.0]}], + "elements": [{"oid": "0x2", "role": "button", "label": "Ready", "enabled": true, "frame": [10.0, 20.0, 120.0, 40.0]}] + }); + let _ = stream.write_all(format!("{reply}\n").as_bytes()); + } + }); + + let opts = SnapOpts { no_ocr: true, timeout_ms: 350, ..Default::default() }; + let s1 = snapshot_once_with_guest_states(&inst, opts.clone(), Some(HashMap::from([(200, 'S')]))).unwrap(); + assert!(s1.foreground_incomplete); + assert_eq!(s1.incomplete_reason.as_deref(), Some("fg_timeout")); + + // Snapshot #2 must NOT be trapped at 80 ms; the 140 ms healthy reply must succeed. + let s2 = snapshot_once_with_guest_states(&inst, opts, Some(HashMap::from([(200, 'S')]))).unwrap(); + assert!(!s2.foreground_incomplete); + assert_eq!(s2.front, vec!["com.example.slow".to_string()]); + assert_eq!(s2.elements.len(), 1); + + let _ = server.join(); + let _ = std::fs::remove_dir_all(&dir); + } } From 619f624dbb6a94f182a14ee45517144dc580e5da Mon Sep 17 00:00:00 2001 From: abdelrahman fahmy <104788132+Apdelrahman1911@users.noreply.github.com> Date: Sun, 6 Dec 2026 06:58:51 +0000 Subject: [PATCH 2/5] test(ax): include SpringBoard peer in live_slow_foreground_app_recovers_after_timeout --- tools/launcher/core/src/ax.rs | 32 +++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/tools/launcher/core/src/ax.rs b/tools/launcher/core/src/ax.rs index 06240bdc..e292ef3d 100644 --- a/tools/launcher/core/src/ax.rs +++ b/tools/launcher/core/src/ax.rs @@ -3501,6 +3501,30 @@ mod tests { created: 0, }; + let sb_sock = dir.join("x86sim-ax-fixture-slowfg-100.sock"); + let sb_fg = dir.join("x86sim-ax-fixture-slowfg-100.fg"); + std::fs::write(&sb_fg, "com.apple.springboard\n").unwrap(); + let sb_listener = UnixListener::bind(&sb_sock).unwrap(); + let sb_server = std::thread::spawn(move || { + for stream in sb_listener.incoming().take(2) { + let mut stream = stream.unwrap(); + let mut line = String::new(); + let _ = BufReader::new(&stream).read_line(&mut line); + let reply = json!({ + "pid": 100, + "bundle": "com.apple.springboard", + "state": "active", + "partial": false, + "locked": false, + "suspended": [], + "screen": [390.0, 844.0, 3.0], + "windows": [{"class": "UIWindow", "frame": [0.0, 0.0, 390.0, 844.0]}], + "elements": [] + }); + let _ = stream.write_all(format!("{reply}\n").as_bytes()); + } + }); + let slow_sock = dir.join("x86sim-ax-fixture-slowfg-200.sock"); let slow_fg = dir.join("x86sim-ax-fixture-slowfg-200.fg"); std::fs::write(&slow_fg, "com.example.slow\n").unwrap(); @@ -3531,16 +3555,18 @@ mod tests { }); let opts = SnapOpts { no_ocr: true, timeout_ms: 350, ..Default::default() }; - let s1 = snapshot_once_with_guest_states(&inst, opts.clone(), Some(HashMap::from([(200, 'S')]))).unwrap(); + let states = HashMap::from([(100, 'S'), (200, 'S')]); + let s1 = snapshot_once_with_guest_states(&inst, opts, Some(states.clone())).unwrap(); assert!(s1.foreground_incomplete); assert_eq!(s1.incomplete_reason.as_deref(), Some("fg_timeout")); // Snapshot #2 must NOT be trapped at 80 ms; the 140 ms healthy reply must succeed. - let s2 = snapshot_once_with_guest_states(&inst, opts, Some(HashMap::from([(200, 'S')]))).unwrap(); + let s2 = snapshot_once_with_guest_states(&inst, opts, Some(states)).unwrap(); assert!(!s2.foreground_incomplete); - assert_eq!(s2.front, vec!["com.example.slow".to_string()]); + assert!(s2.front.contains(&"com.example.slow".to_string())); assert_eq!(s2.elements.len(), 1); + let _ = sb_server.join(); let _ = server.join(); let _ = std::fs::remove_dir_all(&dir); } From 709022393df3907155d8a09580920d9f90f6703b Mon Sep 17 00:00:00 2001 From: abdelrahman fahmy <104788132+Apdelrahman1911@users.noreply.github.com> Date: Sun, 6 Dec 2026 07:02:49 +0000 Subject: [PATCH 3/5] test(ax): synchronize mock server between s1 timeout and s2 recovery --- tools/launcher/core/src/ax.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tools/launcher/core/src/ax.rs b/tools/launcher/core/src/ax.rs index e292ef3d..2d6cffd7 100644 --- a/tools/launcher/core/src/ax.rs +++ b/tools/launcher/core/src/ax.rs @@ -3529,6 +3529,7 @@ mod tests { let slow_fg = dir.join("x86sim-ax-fixture-slowfg-200.fg"); std::fs::write(&slow_fg, "com.example.slow\n").unwrap(); let listener = UnixListener::bind(&slow_sock).unwrap(); + let (first_done_tx, first_done_rx) = std::sync::mpsc::channel(); let server = std::thread::spawn(move || { for (idx, stream) in listener.incoming().take(2).enumerate() { let mut stream = stream.unwrap(); @@ -3536,11 +3537,12 @@ mod tests { let _ = BufReader::new(&stream).read_line(&mut line); if idx == 0 { // Exceeds snapshot #1 timeout (350 ms) to simulate slow cold launch. - std::thread::sleep(Duration::from_millis(550)); + std::thread::sleep(Duration::from_millis(450)); + let _ = first_done_tx.send(()); continue; } // Exceeds old 80 ms stuck timeout, well below 350 ms snapshot #2 timeout. - std::thread::sleep(Duration::from_millis(140)); + std::thread::sleep(Duration::from_millis(160)); let reply = json!({ "pid": 200, "bundle": "com.example.slow", @@ -3559,8 +3561,9 @@ mod tests { let s1 = snapshot_once_with_guest_states(&inst, opts, Some(states.clone())).unwrap(); assert!(s1.foreground_incomplete); assert_eq!(s1.incomplete_reason.as_deref(), Some("fg_timeout")); + first_done_rx.recv().unwrap(); - // Snapshot #2 must NOT be trapped at 80 ms; the 140 ms healthy reply must succeed. + // Snapshot #2 must NOT be trapped at 80 ms; the 160 ms healthy reply must succeed. let s2 = snapshot_once_with_guest_states(&inst, opts, Some(states)).unwrap(); assert!(!s2.foreground_incomplete); assert!(s2.front.contains(&"com.example.slow".to_string())); From 676ee66854182cb25e594ffa5bc2b033b9e59991 Mon Sep 17 00:00:00 2001 From: abdelrahman fahmy <104788132+Apdelrahman1911@users.noreply.github.com> Date: Sun, 6 Dec 2026 07:06:34 +0000 Subject: [PATCH 4/5] test(ax): include required focused boolean on mock element --- tools/launcher/core/src/ax.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/launcher/core/src/ax.rs b/tools/launcher/core/src/ax.rs index 2d6cffd7..93c0bcbc 100644 --- a/tools/launcher/core/src/ax.rs +++ b/tools/launcher/core/src/ax.rs @@ -3550,7 +3550,7 @@ mod tests { "partial": false, "screen": [390.0, 844.0, 3.0], "windows": [{"class": "UIWindow", "frame": [0.0, 0.0, 390.0, 844.0]}], - "elements": [{"oid": "0x2", "role": "button", "label": "Ready", "enabled": true, "frame": [10.0, 20.0, 120.0, 40.0]}] + "elements": [{"oid": "0x2", "role": "button", "label": "Ready", "focused": false, "enabled": true, "frame": [10.0, 20.0, 120.0, 40.0]}] }); let _ = stream.write_all(format!("{reply}\n").as_bytes()); } @@ -3565,7 +3565,7 @@ mod tests { // Snapshot #2 must NOT be trapped at 80 ms; the 160 ms healthy reply must succeed. let s2 = snapshot_once_with_guest_states(&inst, opts, Some(states)).unwrap(); - assert!(!s2.foreground_incomplete); + assert!(!s2.foreground_incomplete, "unexpected incomplete_reason={:?}", s2.incomplete_reason); assert!(s2.front.contains(&"com.example.slow".to_string())); assert_eq!(s2.elements.len(), 1); From 3f037ca70a71dcf716bb697b46852aeea7edebbc Mon Sep 17 00:00:00 2001 From: abdelrahman fahmy <104788132+Apdelrahman1911@users.noreply.github.com> Date: Sun, 6 Dec 2026 07:11:00 +0000 Subject: [PATCH 5/5] test(ax): include window screen array on mock UIWindow so place() accepts elements --- tools/launcher/core/src/ax.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/launcher/core/src/ax.rs b/tools/launcher/core/src/ax.rs index 93c0bcbc..6f483c4d 100644 --- a/tools/launcher/core/src/ax.rs +++ b/tools/launcher/core/src/ax.rs @@ -3518,7 +3518,7 @@ mod tests { "locked": false, "suspended": [], "screen": [390.0, 844.0, 3.0], - "windows": [{"class": "UIWindow", "frame": [0.0, 0.0, 390.0, 844.0]}], + "windows": [{"class": "UIWindow", "frame": [0.0, 0.0, 390.0, 844.0], "screen": [390.0, 844.0, 3.0]}], "elements": [] }); let _ = stream.write_all(format!("{reply}\n").as_bytes()); @@ -3549,7 +3549,7 @@ mod tests { "state": "active", "partial": false, "screen": [390.0, 844.0, 3.0], - "windows": [{"class": "UIWindow", "frame": [0.0, 0.0, 390.0, 844.0]}], + "windows": [{"class": "UIWindow", "frame": [0.0, 0.0, 390.0, 844.0], "screen": [390.0, 844.0, 3.0]}], "elements": [{"oid": "0x2", "role": "button", "label": "Ready", "focused": false, "enabled": true, "frame": [10.0, 20.0, 120.0, 40.0]}] }); let _ = stream.write_all(format!("{reply}\n").as_bytes());