exprim 0.4.0

A concurrent, memory-bounded PDF reader and renderer: parse, extract text, and rasterize pages on an immutable document snapshot
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
//! Parallel page pipeline (roadmap §7 Phase 5):
//!
//! ```text
//! DocumentSnapshot → compile pool → bounded CompiledPage queue
//!                  → render pool  → reorder buffer → in-order output
//! ```
//!
//! Separate bounded stages so slow rendering doesn't block parsing, parsing
//! can't run unboundedly ahead, and memory stays bounded. Worker count
//! alone does NOT bound memory — jobs acquire [`MemoryBudget`] permits for
//! their estimated peak bytes before running.
//!
//! The pipeline internals are Phase 5; the *shape* (these types) is fixed
//! now, and the two genuinely load-bearing primitives — the budget and the
//! reorder buffer — are fully implemented and tested.

use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Arc;

use crate::document::{DocumentSnapshot, PageIndex};
use crate::render_api::{
    CancellationToken, RenderBackend, RenderError, RenderRequest, RenderedPage,
};

mod budget;
mod reorder;

pub use budget::{MemoryBudget, MemoryPermit};
pub use reorder::ReorderBuffer;

/// Scheduler configuration.
#[derive(Debug, Clone)]
pub struct SchedulerOptions {
    /// Page-compilation workers.
    pub compile_workers: usize,
    /// Concurrent render jobs.
    pub render_workers: usize,
    /// Bound on compiled pages waiting for a render slot.
    pub compiled_queue_depth: usize,
    /// Maximum number of pages admitted to the pipeline but not yet emitted.
    ///
    /// This is an ordered sliding window, not a bounded result channel: the
    /// next expected page is always admitted, so a slow early page can still
    /// complete and release later completed surfaces from the reorder buffer.
    ///
    /// The window must comfortably exceed the worker count: every page that
    /// finished out of order holds a slot while it waits in the reorder
    /// buffer, and each such slot is one fewer page the render workers can be
    /// given. With a window close to the worker count a short document never
    /// reaches full occupancy — a 22-page book at twelve workers ran ~40%
    /// slower with a window of 12 than with one of 32. The default therefore
    /// scales with the workers (see [`SchedulerOptions::default`]). Surfaces
    /// held in the reorder buffer are *not* charged to `memory_limit_bytes`
    /// (that covers active renders), so the window is also the bound on that
    /// unbudgeted memory: `(window - 1)` surfaces in the worst case.
    pub reorder_window_depth: usize,
    /// Total bytes all in-flight jobs may hold.
    pub memory_limit_bytes: u64,
}

impl Default for SchedulerOptions {
    fn default() -> Self {
        // One partitioned physical pool (performance advice §12): compile +
        // render workers sum to ≈ the core count rather than 2×cores. Rendering
        // is the heavier stage, so it gets the larger share.
        let cores = std::thread::available_parallelism()
            .map(|n| n.get())
            .unwrap_or(4);
        let render_workers = (cores * 2 / 3).max(1);
        let compile_workers = cores.saturating_sub(render_workers).max(1);
        Self {
            compile_workers,
            render_workers,
            compiled_queue_depth: 12,
            reorder_window_depth: Self::reorder_window_for(compile_workers, render_workers),
            memory_limit_bytes: 4 << 30,
        }
    }
}

impl SchedulerOptions {
    /// Reorder window that keeps `render_workers` busy on a short document.
    ///
    /// Four slots per worker: a worker's current page, the pages it finished
    /// that wait behind a slower earlier page, and a compiled page ready for
    /// it. Measured on a 22-page book at 2 + 6 workers: window 12 → 35 ms,
    /// 20 → 31 ms, 32 → 23 ms, 48 → no further gain; at 4 + 8 the knee is
    /// the same (24 → 28 ms, 48 → 31 ms). Long documents are unaffected by
    /// the window once it exceeds the worker count. Callers that set the
    /// worker counts themselves should set the window through this too, or
    /// the default 12 silently throttles them.
    pub fn reorder_window_for(compile_workers: usize, render_workers: usize) -> usize {
        (compile_workers.max(1) + render_workers.max(1))
            .saturating_mul(4)
            .max(12)
    }
}

