feat(oakrender): render-process isolation S2 - process backend by default, zero-copy onscreen
- WorkerPool thread pool deleted; RenderManager defaults to the Processes backend (oak-worker children), Threads kept as a test-only inline dispatcher; audio tickets stay in-process until S3. - Onscreen path reads worker shm slots directly: BGRA8 slot format, RenderedFrame::Shm wrapped into the display buffer (single disclosed GPU-staging memcpy), scopes analyze BGRA8; the long-lived full-res / thumbnail paths take the counted slot_to_vec copy and release. - Playback pre-render window: forward 120 frames (configurable) fed to the PreviewScheduler at Playback priority, interleaved across workers, cached in shm slots until the playhead consumes them; generation-based invalidation cancels and releases on edits. - oaktask export and oak-cli run on private ProcessDispatchers (fixed a pump-while-locked self-deadlock in the export loop); facade get_frame handles ShmFrame payloads. - Acceptance: preview path main_heap_frame_copies == 0 with spawned workers, CLI transcode/render verified end to end.
This commit is contained in:
@@ -297,7 +297,7 @@ mod tests {
|
||||
|
||||
use crate::frame::VideoParamsPod;
|
||||
use crate::texture::{Frame, Texture};
|
||||
use crate::worker::WorkerPool;
|
||||
use crate::worker::{InlineDispatcher, JobDispatch};
|
||||
|
||||
fn frame_producer() -> crate::ticket::Producer {
|
||||
Arc::new(|_, _| {
|
||||
@@ -311,16 +311,18 @@ mod tests {
|
||||
})
|
||||
}
|
||||
|
||||
fn new_cacher() -> (PreviewAutoCacher, WorkerPool) {
|
||||
let mut pool = WorkerPool::new(2);
|
||||
pool.start();
|
||||
let arena = Arc::new(TicketArena::new(Arc::new(pool.clone()), frame_producer()));
|
||||
(PreviewAutoCacher::new(arena), pool)
|
||||
/// A cacher on a queued inline dispatcher: jobs run only when the test
|
||||
/// drains it with `InlineDispatcher::run` (deterministic ordering, no
|
||||
/// worker threads).
|
||||
fn new_cacher() -> (PreviewAutoCacher, Arc<InlineDispatcher>) {
|
||||
let d = InlineDispatcher::queued();
|
||||
let arena = Arc::new(TicketArena::new(d.clone(), frame_producer()));
|
||||
(PreviewAutoCacher::new(arena), d)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attach_detach_lifecycle() {
|
||||
let (mut c, mut pool) = new_cacher();
|
||||
let (mut c, d) = new_cacher();
|
||||
assert!(c.attach(0).is_err(), "zero identity rejected");
|
||||
c.attach(42).unwrap();
|
||||
assert_eq!(c.copied_project, 42);
|
||||
@@ -332,31 +334,32 @@ mod tests {
|
||||
c.detach();
|
||||
assert_eq!(c.copied_project, 0);
|
||||
assert!(c.live_jobs().is_empty());
|
||||
pool.shutdown();
|
||||
d.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_frame_cancels_previous() {
|
||||
// The race this asserts ("the previous frame is cancelled") is only
|
||||
// deterministic when the first job cannot finish before the
|
||||
// superseding submit lands — produce frames slowly for this test.
|
||||
let (mut c, mut pool) = new_cacher_slow();
|
||||
// The race this asserts ("the previous frame is cancelled") is
|
||||
// deterministic on the queued inline dispatcher: the first job stays
|
||||
// queued until `run`, so the superseding submit's cancel lands first.
|
||||
let (mut c, d) = new_cacher_slow();
|
||||
c.attach(7);
|
||||
let first = c.single_frame(Rational::new(0, 1));
|
||||
let second = c.single_frame(Rational::new(1, 1));
|
||||
assert_ne!(first, second);
|
||||
// The first ticket is cancelled: its completion fired with State.
|
||||
d.run();
|
||||
c.arena.wait(first).unwrap();
|
||||
let r = c.arena.result(first).unwrap();
|
||||
assert!(r.is_err());
|
||||
pool.shutdown();
|
||||
d.shutdown();
|
||||
}
|
||||
|
||||
/// A cacher whose frames take ~100ms to produce (see
|
||||
/// [`single_frame_cancels_previous`]).
|
||||
fn new_cacher_slow() -> (PreviewAutoCacher, WorkerPool) {
|
||||
let mut pool = WorkerPool::new(2);
|
||||
pool.start();
|
||||
/// [`single_frame_cancels_previous`] — the sleep is irrelevant on the
|
||||
/// queued dispatcher, kept for the original async-backend semantics).
|
||||
fn new_cacher_slow() -> (PreviewAutoCacher, Arc<InlineDispatcher>) {
|
||||
let d = InlineDispatcher::queued();
|
||||
let producer: crate::ticket::Producer = Arc::new(|_, _| {
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
let mut f = Frame::new();
|
||||
@@ -367,41 +370,43 @@ mod tests {
|
||||
f.allocate();
|
||||
Ok(crate::ticket::TicketPayload::Video(Texture::wrap_frame(f)))
|
||||
});
|
||||
let arena = Arc::new(TicketArena::new(Arc::new(pool.clone()), producer));
|
||||
(PreviewAutoCacher::new(arena), pool)
|
||||
let arena = Arc::new(TicketArena::new(d.clone(), producer));
|
||||
(PreviewAutoCacher::new(arena), d)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignore_requests_suppresses_jobs() {
|
||||
let (mut c, mut pool) = new_cacher();
|
||||
let (mut c, d) = new_cacher();
|
||||
c.attach(7);
|
||||
c.ignore_requests = true;
|
||||
c.on_cache_request(7, TimeRange::new(Rational::new(0, 1), Rational::new(5, 1)));
|
||||
assert!(c.live_jobs().is_empty());
|
||||
pool.shutdown();
|
||||
d.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renders_paused_queues_but_does_not_start() {
|
||||
let (mut c, mut pool) = new_cacher();
|
||||
let (mut c, d) = new_cacher();
|
||||
c.attach(7);
|
||||
c.renders_paused = true;
|
||||
c.on_cache_request(7, TimeRange::new(Rational::new(0, 1), Rational::new(5, 1)));
|
||||
assert!(c.live_jobs().is_empty(), "paused: no jobs started");
|
||||
assert_eq!(c.pending_requests().len(), 1);
|
||||
pool.shutdown();
|
||||
d.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_video_tasks_wait_blocks_until_idle() {
|
||||
let (mut c, mut pool) = new_cacher();
|
||||
let (mut c, d) = new_cacher();
|
||||
c.attach(7);
|
||||
c.force_range(TimeRange::new(Rational::new(0, 1), Rational::new(1, 1)));
|
||||
assert!(c.is_rendering_custom_range() || c.live_jobs().len() == 1);
|
||||
// Drain so the wait below observes every job finished.
|
||||
d.run();
|
||||
c.cancel_video_tasks(true);
|
||||
assert!(c.live_jobs().iter().all(|id| c.arena.is_finished(*id)));
|
||||
assert!(!c.is_rendering_custom_range());
|
||||
pool.shutdown();
|
||||
d.shutdown();
|
||||
}
|
||||
|
||||
struct Probe {
|
||||
@@ -421,7 +426,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn events_deliver_progress() {
|
||||
let (mut c, mut pool) = new_cacher();
|
||||
let (mut c, d) = new_cacher();
|
||||
let probe = Arc::new(Probe {
|
||||
progress: AtomicU32::new(0),
|
||||
stop: AtomicU32::new(0),
|
||||
@@ -432,7 +437,7 @@ mod tests {
|
||||
c.request_stop_proxy_tasks();
|
||||
assert_eq!(probe.progress.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(probe.stop.load(Ordering::Relaxed), 1);
|
||||
pool.shutdown();
|
||||
d.shutdown();
|
||||
}
|
||||
|
||||
struct ProbeEvents {
|
||||
@@ -450,25 +455,23 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn clear_finished_single_frames_removes_done() {
|
||||
let (mut c, mut pool) = new_cacher();
|
||||
let (mut c, d) = new_cacher();
|
||||
c.attach(7);
|
||||
let id = c.single_frame(Rational::new(0, 1));
|
||||
d.run();
|
||||
c.arena.wait(id).unwrap();
|
||||
assert_eq!(c.live_jobs().len(), 1, "finished job still tracked");
|
||||
c.clear_finished_single_frames();
|
||||
assert!(c.live_jobs().is_empty());
|
||||
pool.shutdown();
|
||||
d.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noop_events_sink_never_panics() {
|
||||
let mut c = {
|
||||
let mut pool = WorkerPool::new(1);
|
||||
pool.start();
|
||||
let arena = Arc::new(TicketArena::new(Arc::new(pool.clone()), frame_producer()));
|
||||
let c = PreviewAutoCacher::new(arena);
|
||||
pool.shutdown();
|
||||
c
|
||||
let d = InlineDispatcher::sync();
|
||||
let arena = Arc::new(TicketArena::new(d, frame_producer()));
|
||||
PreviewAutoCacher::new(arena)
|
||||
};
|
||||
c.set_events(Box::new(NoopEvents));
|
||||
c.report_progress(1.0);
|
||||
|
||||
@@ -25,7 +25,8 @@
|
||||
//! - `cache` — PlaybackCache/FrameHashCache family + disk state
|
||||
//! - `color` — ColorProcessor over `ocio-rs` + LUT library
|
||||
//! - `ticket` — ticket arena with exactly-once completion
|
||||
//! - `worker` — worker pool + graph snapshot store
|
||||
//! - `worker` — the JobDispatch seam + thread-free inline dispatcher +
|
||||
//! graph snapshot store (the in-process thread pool was deleted in M15 S2)
|
||||
//! - `manager` — RenderManager singleton + disk cache
|
||||
//! - `autocacher` — PreviewAutoCacher
|
||||
//! - `eval` — the evaluation seam (RenderHooks)
|
||||
|
||||
@@ -14,8 +14,8 @@
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! The render manager: process-wide singleton owning the worker pool,
|
||||
//! the ticket arena, the auto-cacher, and backend selection
|
||||
//! The render manager: process-wide singleton owning the process
|
||||
//! dispatcher, the ticket arena, the auto-cacher, and backend selection
|
||||
//! (C++ `RenderManager`).
|
||||
//!
|
||||
//! The singleton lives behind a `Mutex<Option<Arc<…>>>` so `init` /
|
||||
@@ -31,9 +31,9 @@ use crate::autocacher::PreviewAutoCacher;
|
||||
use crate::backend::BackendKind;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::eval;
|
||||
use crate::procpool::{DispatcherConfig, ProcessDispatcher};
|
||||
use crate::procpool::{DispatcherConfig, ProcessDispatcher, ShmFrameRef};
|
||||
use crate::ticket::{TicketArena, TicketId};
|
||||
use crate::worker::{JobDispatch, WorkerPool};
|
||||
use crate::worker::{InlineDispatcher, JobDispatch};
|
||||
|
||||
static MANAGER: Mutex<Option<Arc<RenderManager>>> = Mutex::new(None);
|
||||
|
||||
@@ -41,23 +41,26 @@ fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||
m.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// The render backend the manager initializes (M15 S1: the thread pool
|
||||
/// and the process-isolated dispatcher coexist; S2 makes Processes the
|
||||
/// default and removes the pool).
|
||||
/// The render backend the manager initializes (M15 S2).
|
||||
pub enum RenderBackendChoice {
|
||||
/// In-process thread pool (the default; C++ parity).
|
||||
/// In-process thread-free dispatch (**test-only** after M15 S2: the
|
||||
/// internal render thread pool was deleted by mandate; this backend
|
||||
/// runs jobs synchronously on the calling thread). Kept so manager /
|
||||
/// integration tests do not spawn oak-worker children.
|
||||
Threads,
|
||||
/// Process-isolated oak-worker pool (crash isolation + shm frames).
|
||||
/// The M15 S2 default.
|
||||
Processes(DispatcherConfig),
|
||||
}
|
||||
|
||||
/// The manager. Created by `oakrender_manager_init` (C ABI), accessed
|
||||
/// internally through [`RenderManager::global`].
|
||||
pub struct RenderManager {
|
||||
/// Video job dispatch (thread pool or process dispatcher, M15).
|
||||
/// Video job dispatch (the process dispatcher, M15).
|
||||
pub dispatch: Arc<dyn JobDispatch>,
|
||||
/// Audio job dispatch — kept on main-process threads until S3
|
||||
/// (design §3.7: crash risk is dominated by video plugins).
|
||||
/// Audio job dispatch — kept on main-process inline execution until S3
|
||||
/// (design §3.7: crash risk is dominated by video plugins, which live
|
||||
/// in oak-worker).
|
||||
pub audio_dispatch: Arc<dyn JobDispatch>,
|
||||
/// Ticket arena.
|
||||
pub tickets: Arc<TicketArena>,
|
||||
@@ -73,16 +76,16 @@ pub struct RenderManager {
|
||||
}
|
||||
|
||||
impl RenderManager {
|
||||
/// Initialize the process-wide manager with the default backend
|
||||
/// (in-process threads; idempotent; C++ instance() semantics — only
|
||||
/// the main GUI process does this).
|
||||
/// Initialize the process-wide manager with the default backend — the
|
||||
/// process-isolated oak-worker pool (M15 S2 mandate; idempotent; C++
|
||||
/// instance() semantics — only the main GUI process does this).
|
||||
pub fn init() -> Result<()> {
|
||||
Self::init_with_backend(RenderBackendChoice::Threads)
|
||||
Self::init_with_backend(RenderBackendChoice::Processes(DispatcherConfig::default()))
|
||||
}
|
||||
|
||||
/// Initialize the process-wide manager with an explicit backend
|
||||
/// (M15 S1: `Threads` keeps the C++ parity path, `Processes` spawns
|
||||
/// the oak-worker pool).
|
||||
/// Initialize the process-wide manager with an explicit backend.
|
||||
/// `Threads` is the test-only inline backend (no worker threads, no
|
||||
/// child processes); `Processes` spawns the oak-worker pool.
|
||||
pub fn init_with_backend(choice: RenderBackendChoice) -> Result<()> {
|
||||
let mut guard = lock(&MANAGER);
|
||||
if guard.is_some() {
|
||||
@@ -96,18 +99,19 @@ impl RenderManager {
|
||||
let (dispatch, audio_dispatch): (Arc<dyn JobDispatch>, Arc<dyn JobDispatch>) =
|
||||
match choice {
|
||||
RenderBackendChoice::Threads => {
|
||||
let mut pool = WorkerPool::new(0);
|
||||
pool.start();
|
||||
let pool = Arc::new(pool);
|
||||
(pool.clone(), pool)
|
||||
// Test-only inline backend: synchronous execution on the
|
||||
// calling thread, shared by video and audio.
|
||||
let inline = InlineDispatcher::sync();
|
||||
(inline.clone(), inline)
|
||||
}
|
||||
RenderBackendChoice::Processes(config) => {
|
||||
let dispatcher = ProcessDispatcher::new(config)?;
|
||||
dispatcher.start()?;
|
||||
// Audio stays on main-process threads (design §3.7).
|
||||
let mut audio = WorkerPool::new(2);
|
||||
audio.start();
|
||||
(dispatcher, Arc::new(audio))
|
||||
// Audio stays on main-process inline execution until S3
|
||||
// (design §3.7): render_audio_samples runs synchronously
|
||||
// on the posting thread.
|
||||
let audio = InlineDispatcher::sync();
|
||||
(dispatcher, audio)
|
||||
}
|
||||
};
|
||||
let tickets = Arc::new(TicketArena::new_with_audio(
|
||||
@@ -147,14 +151,35 @@ impl RenderManager {
|
||||
if let Some(manager) = manager {
|
||||
manager.tickets.cancel_all();
|
||||
// Drain after the cancels so queued completions fire. Both
|
||||
// dispatches are idempotent (the Threads backend shares one
|
||||
// Arc for video + audio).
|
||||
// dispatches are idempotent.
|
||||
manager.dispatch.shutdown();
|
||||
manager.audio_dispatch.shutdown();
|
||||
drop(manager);
|
||||
}
|
||||
}
|
||||
|
||||
/// Pump the video backend's control plane (M15 S2): the process
|
||||
/// dispatcher delivers ticket completions from its poll loop, so the
|
||||
/// UI tick and any blocking wait must call this regularly. No-op on
|
||||
/// backends that deliver inline.
|
||||
pub fn poll(&self) {
|
||||
self.dispatch.poll();
|
||||
}
|
||||
|
||||
/// Release a consumed shm frame's slot back to its worker (M15 S2
|
||||
/// zero-copy onscreen path: slot release = cache eviction). No-op on
|
||||
/// backends that hold no slots.
|
||||
pub fn release_frame(&self, frame: &ShmFrameRef) {
|
||||
self.dispatch.release_frame(frame);
|
||||
}
|
||||
|
||||
/// Cancel every pending AND claimed frame of `sequence` (M15 S2
|
||||
/// preview-window invalidation); their completions fire with
|
||||
/// `Error::State`. No-op on backends that schedule no window.
|
||||
pub fn cancel_preview_sequence(&self, sequence: u64) {
|
||||
self.dispatch.cancel_preview_sequence(sequence);
|
||||
}
|
||||
|
||||
/// Aggressive-GC toggle (C++ `SetAggressiveGarbageCollection`).
|
||||
pub fn set_aggressive_gc(&self, on: bool) {
|
||||
self.aggressive_gc.store(on, Ordering::Release);
|
||||
@@ -243,19 +268,22 @@ mod tests {
|
||||
#[test]
|
||||
fn init_shutdown_roundtrip() {
|
||||
let _lock = manager_lock();
|
||||
// Ensure a clean slate.
|
||||
// Ensure a clean slate. The manager tests use the test-only inline
|
||||
// backend (the process backend spawns real oak-worker children).
|
||||
RenderManager::shutdown();
|
||||
RenderManager::init().unwrap();
|
||||
RenderManager::init_with_backend(RenderBackendChoice::Threads).unwrap();
|
||||
assert!(RenderManager::global().is_some());
|
||||
// Idempotence: second init is a state error.
|
||||
assert_eq!(
|
||||
RenderManager::init().unwrap_err().code(),
|
||||
RenderManager::init_with_backend(RenderBackendChoice::Threads)
|
||||
.unwrap_err()
|
||||
.code(),
|
||||
Error::State.code()
|
||||
);
|
||||
RenderManager::shutdown();
|
||||
assert!(RenderManager::global().is_none());
|
||||
// Re-init works after shutdown (C++ destroy_instance semantics).
|
||||
RenderManager::init().unwrap();
|
||||
RenderManager::init_with_backend(RenderBackendChoice::Threads).unwrap();
|
||||
RenderManager::shutdown();
|
||||
}
|
||||
|
||||
@@ -263,7 +291,7 @@ mod tests {
|
||||
fn aggressive_gc_toggle() {
|
||||
let _lock = manager_lock();
|
||||
RenderManager::shutdown();
|
||||
RenderManager::init().unwrap();
|
||||
RenderManager::init_with_backend(RenderBackendChoice::Threads).unwrap();
|
||||
let m = RenderManager::global().unwrap();
|
||||
assert!(!m.aggressive_gc());
|
||||
m.set_aggressive_gc(true);
|
||||
@@ -275,7 +303,7 @@ mod tests {
|
||||
fn cacher_is_lazily_created() {
|
||||
let _lock = manager_lock();
|
||||
RenderManager::shutdown();
|
||||
RenderManager::init().unwrap();
|
||||
RenderManager::init_with_backend(RenderBackendChoice::Threads).unwrap();
|
||||
let m = RenderManager::global().unwrap();
|
||||
{
|
||||
let g = m.get_cacher();
|
||||
|
||||
@@ -49,9 +49,12 @@
|
||||
//! worker dead: its claimed frames are re-queued to the scheduler
|
||||
//! (any healthy worker may claim them), the child is reaped, the
|
||||
//! segment recreated and the process respawned (bounded restarts).
|
||||
//! - **Coexistence.** S1 keeps the in-process [`crate::worker::WorkerPool`]
|
||||
//! alive; [`crate::manager::RenderManager`] picks the backend at
|
||||
//! init. S2 deletes the thread pool.
|
||||
//! - **S2 model.** The in-process [`crate::worker::WorkerPool`] is
|
||||
//! gone (M15 S2 mandate); [`crate::manager::RenderManager`] defaults
|
||||
//! to this backend. The ticket arena also routes **playback-window**
|
||||
//! frames here via [`JobSchedule::playback`], and the app pumps the
|
||||
//! control plane from the UI tick ([`ProcessDispatcher::poll`]) and
|
||||
//! from blocking ticket waits.
|
||||
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::io::Write as _;
|
||||
@@ -71,7 +74,7 @@ use crate::ipc::{
|
||||
WireMontageClip, SLOT_FORMAT_BGRA8, TYPE_BATCH_ACCEPTED, TYPE_ERROR, TYPE_FRAME_FAILED,
|
||||
TYPE_FRAME_READY, TYPE_HANDSHAKE, TYPE_HELLO_CAPS,
|
||||
};
|
||||
use crate::scheduler::{FrameKey, FramePriority, FrameRequest, PreviewScheduler};
|
||||
use crate::scheduler::{FrameKey, FrameRequest, PreviewScheduler, SubmitOutcome};
|
||||
use crate::ticket::{Completion, TicketPayload, TicketResult, VideoTicketParams};
|
||||
use crate::worker::{Job, JobDispatch};
|
||||
|
||||
@@ -261,6 +264,45 @@ impl std::fmt::Debug for ShmFrameRef {
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Slot pixel conversions (M15 S2)
|
||||
// ---------------------------------------------------------------------------
|
||||
//
|
||||
// The process backend writes BGRA8 into slots (the viewer preview format).
|
||||
// Long-lived consumers that need the bytes in a different order/format
|
||||
// convert once after copying out of the slot.
|
||||
|
||||
/// Convert a BGRA8 block into an RGBA8 block (swapping R and B). Used by
|
||||
/// PNG writers (footage thumbnails) and PPM/CLI output, which require
|
||||
/// RGB-order buffers. `src.len()` must be a multiple of 4.
|
||||
pub fn bgra8_to_rgba8(src: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(src.len());
|
||||
for px in src.chunks_exact(4) {
|
||||
out.push(px[2]); // R
|
||||
out.push(px[1]); // G
|
||||
out.push(px[0]); // B
|
||||
out.push(px[3]); // A
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Convert a BGRA8 block into tightly-packed F32 RGBA samples (`0..=1`).
|
||||
/// Used by the export/encoder path, which declares F32 input: the worker
|
||||
/// converts its F32 pipeline output to BGRA8 for the slot (design §3.1),
|
||||
/// and the export converts back — a necessary conversion at the encoder
|
||||
/// boundary with 8-bit quantization (S2; per-ticket slot formats are S3
|
||||
/// work).
|
||||
pub fn bgra8_to_f32_rgba(src: &[u8]) -> Vec<f32> {
|
||||
let mut out = Vec::with_capacity(src.len() / 4 * 4);
|
||||
for px in src.chunks_exact(4) {
|
||||
out.push(f32::from(px[2]) / 255.0); // R
|
||||
out.push(f32::from(px[1]) / 255.0); // G
|
||||
out.push(f32::from(px[0]) / 255.0); // B
|
||||
out.push(f32::from(px[3]) / 255.0); // A
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Configuration
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -1128,10 +1170,15 @@ impl ProcessDispatcher {
|
||||
|
||||
impl JobDispatch for ProcessDispatcher {
|
||||
/// Submit one frame job (the ticket-arena seam). The job joins the
|
||||
/// scheduler as a Seek-priority request and is dispatched on the
|
||||
/// next pump; the completion fires with
|
||||
/// scheduler under its [`JobSchedule`] (Seek single-frame by default,
|
||||
/// Playback for the pre-render window, Background for exports) and is
|
||||
/// dispatched on the next pump; the completion fires with
|
||||
/// `TicketPayload::ShmFrame(ShmFrameRef)` — never a pixel buffer.
|
||||
/// Re-submitting a key that is still pending replaces the old request
|
||||
/// and cancels its ticket; a key already in flight is left running
|
||||
/// (its result is still valid for the same params).
|
||||
fn post(&self, job: Job) -> bool {
|
||||
let mut fired: Vec<(Completion, TicketResult)> = Vec::new();
|
||||
{
|
||||
let mut inner = lock(&self.inner);
|
||||
if inner.shutting_down {
|
||||
@@ -1139,10 +1186,11 @@ impl JobDispatch for ProcessDispatcher {
|
||||
}
|
||||
let id = inner.next_ticket;
|
||||
inner.next_ticket += 1;
|
||||
let frame = job.schedule.frame.unwrap_or(id);
|
||||
let key = FrameKey {
|
||||
sequence: job.node_identity,
|
||||
frame: id,
|
||||
version: 0,
|
||||
frame,
|
||||
version: job.schedule.version,
|
||||
};
|
||||
inner.tickets.insert(
|
||||
id,
|
||||
@@ -1152,18 +1200,73 @@ impl JobDispatch for ProcessDispatcher {
|
||||
done: Some(job.done),
|
||||
},
|
||||
);
|
||||
inner.scheduler.submit(FrameRequest {
|
||||
let request = FrameRequest {
|
||||
key,
|
||||
priority: FramePriority::Seek,
|
||||
distance: 0,
|
||||
priority: job.schedule.priority,
|
||||
distance: job.schedule.distance,
|
||||
payload: id,
|
||||
});
|
||||
};
|
||||
match inner.scheduler.submit(request) {
|
||||
SubmitOutcome::Accepted => {}
|
||||
SubmitOutcome::Replaced(old) => {
|
||||
// A newer request for the same key superseded the old
|
||||
// pending one: cancel the old ticket's completion.
|
||||
if let Some(pt) = inner.tickets.get_mut(&old.payload) {
|
||||
if let Some(done) = pt.done.take() {
|
||||
fired.push((done, Err(Error::State)));
|
||||
}
|
||||
}
|
||||
}
|
||||
SubmitOutcome::InFlight => {
|
||||
// Already claimed by a worker; the rendered frame is
|
||||
// still valid for the same params (playback window
|
||||
// slides re-request frames that are in flight).
|
||||
}
|
||||
}
|
||||
}
|
||||
for (done, result) in fired {
|
||||
done(result);
|
||||
}
|
||||
// Pump once so a live worker picks the frame up immediately.
|
||||
self.poll();
|
||||
true
|
||||
}
|
||||
|
||||
/// Cancel every pending AND claimed request of `sequence` (M15 S2
|
||||
/// preview-window invalidation — graph/proxy/resolution/color bump or
|
||||
/// a sequence switch). Dropped completions fire `Error::State`;
|
||||
/// frames already dispatched recycle their slots when the late
|
||||
/// `frame_ready` arrives.
|
||||
fn cancel_preview_sequence(&self, sequence: u64) {
|
||||
let mut fired: Vec<(Completion, TicketResult)> = Vec::new();
|
||||
{
|
||||
let mut inner = lock(&self.inner);
|
||||
let dropped = inner.scheduler.cancel_sequence(sequence);
|
||||
for request in dropped {
|
||||
if let Some(pt) = inner.tickets.get_mut(&request.payload) {
|
||||
if let Some(done) = pt.done.take() {
|
||||
fired.push((done, Err(Error::State)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (done, result) in fired {
|
||||
done(result);
|
||||
}
|
||||
}
|
||||
|
||||
/// Pump the control plane (delegates to the inherent poll — the UI
|
||||
/// tick and blocking ticket waits call this through the trait seam).
|
||||
fn poll(&self) {
|
||||
self.poll();
|
||||
}
|
||||
|
||||
/// Release a consumed frame's slot (delegates to the inherent
|
||||
/// release — see [`ProcessDispatcher::release_frame`]).
|
||||
fn release_frame(&self, frame: &ShmFrameRef) {
|
||||
self.release_frame(frame);
|
||||
}
|
||||
|
||||
/// Graceful shutdown: `shutdown` messages, a short drain pumping
|
||||
/// completions, then kill stragglers; every ticket still open
|
||||
/// completes with `Error::State`.
|
||||
|
||||
@@ -62,9 +62,10 @@ pub struct FrameKey {
|
||||
}
|
||||
|
||||
/// Frame request priority class (lower value = more urgent).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Default)]
|
||||
pub enum FramePriority {
|
||||
/// Seek / current playhead frame (single-frame insert, top priority).
|
||||
#[default]
|
||||
Seek,
|
||||
/// Playback window frames (ordered by [`FrameRequest::distance`]).
|
||||
Playback,
|
||||
@@ -112,6 +113,19 @@ struct PendingEntry<P> {
|
||||
any_worker: bool,
|
||||
}
|
||||
|
||||
/// The outcome of [`PreviewScheduler::submit`].
|
||||
#[derive(Debug)]
|
||||
pub enum SubmitOutcome<P> {
|
||||
/// A new request was accepted (nothing was pending under its key).
|
||||
Accepted,
|
||||
/// An existing pending request under the same key was replaced; the
|
||||
/// superseded request is returned so the dispatcher can cancel its
|
||||
/// ticket completion (M15 S2).
|
||||
Replaced(FrameRequest<P>),
|
||||
/// The key is already claimed (in flight); the request was rejected.
|
||||
InFlight,
|
||||
}
|
||||
|
||||
/// The scheduler state machine (single-threaded by contract).
|
||||
pub struct PreviewScheduler<P> {
|
||||
workers: usize,
|
||||
@@ -155,21 +169,25 @@ impl<P: Clone> PreviewScheduler<P> {
|
||||
|
||||
/// Submit a frame request. An already-pending request with the same
|
||||
/// key is replaced; a key already claimed (in flight) is rejected —
|
||||
/// the dispatcher must cancel/re-version it first. Returns true when
|
||||
/// the request was accepted.
|
||||
pub fn submit(&mut self, request: FrameRequest<P>) -> bool {
|
||||
/// the dispatcher must cancel/re-version it first.
|
||||
pub fn submit(&mut self, request: FrameRequest<P>) -> SubmitOutcome<P> {
|
||||
if self.claimed.contains_key(&request.key) {
|
||||
return false;
|
||||
return SubmitOutcome::InFlight;
|
||||
}
|
||||
if let Some(entry) = self.pending.iter_mut().find(|e| e.request.key == request.key) {
|
||||
entry.request = request;
|
||||
return true;
|
||||
let old = std::mem::replace(&mut entry.request, request);
|
||||
return SubmitOutcome::Replaced(old);
|
||||
}
|
||||
self.pending.push(PendingEntry {
|
||||
request,
|
||||
any_worker: false,
|
||||
});
|
||||
true
|
||||
SubmitOutcome::Accepted
|
||||
}
|
||||
|
||||
/// Whether `key` is currently claimed (in flight).
|
||||
pub fn is_claimed(&self, key: &FrameKey) -> bool {
|
||||
self.claimed.contains_key(key)
|
||||
}
|
||||
|
||||
/// Claim the next batch for `worker`: the worker's interleaved shard
|
||||
@@ -300,14 +318,27 @@ impl<P: Clone> PreviewScheduler<P> {
|
||||
|
||||
/// Cancel every pending AND claimed frame of `sequence` (frame-key
|
||||
/// invalidation; the `cancel` wire message covers the worker side).
|
||||
/// Returns the number of dropped requests.
|
||||
pub fn cancel_sequence(&mut self, sequence: u64) -> usize {
|
||||
let before_pending = self.pending.len();
|
||||
self.pending.retain(|e| e.request.key.sequence != sequence);
|
||||
let dropped_pending = before_pending - self.pending.len();
|
||||
let before_claimed = self.claimed.len();
|
||||
self.claimed.retain(|_, c| c.request.key.sequence != sequence);
|
||||
dropped_pending + (before_claimed - self.claimed.len())
|
||||
/// Returns the dropped requests so the dispatcher can fire their
|
||||
/// completions with `Error::State`.
|
||||
pub fn cancel_sequence(&mut self, sequence: u64) -> Vec<FrameRequest<P>> {
|
||||
let mut dropped = Vec::new();
|
||||
self.pending.retain(|e| {
|
||||
if e.request.key.sequence == sequence {
|
||||
dropped.push(e.request.clone());
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
});
|
||||
self.claimed.retain(|_, c| {
|
||||
if c.request.key.sequence == sequence {
|
||||
dropped.push(c.request.clone());
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
});
|
||||
dropped
|
||||
}
|
||||
|
||||
/// Pending (unclaimed) request count.
|
||||
@@ -373,7 +404,7 @@ mod tests {
|
||||
fn no_stealing_every_frame_claimed_exactly_once() {
|
||||
let mut s: PreviewScheduler<u64> = PreviewScheduler::new(3, 4);
|
||||
for f in 0..40 {
|
||||
assert!(s.submit(req(1, f, FramePriority::Playback)));
|
||||
assert!(matches!(s.submit(req(1, f, FramePriority::Playback)), SubmitOutcome::Accepted));
|
||||
}
|
||||
let claims = claim_all(&mut s);
|
||||
assert_eq!(claims.len(), 40, "every frame claimed");
|
||||
@@ -527,14 +558,42 @@ mod tests {
|
||||
let mut s: PreviewScheduler<u64> = PreviewScheduler::new(1, 4);
|
||||
let r = req(1, 5, FramePriority::Playback);
|
||||
let key = r.key;
|
||||
s.submit(r);
|
||||
assert!(matches!(s.submit(r), SubmitOutcome::Accepted));
|
||||
let _ = s.claim_batch(0, 4).unwrap();
|
||||
// In flight: rejected.
|
||||
assert!(!s.submit(req(1, 5, FramePriority::Seek)));
|
||||
assert!(matches!(
|
||||
s.submit(req(1, 5, FramePriority::Seek)),
|
||||
SubmitOutcome::InFlight
|
||||
));
|
||||
s.frame_done(&key);
|
||||
// After completion the same key may be requested again (new
|
||||
// version in practice).
|
||||
assert!(s.submit(req(1, 5, FramePriority::Seek)));
|
||||
assert!(matches!(
|
||||
s.submit(req(1, 5, FramePriority::Seek)),
|
||||
SubmitOutcome::Accepted
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resubmit_replaces_pending_and_returns_the_old_request() {
|
||||
let mut s: PreviewScheduler<u64> = PreviewScheduler::new(1, 4);
|
||||
let first = req(1, 5, FramePriority::Playback);
|
||||
let key = first.key;
|
||||
assert!(matches!(s.submit(first), SubmitOutcome::Accepted));
|
||||
// A second submission under the same key replaces the pending entry
|
||||
// and hands the superseded request back (the dispatcher cancels its
|
||||
// ticket completion with Error::State).
|
||||
let second = req(1, 5, FramePriority::Seek);
|
||||
let second_key = second.key;
|
||||
match s.submit(second) {
|
||||
SubmitOutcome::Replaced(old) => {
|
||||
assert_eq!(old.key, key);
|
||||
assert_eq!(old.priority, FramePriority::Playback);
|
||||
}
|
||||
other => panic!("expected Replaced, got {other:?}"),
|
||||
}
|
||||
let _ = s.claim_batch(0, 4).unwrap();
|
||||
assert_eq!(s.claimed_worker(&second_key), Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -545,7 +604,8 @@ mod tests {
|
||||
}
|
||||
let _ = s.claim_batch(0, 4).unwrap(); // claims 4 of sequence 7
|
||||
s.submit(req(8, 0, FramePriority::Playback)); // other sequence
|
||||
assert_eq!(s.cancel_sequence(7), 6);
|
||||
let dropped = s.cancel_sequence(7);
|
||||
assert_eq!(dropped.len(), 6, "all 6 sequence-7 requests dropped");
|
||||
assert_eq!(s.pending_count(), 1, "sequence 8 untouched");
|
||||
assert_eq!(s.claimed_count(), 0);
|
||||
}
|
||||
|
||||
+128
-48
@@ -33,7 +33,7 @@ use oakcore_rs::{Rational, TimeRange};
|
||||
use crate::error::{Error, Result};
|
||||
use crate::eval;
|
||||
use crate::texture::Texture;
|
||||
use crate::worker::JobDispatch;
|
||||
use crate::worker::{JobDispatch, JobSchedule};
|
||||
|
||||
/// One clip of a sequence montage (M12 P0): the facade resolves the
|
||||
/// timeline into an ordered list of clips; the producer decodes each and
|
||||
@@ -194,11 +194,21 @@ struct TicketSlot {
|
||||
delivered: AtomicBool,
|
||||
completion: Mutex<Option<Completion>>,
|
||||
result: Mutex<Option<Arc<TicketResult>>>,
|
||||
/// The dispatch the ticket posted through (M15 S2: a cancelled ticket
|
||||
/// whose render completed must recycle its shm slot — the consumer
|
||||
/// never sees the `ShmFrame` payload).
|
||||
dispatch: Arc<dyn JobDispatch>,
|
||||
}
|
||||
|
||||
impl TicketSlot {
|
||||
fn finish(&self, mut result: TicketResult) {
|
||||
if self.cancel.load(Ordering::Acquire) {
|
||||
// A cancelled ticket still holds its shm slot when the render
|
||||
// completed: recycle it now, before the payload is replaced by
|
||||
// `Error::State` and the consumer loses it.
|
||||
if let Ok(TicketPayload::ShmFrame(frame)) = &result {
|
||||
self.dispatch.release_frame(frame);
|
||||
}
|
||||
result = Err(Error::State);
|
||||
}
|
||||
// Publish the result before flipping the state flag: `wait()` only
|
||||
@@ -296,12 +306,27 @@ impl TicketArena {
|
||||
|
||||
/// Submit a video ticket with a caller-reserved id (allocated by
|
||||
/// [`TicketArena::next_id`]); completion fires exactly once, including
|
||||
/// on cancellation (with `Error::State`).
|
||||
/// on cancellation (with `Error::State`). The job posts as a Seek
|
||||
/// single-frame request (M15 S2; see
|
||||
/// [`TicketArena::submit_playback`] for the pre-render window).
|
||||
pub fn submit_video_with_id(
|
||||
&self,
|
||||
id: TicketId,
|
||||
params: VideoTicketParams,
|
||||
done: Completion,
|
||||
) -> TicketId {
|
||||
self.submit_video_impl(id, params, done, JobSchedule::seek())
|
||||
}
|
||||
|
||||
/// The shared video-ticket submit path: register the slot, post the
|
||||
/// job with `schedule` (M15 S2), and deliver `Error::State`
|
||||
/// immediately when the backend is gone.
|
||||
fn submit_video_impl(
|
||||
&self,
|
||||
id: TicketId,
|
||||
params: VideoTicketParams,
|
||||
done: Completion,
|
||||
schedule: JobSchedule,
|
||||
) -> TicketId {
|
||||
let meta = TicketMeta {
|
||||
kind: Some(ticket_kind::VIDEO),
|
||||
@@ -322,6 +347,7 @@ impl TicketArena {
|
||||
delivered: AtomicBool::new(false),
|
||||
completion: Mutex::new(Some(done)),
|
||||
result: Mutex::new(None),
|
||||
dispatch: self.dispatch.clone(),
|
||||
});
|
||||
self.allocate(slot.clone());
|
||||
|
||||
@@ -334,6 +360,7 @@ impl TicketArena {
|
||||
params,
|
||||
produce: producer,
|
||||
done: Box::new(move |result| slot_done.finish(result)),
|
||||
schedule,
|
||||
};
|
||||
if !self.dispatch.post(job) {
|
||||
// Backend is gone (shutdown raced the submit): deliver now.
|
||||
@@ -342,6 +369,51 @@ impl TicketArena {
|
||||
id
|
||||
}
|
||||
|
||||
/// Submit a playback-window frame (M15 S2 pre-render window): the
|
||||
/// frame joins the scheduler at Playback priority, ordered by
|
||||
/// `distance` from the playhead and keyed under `version`. `frame` is
|
||||
/// the sequence frame number (the scheduler key / interleaved shard).
|
||||
/// The completion fires (from the dispatcher's poll) with
|
||||
/// `TicketPayload::ShmFrame`.
|
||||
pub fn submit_playback(
|
||||
&self,
|
||||
params: VideoTicketParams,
|
||||
frame: i64,
|
||||
distance: i64,
|
||||
version: u64,
|
||||
done: Completion,
|
||||
) -> TicketId {
|
||||
let id = self.next_id();
|
||||
self.submit_video_impl(
|
||||
id,
|
||||
params,
|
||||
done,
|
||||
JobSchedule::playback(frame, distance, version),
|
||||
)
|
||||
}
|
||||
|
||||
/// Submit a Background-priority frame (M15 S2 exports/precache): the
|
||||
/// scheduler renders it whenever no Seek/Playback work is pending.
|
||||
pub fn submit_video_background(
|
||||
&self,
|
||||
params: VideoTicketParams,
|
||||
done: Completion,
|
||||
) -> TicketId {
|
||||
let id = self.next_id();
|
||||
self.submit_video_background_with_id(id, params, done)
|
||||
}
|
||||
|
||||
/// [`TicketArena::submit_video_background`] with a caller-reserved id
|
||||
/// (the export loop pre-allocates ids through [`TicketArena::next_id`]).
|
||||
pub fn submit_video_background_with_id(
|
||||
&self,
|
||||
id: TicketId,
|
||||
params: VideoTicketParams,
|
||||
done: Completion,
|
||||
) -> TicketId {
|
||||
self.submit_video_impl(id, params, done, JobSchedule::background())
|
||||
}
|
||||
|
||||
/// Submit a video ticket; completion fires exactly once, including
|
||||
/// on cancellation (with `Error::State`).
|
||||
pub fn submit_video(&self, params: VideoTicketParams, done: Completion) -> TicketId {
|
||||
@@ -376,6 +448,7 @@ impl TicketArena {
|
||||
delivered: AtomicBool::new(false),
|
||||
completion: Mutex::new(Some(done)),
|
||||
result: Mutex::new(None),
|
||||
dispatch: self.audio_dispatch.clone(),
|
||||
});
|
||||
self.allocate(slot.clone());
|
||||
|
||||
@@ -403,6 +476,7 @@ impl TicketArena {
|
||||
}),
|
||||
produce: producer,
|
||||
done: Box::new(move |result| slot_done.finish(result)),
|
||||
schedule: JobSchedule::seek(),
|
||||
};
|
||||
if !self.audio_dispatch.post(job) {
|
||||
slot.finish(Err(Error::State));
|
||||
@@ -425,12 +499,28 @@ impl TicketArena {
|
||||
}
|
||||
}
|
||||
|
||||
/// Blocking wait for completion (C++ wait_for_finished).
|
||||
/// Blocking wait for completion (C++ wait_for_finished). M15 S2: the
|
||||
/// process dispatcher delivers completions from its poll loop, so a
|
||||
/// blocking wait pumps it (the UI tick may be blocked right here).
|
||||
pub fn wait(&self, id: TicketId) -> Result<()> {
|
||||
let slot = lock(&self.slots).get(&id).cloned().ok_or(Error::NotFound)?;
|
||||
let mut state = lock(&slot.state);
|
||||
while !matches!(*state, SlotState::Finished) {
|
||||
state = slot.cv.wait(state).unwrap_or_else(|e| e.into_inner());
|
||||
// Pump the backend before blocking again. The slot lock is
|
||||
// dropped first: poll() delivers completions that finish this
|
||||
// very slot (finish() takes the same lock).
|
||||
drop(state);
|
||||
self.dispatch.poll();
|
||||
state = lock(&slot.state);
|
||||
if matches!(*state, SlotState::Finished) {
|
||||
break;
|
||||
}
|
||||
let timeout = std::time::Duration::from_millis(5);
|
||||
let (g, _) = slot
|
||||
.cv
|
||||
.wait_timeout(state, timeout)
|
||||
.unwrap_or_else(|e| e.into_inner());
|
||||
state = g;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -470,8 +560,8 @@ impl TicketArena {
|
||||
}
|
||||
|
||||
/// Cancel all pending tickets (manager shutdown path). Delivery happens
|
||||
/// when the pool drains the queued jobs (or the running jobs finish);
|
||||
/// call [`WorkerPool::shutdown`] afterwards to guarantee all
|
||||
/// when the backend drains the queued jobs (or the running jobs
|
||||
/// finish); call the backend's `shutdown` afterwards to guarantee all
|
||||
/// completions have fired.
|
||||
pub fn cancel_all(&self) {
|
||||
self.shutting_down.store(true, Ordering::Release);
|
||||
@@ -494,7 +584,7 @@ mod tests {
|
||||
|
||||
use crate::frame::VideoParamsPod;
|
||||
use crate::texture::Frame;
|
||||
use crate::worker::WorkerPool;
|
||||
use crate::worker::{InlineDispatcher, JobDispatch};
|
||||
|
||||
fn small_frame() -> Frame {
|
||||
let mut f = Frame::new();
|
||||
@@ -510,12 +600,19 @@ mod tests {
|
||||
Arc::new(|_, _| Ok(TicketPayload::Video(Texture::wrap_frame(small_frame()))))
|
||||
}
|
||||
|
||||
/// A queued inline dispatcher for video (deterministic cancel-race and
|
||||
/// shutdown semantics) plus a sync inline dispatcher for audio (the
|
||||
/// production audio mode). `run` drains the video queue.
|
||||
fn test_arena(producer: Producer) -> (TicketArena, Arc<InlineDispatcher>) {
|
||||
let video = InlineDispatcher::queued();
|
||||
let audio = InlineDispatcher::sync();
|
||||
let arena = TicketArena::new_with_audio(video.clone(), audio, producer);
|
||||
(arena, video)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_fires_exactly_once_on_success() {
|
||||
let pool = WorkerPool::new(2);
|
||||
let mut pool = pool;
|
||||
pool.start();
|
||||
let arena = TicketArena::new(Arc::new(pool.clone()), ok_producer());
|
||||
let (arena, video) = test_arena(ok_producer());
|
||||
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let id = arena.submit_video(
|
||||
@@ -536,6 +633,7 @@ mod tests {
|
||||
}),
|
||||
);
|
||||
|
||||
video.run();
|
||||
arena.wait(id).unwrap();
|
||||
let ok = rx.recv_timeout(Duration::from_secs(5)).unwrap();
|
||||
assert!(ok, "completion fired with success");
|
||||
@@ -553,24 +651,16 @@ mod tests {
|
||||
(4, 4)
|
||||
);
|
||||
assert!(arena.is_finished(id));
|
||||
pool.shutdown();
|
||||
video.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_fires_exactly_once_on_cancel() {
|
||||
let pool = WorkerPool::new(1);
|
||||
let mut pool = pool;
|
||||
pool.start();
|
||||
// Producer blocks until cancelled: exercises the cancel race.
|
||||
let release = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let release2 = release.clone();
|
||||
let producer: Producer = Arc::new(move |_, _| {
|
||||
while !release2.load(Ordering::Acquire) {
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
Ok(TicketPayload::Video(Texture::wrap_frame(small_frame())))
|
||||
});
|
||||
let arena = TicketArena::new(Arc::new(pool.clone()), producer);
|
||||
// Queued mode: the job is posted but not run yet, so a cancel
|
||||
// before `run` must deliver State exactly once (the old worker-pool
|
||||
// test used a blocking producer; the inline queue makes the same
|
||||
// cancel-before-completion race deterministic without threads).
|
||||
let (arena, video) = test_arena(ok_producer());
|
||||
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let id = arena.submit_video(
|
||||
@@ -591,9 +681,9 @@ mod tests {
|
||||
}),
|
||||
);
|
||||
|
||||
// Cancel while the job is running, then release the job.
|
||||
// Cancel before the job runs.
|
||||
arena.cancel(id);
|
||||
release.store(true, Ordering::Release);
|
||||
video.run();
|
||||
arena.wait(id).unwrap();
|
||||
|
||||
let res = rx.recv_timeout(Duration::from_secs(5)).unwrap();
|
||||
@@ -602,39 +692,32 @@ mod tests {
|
||||
rx.recv_timeout(Duration::from_millis(50)).is_err(),
|
||||
"exactly once"
|
||||
);
|
||||
pool.shutdown();
|
||||
video.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_of_unknown_id_is_ignored() {
|
||||
let pool = WorkerPool::new(1);
|
||||
let mut pool = pool;
|
||||
pool.start();
|
||||
let arena = TicketArena::new(Arc::new(pool.clone()), ok_producer());
|
||||
let (arena, video) = test_arena(ok_producer());
|
||||
arena.cancel(TicketId(12345));
|
||||
assert!(!arena.is_finished(TicketId(12345)));
|
||||
pool.shutdown();
|
||||
video.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wait_unknown_id_errors() {
|
||||
let pool = WorkerPool::new(1);
|
||||
let mut pool = pool;
|
||||
pool.start();
|
||||
let arena = TicketArena::new(Arc::new(pool.clone()), ok_producer());
|
||||
let (arena, video) = test_arena(ok_producer());
|
||||
assert_eq!(
|
||||
arena.wait(TicketId(999)).unwrap_err().code(),
|
||||
Error::NotFound.code()
|
||||
);
|
||||
pool.shutdown();
|
||||
video.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_ticket_meta_and_kind() {
|
||||
let pool = WorkerPool::new(1);
|
||||
let mut pool = pool;
|
||||
pool.start();
|
||||
let arena = TicketArena::new(Arc::new(pool.clone()), ok_producer());
|
||||
// Audio runs on the sync inline backend (the production audio
|
||||
// mode), so the completion fires during the submit.
|
||||
let (arena, video) = test_arena(ok_producer());
|
||||
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let range = TimeRange::new(Rational::new(0, 1), Rational::new(10, 1));
|
||||
@@ -659,15 +742,12 @@ mod tests {
|
||||
assert!(!rx.recv_timeout(Duration::from_secs(5)).unwrap());
|
||||
// get_time equivalent: audio tickets report range.in.
|
||||
assert_eq!(arena.time(id), Some(range.in_()));
|
||||
pool.shutdown();
|
||||
video.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ticket_ids_are_monotonic() {
|
||||
let pool = WorkerPool::new(1);
|
||||
let mut pool = pool;
|
||||
pool.start();
|
||||
let arena = TicketArena::new(Arc::new(pool.clone()), ok_producer());
|
||||
let (arena, video) = test_arena(ok_producer());
|
||||
let a = arena.submit_video(
|
||||
VideoTicketParams {
|
||||
viewer: 1,
|
||||
@@ -700,6 +780,6 @@ mod tests {
|
||||
);
|
||||
assert!(b.0 > a.0);
|
||||
assert_ne!(a, b);
|
||||
pool.shutdown();
|
||||
video.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
+215
-260
@@ -14,28 +14,41 @@
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! The worker layer (C++ RenderWorkerPool + RenderThread +
|
||||
//! workerprocess/workerjson): thread pool AND process-isolated pool
|
||||
//! behind one dispatch seam.
|
||||
//! The job-dispatch seam (M15 S2): what a render ticket posts through.
|
||||
//!
|
||||
//! This pass ships the in-process [`WorkerPool`] fully. The
|
||||
//! process-isolated backend landed in M15 S1 as
|
||||
//! [`crate::procpool::ProcessDispatcher`] (spawn/handshake/crash-restart
|
||||
//! of oak-worker binaries over NDJSON + shared memory); both backends
|
||||
//! implement the [`JobDispatch`] seam the ticket arena posts through.
|
||||
//! [`ProcessPool`] below is the frozen pre-M15 facade stub kept for C
|
||||
//! ABI parity.
|
||||
//! The in-process thread pool was **removed** in M15 S2 (user mandate:
|
||||
//! "delete the internal render thread pool"); the only video backend is
|
||||
//! the process-isolated [`crate::procpool::ProcessDispatcher`]
|
||||
//! (oak-worker children over NDJSON + shared memory). This module keeps
|
||||
//! the ticket-facing surface:
|
||||
//!
|
||||
//! - [`Job`] — one unit of render work plus its scheduler hints.
|
||||
//! - [`JobDispatch`] — the backend seam the arena posts through, with
|
||||
//! default no-ops for the process-backend extras (poll / release /
|
||||
//! preview-window cancellation).
|
||||
//! - [`InlineDispatcher`] — a thread-free dispatcher that executes jobs
|
||||
//! on the calling thread. Used as the **audio** backend (audio stays on
|
||||
//! main-process inline execution until S3 — design §3.7) and by the
|
||||
//! manager's test-only `Threads` backend and by unit tests.
|
||||
//! - [`GraphSnapshotStore`] — the graph-snapshot file refcounting cache
|
||||
//! shared with worker processes.
|
||||
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::panic::{catch_unwind, AssertUnwindSafe};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
|
||||
use std::sync::{Arc, Mutex, MutexGuard};
|
||||
|
||||
use oakcore_rs::Rational;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::procpool::ShmFrameRef;
|
||||
use crate::scheduler::FramePriority;
|
||||
use crate::ticket::{Completion, Producer, VideoTicketParams};
|
||||
|
||||
fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||
m.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// A unit of render work (produced by the ticket arena).
|
||||
pub struct Job {
|
||||
/// The graph position this job evaluates.
|
||||
@@ -44,21 +57,63 @@ pub struct Job {
|
||||
pub time: Rational,
|
||||
/// Ticket parameters (size/format overrides).
|
||||
pub params: Arc<VideoTicketParams>,
|
||||
/// Frame producer (arena-installed).
|
||||
/// Frame producer (arena-installed; the process backend never invokes
|
||||
/// it — workers render from the wire spec).
|
||||
pub produce: Producer,
|
||||
/// Completion delivery.
|
||||
pub done: Completion,
|
||||
/// Scheduler hints (M15 S2). Defaults to a Seek single-frame request.
|
||||
pub schedule: JobSchedule,
|
||||
}
|
||||
|
||||
fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||
m.lock().unwrap_or_else(|e| e.into_inner())
|
||||
/// Scheduler hints a posted job carries (M15 S2). The process dispatcher
|
||||
/// maps these onto [`crate::scheduler::FrameKey`] / priority; the inline
|
||||
/// dispatcher ignores them.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct JobSchedule {
|
||||
/// Priority class. Default [`FramePriority::Seek`] (single-frame).
|
||||
pub priority: FramePriority,
|
||||
/// Scheduler key frame number. `None` = the ticket id (the Seek
|
||||
/// single-frame convention).
|
||||
pub frame: Option<i64>,
|
||||
/// Playhead distance (orders the Playback class).
|
||||
pub distance: i64,
|
||||
/// Parameter version (graph/proxy/resolution/color); bumping it
|
||||
/// invalidates stale requests for the same sequence+frame.
|
||||
pub version: u64,
|
||||
}
|
||||
|
||||
impl JobSchedule {
|
||||
/// A Seek single-frame request (the default for every ticket).
|
||||
pub fn seek() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// A Background request (exports / precache): rendered whenever the
|
||||
/// workers have no Seek/Playback work.
|
||||
pub fn background() -> Self {
|
||||
Self {
|
||||
priority: FramePriority::Background,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A Playback-window request at `frame`, ordered by `distance` from
|
||||
/// the playhead and keyed under `version`.
|
||||
pub fn playback(frame: i64, distance: i64, version: u64) -> Self {
|
||||
Self {
|
||||
priority: FramePriority::Playback,
|
||||
frame: Some(frame),
|
||||
distance,
|
||||
version,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The job-dispatch seam (M15 S1): the ticket arena posts [`Job`]s
|
||||
/// through this interface without knowing the backend. Implemented by
|
||||
/// the in-process [`WorkerPool`] (threads) and the process-isolated
|
||||
/// [`crate::procpool::ProcessDispatcher`] (oak-worker children); S2
|
||||
/// removes the thread pool and this seam becomes process-only.
|
||||
/// through this interface without knowing the backend. Implemented by the
|
||||
/// process-isolated [`crate::procpool::ProcessDispatcher`] (oak-worker
|
||||
/// children) and the thread-free [`InlineDispatcher`] (audio / tests).
|
||||
pub trait JobDispatch: Send + Sync {
|
||||
/// Enqueue a job; false when the backend is gone (the arena then
|
||||
/// delivers the completion itself with `Error::State`).
|
||||
@@ -67,197 +122,127 @@ pub trait JobDispatch: Send + Sync {
|
||||
/// Stop accepting work, deliver the queued completions (cancelled)
|
||||
/// and release the backend. Idempotent.
|
||||
fn shutdown(&self);
|
||||
|
||||
/// Pump backend completions (the process dispatcher's poll loop).
|
||||
/// Default no-op: backends that deliver inline have nothing to pump.
|
||||
/// The UI tick and blocking ticket waits call this so the process
|
||||
/// backend's completions are delivered without a dedicated thread.
|
||||
fn poll(&self) {}
|
||||
|
||||
/// Release a consumed shm frame's slot back to its worker (slot
|
||||
/// release = cache eviction, design §3.1). Default no-op: only the
|
||||
/// process backend holds slots.
|
||||
fn release_frame(&self, _frame: &ShmFrameRef) {}
|
||||
|
||||
/// Cancel every pending AND claimed request of `sequence` (M15 S2
|
||||
/// preview-window invalidation); their completions fire with
|
||||
/// `Error::State`. Default no-op: only the process backend schedules.
|
||||
fn cancel_preview_sequence(&self, _sequence: u64) {}
|
||||
}
|
||||
|
||||
/// Thread-pool backend (C++ RenderThread model). Cheap to clone (all
|
||||
/// state is behind an `Arc`); the manager and the ticket arena share one
|
||||
/// pool.
|
||||
#[derive(Clone)]
|
||||
pub struct WorkerPool {
|
||||
inner: Arc<PoolInner>,
|
||||
/// Thread-free job dispatcher (M15 S2). Executes jobs on the calling
|
||||
/// thread — there are deliberately **no worker threads**:
|
||||
///
|
||||
/// - **Sync mode** ([`InlineDispatcher::sync`]): every `post` runs its
|
||||
/// job immediately on the caller's thread. This is the production
|
||||
/// **audio** backend (audio stays on main-process inline execution
|
||||
/// until S3 — design §3.7: the crash risk is dominated by video
|
||||
/// plugins, which already live in oak-worker) and the manager's
|
||||
/// test-only `Threads` backend.
|
||||
/// - **Queued mode** ([`InlineDispatcher::queued`]): `post` queues the
|
||||
/// job; the test drains it with [`InlineDispatcher::run`]. This keeps
|
||||
/// the arena's cancel-race and shutdown semantics deterministic
|
||||
/// without any threads.
|
||||
pub struct InlineDispatcher {
|
||||
inner: Arc<InlineInner>,
|
||||
}
|
||||
|
||||
struct PoolInner {
|
||||
workers: usize,
|
||||
struct InlineInner {
|
||||
queue: Mutex<VecDeque<Job>>,
|
||||
cv: Condvar,
|
||||
sync: bool,
|
||||
stopping: AtomicBool,
|
||||
threads: Mutex<Vec<std::thread::JoinHandle<()>>>,
|
||||
}
|
||||
|
||||
impl WorkerPool {
|
||||
/// Pool with `workers` threads (0 = hardware concurrency).
|
||||
pub fn new(workers: usize) -> Self {
|
||||
let workers = if workers == 0 {
|
||||
std::thread::available_parallelism()
|
||||
.map(|n| n.get())
|
||||
.unwrap_or(1)
|
||||
} else {
|
||||
workers
|
||||
};
|
||||
Self {
|
||||
inner: Arc::new(PoolInner {
|
||||
workers,
|
||||
impl InlineDispatcher {
|
||||
/// A sync-mode dispatcher: jobs run immediately on the posting thread.
|
||||
pub fn sync() -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
inner: Arc::new(InlineInner {
|
||||
queue: Mutex::new(VecDeque::new()),
|
||||
cv: Condvar::new(),
|
||||
sync: true,
|
||||
stopping: AtomicBool::new(false),
|
||||
threads: Mutex::new(Vec::new()),
|
||||
}),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The number of worker threads.
|
||||
pub fn worker_count(&self) -> usize {
|
||||
self.inner.workers
|
||||
/// A queued-mode dispatcher: jobs wait for [`InlineDispatcher::run`].
|
||||
pub fn queued() -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
inner: Arc::new(InlineInner {
|
||||
queue: Mutex::new(VecDeque::new()),
|
||||
sync: false,
|
||||
stopping: AtomicBool::new(false),
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
/// Start threads (idempotent).
|
||||
pub fn start(&mut self) {
|
||||
let mut threads = lock(&self.inner.threads);
|
||||
if !threads.is_empty() {
|
||||
/// Run every queued job synchronously on the calling thread (queued
|
||||
/// mode). Jobs posted after `shutdown` are refused by `post`.
|
||||
pub fn run(&self) {
|
||||
if self.inner.stopping.load(Ordering::Acquire) {
|
||||
return;
|
||||
}
|
||||
for _ in 0..self.inner.workers {
|
||||
let inner = self.inner.clone();
|
||||
let handle = std::thread::spawn(move || worker_loop(inner));
|
||||
threads.push(handle);
|
||||
loop {
|
||||
let job = lock(&self.inner.queue).pop_front();
|
||||
let Some(job) = job else { break };
|
||||
execute_job(job);
|
||||
}
|
||||
}
|
||||
|
||||
/// True when threads are running.
|
||||
pub fn is_running(&self) -> bool {
|
||||
!lock(&self.inner.threads).is_empty()
|
||||
/// The number of queued (not yet run) jobs.
|
||||
pub fn queued_count(&self) -> usize {
|
||||
lock(&self.inner.queue).len()
|
||||
}
|
||||
}
|
||||
|
||||
/// Enqueue a job. Returns false when the pool is shut down.
|
||||
pub fn post(&self, job: Job) -> bool {
|
||||
// The stopping check and the push share one queue lock: a shutdown
|
||||
// racing the check would otherwise leave the job queued after every
|
||||
// worker exited (and after the defensive drain), so its completion
|
||||
// could never fire.
|
||||
fn execute_job(job: Job) {
|
||||
let result = catch_unwind(AssertUnwindSafe(|| (job.produce)(job.time, &job.params)))
|
||||
.unwrap_or_else(|_| Err(Error::Failed("frame producer panicked".into())));
|
||||
(job.done)(result);
|
||||
}
|
||||
|
||||
impl JobDispatch for InlineDispatcher {
|
||||
fn post(&self, job: Job) -> bool {
|
||||
if self.inner.sync {
|
||||
// Sync mode: run now (refusing only when shutting down).
|
||||
if self.inner.stopping.load(Ordering::Acquire) {
|
||||
return false;
|
||||
}
|
||||
execute_job(job);
|
||||
return true;
|
||||
}
|
||||
let mut queue = lock(&self.inner.queue);
|
||||
if self.inner.stopping.load(Ordering::Acquire) {
|
||||
return false;
|
||||
}
|
||||
queue.push_back(job);
|
||||
self.inner.cv.notify_one();
|
||||
true
|
||||
}
|
||||
|
||||
/// Stop accepting, drain, join all workers. In-flight job completions
|
||||
/// fire with cancellation (queued jobs are delivered `Error::State`
|
||||
/// without running); running jobs are joined so no completion fires
|
||||
/// after shutdown returns.
|
||||
pub fn shutdown(&mut self) {
|
||||
self.shutdown_ref();
|
||||
}
|
||||
|
||||
/// [`Self::shutdown`] on a shared reference (the [`JobDispatch`]
|
||||
/// seam; all state is interior-mutable). Idempotent.
|
||||
pub fn shutdown_ref(&self) {
|
||||
// Set the flag and wake the workers while holding the queue lock.
|
||||
// Workers decide whether to block in `cv.wait` while holding that
|
||||
// lock, so a flag set outside it could land between a worker's
|
||||
// predicate check and its wait: the wakeup is lost, the worker
|
||||
// sleeps forever, and the join below hangs. Serializing store +
|
||||
// notify with the waiters' lock closes that window.
|
||||
{
|
||||
let _guard = lock(&self.inner.queue);
|
||||
self.inner.stopping.store(true, Ordering::Release);
|
||||
self.inner.cv.notify_all();
|
||||
}
|
||||
|
||||
let threads = std::mem::take(&mut *lock(&self.inner.threads));
|
||||
for handle in threads {
|
||||
let _ = handle.join();
|
||||
}
|
||||
|
||||
// Defensive drain: any job that landed between `stopping` and the
|
||||
// workers' exit (post() refuses them, so this is normally empty).
|
||||
let mut queue = lock(&self.inner.queue);
|
||||
while let Some(job) = queue.pop_front() {
|
||||
deliver_cancelled(job);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl JobDispatch for WorkerPool {
|
||||
fn post(&self, job: Job) -> bool {
|
||||
WorkerPool::post(self, job)
|
||||
}
|
||||
|
||||
fn shutdown(&self) {
|
||||
self.shutdown_ref();
|
||||
}
|
||||
}
|
||||
|
||||
fn worker_loop(inner: Arc<PoolInner>) {
|
||||
loop {
|
||||
let job = {
|
||||
let mut queue = lock(&inner.queue);
|
||||
while !inner.stopping.load(Ordering::Acquire) && queue.is_empty() {
|
||||
queue = inner.cv.wait(queue).unwrap_or_else(|e| e.into_inner());
|
||||
}
|
||||
queue.pop_front()
|
||||
// Stop accepting and drain the queue with cancellation (queued
|
||||
// jobs never run after shutdown).
|
||||
let jobs: Vec<Job> = {
|
||||
let mut queue = lock(&self.inner.queue);
|
||||
self.inner.stopping.store(true, Ordering::Release);
|
||||
queue.drain(..).collect()
|
||||
};
|
||||
let Some(job) = job else {
|
||||
return; // stopping and queue drained
|
||||
};
|
||||
if inner.stopping.load(Ordering::Acquire) {
|
||||
// Shutdown raced this pop: deliver cancellation.
|
||||
deliver_cancelled(job);
|
||||
continue;
|
||||
for job in jobs {
|
||||
(job.done)(Err(Error::State));
|
||||
}
|
||||
let result = catch_unwind(AssertUnwindSafe(|| (job.produce)(job.time, &job.params)))
|
||||
.unwrap_or_else(|_| Err(Error::Failed("frame producer panicked".into())));
|
||||
(job.done)(result);
|
||||
}
|
||||
}
|
||||
|
||||
fn deliver_cancelled(job: Job) {
|
||||
(job.done)(Err(Error::State));
|
||||
}
|
||||
|
||||
/// Process-isolated worker backend (C++ RenderWorkerPool +
|
||||
/// PooledWorker). Child processes talk the oakengine_ipc C ABI; this side
|
||||
/// is only a client (spawn, dispatch, reap). Not wired in this pass.
|
||||
pub struct ProcessPool {
|
||||
workers: usize,
|
||||
}
|
||||
|
||||
impl ProcessPool {
|
||||
/// Pool of `workers` child processes.
|
||||
pub fn new(workers: usize) -> Self {
|
||||
Self { workers }
|
||||
}
|
||||
|
||||
/// The configured child count.
|
||||
pub fn worker_count(&self) -> usize {
|
||||
self.workers
|
||||
}
|
||||
|
||||
/// Spawn children and handshake.
|
||||
pub fn start(&mut self) -> Result<()> {
|
||||
Err(Error::Failed(
|
||||
"oakengine_ipc worker-process bridge not implemented in this pass".into(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Dispatch a job to a free child.
|
||||
pub fn post(&self, _job: Job) -> Result<()> {
|
||||
Err(Error::Failed(
|
||||
"oakengine_ipc worker-process bridge not implemented in this pass".into(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Cancel the job running in a child (C++ cancel_active_process).
|
||||
pub fn cancel_active(&self, _process_slot: usize) {}
|
||||
|
||||
/// Terminate and reap all children; pending jobs complete with
|
||||
/// cancellation.
|
||||
pub fn shutdown(&mut self) {}
|
||||
}
|
||||
|
||||
/// Graph snapshot files shared with worker processes (C++
|
||||
/// write_graph_snapshot + path refcounting): a snapshot is written once
|
||||
/// and reference-counted; the file is unlinked at zero.
|
||||
@@ -355,27 +340,20 @@ impl Default for GraphSnapshotStore {
|
||||
}
|
||||
}
|
||||
|
||||
/// The pool the manager runs (config-selected, C++ parity).
|
||||
pub enum WorkerBackend {
|
||||
/// In-process threads.
|
||||
Threads(WorkerPool),
|
||||
/// Child processes (crash isolation).
|
||||
Processes(ProcessPool),
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::texture::Texture;
|
||||
|
||||
fn job(tag: u64, tx: mpsc::Sender<u64>, gate: Option<Arc<AtomicUsize>>) -> Job {
|
||||
fn job(tag: u64, tx: mpsc::Sender<u64>, gate: Option<Arc<AtomicBool>>) -> Job {
|
||||
let produce: Producer = Arc::new(move |_, _| {
|
||||
if let Some(g) = &gate {
|
||||
g.fetch_add(1, Ordering::SeqCst);
|
||||
if g.load(Ordering::Acquire) {
|
||||
return Err(Error::Failed("gated producer".into()));
|
||||
}
|
||||
}
|
||||
Ok(crate::ticket::TicketPayload::Video(Texture::dummy()))
|
||||
});
|
||||
@@ -399,56 +377,58 @@ mod tests {
|
||||
assert!(r.is_ok(), "producer must succeed here");
|
||||
let _ = tx.send(tag);
|
||||
}),
|
||||
schedule: JobSchedule::seek(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pool_saturation_all_jobs_complete() {
|
||||
let mut pool = WorkerPool::new(4);
|
||||
pool.start();
|
||||
fn sync_dispatcher_runs_every_job_immediately() {
|
||||
let d = InlineDispatcher::sync();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
for i in 0..64u64 {
|
||||
assert!(pool.post(job(i, tx.clone(), None)));
|
||||
for i in 0..8u64 {
|
||||
assert!(d.post(job(i, tx.clone(), None)));
|
||||
}
|
||||
drop(tx);
|
||||
let mut seen = Vec::new();
|
||||
while let Ok(tag) = rx.recv_timeout(Duration::from_secs(10)) {
|
||||
while let Ok(tag) = rx.recv_timeout(Duration::from_secs(5)) {
|
||||
seen.push(tag);
|
||||
}
|
||||
assert_eq!(seen.len(), 64);
|
||||
seen.sort_unstable();
|
||||
for (i, tag) in seen.iter().enumerate() {
|
||||
assert_eq!(*tag, i as u64, "every job runs exactly once");
|
||||
}
|
||||
pool.shutdown();
|
||||
assert_eq!(seen.len(), 8, "every job ran on the posting thread");
|
||||
d.shutdown();
|
||||
// Post after shutdown is refused.
|
||||
let (tx2, _rx2) = mpsc::channel();
|
||||
assert!(!d.post(job(9, tx2, None)), "post after shutdown is refused");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shutdown_delivers_cancellation_to_queued_jobs() {
|
||||
// 1 worker + a gate that blocks: jobs 2..N stay queued and must be
|
||||
// delivered Err(State) at shutdown.
|
||||
let gate = Arc::new(AtomicUsize::new(0));
|
||||
let mut pool = WorkerPool::new(1);
|
||||
pool.start();
|
||||
fn queued_dispatcher_runs_on_demand() {
|
||||
let d = InlineDispatcher::queued();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
for i in 0..8u64 {
|
||||
assert!(d.post(job(i, tx.clone(), None)));
|
||||
}
|
||||
assert_eq!(d.queued_count(), 8, "nothing ran yet");
|
||||
d.run();
|
||||
assert_eq!(d.queued_count(), 0);
|
||||
drop(tx);
|
||||
let mut seen = Vec::new();
|
||||
while let Ok(tag) = rx.recv_timeout(Duration::from_secs(5)) {
|
||||
seen.push(tag);
|
||||
}
|
||||
assert_eq!(seen.len(), 8);
|
||||
d.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queued_dispatcher_shutdown_delivers_cancellation() {
|
||||
let d = InlineDispatcher::queued();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
for _ in 0..4 {
|
||||
let tx = tx.clone();
|
||||
let gate = gate.clone();
|
||||
let produce: Producer = Arc::new(move |_, _| {
|
||||
if i == 0 {
|
||||
// First job blocks until shutdown begins.
|
||||
let start = std::time::Instant::now();
|
||||
while gate.load(Ordering::Acquire) == 0
|
||||
&& start.elapsed() < Duration::from_secs(5)
|
||||
{
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
Ok(crate::ticket::TicketPayload::Video(Texture::dummy()))
|
||||
});
|
||||
let job = Job {
|
||||
node_identity: i,
|
||||
time: Rational::new(i as i64, 1),
|
||||
let p: Producer = Arc::new(|_, _| Ok(crate::ticket::TicketPayload::Video(Texture::dummy())));
|
||||
d.post(Job {
|
||||
node_identity: 1,
|
||||
time: Rational::new(0, 1),
|
||||
params: Arc::new(VideoTicketParams {
|
||||
viewer: 0,
|
||||
time: Rational::new(0, 1),
|
||||
@@ -461,44 +441,28 @@ mod tests {
|
||||
footage: None,
|
||||
montage: Vec::new(),
|
||||
}),
|
||||
produce,
|
||||
produce: p,
|
||||
done: Box::new(move |r| {
|
||||
let _ = tx.send(r.is_err());
|
||||
}),
|
||||
};
|
||||
pool.post(job);
|
||||
schedule: JobSchedule::seek(),
|
||||
});
|
||||
}
|
||||
drop(tx);
|
||||
gate.store(1, Ordering::Release);
|
||||
pool.shutdown();
|
||||
|
||||
d.shutdown();
|
||||
let mut delivered = Vec::new();
|
||||
while let Ok(is_err) = rx.recv_timeout(Duration::from_secs(5)) {
|
||||
delivered.push(is_err);
|
||||
while let Ok(err) = rx.recv_timeout(Duration::from_secs(5)) {
|
||||
delivered.push(err);
|
||||
}
|
||||
assert_eq!(delivered.len(), 8, "all 8 completions fire");
|
||||
assert!(
|
||||
delivered.iter().filter(|&&e| e).count() >= 7,
|
||||
"queued jobs complete with cancellation"
|
||||
);
|
||||
assert_eq!(delivered.len(), 4, "all queued completions fire");
|
||||
assert!(delivered.iter().all(|&e| e), "queued jobs cancel at shutdown");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn post_after_shutdown_is_refused() {
|
||||
let mut pool = WorkerPool::new(1);
|
||||
pool.start();
|
||||
pool.shutdown();
|
||||
let (tx, _rx) = mpsc::channel();
|
||||
assert!(!pool.post(job(1, tx, None)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn producer_panic_does_not_kill_worker() {
|
||||
let mut pool = WorkerPool::new(1);
|
||||
pool.start();
|
||||
fn producer_panic_does_not_kill_the_dispatcher() {
|
||||
let d = InlineDispatcher::sync();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let tx1 = tx.clone();
|
||||
let tx2 = tx.clone();
|
||||
let boom: Producer = Arc::new(|_, _| panic!("boom"));
|
||||
let ok: Producer = Arc::new(|_, _| Ok(crate::ticket::TicketPayload::Video(Texture::dummy())));
|
||||
let params = Arc::new(VideoTicketParams {
|
||||
@@ -513,7 +477,7 @@ mod tests {
|
||||
footage: None,
|
||||
montage: Vec::new(),
|
||||
});
|
||||
pool.post(Job {
|
||||
d.post(Job {
|
||||
node_identity: 0,
|
||||
time: Rational::new(0, 1),
|
||||
params: params.clone(),
|
||||
@@ -522,34 +486,25 @@ mod tests {
|
||||
assert!(r.is_err());
|
||||
let _ = tx1.send(1u64);
|
||||
}),
|
||||
schedule: JobSchedule::seek(),
|
||||
});
|
||||
pool.post(Job {
|
||||
d.post(Job {
|
||||
node_identity: 1,
|
||||
time: Rational::new(1, 1),
|
||||
params,
|
||||
produce: ok,
|
||||
done: Box::new(move |r| {
|
||||
assert!(r.is_ok());
|
||||
let _ = tx2.send(2u64);
|
||||
let _ = tx.send(2u64);
|
||||
}),
|
||||
schedule: JobSchedule::seek(),
|
||||
});
|
||||
let mut got = Vec::new();
|
||||
while let Ok(v) = rx.recv_timeout(Duration::from_secs(5)) {
|
||||
got.push(v);
|
||||
}
|
||||
assert_eq!(got.len(), 2, "worker survives a panicking producer");
|
||||
pool.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_pool_is_documented_stub() {
|
||||
let mut pp = ProcessPool::new(2);
|
||||
assert_eq!(pp.worker_count(), 2);
|
||||
assert!(pp.start().is_err(), "oakengine_ipc bridge pending");
|
||||
let (tx, _rx) = mpsc::channel();
|
||||
assert!(pp.post(job(1, tx, None)).is_err());
|
||||
pp.cancel_active(0); // no-op
|
||||
pp.shutdown(); // no-op
|
||||
assert_eq!(got.len(), 2, "the dispatcher survives a panicking producer");
|
||||
d.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in New Issue
Block a user