Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

#158: a render can't wait forever on a frame its runtime lost. Ragul's long 4K renders hung before their first frame about half the time on 0.1.4 (2 of 6 on 0.1.2): the main thread waiting in settle's wait_flush, the JS thread idle, no output, no exit. Settle's no-progress guard took any JS time anywhere as progress, and the JS thread ticks its timer queue every 500 ms even when it's empty, so a frame that would never come was waited on for good; it also read every runtime's flushes, and a render's 3D rows run three runtimes.

shinyobjectz19c877037aef
diff --git a/runtime/bake/src/lib.rs b/runtime/bake/src/lib.rs
index 33ea7d7c..11cc7674 100644
--- a/runtime/bake/src/lib.rs
+++ b/runtime/bake/src/lib.rs
@@ -219,12 +219,17 @@ pub fn step_frames_with(app: &mut App, a: i64, b: i64, answer: &mut raea_runtime
let (t0, w0, a0, j0) = (std::time::Instant::now(), ld(&raea_runtime_react::FLUSH_WAIT_NS), ld(&raea_runtime_react::APPLY_NS), ld(&raea_runtime_react::JS_NS));
let mut t_each = std::time::Duration::ZERO;
app.world().resource::<ReactOutbox>().send(json!({"t": "event", "name": "raea-frames", "value": {"from": a, "to": b}}));
- for g in a..b {
+ // the range's end, for a settle that finds a frame lost to ask for the rest again (#158)
+ app.world_mut().insert_resource(raea_runtime_react::Stepping { to: b });
+ let stepped = (a..b).try_for_each(|g| {
raea_runtime_react::scene::settle_with(app, Some(g), 20.0, answer)?;
let te = std::time::Instant::now();
each(app, g)?;
t_each += te.elapsed();
- }
+ Ok::<(), String>(())
+ });
+ app.world_mut().remove_resource::<raea_runtime_react::Stepping>();
+ stepped?;
if std::env::var_os("RAEA_BAKE_TRACE").is_some() {
let ms = |a: &std::sync::atomic::AtomicU64, z: u64| (ld(a) - z) as f64 / 1e6;
eprintln!(
diff --git a/runtime/bundle/src/entry.rs b/runtime/bundle/src/entry.rs
index 134600e7..a23bd224 100644
--- a/runtime/bundle/src/entry.rs
+++ b/runtime/bundle/src/entry.rs
@@ -148,7 +148,7 @@ function Marker({{ f, to, conf, next }}: {{ f: number; to: number; conf: string;
}}, [done]);
return <div data-raea-frame={{f}} data-raea-done={{done}} data-raea-config={{conf}} />;
}}
-mount(<surface id="motion" w={{1}} px={{cfg.width}} pxH={{cfg.height}}><Root /></surface>);
+mount(<surface id="motion" w={{1}} px={{cfg.width}} pxH={{cfg.height}}><Root /></surface>).catch((globalThis as any).__raea_loop_died);
"#,
comp = comp.map(|c| format!("{c:?}")).unwrap_or("null".into())
)
@@ -241,7 +241,7 @@ addEventListener("raea-frame", (v: any) => {{
// render sends its own ops)
reset();
draw();
-runEventLoop();
+runEventLoop().catch((globalThis as any).__raea_loop_died);
"#,
preamble = &full[start..end],
marker = if o.comps { "<Marker f={f} />" } else { "<div data-raea-frame={f} data-raea-done={HOLD.n ? -3 : f} data-raea-config={conf} />" },
diff --git a/runtime/react/src/lib.rs b/runtime/react/src/lib.rs
index 5658f39f..4b0e1e23 100644
--- a/runtime/react/src/lib.rs
+++ b/runtime/react/src/lib.rs
@@ -21,7 +21,7 @@ pub mod scene;
/// React's on* props on the entities it makes: Bevy picking's pointer events to their handlers (S2c, B3 H3)
pub mod pointer;
/// state React and the World share: useResource, useComponent (docs/blitz-bevy.feature B3 H4)
-pub use raea_runtime_shared::{self as shared, ReactOutbox};
+pub use raea_runtime_shared::{self as shared, JsState, ReactJs, ReactOutbox, Stepping};
pub use raea_runtime_calls::{self as native, CLI};
use serde_json::Value;
@@ -171,16 +171,18 @@ impl Plugin for ReactPlugin {
// the runtime's layout reads (layout.rs): asked on its JS thread, answered by its settle
let ask = layout::LayoutAsk::default();
let js_ask = ask.0.clone();
+ let state = std::sync::Arc::new(JsState::default());
+ let js_state = state.clone();
std::thread::Builder::new()
.name("raea-runtime-react js".into())
.spawn(move || {
layout::ASK.with(|a| *a.borrow_mut() = Some(js_ask));
// JavaScriptCore on Apple (the system's engine, the JIT on with the entitlement tools/link-jit.sh signs in),
// QuickJS elsewhere
- js_thread(bundle, tx, out_rx)
+ js_thread(bundle, tx, out_rx, js_state)
})
.expect("the JS thread");
- app.insert_resource(ask);
+ app.insert_resource(ask).insert_resource(ReactJs(state));
app.insert_resource(ReactOutbox(Mutex::new(out_tx)));
let root = app.world_mut().spawn((ReactRoot, ReactNode(ROOT_ID), ReactKind("#root".into()))).id();
let mut ents = ReactEntities::default();
@@ -195,7 +197,7 @@ impl Plugin for ReactPlugin {
}
thread_local! {
- static FLUSH: std::cell::RefCell<Option<Sender<Batch>>> = const { std::cell::RefCell::new(None) };
+ static FLUSH: std::cell::RefCell<Option<(Sender<Batch>, std::sync::Arc<JsState>)>> = const { std::cell::RefCell::new(None) };
}
/// The bundle's own throw while it was evaluated (before React committed anything): a render waiting for its first
@@ -243,16 +245,18 @@ pub fn js_call_for() -> Option<Duration> {
Some(if at == 0 { Duration::ZERO } else { JS_BASE.elapsed().saturating_sub(Duration::from_millis(at - 1)) })
}
-fn js_call_begins(deliver: bool) {
+fn js_call_begins(deliver: bool, state: &JsState) {
use std::sync::atomic::Ordering::SeqCst;
+ state.in_call(true);
if JS_CALLS.fetch_add(1, SeqCst) == 0 {
JS_CALL_WHO.store(JS_RUNTIME.get() * 2 + deliver as u64, SeqCst);
JS_CALL_SINCE.store(JS_BASE.elapsed().as_millis() as u64 + 1, SeqCst);
}
}
-fn js_call_ends() {
+fn js_call_ends(state: &JsState) {
use std::sync::atomic::Ordering::SeqCst;
+ state.in_call(false);
if JS_CALLS.fetch_sub(1, SeqCst) == 1 {
JS_CALL_SINCE.store(0, SeqCst);
}
diff --git a/runtime/react/src/scene/settle.rs b/runtime/react/src/scene/settle.rs
index 94c96a57..236534ac 100644
--- a/runtime/react/src/scene/settle.rs
+++ b/runtime/react/src/scene/settle.rs
@@ -50,9 +50,9 @@ pub fn settle_with(app: &mut App, want: Option<i64>, secs: f64, answer: &mut cra
// no polling for quiet: each pass applies what React flushed, then waits for its next flush. The composition marks
// a frame done (data-raea-done) once its commit and that commit's effects have run, so the frame is taken the
// moment the mark lands (it waited for three quiet updates with 1 ms sleeps, ~4 ms a frame)
- // the last time anything moved, and what it was (settle's no-progress guard, below)
- let mut still = std::time::Instant::now();
- let mut moved = (u64::MAX, u64::MAX, f64::NAN);
+ // the no-progress guard over this runtime's JS thread (shared stall.rs; a replay's App has none: the process's counts)
+ let js = app.world().get_resource::<crate::ReactJs>().map(|j| j.0.clone());
+ let mut watch = crate::shared::Settling::default();
// the marker as last seen (frame, done), for the refusal's message
let mut marked = (-2i64, -2i64);
// the frame is held (below): its marker at the frame, not done
@@ -131,36 +131,34 @@ pub fn settle_with(app: &mut App, want: Option<i64>, secs: f64, answer: &mut cra
if let Some(e) = crate::BUNDLE_ERROR.lock().unwrap().take() {
return Err(format!("the composition threw before its first frame: {e}"));
}
- // refused only when nothing moves for `secs`: no commit flushed, no JS run, nothing made on first use (a
- // matchmove solve: minutes). A call the JS thread is still in counts too, up to HANG_SECS (a frame's render
- // under load runs seconds before its first flush). A total-time limit refused film.tsx under load (10-27)
- let now = (crate::flushed(), crate::JS_NS.load(std::sync::atomic::Ordering::Relaxed), track::making_secs());
- let in_call = crate::js_call_for().is_some_and(|d| d.as_secs_f64() < HANG_SECS);
- if now != moved || in_call {
- moved = now;
- still = std::time::Instant::now();
- }
+ // refused only when nothing moves for `secs`, by this runtime's own counts (Settling, raea-runtime-shared
+ // stall.rs); a call the JS thread is still in counts too, up to HANG_SECS
+ let (flushed, work) = js.as_ref().map_or_else(|| (crate::flushed(), crate::JS_NS.load(std::sync::atomic::Ordering::Relaxed)), |j| j.counts());
+ let in_call = js.as_ref().map_or_else(crate::js_call_for, |j| j.since(&j.call_since)).is_some_and(|d| d.as_secs_f64() < HANG_SECS);
// a held frame (delayRender, a scene still loading: its marker at the frame, not done) waits up to
// HOLD_SECS, so a hold's own timeout (30 s unless it says) fails the render naming it first (layout-reads LR9)
held = want.is_some_and(|w| marked.0 == w && marked.1 != w);
- let left = if held { secs.max(HOLD_SECS) } else { secs } - still.elapsed().as_secs_f64();
- if left <= 0.0 {
- break;
- }
+ let Some(left) = watch.watch((flushed, work, track::making_secs()), in_call, if held { secs.max(HOLD_SECS) } else { secs }, HOLD_SECS) else { break };
// commits held to be applied one an update (OneBatch): the next is applied without waiting
if app.world().get_resource::<crate::OneBatch>().is_some_and(|q| !q.0.is_empty()) {
continue;
}
+ // a stepped range's frame lost (#158): its runtime idle, the frame neither drawn nor held. Asked for again (pure)
+ if let (Some(j), Some(s), Some(o)) = (&js, app.world().get_resource::<crate::Stepping>(), app.world().get_resource::<crate::ReactOutbox>())
+ && watch.nudge(j, want.unwrap_or(-1), s.to, held, marked)
+ {
+ o.send(serde_json::json!({"t": "event", "name": "raea-frames", "value": {"from": want, "to": s.to}}));
+ }
seen = crate::wait_flush(seen, std::time::Duration::from_secs_f64(left.min(0.5)), ask.as_deref());
}
// a call past HANG_SECS is a hang, named: which runtime's call, and how long it has run
- if let Some(d) = crate::js_call_for().filter(|d| d.as_secs_f64() >= HANG_SECS) {
+ if let Some(d) = js.as_ref().map_or_else(crate::js_call_for, |j| j.since(&j.call_since)).filter(|d| d.as_secs_f64() >= HANG_SECS) {
return Err(format!("the composition hangs on frame {want:?}: {} has run for {:.0} s without returning (past {HANG_SECS} s: an endless loop, or a native call that never returns; `sample <pid>` shows where), its marker at frame {} (done {})", crate::js_call_who(), d.as_secs_f64(), marked.0, marked.1));
}
if held {
return Err(format!("frame {want:?} was held for {HOLD_SECS} s and never released: a delayRender never continued, or a scene that never finished loading"));
}
- Err(format!("the composition made no progress on frame {want:?} for {secs} s, its marker at frame {} (done {}) (does it throw? its [js] lines are above, and `raea traces show last` has the run's log)", marked.0, marked.1))
+ Err(watch.refusal(js.as_deref(), want, secs, HOLD_SECS, marked))
}
/// The entity carrying the frame marker (data-raea-frame), once found.
diff --git a/runtime/react/src/thread.rs b/runtime/react/src/thread.rs
index 4a096125..d2248ba0 100644
--- a/runtime/react/src/thread.rs
+++ b/runtime/react/src/thread.rs
@@ -10,8 +10,9 @@ fn flush(a: &[String]) -> Result<Ret, String> {
let json = arg(a, 0).to_string();
let len = json.len() as u64;
FLUSH.with(|f| {
- if let Some(tx) = f.borrow().as_ref() {
+ if let Some((tx, state)) = f.borrow().as_ref() {
let _ = tx.send(Batch(json));
+ state.flushed.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
}
});
FLUSH_BYTES.fetch_add(len, std::sync::atomic::Ordering::Relaxed);
@@ -42,8 +43,8 @@ pub fn register_natives() {
/// The JS thread: the prelude, the shims, the bundle, then timers and Bevy's events. Both engines run promise jobs as
/// each call returns, so there are no microtask checkpoints to make.
-pub(crate) fn js_thread(bundle: PathBuf, tx: Sender<Batch>, events: Receiver<String>) {
- FLUSH.with(|f| *f.borrow_mut() = Some(tx));
+pub(crate) fn js_thread(bundle: PathBuf, tx: Sender<Batch>, events: Receiver<String>, state: std::sync::Arc<JsState>) {
+ FLUSH.with(|f| *f.borrow_mut() = Some((tx, state.clone())));
let code = match std::fs::read_to_string(&bundle) {
Ok(c) => c,
Err(e) => {
@@ -91,11 +92,15 @@ pub(crate) fn js_thread(bundle: PathBuf, tx: Sender<Batch>, events: Receiver<Str
let mut delivered: u64 = 0;
let release_every: f64 = std::env::var("RAEA_JSC_RELEASE_S").ok().and_then(|v| v.parse().ok()).unwrap_or(5.0);
let mut released = Instant::now();
+ let mut fault = raea_runtime_shared::DropFault::from_env();
+ // the next timers call has a timer to run (an empty tick isn't work, #158): the bundle's, an event handler's, or one
+ // that came due while the thread waited
+ let mut due = true;
loop {
let busy = Instant::now();
- js_call_begins(false);
+ js_call_begins(false, &state);
let timers = ctx.call("__raea_timers", &[Arg::Num(now_ms())]);
- js_call_ends();
+ js_call_ends(&state);
let next = match timers {
None => break,
Some(Ok(n)) if n.is_finite() => n,
@@ -106,25 +111,33 @@ pub(crate) fn js_thread(bundle: PathBuf, tx: Sender<Batch>, events: Receiver<Str
}
};
JS_NS.fetch_add(busy.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed);
+ state.timers(due, next);
let wait = if next < 0.0 { Duration::from_millis(500) } else { Duration::from_millis(next.clamp(0.0, 500.0) as u64) };
+ due = (0.0..=500.0).contains(&next);
let msg = match events.recv_timeout(wait) {
Ok(json) => Some(json),
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => continue,
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => None,
};
+ if msg.as_deref().is_some_and(|j| fault.drops(j)) {
+ continue;
+ }
let busy = Instant::now();
let event = match &msg {
Some(json) => Arg::Str(json),
None => Arg::Null,
};
- js_call_begins(true);
+ js_call_begins(true, &state);
let outcome = ctx.call("__raea_deliver", &[event]);
- js_call_ends();
- match outcome {
+ js_call_ends(&state);
+ match &outcome {
None => break,
Some(Err(e)) => error!("raea-runtime-react: an event threw: {e}"),
Some(Ok(_)) => {}
}
+ // the prelude answers 0 for an event queued with no one waiting: the bridge's event loop has stopped
+ state.delivered(!matches!(outcome, Some(Ok(n)) if n == 0.0));
+ due = true;
JS_NS.fetch_add(busy.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed);
// a young collection after the frame when RAEA_JSC_EDEN is set (off: each cost ~0.5 ms and held memory no
// flatter in pong; every 16th frame left 1 collection of 360 started by allocation inside a frame, where 71
diff --git a/runtime/shared/src/lib.rs b/runtime/shared/src/lib.rs
index 50a5c68a..bb9253c7 100644
--- a/runtime/shared/src/lib.rs
+++ b/runtime/shared/src/lib.rs
@@ -34,6 +34,9 @@ use std::sync::mpsc::Sender;
#[cfg(test)]
mod tests;
+/// one runtime's JS thread as its settle sees it, and the settle's watch (#158)
+pub mod stall;
+pub use stall::{DropFault, JsState, ReactJs, Settling, Stepping};
/// Bevy to React: events for the bridge's `op_next_event` (bevy-react's Outbound messages, as JSON).
#[derive(Resource)]
diff --git a/runtime/shared/src/stall.rs b/runtime/shared/src/stall.rs
new file mode 100644
index 00000000..223ec594
--- /dev/null
+++ b/runtime/shared/src/stall.rs
@@ -0,0 +1,189 @@
+//! One React runtime's JS thread as its settle sees it, and the settle's watch over it (#158).
+//!
+//! A render runs several runtimes in one process (the 3D rows' workers, the page's frames), and settle's no-progress
+//! guard read the process's counts: every runtime's flushes, and the JS time of a thread ticking an empty timer queue
+//! every 500 ms. A frame a runtime lost was then waited on for good, with no output and no exit. Each runtime now keeps
+//! its own [`JsState`]: its flushes, its work (an event delivered, or a timers call with a timer due; an empty tick isn't
+//! work), its current call, and since when it has waited with nothing scheduled. [`Settling`] is one settle's watch:
+//! when to give up, when to ask a stepped range's lost frame again, and what to say when it gives up.
+
+use std::sync::atomic::{AtomicU64, Ordering::SeqCst};
+use std::time::{Duration, Instant};
+
+use bevy::prelude::Resource;
+
+/// One runtime's JS thread: written by the thread, read by its settle.
+pub struct JsState {
+ base: Instant,
+ /// commits this runtime's React has flushed
+ pub flushed: AtomicU64,
+ /// calls that did something: an event delivered, or a timers call with a timer due
+ pub work: AtomicU64,
+ /// when the thread's current call began, in ms after `base` plus 1 (0: not in a call)
+ pub call_since: AtomicU64,
+ /// since when the thread has waited with nothing scheduled (no timer set, no event), as call_since (0: not idle)
+ pub idle_since: AtomicU64,
+ /// events delivered while the bridge's event loop wasn't waiting for one: it had stopped, so they queue unread
+ pub unheard: AtomicU64,
+}
+
+impl Default for JsState {
+ fn default() -> Self {
+ JsState { base: Instant::now(), flushed: AtomicU64::new(0), work: AtomicU64::new(0), call_since: AtomicU64::new(0), idle_since: AtomicU64::new(0), unheard: AtomicU64::new(0) }
+ }
+}
+
+impl JsState {
+ fn now(&self) -> u64 {
+ self.base.elapsed().as_millis() as u64 + 1
+ }
+ /// (flushed, work): what settle's guard counts as this runtime moving.
+ pub fn counts(&self) -> (u64, u64) {
+ (self.flushed.load(SeqCst), self.work.load(SeqCst))
+ }
+ /// How long ago `at` (call_since or idle_since) was set, if it is.
+ pub fn since(&self, at: &AtomicU64) -> Option<Duration> {
+ match at.load(SeqCst) {
+ 0 => None,
+ t => Some(self.base.elapsed().saturating_sub(Duration::from_millis(t - 1))),
+ }
+ }
+ /// The thread enters a call (`true`) or leaves it.
+ pub fn in_call(&self, entering: bool) {
+ self.call_since.store(if entering { self.now() } else { 0 }, SeqCst);
+ }
+ /// A timers call returned `next` (ms to its next timer, negative for none); `due` says it had a timer to run. With
+ /// nothing scheduled the thread is idle from now until an event is delivered (a lost one leaves it idle).
+ pub fn timers(&self, due: bool, next: f64) {
+ if due {
+ self.work.fetch_add(1, SeqCst);
+ }
+ if next < 0.0 {
+ let _ = self.idle_since.compare_exchange(0, self.now(), SeqCst, SeqCst);
+ } else {
+ self.idle_since.store(0, SeqCst);
+ }
+ }
+ /// An event was delivered: `heard` when the bridge's loop took it, not queued unread.
+ pub fn delivered(&self, heard: bool) {
+ self.idle_since.store(0, SeqCst);
+ self.work.fetch_add(1, SeqCst);
+ if !heard {
+ self.unheard.fetch_add(1, SeqCst);
+ }
+ }
+}
+
+/// The runtime's JsState, in its App (ReactPlugin puts it there and on its JS thread).
+#[derive(Resource, Clone)]
+pub struct ReactJs(pub std::sync::Arc<JsState>);
+
+/// The range of frames being stepped (step_frames: raea-frames from..to), while it is: a settle that finds its runtime
+/// idle with its frame not drawn asks for the rest of the range again from that frame.
+#[derive(Resource, Clone, Copy)]
+pub struct Stepping {
+ pub to: i64,
+}
+
+/// RAEA_FAULT_DROP_EVENT=NAME: the first event named NAME never reaches the composition, as if it had missed it (the
+/// lost frame settle's nudge recovers); NAME* drops every one (the frame lost for good, which settle fails naming).
+/// tools/settle-nudge.sh runs both.
+pub struct DropFault {
+ name: Option<String>,
+ every: bool,
+}
+
+impl DropFault {
+ pub fn from_env() -> Self {
+ let spec = std::env::var("RAEA_FAULT_DROP_EVENT").ok().filter(|n| !n.is_empty());
+ let every = spec.as_deref().is_some_and(|n| n.ends_with('*'));
+ DropFault { name: spec.map(|n| format!("\"name\":\"{}\"", n.trim_end_matches('*'))), every }
+ }
+ /// Whether to drop this event (said on stderr).
+ pub fn drops(&mut self, json: &str) -> bool {
+ if !self.name.as_deref().is_some_and(|n| json.contains(n)) {
+ return false;
+ }
+ eprintln!("raea-runtime-react: RAEA_FAULT_DROP_EVENT dropped {json}");
+ if !self.every {
+ self.name = None;
+ }
+ true
+ }
+}
+
+/// A runtime stepping a range whose JS thread has waited this long with nothing scheduled, its frame neither drawn nor
+/// held, has lost the frame: nothing would ever come, so settle asks for the rest of the range again from it.
+pub const NUDGE_IDLE_SECS: f64 = 1.0;
+
+/// How many times a frame is asked for again (settle still fails only after its time with nothing moving).
+pub const NUDGES: u32 = 3;
+
+/// One settle's watch over its runtime: refused when nothing moves for its time (no commit, no JS work, nothing made on
+/// first use: a matchmove solve takes minutes; a call still running counts, up to the caller's hang limit); a thread
+/// that only runs timers (an interval polling for what never comes) is work, but not for longer than `hold` without a
+/// commit. A total-time limit refused film.tsx under load (10-27).
+pub struct Settling {
+ still: Instant,
+ moved: (u64, u64, f64),
+ drawn: Instant,
+ drew: (u64, f64),
+ nudges: u32,
+ nudged: Instant,
+ /// refused because the thread only ran timers, committing nothing
+ timers_only: bool,
+}
+
+impl Default for Settling {
+ fn default() -> Self {
+ let now = Instant::now();
+ Settling { still: now, moved: (u64::MAX, u64::MAX, f64::NAN), drawn: now, drew: (u64::MAX, f64::NAN), nudges: 0, nudged: now, timers_only: false }
+ }
+}
+
+impl Settling {
+ /// This pass's counts (flushes, work, seconds spent making), whether a call is running, the time allowed with nothing
+ /// moving and with only timers: the seconds left, or None to give up.
+ pub fn watch(&mut self, now: (u64, u64, f64), in_call: bool, limit: f64, hold: f64) -> Option<f64> {
+ if now != self.moved || in_call {
+ self.moved = now;
+ self.still = Instant::now();
+ }
+ if (now.0, now.2) != self.drew || in_call {
+ self.drew = (now.0, now.2);
+ self.drawn = Instant::now();
+ }
+ let left = limit - self.still.elapsed().as_secs_f64();
+ self.timers_only = left > 0.0 && self.drawn.elapsed().as_secs_f64() >= limit.max(hold);
+ (left > 0.0 && !self.timers_only).then_some(left)
+ }
+ /// Whether to ask frame `want` again now (said on stderr): a range is stepped (`to`), the frame isn't held, and the
+ /// runtime's thread, in no call, has waited on nothing for NUDGE_IDLE_SECS, at most NUDGES times, twice that apart
+ /// and not in the settle's first 2 x NUDGE_IDLE_SECS (the range's own event may not be taken yet).
+ pub fn nudge(&mut self, js: &JsState, want: i64, to: i64, held: bool, marked: (i64, i64)) -> bool {
+ let idle = js.call_since.load(SeqCst) == 0 && js.since(&js.idle_since).is_some_and(|d| d.as_secs_f64() >= NUDGE_IDLE_SECS);
+ if !idle || held || want < 0 || want >= to || self.nudges >= NUDGES || self.nudged.elapsed().as_secs_f64() < 2.0 * NUDGE_IDLE_SECS {
+ return false;
+ }
+ self.nudges += 1;
+ self.nudged = Instant::now();
+ eprintln!("raea: frame {want}'s runtime went idle without drawing it (its marker at frame {} done {}): asked for frames {want}..{to} again ({} of {NUDGES})", marked.0, marked.1, self.nudges);
+ true
+ }
+ /// The settle's refusal of frame `want` after `secs` with nothing moving (`hold`, when only timers ran), its marker as
+ /// last seen, and what the runtime's JS thread was doing (nothing said for a replay's App, which has none).
+ pub fn refusal(&self, js: Option<&JsState>, want: Option<i64>, secs: f64, hold: f64, marked: (i64, i64)) -> String {
+ let frame = want.map_or("?".to_string(), |w| w.to_string());
+ let quiet = if self.timers_only { format!("{:.0} s (its JS thread ran only timers, committing nothing)", secs.max(hold)) } else { format!("{secs} s") };
+ format!("the composition made no progress on frame {frame} for {quiet}, its marker at frame {} (done {}).{} Does it throw? Its [js] lines are above, and `raea traces show last` has the run's log", marked.0, marked.1, self.thread(js))
+ }
+ /// What the thread was doing when the settle gave up, as a sentence ("" with no JS thread).
+ fn thread(&self, js: Option<&JsState>) -> String {
+ let Some(j) = js else { return String::new() };
+ let idle = j.since(&j.idle_since).map_or("busy or waiting on a timer".to_string(), |d| format!("idle for {:.1} s with nothing scheduled", d.as_secs_f64()));
+ let asked = if self.nudges > 0 { format!(", asked for the frame again {} times", self.nudges) } else { String::new() };
+ let unheard = j.unheard.load(SeqCst);
+ let stopped = if unheard > 0 { format!("; its event loop had stopped taking events ({unheard} went unread: an error thrown out of an event handler?)") } else { String::new() };
+ format!(" Its JS thread was {idle}{asked}{stopped}.")
+ }
+}
diff --git a/sdk/react/js/src/prelude.js b/sdk/react/js/src/prelude.js
index c2341cbc..9c00aa13 100644
--- a/sdk/react/js/src/prelude.js
+++ b/sdk/react/js/src/prelude.js
@@ -38,7 +38,18 @@
const m = json === null ? null : JSON.parse(json);
// the World's shared values that changed (B3 H4): to @raea/app's hooks.ts store, not the bridge
if (m && m.t === "event" && m.name === "raea-world") { if (g.__raea_world) g.__raea_world(m.value); return; }
- if (waiter) { const w = waiter; waiter = null; w(m); } else inbox.push(m);
+ // 1: handed to the bridge's waiting loop; 0: queued with no one waiting. Between the host's calls the loop always
+ // waits on op_next_event, so a 0 means it has stopped, and the host says so if a frame then never comes (#158)
+ if (waiter) { const w = waiter; waiter = null; w(m); return 1; }
+ inbox.push(m);
+ return 0;
+ };
+ // the bridge's event loop ended by a throw (an error out of an event handler's flushSync, which nothing caught): put
+ // where Rust reads a composition's error, so the render fails naming it, not waiting on a loop that stopped (#158)
+ g.__raea_loop_died = (e) => {
+ const msg = "the composition's event loop stopped: " + (e && e.message ? (e.name || "Error") + ": " + e.message + (e.stack ? "\n" + e.stack : "") : String(e));
+ console.error("[js] " + msg);
+ __raea_flush(JSON.stringify([{ op: "create", id: 2 ** 52 - 1, kind: "div", props: { "data-raea-error": msg.slice(0, 4000) } }]));
};
// Number's toLocaleString through one Intl.NumberFormat per locale and options, kept: the spec's toLocaleString(l, o)
// is new Intl.NumberFormat(l, o).format(n), and JavaScriptCore made that formatter at every call. A counter a
diff --git a/tools/dupes.max b/tools/dupes.max
index 7646c7b0..96bd92b6 100644
--- a/tools/dupes.max
+++ b/tools/dupes.max
@@ -19,5 +19,5 @@
# io/capcut store.rs:67 (tasklist's stdout, lower-cased; sdk/ui/parity main.rs:88 trims a command's stdout),
# io/capcut build.rs:24 parse (serde_json::from_str + expect; engine/native node.rs:172 js_string, to_string), and
# apps/capcut plan.rs:67 (a box moved more than 1 px; systems/layout mod.rs:406, within 1.5 px)
-exact=293
+exact=292
near=59
diff --git a/tools/settle-nudge.sh b/tools/settle-nudge.sh
new file mode 100755
index 00000000..1f8e4c6d
--- /dev/null
+++ b/tools/settle-nudge.sh
@@ -0,0 +1,41 @@
+#!/bin/bash
+# #158: a frame a render's runtime loses is asked for again, and one lost for good fails with a named error instead of
+# a render that waits forever. RAEA_FAULT_DROP_EVENT (runtime/react thread.rs) loses the 3D rows' raea-frames event:
+# 1. the first one only: the render finishes, saying it asked for the frames again
+# 2. every one: the render fails within a minute, naming the frame and that its JS thread sat idle
+# Usage: tools/settle-nudge.sh [RAEA_BINARY] (default: raea on PATH)
+set -uo pipefail
+RAEA=${1:-raea}
+T=$(mktemp -d "${TMPDIR:-/tmp}/settle-nudge.XXXX")
+trap 'rm -rf "${T:?}"' EXIT
+# a command killed (SIGALRM, exit 142) once it has run SECS: macOS has no timeout(1)
+limit() { local s=$1; shift; perl -e 'alarm shift @ARGV; exec @ARGV or die "exec: $!"' "$s" "$@"; }
+cat >"$T/comp.tsx" <<'EOF'
+import React from "react";
+import { AbsoluteFill, Composition, registerRoot, useCurrentFrame } from "raea";
+const C = () => {
+ const f = useCurrentFrame();
+ return <AbsoluteFill style={{ background: "#123" }}><div style={{ position: "absolute", left: f % 200, top: 40, width: 40, height: 40, background: "#fc0" }} /></AbsoluteFill>;
+};
+registerRoot(() => <Composition id="nudge" component={C} width={320} height={180} fps={30} durationInFrames={600} />);
+EOF
+fail=0
+# 1: the first raea-frames lost
+out=$(cd "$T" && RAEA_AUDIO_MUTE=1 RAEA_FAULT_DROP_EVENT=raea-frames limit 120 "$RAEA" render comp.tsx -o "$T/one.png" --frame 300 2>&1)
+code=$?
+if [ $code -eq 0 ] && [ -s "$T/one.png" ] && grep -q "asked for frames" <<<"$out"; then
+ echo "ok 1: a lost frame was asked for again and the render finished"
+else
+ echo "FAIL 1: exit $code (142 is the time limit: it hung)"; tail -5 <<<"$out"; fail=1
+fi
+# 2: every raea-frames lost
+t0=$(date +%s)
+out=$(cd "$T" && RAEA_AUDIO_MUTE=1 RAEA_FAULT_DROP_EVENT='raea-frames*' limit 150 "$RAEA" render comp.tsx -o "$T/two.png" --frame 300 2>&1)
+code=$?
+dt=$(( $(date +%s) - t0 ))
+if [ $code -ne 0 ] && [ $code -ne 142 ] && grep -q "made no progress on frame" <<<"$out" && grep -q "idle for" <<<"$out"; then
+ echo "ok 2: a frame lost for good failed in ${dt}s, naming it"
+else
+ echo "FAIL 2: exit $code after ${dt}s (142 is the time limit: it hung)"; tail -5 <<<"$out"; fail=1
+fi
+exit $fail