Skip to content

Commit d8221c6

Browse files
OneSlipsclaude
andcommitted
DUAL-GPU-THUMBS: merge storytold#3080 (a46e968): retry frames, build that can't start, cull_bench settings
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2 parents 6654098 + a46e968 commit d8221c6

6 files changed

Lines changed: 107 additions & 6 deletions

File tree

‎crates/engine/src/cmd/previews.rs‎

Lines changed: 38 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -400,6 +400,22 @@ pub(crate) mod test_gate {
400400
pub(crate) fn take() -> Option<Arc<PreviewGate>> {
401401
NEXT_GATE.with(|g| g.borrow_mut().take())
402402
}
403+
404+
thread_local! {
405+
/// The next build started on this thread fails to start its worker (a thread the system
406+
/// won't give), taken by `build`.
407+
static FAIL_SPAWN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
408+
}
409+
410+
/// Have the next build started on this thread fail to start its worker.
411+
pub(crate) fn fail_next_spawn() {
412+
FAIL_SPAWN.with(|f| f.set(true));
413+
}
414+
415+
/// Whether this build's worker is to fail to start (once).
416+
pub(crate) fn take_fail_spawn() -> bool {
417+
FAIL_SPAWN.with(std::cell::Cell::take)
418+
}
403419
}
404420

405421
/// One photo's work in a build: its id and its render jobs ([`jobs_for`]).
@@ -525,9 +541,9 @@ fn build(s: &mut Session, p: &Value) -> Result<Value> {
525541
s.visible_cloned()
526542
};
527543
let jobs: Vec<PhotoJobs> = ids.iter().map(|id| (id.0, jobs_for(s, *id, edge))).filter(|j| !j.1.is_empty()).collect();
528-
if let Some(cancel) = gives_way {
529-
cancel.store(true, Ordering::Relaxed);
530-
}
544+
// the background build stays the session's until this one has started (a worker that can't
545+
// start leaves it running and in place: CodeRabbit on #3544)
546+
let previous = s.preview_build.clone();
531547
let order = jobs.iter().map(|j| j.0).collect();
532548
#[cfg_attr(not(test), allow(unused_mut))]
533549
let mut build_state = PreviewBuild { total: jobs.len(), background, order, ..Default::default() };
@@ -545,20 +561,38 @@ fn build(s: &mut Session, p: &Value) -> Result<Value> {
545561
let lanes = if background { crate::prep::background_lanes() } else { lanes(jobs.len(), edge.is_none()) };
546562
let wait = p.get("wait").and_then(Value::as_bool).unwrap_or(false) || cfg!(target_arch = "wasm32");
547563
if wait {
564+
if let Some(cancel) = gives_way {
565+
cancel.store(true, Ordering::Relaxed);
566+
}
548567
run_all(jobs, &state, task.as_ref(), lanes, force);
549568
return Ok(state.json());
550569
}
551570
#[cfg(not(target_arch = "wasm32"))]
552571
{
553572
// the row stays while the worker runs (it is dropped with the closure, however that ends)
554573
let st = state.clone();
574+
#[cfg(test)]
575+
let started = if test_gate::take_fail_spawn() {
576+
drop(task);
577+
Err(std::io::Error::other("no thread (test)"))
578+
} else {
579+
std::thread::Builder::new().name("lc-build-previews".into()).spawn(move || run_all(jobs, &st, task.as_ref(), lanes, force))
580+
};
581+
#[cfg(not(test))]
555582
let started = std::thread::Builder::new().name("lc-build-previews".into()).spawn(move || run_all(jobs, &st, task.as_ref(), lanes, force));
556583
if let Err(e) = started {
557-
// never started: not left "running", which would hold every later build back
584+
// never started: not left "running", which would hold every later build back, and the
585+
// build it was to replace carries on
558586
state.finished.store(true, Ordering::Relaxed);
587+
s.preview_build = previous;
559588
return Err(bad(C, format!("could not start: {e}")));
560589
}
590+
if let Some(cancel) = gives_way {
591+
cancel.store(true, Ordering::Relaxed);
592+
}
561593
}
594+
#[cfg(target_arch = "wasm32")]
595+
let _ = previous;
562596
Ok(state.json())
563597
}
564598