/// A finished page emitted by the pipeline, tagged with its index so
/// downstream stages can rely on ordering.
#[derive(Debug)]
pub struct PipelineOutput {
    pub page: PageIndex,
    pub result: Result<RenderedPage, RenderError>,
    /// Time from pipeline start until this page finished rendering, captured
    /// before in-order delivery can hold it behind an earlier page.
    #[cfg(feature = "profiling")]
    pub completion_latency: std::time::Duration,
}

/// The page-render pipeline. Owns worker pools and stage queues.
#[derive(Debug)]
pub struct RenderScheduler {
    options: SchedulerOptions,
    backend: Arc<dyn RenderBackend>,
    budget: MemoryBudget,
}

impl RenderScheduler {
    pub fn new(backend: Arc<dyn RenderBackend>, options: SchedulerOptions) -> Self {
        let budget = MemoryBudget::new(options.memory_limit_bytes);
        Self {
            options,
            backend,
            budget,
        }
    }

    pub fn options(&self) -> &SchedulerOptions {
        &self.options
    }

    pub fn budget(&self) -> &MemoryBudget {
        &self.budget
    }

    /// Render a contiguous page range, delivering results **in page order** to
    /// `emit` while compiling and rendering out of order internally.
    ///
    /// The pipeline (roadmap §7 Phase 5): a compile-worker set turns pages into
    /// `RenderRequest`s and feeds a **bounded** compiled queue (backpressure —
    /// parsing cannot run unboundedly ahead of rendering); a render-worker set
    /// drains it, reserving a [`MemoryBudget`] permit per job so worker count
    /// alone does not bound memory; a reorder buffer emits in page order.
    ///
    /// Guarantees: deterministic output for any worker counts (each page is
    /// independent — its own parse/render context, the snapshot is immutable,
    /// no document-wide lock); `cancel` stops queued and active jobs (it is
    /// checked before each stage *and* linked with each request's
    /// `limits.cancellation` so either token can stop mid-render). Cancellation
    /// drains the requested range, emitting one result per page in order;
    /// a panic or
    /// error on one page becomes that page's `Err` and never corrupts
    /// another page's job.
    pub fn render_range(
        &self,
        snapshot: &DocumentSnapshot,
        pages: std::ops::Range<u32>,
        make_request: &(
             dyn Fn(&DocumentSnapshot, PageIndex) -> Result<RenderRequest, RenderError> + Sync
         ),
        cancel: Option<&CancellationToken>,
        emit: &mut dyn FnMut(PipelineOutput),
    ) {
        use crossbeam_channel::{bounded, unbounded};

        let start_seq = pages.start as u64;
        let cancelled = || cancel.is_some_and(|t| t.is_cancelled());
        #[cfg(feature = "profiling")]
        let pipeline_start = std::time::Instant::now();

        // Stage 0: page indices to compile. Keep this bounded too: eagerly
        // enqueueing a caller-controlled `u32` range before any worker starts
        // can otherwise consume gigabytes before the actual pipeline runs.
        // The feeder admits up to a full window at once, so size this to the
        // window: a smaller bound only makes the feeder block for nothing.
        let reorder_window = self.options.reorder_window_depth.max(1) as u64;
        let (page_tx, page_rx) =
            bounded::<u32>((reorder_window as usize).max(self.options.compiled_queue_depth.max(1)));

        // Stage 1→2: bounded compiled queue (bounds compiled-page memory).
        type Compiled = (u32, Result<RenderRequest, RenderError>);
        let (compiled_tx, compiled_rx) =
            bounded::<Compiled>(self.options.compiled_queue_depth.max(1));
        // Stage 2→collector.
        #[cfg(feature = "profiling")]
        type PipelineResult = (u32, Result<RenderedPage, RenderError>, std::time::Duration);
        #[cfg(not(feature = "profiling"))]
        type PipelineResult = (u32, Result<RenderedPage, RenderError>);
        let (result_tx, result_rx) = unbounded::<PipelineResult>();
        // Advancing this channel means one in-order output was emitted. The
        // feeder uses it to extend the admission window. It only carries
        // zero-sized completion credits, never rendered surfaces.
        let (emitted_tx, emitted_rx) = unbounded::<()>();

        std::thread::scope(|scope| {
            // Admit an ordered sliding window. This bounds *all* pages that
            // can reach the reorder buffer while reserving its first slot for
            // the page the collector is waiting for. Bounding `result_tx`
            // instead can deadlock when later workers fill it before that
            // early page finishes.
            scope.spawn(move || {
                let mut pages = pages;
                let mut admitted = 0_u64;
                let mut emitted = 0_u64;
                loop {
                    let limit = emitted.saturating_add(reorder_window);
                    while admitted < limit {
                        let Some(n) = pages.next() else {
                            return;
                        };
                        if page_tx.send(n).is_err() {
                            return;
                        }
                        admitted += 1;
                    }
                    match emitted_rx.recv() {
                        Ok(()) => emitted += 1,
                        Err(_) => return,
                    }
                }
            });

            // Compile workers.
            for _ in 0..self.options.compile_workers.max(1) {
                let page_rx = page_rx.clone();
                let compiled_tx = compiled_tx.clone();
                scope.spawn(move || {
                    while let Ok(n) = page_rx.recv() {
                        let item = if cancelled() {
                            Err(RenderError::Cancelled)
                        } else {
                            match catch_unwind(AssertUnwindSafe(|| {
                                make_request(snapshot, PageIndex(n))
                            })) {
                                Ok(r) => r,
                                Err(_) => Err(RenderError::Backend(format!(
                                    "compile panicked on page {n}"
                                ))),
                            }
                        };
                        if compiled_tx.send((n, item)).is_err() {
                            break;
                        }
                    }
                });
            }
            drop(compiled_tx);
            drop(page_rx);

            // Render workers.
            for _ in 0..self.options.render_workers.max(1) {
                let compiled_rx = compiled_rx.clone();
                let result_tx = result_tx.clone();
                let budget = self.budget.clone();
                let backend = self.backend.clone();
                scope.spawn(move || {
                    while let Ok((n, item)) = compiled_rx.recv() {
                        let result = match item {
                            Err(e) => Err(e),
                            Ok(request) if cancelled() => {
                                drop(request);
                                Err(RenderError::Cancelled)
                            }
                            Ok(mut request) => {
                                // Preserve both cancellation sources through budget
                                // admission and active backend execution.
                                if let Some(pipeline) = cancel {
                                    request.limits.cancellation =
                                        Some(match &request.limits.cancellation {
                                            Some(local) => local.linked_with(pipeline),
                                            None => pipeline.clone(),
                                        });
                                }
                                render_job(backend.as_ref(), &budget, request)
                            }
                        };
                        #[cfg(feature = "profiling")]
                        let sent = result_tx.send((n, result, pipeline_start.elapsed()));
                        #[cfg(not(feature = "profiling"))]
                        let sent = result_tx.send((n, result));
                        if sent.is_err() {
                            break;
                        }
                    }
                });
            }
            drop(result_tx);
            drop(compiled_rx);

            // Collector (this thread): reorder → in-order emit.
            let mut reorder = ReorderBuffer::new(start_seq);
            while let Ok(item) = result_rx.recv() {
                #[cfg(feature = "profiling")]
                let (n, result, completion_latency) = item;
                #[cfg(not(feature = "profiling"))]
                let (n, result) = item;
                reorder.insert(
                    n as u64,
                    PipelineOutput {
                        page: PageIndex(n),
                        result,
                        #[cfg(feature = "profiling")]
                        completion_latency,
                    },
                );
                for (_, out) in reorder.drain_ready() {
                    emit(out);
                    let _ = emitted_tx.send(());
                }
            }
            for (_, out) in reorder.drain_ready() {
                emit(out);
                let _ = emitted_tx.send(());
            }
        });
    }

