diff --git a/bench/realtime/cases/held.tsx b/bench/realtime/cases/held.tsx new file mode 100644 index 00000000..38829663 --- /dev/null +++ b/bench/realtime/cases/held.tsx @@ -0,0 +1,26 @@ +// A prop the running world can't take (docs/realtime.feature RT4g): the hero cube's size, which lands in the mesh's +// shape, a column the live scene keeps from the part's first frame (runtime/scene/src/live.rs live_dynamic). The stage +// answers stage.props with the part it held, and a written file with only the value changed is opened again rather +// than taken in place, so the frame matches the render after all. +import { AbsoluteFill, Composition, registerRoot, useCurrentFrame } from "raea"; +import { Camera3d } from "raea/camera"; +import { AmbientLight, DirectionalLight } from "raea/light"; +import { Cuboid, Mesh3d } from "raea/mesh"; +import { StandardMaterial } from "raea/pbr"; +import { Transform } from "raea/transform"; + +function Held({ size = 0.6 }: { size?: number }) { + const f = useCurrentFrame(); + const a = 0.4 + f * 0.012; + return ( + + + + + + + + ); +} + +registerRoot(() => ); diff --git a/bench/realtime/stage.mjs b/bench/realtime/stage.mjs index dbedbf53..68a60b0d 100644 --- a/bench/realtime/stage.mjs +++ b/bench/realtime/stage.mjs @@ -4,17 +4,29 @@ // UPDATES draws of that frame (a paused stage draws again on a pointer move: one engine update each) // 2. stage.props {PROP: B} on that running world: the frame drawn again with them (ab), captured the same way, and // the time from the call to the stage's next painted frame -// 3. the same frame seeked to again, as the app's useStage does after props on a paused stage (abs): the time from +// 3. the same frame seeked to again, as the app's useStage did after props on a paused stage (abs): the time from // the props call to the frame it paints, and captures as above -// 4. the copy with B written into defaultProps shown fresh and captured the same way (b) -// Captures are the window's own frame (frame_png), one window point a stage pixel. Writes OUT/{a,ab,abs,b}-K.png and -// OUT/stage.json ({ props_ms, steps, window, scale }). -// node bench/realtime/stage.mjs PORT OUT A.tsx B.tsx PROP VALUE_JSON FRAME W H UPDATES +// 4. a drag (RT4e): DRAGS props changes one after another, A and B in turn (ending on B), each waited for until +// painted: the milliseconds from each call to the window's next painted frame (over MCP, an upper bound) and the +// stage's own (status.props.ms: the call taken to the frame in the stage's texture), p50 and p95 +// 5. a burst: BURST props sent at once from the page (rt.calls), ending on B, as a drag sends them faster than a +// frame draws: how many the stage passed over (newest wins), how many it drew, the values it ends on, and the +// frame captured once (burst) +// 6. the copy with B written into defaultProps shown over it (RT4f): taken in place when only values changed and +// the 3D keeps none of them (status.last_show "adopted"), else opened; the time to its frame, captured (ad) +// 7. the copy shown fresh (the stage cleared first, so it is opened) and captured the same way (b) +// Captures are the window's own frame (frame_png), one window point a stage pixel. Writes OUT/{a,ab,abs,burst,ad,b}-K.png +// and OUT/stage.json ({ props_ms, drag, burst, adopt, steps, window, scale }). +// node bench/realtime/stage.mjs PORT OUT A.tsx B.tsx PROP A_JSON B_JSON FRAME W H UPDATES [MODE] +// MODE: render (the default: stage.show {render: true}, drawn as `raea render` draws it) or live (as a game: the +// stage's own session). RT_DRAGS (30) and RT_BURST (12) size steps 4 and 5. import { writeFileSync } from "node:fs"; -const [port, out, fileA, fileB, prop, valueJson, frameS, wS, hS, updatesS] = process.argv.slice(2); +const [port, out, fileA, fileB, prop, aJson, valueJson, frameS, wS, hS, updatesS, modeS] = process.argv.slice(2); const N = Number(frameS), W = Number(wS), H = Number(hS), UPDATES = Number(updatesS ?? 3); -const value = JSON.parse(valueJson); +const was0 = JSON.parse(aJson), value = JSON.parse(valueJson); +const RENDER = (modeS ?? "render") !== "live"; +const DRAGS = Number(process.env.RT_DRAGS ?? 30), BURST = Number(process.env.RT_BURST ?? 12); let id = 0; async function tool(name, args = {}) { const r = await fetch(`http://127.0.0.1:${port}/mcp`, { @@ -98,11 +110,15 @@ async function captures(tag) { console.error(`captured ${tag}-${k}`); } } +const pct = (xs, p) => { + const v = [...xs].sort((a, b) => a - b); + return v.length ? Math.round(v[Math.min(v.length - 1, Math.floor((p / 100) * v.length))] * 10) / 10 : null; +}; async function show(file, tag) { const t0 = Date.now(); // answered once sent; an answer that didn't come back in time (the stage thread opening the last file) is waited // out by the status below - await stage("stage.show", { src: file, w: W, h: H }).catch((e) => console.error(`show: ${e.message}`)); + await stage("stage.show", { src: file, w: W, h: H, render: RENDER }).catch((e) => console.error(`show: ${e.message}`)); await until(`${tag} opened`, (s) => s.showing === file && s.painted > 0, 180_000); const opened = Date.now() - t0; await stage("stage.play", { on: false }); @@ -124,7 +140,9 @@ try { const answer = await stage("stage.props", { props: { [prop]: value } }); const answered = performance.now() - t0; await until("props drawn", (s) => s.painted > was, 30_000); - result.props_ms = { answered: Math.round(answered), painted: Math.round(performance.now() - t0), answer }; + const after = await status(); + result.props_ms = { answered: Math.round(answered), painted: Math.round(performance.now() - t0), stage: after.props?.ms ?? null, answer }; + result.held = answer?.held ?? null; await captures("ab"); // props, then the frame seeked to again behind them (the app sends the seek without waiting for the props' answer; // here it follows the answer, so the time is an upper bound by one round trip) @@ -135,7 +153,57 @@ try { await until("props and seek drawn", (s) => s.painted >= was2 + 2 && s.frame === N, 30_000); result.props_seek_ms = Math.round(performance.now() - t1); await captures("abs"); + // a drag: each change waited for until painted + const wall = [], own = []; + for (let i = 0; i < DRAGS; i++) { + const v = i % 2 === 0 ? was0 : value; + const w = (await status()).painted; + const t = performance.now(); + await stage("stage.props", { props: { [prop]: v } }); + const s = await until(`drag ${i}`, (s) => s.painted > w && s.props?.ms > 0, 30_000); + wall.push(performance.now() - t); + own.push(s.props.ms); + } + result.drag = { n: DRAGS, wall_p50: pct(wall, 50), wall_p95: pct(wall, 95), stage_p50: pct(own, 50), stage_p95: pct(own, 95), stage_max: pct(own, 100) }; + console.error(`drag ${JSON.stringify(result.drag)}`); + // a burst, ending on B (the drag ended on B too: the frame is compared against B's render either way) + if (BURST > 0) { + const s0 = await status(); + const calls = Array.from({ length: BURST }, (_, i) => ({ name: "stage.props", args: { props: { [prop]: (BURST - 1 - i) % 2 === 0 ? value : was0 } } })); + const t = performance.now(); + const res = await tool("action", { name: "rt.calls", args: { calls } }); + const answers = JSON.parse(text(res) ?? "null"); + const answered = performance.now() - t; + // each props set is passed over or drawn (painted in the stage's turn that took it) + const s1 = await until("burst drawn", (s) => s.props.drawn + s.props.dropped >= s0.props.drawn + s0.props.dropped + BURST, 30_000); + const list = Array.isArray(answers) ? answers : answers?.value; + result.burst = { sent: BURST, answered_ms: Math.round(answered), dropped: s1.props.dropped - s0.props.dropped, drawn: s1.props.drawn - s0.props.drawn, ends_on: s1.values?.[prop], dropped_answers: Array.isArray(list) ? list.filter((a) => a?.value?.dropped).length : null }; + console.error(`burst ${JSON.stringify(result.burst)}`); + await tool("frame_png"); + await png(`${out}/burst-0.png`); + } + // the copy written with B: taken in place, or opened when the 3D held the value + { + const s0 = await status(); + const t = performance.now(); + await stage("stage.show", { src: fileB, w: W, h: H, render: RENDER }).catch((e) => console.error(`adopt: ${e.message}`)); + const s1 = await until("copy shown", (s) => s.showing === fileB && (s.adopted > s0.adopted || s.opens > s0.opens) && s.painted > 0, 180_000); + let s2 = s1; + if (s1.opens > s0.opens) { + // opened: paused and seeked back to N, as the app's useStage does after a reopen + await stage("stage.play", { on: false }); + const w = (await status()).painted; + await stage("stage.seek", { frame: N }); + s2 = await until("reopened at N", (s) => s.frame === N && s.painted > w && !s.playing, 60_000); + } else await until("adopted drawn", (s) => s.painted > s0.painted, 30_000); + result.adopt = { how: s1.last_show?.how, stage_ms: s1.last_show?.ms, wall_ms: Math.round(performance.now() - t), frame: s2.frame, playing: s2.playing, values: s2.values?.[prop] }; + console.error(`adopt ${JSON.stringify(result.adopt)}`); + await captures("ad"); + } + await stage("stage.show", { src: null, w: W, h: H }).catch((e) => console.error(`clear: ${e.message}`)); + await until("cleared", (s) => s.showing == null, 30_000); await show(fileB, "b"); + result.status = await status(); result.ok = true; } catch (e) { result.ok = false; @@ -143,5 +211,5 @@ try { console.error(`FAIL ${result.error}`); } writeFileSync(`${out}/stage.json`, JSON.stringify(result, null, 1)); -console.log(JSON.stringify({ ok: result.ok, props_ms: result.props_ms, props_seek_ms: result.props_seek_ms, steps: result.steps, window: result.window, scale: result.scale, error: result.error })); +console.log(JSON.stringify({ ok: result.ok, props_ms: result.props_ms, props_seek_ms: result.props_seek_ms, held: result.held, drag: result.drag, burst: result.burst, adopt: result.adopt, steps: result.steps, window: result.window, scale: result.scale, error: result.error })); process.exit(result.ok ? 0 : 1); diff --git a/bench/realtime/stage/page.tsx b/bench/realtime/stage/page.tsx index cf68fafa..00add9a5 100644 --- a/bench/realtime/stage/page.tsx +++ b/bench/realtime/stage/page.tsx @@ -1,13 +1,24 @@ // The page the realtime bench drives (bench/realtime/stage.sh): nothing but the engine's stage, its image filling the // window at one window point a stage pixel, so a capture of the window is the stage's own frame. One action, // `rt.call {name, args}`, makes any stage host call (engine/page/stage: stage.show, stage.seek, stage.props, ...) and -// answers what it answered, so a driver outside the page plays the stage as the app's useStage does. +// answers what it answered, so a driver outside the page plays the stage as the app's useStage does; `rt.calls +// {calls: [{name, args}]}` makes several at once without waiting between them, as a drag sends props (each answer, in +// order, and the milliseconds to each). import "@raea/ui/dom-globals"; import { mount } from "@raea/ui/react"; import { call, emit, on } from "@raea/ui/wire"; -emit("actions", [{ name: "rt.call", about: "a stage host call: {name, args}", args: {} }]); -on<{ id: number; name: string; args?: { name: string; args?: unknown } }>("action", ({ id, name, args }) => { +emit("actions", [ + { name: "rt.call", about: "a stage host call: {name, args}", args: {} }, + { name: "rt.calls", about: "several stage host calls sent at once: {calls: [{name, args}]}", args: {} }, +]); +type One = { name: string; args?: unknown }; +on<{ id: number; name: string; args?: One & { calls?: One[] } }>("action", ({ id, name, args }) => { + if (name === "rt.calls" && Array.isArray(args?.calls)) { + const t0 = performance.now(); + const sent = args.calls.map((c) => call(c.name, c.args ?? null).then((value) => ({ value: value === undefined ? null : JSON.parse(JSON.stringify(value)), ms: performance.now() - t0 }), (e: unknown) => ({ error: String((e as Error)?.message ?? e), ms: performance.now() - t0 }))); + return void Promise.all(sent).then((value) => emit("actionDone", { id, value })); + } if (name !== "rt.call" || !args?.name) return emit("actionDone", { id, error: `no action ${name}` }); call(args.name, args.args ?? null).then( (value) => emit("actionDone", { id, value: value === undefined ? null : JSON.parse(JSON.stringify(value)) }), diff --git a/docs/layout-reads.feature b/docs/layout-reads.feature index 0752cc1c..e1bc044f 100644 --- a/docs/layout-reads.feature +++ b/docs/layout-reads.feature @@ -147,6 +147,38 @@ Feature: Layout reads: a composition measures its text and layout as Chrome does --offscreen --no-vsync, 5 s, twice): a frame's step p50 0.39-0.41 ms without the read, 1.8-2.0 ms with it; work p50 3.8-4.2 ms against 4.3-5.0 ms. Under a tenth of a 60 fps frame. + @needs:LR1 @done + Scenario: LR12. A read in a stepped range lets settle take every frame (#158) + Given a range of frames stepped back to back (raea-frames: the 3D rows' pre-pass, a bake), its commits applied + one a pass (OneBatch) + And a component reads its layout in an effect while frames of the range wait in the queue + Then the read is answered once every commit sent before it is applied, one a pass, and each pass's commit is read + for the frame's marker as any commit is + And a frame the runtime has gone past with nothing left to apply is asked for again at once, and fails the + settle in seconds, naming the frame and where the runtime is, when asking doesn't bring it back + And 11-16, built: + - settle answered a read by applying every queued commit at once and going on, unread. The frames queued + behind the read went by, and settle waited on a frame already gone: for good on 0.1.4 (the main thread in + wait_flush, the JS idle), 20 to 120 s and "made no progress" on 0.1.5. It came by chance, when a read + landed while frames were queued, so long renders with more runtimes hit it more often. + - The read is answered only when nothing is queued (raea-runtime-react's queued); until then the loop takes + a commit a pass and checks the marker. Settling's gone and nudge (raea-runtime-shared stall.rs) are the + watchdog. + - runtime/bake/tests/reads.rs: a hand-written bundle steps frames 0 to 3 and reads after the last, all + queued before settle looks. Before: "made no progress on frame 0 for 5 s, its marker at frame 3 (done 3)". + After: each frame's settle returns at that frame, 0.4 s for the four. + - A repro shaped like the report (2160x3840, 30 fps, 752 frames: Sequences, an @font-face font, Imgs, the + six-layer Freeze blur, a component that measures itself in a layout effect) rendered with --alpha to a + folder of PNGs: 0.1.5 refused it after 21 s with no frame written; the fix wrote all 752 + frames in 72 s. Its pre-pass alone (raea scene light) failed every run before, and passed 12 of 12 after. + + Scenario: LR13. A pre-pass's runtimes keep their errors apart + Given a render's 3D-rows pre-pass runs several runtimes in one process, each with its own ask (LR1) + Then a composition's thrown error (COMPOSITION_ERROR) and a bundle's (BUNDLE_ERROR) are each runtime's own, as + its LayoutAsk is + And today they are process-wide statics: whichever runtime's settle looks first takes the error, so the render + still fails, but it can name the wrong runtime's frame + Rule: a ref has the DOM a web component reads @needs:LR1 @done diff --git a/runtime/react/src/commits.rs b/runtime/react/src/commits.rs index 549b1934..fdfdd43c 100644 --- a/runtime/react/src/commits.rs +++ b/runtime/react/src/commits.rs @@ -192,6 +192,15 @@ pub(crate) fn apply_commits( } } +/// The commits a OneBatch runtime has yet to apply, what React has sent since moved to its queue unapplied (None for a +/// runtime that applies everything sent each update). +pub(crate) fn queued(world: &mut World) -> Option { + let sent: Vec = world.contains_resource::().then(|| world.get_resource::().map(|i| i.0.lock().unwrap().try_iter().collect()).unwrap_or_default())?; + let mut q = world.resource_mut::(); + q.0.extend(sent); + Some(q.0.len()) +} + /// One pass of apply_commits timed and its allocations counted, into APPLY_NS and APPLY_ALLOC* as it drops. pub(crate) struct ApplyTimer(pub(crate) Instant, pub(crate) (u64, u64)); impl Drop for ApplyTimer { diff --git a/runtime/react/src/lib.rs b/runtime/react/src/lib.rs index 4b0e1e23..eccfa5a0 100644 --- a/runtime/react/src/lib.rs +++ b/runtime/react/src/lib.rs @@ -211,56 +211,10 @@ static FLUSHED: (Mutex, std::sync::Condvar) = (Mutex::new(0), std::sync::Co /// Where a frame's step goes: nanoseconds the JS thread ran (timers, events, microtasks), nanoseconds Bevy spent /// applying commits (JSON parse, entities, the page mirror), and bytes of commit JSON sent. Read as deltas per frame. pub static JS_NS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); -/// When the JS threads' current calls began, in ms after JS_BASE plus 1 (0: none is in a call): a render's settle counts -/// a call still running as progress (a frame's render under load can take seconds before its first flush). A render runs -/// several runtimes, each with a JS thread, so JS_CALLS counts the calls under way and the time is cleared only when the -/// last ends: one thread's call ending zeroed it while another's ran on (film.tsx frame 1334 under load, 10-27). -pub static JS_CALL_SINCE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); -pub static JS_BASE: std::sync::LazyLock = std::sync::LazyLock::new(Instant::now); -pub static JS_CALLS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); -/// Which call began the current run of calls: its runtime (numbered as each JS thread starts, from 1) times 2, plus 1 -/// for an event's delivery (__raea_deliver: a frame's render) or 0 for timers (__raea_timers), so a hang's refusal -/// names it -static JS_CALL_WHO: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); -static JS_RUNTIMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); -thread_local! { - static JS_RUNTIME: std::cell::Cell = const { std::cell::Cell::new(0) }; -} +// the process's JS calls across its runtimes (raea-runtime-shared calls.rs) +pub use shared::{js_call_for, js_call_who}; +use shared::{js_call_begins, js_call_ends, js_runtime_starts}; -/// The call that began the current run of calls, in words: "JS runtime 2 of 3's __raea_deliver (a frame's render)". -pub fn js_call_who() -> String { - let who = JS_CALL_WHO.load(std::sync::atomic::Ordering::SeqCst); - let what = if who % 2 == 1 { "__raea_deliver (a frame's render)" } else { "__raea_timers (its timers and effects)" }; - format!("JS runtime {} of {}'s {what}", who / 2, JS_RUNTIMES.load(std::sync::atomic::Ordering::SeqCst)) -} - -/// How long the JS threads have been in calls without a break, if one is in a call (JS_CALLS decides: an ending call can -/// clear the time just after another began, which reads as a call just begun). -pub fn js_call_for() -> Option { - use std::sync::atomic::Ordering::SeqCst; - if JS_CALLS.load(SeqCst) == 0 { - return None; - } - let at = JS_CALL_SINCE.load(SeqCst); - Some(if at == 0 { Duration::ZERO } else { JS_BASE.elapsed().saturating_sub(Duration::from_millis(at - 1)) }) -} - -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(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); - } -} /// This thread at macOS's user-interactive QoS (the class a game's frame threads get): under load from other processes a /// default-QoS JS thread was preempted for ~30 ms at a time, and a 120 fps game missed frames (pong: 8 in 36,000 with a /// load average of 4-10). Live play's JS thread and the thread that steps its frames take it. diff --git a/runtime/react/src/scene/settle.rs b/runtime/react/src/scene/settle.rs index 236534ac..5cef45b3 100644 --- a/runtime/react/src/scene/settle.rs +++ b/runtime/react/src/scene/settle.rs @@ -77,16 +77,19 @@ pub fn settle_with(app: &mut App, want: Option, secs: f64, answer: &mut cra if let Some(e) = crate::COMPOSITION_ERROR.lock().unwrap().take() { return Err(format!("the composition threw at frame {}: {e}", want.map(|w| w.to_string()).unwrap_or("?".into()))); } - // a layout read waiting: every commit sent before it applied (one an update with OneBatch), then answered, and - // the loop goes on (the read's thread carries on from its effect, so more commits and the marker follow) + // a layout read waiting is answered once every commit sent before it is applied (its batch is sent before the + // effect that reads runs), then the read's thread carries on. With OneBatch one a pass, each read for the marker + // below: applied at once, unread, a stepped range's frames queued behind the read went by for good (#158) if let Some(ask) = ask.as_deref().filter(|a| a.asked()) { - // (the read's own commit can land after this pass's update: its batch is sent before its effects run) - app.world_mut().run_schedule(PreUpdate); - while app.world().get_resource::().is_some_and(|q| !q.0.is_empty()) { - app.world_mut().run_schedule(PreUpdate); + match crate::queued(app.world_mut()) { + None => { + app.world_mut().run_schedule(PreUpdate); + crate::layout::answer_if_asked(ask, app.world_mut(), answer); + continue; + } + Some(0) => crate::layout::answer_if_asked(ask, app.world_mut(), answer), + Some(_) => {} } - crate::layout::answer_if_asked(ask, app.world_mut(), answer); - continue; } let world = app.world_mut(); // the marker's entity, remembered (a scan of every entity's props for it each pass was most of a settle) @@ -138,14 +141,17 @@ pub fn settle_with(app: &mut App, want: Option, secs: f64, answer: &mut cra // 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 gone = want.is_some_and(|w| watch.gone(w, marked.0)); 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::().is_some_and(|q| !q.0.is_empty()) { + // commits held to be applied one an update (OneBatch), and any sent since: the next is applied without waiting + let queued = crate::queued(app.world_mut()); + if queued.is_some_and(|n| n > 0) { continue; } - // a stepped range's frame lost (#158): its runtime idle, the frame neither drawn nor held. Asked for again (pure) + // a stepped range's frame lost (#158): its runtime idle, the frame neither drawn nor held, or gone by with nothing + // left to apply. Asked for again (pure), and refused at once when that doesn't bring it back (stall.rs) if let (Some(j), Some(s), Some(o)) = (&js, app.world().get_resource::(), app.world().get_resource::()) - && watch.nudge(j, want.unwrap_or(-1), s.to, held, marked) + && watch.nudge(j, want.unwrap_or(-1), s.to, held, gone && queued == Some(0), marked)? { o.send(serde_json::json!({"t": "event", "name": "raea-frames", "value": {"from": want, "to": s.to}})); } @@ -155,10 +161,7 @@ pub fn settle_with(app: &mut App, want: Option, secs: f64, answer: &mut cra 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 ` 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(watch.refusal(js.as_deref(), want, secs, HOLD_SECS, marked)) + Err(watch.refusal(js.as_deref(), want, secs, HOLD_SECS, held, 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 d2248ba0..8161804e 100644 --- a/runtime/react/src/thread.rs +++ b/runtime/react/src/thread.rs @@ -53,7 +53,7 @@ pub(crate) fn js_thread(bundle: PathBuf, tx: Sender, events: Receiver c, Err(e) => { diff --git a/runtime/shared/src/calls.rs b/runtime/shared/src/calls.rs new file mode 100644 index 00000000..48853486 --- /dev/null +++ b/runtime/shared/src/calls.rs @@ -0,0 +1,60 @@ +//! The process's JS calls, counted across its runtimes: settle's no-progress guard where an App has no JsState (a +//! replay's), and the call a hang's refusal names. Each runtime's own are its JsState (stall.rs). + +use std::sync::atomic::{AtomicU64, Ordering::SeqCst}; +use std::time::{Duration, Instant}; + +use crate::JsState; + +/// When the JS threads' current calls began, in ms after JS_BASE plus 1 (0: none is in a call): a render's settle counts +/// a call still running as progress (a frame's render under load can take seconds before its first flush). A render runs +/// several runtimes, each with a JS thread, so JS_CALLS counts the calls under way and the time is cleared only when the +/// last ends: one thread's call ending zeroed it while another's ran on (film.tsx frame 1334 under load, 10-27). +static JS_CALL_SINCE: AtomicU64 = AtomicU64::new(0); +static JS_BASE: std::sync::LazyLock = std::sync::LazyLock::new(Instant::now); +static JS_CALLS: AtomicU64 = AtomicU64::new(0); +/// Which call began the current run of calls: its runtime (numbered as each JS thread starts, from 1) times 2, plus 1 +/// for an event's delivery (__raea_deliver: a frame's render) or 0 for timers (__raea_timers), so a hang's refusal +/// names it +static JS_CALL_WHO: AtomicU64 = AtomicU64::new(0); +static JS_RUNTIMES: AtomicU64 = AtomicU64::new(0); +thread_local! { + static JS_RUNTIME: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// This thread is a runtime's JS thread: numbered, from 1, for js_call_who. +pub fn js_runtime_starts() { + JS_RUNTIME.set(JS_RUNTIMES.fetch_add(1, SeqCst) + 1); +} + +/// The call that began the current run of calls, in words: "JS runtime 2 of 3's __raea_deliver (a frame's render)". +pub fn js_call_who() -> String { + let who = JS_CALL_WHO.load(SeqCst); + let what = if who % 2 == 1 { "__raea_deliver (a frame's render)" } else { "__raea_timers (its timers and effects)" }; + format!("JS runtime {} of {}'s {what}", who / 2, JS_RUNTIMES.load(SeqCst)) +} + +/// How long the JS threads have been in calls without a break, if one is in a call (JS_CALLS decides: an ending call can +/// clear the time just after another began, which reads as a call just begun). +pub fn js_call_for() -> Option { + if JS_CALLS.load(SeqCst) == 0 { + return None; + } + let at = JS_CALL_SINCE.load(SeqCst); + Some(if at == 0 { Duration::ZERO } else { JS_BASE.elapsed().saturating_sub(Duration::from_millis(at - 1)) }) +} + +pub fn js_call_begins(deliver: bool, state: &JsState) { + 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); + } +} + +pub fn js_call_ends(state: &JsState) { + state.in_call(false); + if JS_CALLS.fetch_sub(1, SeqCst) == 1 { + JS_CALL_SINCE.store(0, SeqCst); + } +} diff --git a/runtime/shared/src/lib.rs b/runtime/shared/src/lib.rs index bb9253c7..5588c13c 100644 --- a/runtime/shared/src/lib.rs +++ b/runtime/shared/src/lib.rs @@ -37,6 +37,9 @@ 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}; +/// the process's JS calls across its runtimes, as a settle with no JsState and a hang's refusal read them +mod calls; +pub use calls::{js_call_begins, js_call_ends, js_call_for, js_call_who, js_runtime_starts}; /// 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 index 223ec594..91f2c0c0 100644 --- a/runtime/shared/src/stall.rs +++ b/runtime/shared/src/stall.rs @@ -132,12 +132,14 @@ pub struct Settling { nudged: Instant, /// refused because the thread only ran timers, committing nothing timers_only: bool, + /// the marker has been at or before the frame in this settle (gone) + reached: 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 } + Settling { still: now, moved: (u64::MAX, u64::MAX, f64::NAN), drawn: now, drew: (u64::MAX, f64::NAN), nudges: 0, nudged: now, timers_only: false, reached: false } } } @@ -157,22 +159,42 @@ impl Settling { 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; + /// Whether frame `want` has gone by in this settle (called each pass with the marker's frame `at`, -2 before it's + /// found): the marker was at or before it and is now past it. A stepped range's frames only move forward, so the + /// frame can't come by itself. (A marker past the frame from the start is a range stepped after a later one.) + pub fn gone(&mut self, want: i64, at: i64) -> bool { + self.reached |= (-1..=want).contains(&at); + want >= 0 && self.reached && at > want + } + /// Whether to ask frame `want` again now (said on stderr): a range is stepped (`to`), the frame isn't held, and either + /// the runtime has gone past it (`past`: gone, nothing left to apply) or its 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 + /// unless past (the range's own event may not be taken yet; a frame gone by is asked for at once). A frame gone by + /// and still gone after every ask, the last that long ago with the thread in no call, is the settle's refusal, at + /// once (Err): waiting out its time would change nothing. + pub fn nudge(&mut self, js: &JsState, want: i64, to: i64, held: bool, past: bool, marked: (i64, i64)) -> Result { + let free = js.call_since.load(SeqCst) == 0; + let idle = free && js.since(&js.idle_since).is_some_and(|d| d.as_secs_f64() >= NUDGE_IDLE_SECS); + let spaced = self.nudged.elapsed().as_secs_f64() >= 2.0 * NUDGE_IDLE_SECS; + if past && free && spaced && self.nudges >= NUDGES { + return Err(format!("frame {want} went by without being read: its runtime stepped on to frame {} (done {}) with nothing left to apply, so the frame can't come, and asking for it again {NUDGES} times didn't bring it back. This is raea's fault, not the composition's: `raea bug` reports it", marked.0, marked.1)); + } + if !(idle || past) || held || want < 0 || want >= to || self.nudges >= NUDGES || !(spaced || past && self.nudges == 0) { + return Ok(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 + let why = if past { format!("frame {want} went by without being read (its runtime's marker is past it, at frame {} done {})", marked.0, marked.1) } else { format!("frame {want}'s runtime went idle without drawing it (its marker at frame {} done {})", marked.0, marked.1) }; + eprintln!("raea: {why}: asked for frames {want}..{to} again ({} of {NUDGES})", self.nudges); + Ok(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, secs: f64, hold: f64, marked: (i64, i64)) -> String { + /// The settle's refusal of frame `want` after `secs` with nothing moving (`hold`, when only timers ran, or the frame + /// `held` that long), 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, secs: f64, hold: f64, held: bool, marked: (i64, i64)) -> String { + if held { + return format!("frame {want:?} was held for {hold} s and never released: a delayRender never continued, or a scene that never finished loading"); + } 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)) @@ -187,3 +209,29 @@ impl Settling { format!(" Its JS thread was {idle}{asked}{stopped}.") } } + +#[cfg(test)] +mod tests { + use super::*; + + /// A stepped frame its runtime went past is asked for again at once, a thread busy or not, and not again until the + /// ask has had its time; a marker past the frame from the start (a range stepped after a later one) isn't gone. + #[test] + fn a_frame_gone_by_is_asked_for_at_once() { + let js = JsState::default(); + js.in_call(true); + let mut w = Settling::default(); + assert!(!w.gone(10, -2) && !w.gone(10, 50), "no marker yet, then an earlier range's, past the frame"); + assert_eq!(w.nudge(&js, 10, 20, false, false, (50, 50)), Ok(false), "a thread in a call, the frame not gone"); + assert!(!w.gone(10, 10)); + assert!(w.gone(10, 12)); + assert_eq!(w.nudge(&js, 10, 20, false, true, (12, 12)), Ok(true), "a frame gone by is asked for at once"); + assert_eq!(w.nudge(&js, 10, 20, false, true, (12, 12)), Ok(false), "and not again within 2 x NUDGE_IDLE_SECS"); + js.in_call(false); + w.nudges = NUDGES; + w.nudged = Instant::now() - std::time::Duration::from_secs_f64(2.0 * NUDGE_IDLE_SECS); + let e = w.nudge(&js, 10, 20, false, true, (12, 12)).unwrap_err(); + assert!(e.starts_with("frame 10 went by without being read: its runtime stepped on to frame 12"), "{e}"); + assert!(!Settling::default().gone(-1, 3), "the settings' settle has no frame to go past"); + } +}