‎crates/engine/src/prep.rs‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,7 @@ pub struct PrepState {
219219
declined_for: Option<u64>,
220220
/// A build that couldn't start: the view (its signature), and when it may try again (not on
221221
/// every tick while the cause lasts; CodeRabbit on #3080).
222-
pub(crate) retry_at: Option<(u64, web_time::Instant)>,
222+
pub retry_at: Option<(u64, web_time::Instant)>,
223223
/// Tests: the next starts to fail, as a build thread that can't be spawned does.
224224
#[cfg(test)]
225225
pub(crate) fail_starts: usize,
@@ -426,6 +426,17 @@ pub fn marked(s: &Session, id: PhotoId) -> bool {
426426
}
427427

428428
impl Session {
429+
/// How long until a view whose build couldn't start tries again ([`RETRY_AFTER`]), while one
430+
/// waits: the app asks for a frame then, so the retry doesn't wait for the next input
431+
/// (CodeRabbit on #3077/#3080). `None` once the time has come.
432+
pub fn prep_retry_in(&self) -> Option<std::time::Duration> {
433+
// (a deadline that has passed asks for nothing: the pass at it tried again, or the view
434+
// can't be tried now and a frame at once on every pass would keep an idle window drawing:
435+
// CodeRabbit on #3077 / #3080)
436+
let wait = self.prep.retry_at.map(|(_, at)| at.saturating_duration_since(web_time::Instant::now()))?;
437+
(!wait.is_zero()).then_some(wait)
438+
}
439+
429440
/// The background preparation settings in use (this library's own, else the app-wide ones).
430441
pub fn prep_settings(&self) -> PrepSettings {
431442
self.prep.settings()

‎crates/engine/src/tests/preview_prep.rs‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -590,6 +590,22 @@ fn a_bad_build_request_leaves_the_background_build_running() {
590590
let _ = std::fs::remove_dir_all(&root);
591591
}
592592

593+
/// CodeRabbit on #3544: a build asked for whose worker can't start fails without stopping or
594+
/// replacing the background preparation that is running.
595+
#[test]
596+
fn a_build_that_cant_start_leaves_the_background_build_running() {
597+
let _hold = crate::prep::TestHold::new();
598+
let (mut s, root, ids) = library("prep-no-thread", 3);
599+
s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids), "background": true})).unwrap();
600+
let b = s.preview_build.clone().expect("the background build");
601+
assert!(b.running());
602+
crate::cmd::previews::test_gate::fail_next_spawn();
603+
assert!(s.execute("library.buildPreviews", &json!({"ids": ids_json(&ids)})).is_err(), "the worker didn't start");
604+
assert!(!b.cancel.load(std::sync::atomic::Ordering::Relaxed), "the background build was not stopped");
605+
assert!(s.preview_build.as_ref().is_some_and(|now| std::sync::Arc::ptr_eq(now, &b)), "and is still the session's build");
606+
let _ = std::fs::remove_dir_all(&root);
607+
}
608+
593609
/// CodeRabbit on #3080: a background build that can't start isn't tried again on every tick; the
594610
/// view tries again once [`crate::prep::RETRY_AFTER`] has passed.
595611
#[test]
@@ -602,10 +618,13 @@ fn a_build_that_cant_start_waits_before_trying_again() {
602618
}
603619
assert!(s.preview_build.is_none(), "the start failed");
604620
assert!(s.prep.retry_at.is_some());
621+
// the app is told when to look again (a frame is asked for then)
622+
assert!(s.prep_retry_in().is_some_and(|d| d <= crate::prep::RETRY_AFTER && d > crate::prep::RETRY_AFTER / 2));
605623
s.prep_tick(mode, Some(ids[2]), false);
606624
assert!(s.preview_build.is_none(), "not tried again at once");
607-
// the wait is over
625+
// the wait is over: no more frames asked for it (CodeRabbit on #3077 / #3080)
608626
s.prep.retry_at = s.prep.retry_at.map(|(view, _)| (view, web_time::Instant::now()));
627+
assert_eq!(s.prep_retry_in(), None, "a deadline that has passed asks for no frame");
609628
s.prep_tick(mode, Some(ids[2]), false);
610629
let b = s.preview_build.clone().expect("tried again");
611630
assert!(b.background && s.prep.retry_at.is_none());