    /// Run the existing pipeline while collecting operation-level throughput
    /// attribution. Per-page compilation/render reports remain owned by the
    /// caller's profiled request builder/backend; this method records the
    /// pipeline envelope without introducing shared counters into hot workers.
    #[cfg(feature = "profiling")]
    pub fn render_range_profiled(
        &self,
        snapshot: &DocumentSnapshot,
        pages: std::ops::Range<u32>,
        make_request: &(
             dyn Fn(&DocumentSnapshot, PageIndex) -> Result<RenderRequest, RenderError> + Sync
         ),
        cancel: Option<&CancellationToken>,
        emit: &mut dyn FnMut(PipelineOutput),
    ) -> crate::profiling::ProfileReport {
        let requested = pages.end.saturating_sub(pages.start) as u64;
        let start = std::time::Instant::now();
        let mut completed = 0u64;
        let mut succeeded = 0u64;
        let mut completion_ns = Vec::with_capacity(requested as usize);
        self.render_range(snapshot, pages, make_request, cancel, &mut |out| {
            completed += 1;
            if out.result.is_ok() {
                succeeded += 1;
            }
            completion_ns.push(out.completion_latency.as_nanos() as u64);
            emit(out);
        });
        completion_ns.sort_unstable();
        let mut profile = crate::profiling::ProfileReport::new();
        profile.add_duration("scheduler.total", start.elapsed());
        profile.increment("scheduler.requested_pages", requested);
        profile.increment("scheduler.completed_pages", completed);
        profile.increment("scheduler.succeeded_pages", succeeded);
        profile.increment(
            "scheduler.compile_workers",
            self.options.compile_workers as u64,
        );
        profile.increment(
            "scheduler.render_workers",
            self.options.render_workers as u64,
        );
        profile.increment(
            "scheduler.memory_limit_bytes",
            self.options.memory_limit_bytes,
        );
        if !completion_ns.is_empty() {
            profile.increment(
                "scheduler.page_latency_p50_ns",
                percentile(&completion_ns, 0.50),
            );
            profile.increment(
                "scheduler.page_latency_p90_ns",
                percentile(&completion_ns, 0.90),
            );
            profile.increment(
                "scheduler.page_latency_p99_ns",
                percentile(&completion_ns, 0.99),
            );
        }
        profile
    }
}

#[cfg(feature = "profiling")]
fn percentile(sorted: &[u64], quantile: f64) -> u64 {
    let index = ((sorted.len().saturating_sub(1)) as f64 * quantile).ceil() as usize;
    sorted[index.min(sorted.len() - 1)]
}

/// Reserve budget for a job's estimated peak, render it, and release on
/// return. A panic in the backend becomes an isolated `Err` for this page.
fn render_job(
    backend: &dyn RenderBackend,
    budget: &MemoryBudget,
    request: RenderRequest,
) -> Result<RenderedPage, RenderError> {
    let estimate = estimate_job_bytes(&request);
    // Wait for budget *cancellably*: a job parked here is woken only by
    // another job's release, so an uncancellable wait would ignore the
    // pipeline token until unrelated work finished.
    let cancellation = request.limits.cancellation.clone();
    let permit = budget
        .acquire_cancellable(estimate, || {
            cancellation.as_ref().is_some_and(|t| t.is_cancelled())
        })
        .map_err(|_| RenderError::LimitExceeded("memory budget"))?;
    let Some(_permit) = permit else {
        return Err(RenderError::Cancelled);
    };
    match catch_unwind(AssertUnwindSafe(|| {
        let ticket = backend
            .submit(request)
            .map_err(|e| RenderError::Backend(e.to_string()))?;
        ticket.wait()
    })) {
        Ok(result) => result,
        // Same typed panic taxonomy as the API boundary
        // (`crate::render_api::render_blocking`): the payload message survives.
        Err(payload) => Err(RenderError::Panic {
            message: crate::render_api::panic_message(payload),
        }),
    }
}