‎crates/ui-egui/examples/cull_bench.rs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,11 @@ fn main() {
3939
.map_err(|e| e.to_string())
4040
.and_then(|v| s.execute("prefs.setBackgroundPrep", &json!({"settings": {"culling": v}})).map_err(|e| e.to_string()));
4141
match set {
42+
// (the library's own settings would win over the app-wide ones set here: CodeRabbit on #3080)
43+
Ok(v) if v["own"].as_bool() == Some(true) => {
44+
eprintln!("CULL_PREP={patch}: this library has its own preparation settings, which take precedence");
45+
std::process::exit(1);
46+
}
4247
Ok(v) => eprintln!("prep {patch}: {}", v["settings"]["culling"]),
4348
Err(e) => {
4449
eprintln!("CULL_PREP={patch}: {e}");
@@ -55,6 +60,9 @@ fn main() {
5560
}
5661
}
5762
let mut h = Headless::new(LightcraftApp::new(s, Services::default()), [1600.0, 1000.0], 1.0);
63+
// the first pass copies the app's saved settings into the session: those asked for are the
64+
// app's too, so the run times them (CodeRabbit on #3080)
65+
h.app.ui.settings.background_prep = h.app.session.prep.app;
5866
let req = |h: &mut Headless, m: &str, p: Value| h.request(m, p, Duration::from_secs(60));
5967
let n = h.app.session.visible_cloned().len();
6068
let start_at = n / 10;

‎crates/ui-egui/src/app.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -550,6 +550,10 @@ impl LightcraftApp {
550550
if self.session.preview_build.as_ref().is_some_and(|b| b.running()) {
551551
ctx.request_repaint_after(std::time::Duration::from_millis(500));
552552
}
553+
// a build that couldn't start tries again at its time, also when nothing else draws a frame
554+
if let Some(wait) = self.session.prep_retry_in() {
555+
ctx.request_repaint_after(wait);
556+
}
553557
}
554558

555559
/// AI masks: apply finished background requests (clicks, descriptions, detail passes) and

‎crates/ui-egui/src/tests/lifecycle_037.rs‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2347,3 +2347,28 @@ fn background_preparation_advances_while_the_window_is_hidden() {
23472347
let _ = ctx.run_logic(&visible, |ctx| app.logic(ctx));
23482348
assert_eq!(app.prep_ticks, 3, "a shown pass advances it once");
23492349
}
2350+
/// CodeRabbit on #3077/#3080: a background build that couldn't start asks for a frame at its retry
2351+
/// time, so the retry happens with no input and no other timed frame.
2352+
#[test]
2353+
fn a_build_waiting_to_retry_asks_for_a_frame_at_its_time() {
2354+
let mut app = app();
2355+
let ctx = egui::Context::default();
2356+
let delays = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
2357+
let seen = delays.clone();
2358+
ctx.set_request_repaint_callback(move |info| seen.lock().unwrap().push(info.delay));
2359+
let wait = std::time::Duration::from_secs(7);
2360+
let hidden = viewport_raw(egui::vec2(800.0, 600.0), false);
2361+
// (the first passes ask for frames at once, which would hide a later request)
2362+
for _ in 0..3 {
2363+
let _ = ctx.run_logic(&hidden, |ctx| app.logic(ctx));
2364+
}
2365+
delays.lock().unwrap().clear();
2366+
app.session.prep.retry_at = Some((0, std::time::Instant::now() + wait));
2367+
let _ = ctx.run_logic(&hidden, |ctx| app.logic(ctx));
2368+
let got = delays.lock().unwrap().clone();
2369+
assert!(got.iter().any(|d| *d > std::time::Duration::from_secs(6) && *d <= wait), "a frame at the retry time: {got:?}");
2370+
app.session.prep.retry_at = None;
2371+
delays.lock().unwrap().clear();
2372+
let _ = ctx.run_logic(&hidden, |ctx| app.logic(ctx));
2373+
assert!(!delays.lock().unwrap().iter().any(|d| *d > std::time::Duration::from_secs(6) && *d <= wait), "none without a retry waiting");
2374+
}

0 commit comments

Comments
 (0)