/// Peak-byte estimate for budgeting. One outer permit owns the output surface,
/// nested transparency intermediates, and the page's largest sequential cold
/// image decode. Decode paths do not acquire a nested scheduler permit, so an
/// exact-fit memory limit always makes forward progress without self-deadlock.
pub fn estimate_job_bytes(request: &RenderRequest) -> u64 {
    let surface = (request.output_size.width as u64)
        .saturating_mul(request.output_size.height as u64)
        .saturating_mul(request.output_format.bytes_per_pixel() as u64);
    surface
        .saturating_add(request.page.complexity.estimated_peak_bytes)
        .saturating_add(request.page.complexity.estimated_image_decode_peak_bytes)
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
    use super::*;
    use crate::page_ir::{DeviceSize, Matrix, PageBounds, PageComplexity, Rect};
    use crate::render_api::{
        AnnotationMode, Background, OutputFormat, OutputResidency, PageTransform,
        RenderColorPolicy, RenderLimits, RenderQuality,
    };

    const fn assert_send_sync<T: Send + Sync>() {}
    const _: () = assert_send_sync::<RenderScheduler>();

    fn request_with_complexity(complexity: PageComplexity) -> RenderRequest {
        let mut page = crate::page_ir::CompiledPage::empty(PageBounds {
            crop: Rect {
                x0: 0.0,
                y0: 0.0,
                x1: 1.0,
                y1: 1.0,
            },
            rotate: 0,
        });
        page.complexity = complexity;
        RenderRequest {
            page: Arc::new(page),
            transform: PageTransform {
                matrix: Matrix::IDENTITY,
            },
            crop: None,
            output_size: DeviceSize {
                width: 2,
                height: 3,
            },
            output_format: OutputFormat::Rgba8PremultipliedSrgb,
            background: Background::White,
            annotations: AnnotationMode::None,
            color_policy: RenderColorPolicy::Original,
            quality: RenderQuality::Normal,
            limits: RenderLimits::default(),
            residency: OutputResidency::HostRequired,
        }
    }

    #[test]
    fn job_estimate_includes_output_groups_and_largest_cold_image() {
        let request = request_with_complexity(PageComplexity {
            estimated_peak_bytes: 7,
            estimated_image_decode_peak_bytes: 11,
            ..PageComplexity::default()
        });
        assert_eq!(estimate_job_bytes(&request), 2 * 3 * 4 + 7 + 11);
    }

    #[test]
    fn exact_fit_outer_permit_covers_decode_without_nested_deadlock() {
        let request = request_with_complexity(PageComplexity {
            estimated_peak_bytes: 1,
            estimated_image_decode_peak_bytes: 2,
            ..PageComplexity::default()
        });
        let estimate = estimate_job_bytes(&request);
        let budget = MemoryBudget::new(estimate);
        let permit = budget.acquire(estimate).expect("exact-fit job is admitted");
        assert_eq!(permit.bytes(), estimate);
        assert_eq!(budget.in_use(), estimate);
        drop(permit);
        assert_eq!(budget.in_use(), 0);
    }

    #[test]
    fn job_estimate_saturates_instead_of_wrapping() {
        let request = request_with_complexity(PageComplexity {
            estimated_peak_bytes: u64::MAX,
            estimated_image_decode_peak_bytes: u64::MAX,
            ..PageComplexity::default()
        });
        assert_eq!(estimate_job_bytes(&request), u64::MAX);
    }
}