app: cherry-pick rune's pause and sound fixes onto the checkout
Rune comes from app/vendor/rune now, a checkout of 63ad0209 on branch ported, carrying the four commits of upstream issues 1320 (a pause while a clip is layered holds the layer's picture and time) and 1325 (a video's sound is read ahead of the clock and leads it). Both were written against eb9f1104 and ported across the refactors since. The faults are the first two and the third in docs/rune-upstream.md; the app's workarounds in review.rs stay until the fixes arrive upstream.
This commit is contained in:
1 parent
80fef698ce
commit
5bf262b82b
3795 files changed
+663463
-28
No files matched your search
+20
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "rune-perf"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "Bounded local performance recording for native apps"
|
||||
autotests = false
|
||||
|
||||
[dependencies]
|
||||
procwatch = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
|
||||
[[test]]
|
||||
name = "no_allocator"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
# rune-perf
|
||||
|
||||
Local, bounded performance diagnostics for native apps. The crate has no Rune,
|
||||
GPU, async-runtime or network dependency. A process opts in by supplying its
|
||||
name and directory; fixtures and production policy belong to the application.
|
||||
|
||||
```rust,no_run
|
||||
use rune_perf::{Config, Frame, Outcome, Recorder};
|
||||
let config = Config::new("diagnostics/my-app-dev", "My App").build("1.4.0");
|
||||
let recorder = Recorder::start(config)?;
|
||||
recorder.record(
|
||||
Frame::new(1, 42, Outcome::Drawn)
|
||||
.update_ms(2.0)
|
||||
.render_ms(1.0)
|
||||
.allocated_bytes(rune_perf::take_allocated_bytes()),
|
||||
);
|
||||
// Off the UI thread, at orderly shutdown:
|
||||
recorder.shutdown().expect("writer panicked");
|
||||
# Ok::<(), std::io::Error>(())
|
||||
```
|
||||
|
||||
`Config` and `Frame` are built with methods, so new fields never break callers.
|
||||
Every `Frame` setter takes a value or an `Option`; an unset field is unavailable.
|
||||
Keep the recorder alive for the process. `record` timestamps, sanitizes optional
|
||||
durations, and tries a fixed-size send. It never formats, allocates in steady
|
||||
state, writes files, takes a drawable, or asks for a frame. Full queues drop
|
||||
samples and count them. All directory creation, locking, sampling and JSON runs
|
||||
on one background thread. Drop is nonblocking; `shutdown` joins off-UI. A
|
||||
replacement waits for the previous writer's directory lock, and cancellation
|
||||
also interrupts this wait. Samples queued before cancellation can be lost if the
|
||||
writer has not acquired the lock; an active writer drains on shutdown.
|
||||
|
||||
## Hook contract
|
||||
|
||||
From the app's existing compositor, measure the update time and the time
|
||||
around its compositor work. In `App::on_frame_encoded`, submit the corresponding
|
||||
sample; preserve any existing callback by calling both from that closure. Never
|
||||
replace a custom compositor just to install diagnostics. Report `None` when a
|
||||
skipped/unchanged frame had no timing. Give each window a stable numeric ID and
|
||||
its own sequence/timing state. `source` is an optional stable numeric site ID,
|
||||
not user content. Attribution must come from the app; this crate cannot infer it.
|
||||
|
||||
At an input handler, retain the oldest `Tx::input_time()` not yet matched to a
|
||||
drawn frame. At the encoding callback subtract it from `FrameEncoded::at()`;
|
||||
only then clear it. This is **input receipt to encoding**, not input-to-screen.
|
||||
Unchanged and skipped frames do not consume pending input. GPU time is an
|
||||
optional **resolved GPU timestamp** supplied by a backend; never wait for GPU
|
||||
queries on the UI thread. Rune's current public frame callback supplies neither
|
||||
GPU execution time nor actual presentation time, so those counters remain null.
|
||||
|
||||
### Explicit allocator installation
|
||||
|
||||
The library never installs a global allocator. It reads procwatch's counting
|
||||
allocator, the same one Rune's `frame-profile` tooling uses, so a binary has one.
|
||||
In the binary's main module:
|
||||
|
||||
```rust,ignore
|
||||
#[global_allocator]
|
||||
static ALLOCATOR: procwatch::alloc::Counting = procwatch::alloc::Counting::system();
|
||||
```
|
||||
|
||||
Use `procwatch::alloc::Counting::new(inner)` to wrap an allocator the binary
|
||||
already has. Pass `rune_perf::take_allocated_bytes()` with each report from the
|
||||
UI thread. It returns the bytes this thread requested since its previous call:
|
||||
`None` without the counting allocator, and `None` on a thread's first call, which
|
||||
only sets the baseline. There is no per-thread enable. Traffic includes
|
||||
successful alloc/zeroed/realloc requests (full new realloc size), excludes frees,
|
||||
other threads, native and GPU allocation, and does not mean retained heap.
|
||||
|
||||
## Files and limits
|
||||
|
||||
| Resource | Bound |
|
||||
| --- | --- |
|
||||
| Pending samples | 256 fixed-size records |
|
||||
| Rolling history | 60 seconds and 600 reports |
|
||||
| Snapshot | Atomic `perf.json`, with each write of incidents, and at shutdown when the run wrote anything, 256 KiB max |
|
||||
| Anomaly logs | `perf.log` + `perf.log.1`, 4 MiB each, kept open for appending; ten frame lines/second, held in memory and written once 2 seconds pass with no new finding (and at shutdown) |
|
||||
| Process log | A line every 30 seconds while frames arrive, kept in memory (the last 20) and written only beside a finding |
|
||||
| Incidents | 16 reusable `perf-incident-NN.json` slots, 256 KiB each |
|
||||
| Dedup keys | 64 recent rule/window/source keys; scoped to this app/build/launch |
|
||||
| Growth history | Six minute buckets |
|
||||
|
||||
Snapshots keep a stable schema-1 core (frame totals, work percentiles, memory,
|
||||
dropped samples) and add app/build/launch identity,
|
||||
capability availability, input/GPU percentiles, fds and incident counts. Missing
|
||||
measurements are null, including lifetime peaks. Capabilities describe observed
|
||||
data in the current window, not a permanent backend promise. Process counters
|
||||
come from `procwatch::usage()`, which reads memory and descriptors without walking
|
||||
threads. macOS supplies resident/physical/lifetime-peak footprint and fds; other
|
||||
platforms currently report those unavailable. Failed reads also return unknown.
|
||||
Memory is checked against the incident rules as frames arrive, at most every 2 seconds and never on a timer, so an idle app wakes nothing; a run with no finding writes no file. The snapshot's timestamp says when it was written.
|
||||
|
||||
An incident preserves the bounded recent history and dropped-sample count. Slot
|
||||
paths are reused: consumers should copy a file promptly if they need durable
|
||||
retention. `Config::incidents` takes a bounded `SyncSender<PathBuf>`.
|
||||
After a successful file write, the writer attempts one notification. A slow,
|
||||
full or disconnected consumer cannot block recording; lost notifications are
|
||||
counted and files remain available. External automation can route these paths
|
||||
to an incident tracker. There is no network export or automatic
|
||||
task creation in Rune.
|
||||
|
||||
## Rules
|
||||
|
||||
Rules warn and provide evidence plus a suggested next measurement:
|
||||
|
||||
- `long-frames`: three measured update+compositor frames ≥16.67 ms within one
|
||||
second for the same window/source.
|
||||
- `frame-stall`: measured update+compositor work ≥250 ms. Idle gaps are never
|
||||
treated as stalls; a permanently hung UI needs an external watchdog.
|
||||
- `memory-growth`: five completed, consecutive minute footprint floors strictly
|
||||
rise by at least 64 MiB and 20% in total.
|
||||
- `fd-growth`: the same pattern, at least 32 descriptors and 20%.
|
||||
|
||||
Spikes, plateaus, missing reads and gaps do not qualify as leaks. Growth remains
|
||||
a suspicion: cache warmup may produce the same pattern. A repeated key needs a
|
||||
60-second cooldown and ≥25% worsening. A global two-second interval bounds
|
||||
incident traffic; suppressed incidents are counted. Restart resets dedup state.
|
||||
|
||||
## Checks
|
||||
|
||||
```sh
|
||||
cargo test -p rune-perf -p procwatch
|
||||
cargo test --profile perf -p rune-perf instrumentation_overhead -- --ignored --nocapture --test-threads=1
|
||||
```
|
||||
|
||||
Tests cover unavailable counters, zero-allocation report paths, queue overflow,
|
||||
window separation, growth false positives, rotation, failures, callback pressure,
|
||||
replacement locking/cancellation, and a binary without the counting allocator.
|
||||
procwatch's tests cover multithreaded allocation byte accounting.
|
||||
The paired component benchmark alternates order for 21 measured rounds after
|
||||
warmup, retaining all outliers and reporting nearest-rank p50/p95. It measures
|
||||
counting-allocator overhead, same-thread timestamp/send/receive, and background writes.
|
||||
It does not establish live-window CPU percentage, GPU cost, native idle behavior,
|
||||
or input-to-screen latency.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Adopt in one app's existing frame hooks and delete its writer/allocator copy.
|
||||
Preserve the app's production/dev/fixture directory policy and CLI reader.
|
||||
2. Each native Rune example and downstream app uses the same startup recipe,
|
||||
unique app/build identity, dev directory, per-window hooks, and explicit main
|
||||
allocator. A fixture opts into an isolated scratch directory, never live data.
|
||||
3. A future standard-runner integration should compose existing hooks and
|
||||
compositors, default on only for debug native runs, and expose an opt-out.
|
||||
This crate deliberately does not make that policy decision invisibly.
|
||||
4. Add platform process adapters and asynchronous GPU timestamps separately;
|
||||
unsupported counters stay unavailable until measured. Web needs a different
|
||||
storage worker; this native file writer is not a browser backend.
|
||||
5. Add source-site maps, phase/subtree capture and an external coverage/doctor
|
||||
command after the basic recorder lands. The numeric source seam is ready;
|
||||
automatic source attribution and detailed captures are not implemented here.
|
||||
|
||||
App fixtures should cover list/history scaling with a fixed viewport, text,
|
||||
images, repeated open/close cycles, idle and teardown. Preserve allocation/work
|
||||
counts in CI; evaluate timing with optimized, paired headless runs and separately
|
||||
measure native idle/presentation. The proposed <1% CPU / <0.1 ms p95 whole-frame
|
||||
overhead and <4 MiB total recorder-memory budgets still require application-level
|
||||
measurement; fixed collection bounds alone do not prove those targets.
|
||||
@@ -0,0 +1,98 @@
|
||||
//! Warning-only rules. Growth is a suspect leak, never proof of ownership or causation.
|
||||
use std::collections::VecDeque;
|
||||
use serde_json::{Value, json};
|
||||
use procwatch::Usage;
|
||||
use crate::{SLOW_MS, Sample, stats::Stats};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Rule { LongFrames, Stall, MemoryGrowth, FdGrowth }
|
||||
impl Rule {
|
||||
pub fn id(self) -> &'static str {
|
||||
match self { Self::LongFrames => "long-frames", Self::Stall => "frame-stall",
|
||||
Self::MemoryGrowth => "memory-growth", Self::FdGrowth => "fd-growth" }
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Finding {
|
||||
pub rule: Rule,
|
||||
pub window: u64,
|
||||
pub source: Option<u64>,
|
||||
pub severity: f64,
|
||||
pub evidence: Value,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Sent { rule: Rule, window: u64, source: Option<u64>, at: u64, severity: f64 }
|
||||
#[derive(Clone, Copy)]
|
||||
struct Floor { minute: u64, memory: Option<u64>, fds: Option<u64> }
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Detector {
|
||||
sent: VecDeque<Sent>,
|
||||
floors: VecDeque<Floor>,
|
||||
pub suppressed: u64,
|
||||
last_sent: Option<u64>,
|
||||
}
|
||||
|
||||
impl Detector {
|
||||
pub fn frame(&self, s: Sample, stats: &Stats) -> Option<Finding> {
|
||||
let work = s.frame.work_ms()?;
|
||||
let rule = if work >= 250.0 { Rule::Stall } else if work >= SLOW_MS {
|
||||
let count = stats.recent.iter().rev().take_while(|p| s.at_ms.saturating_sub(p.at_ms) <= 1000)
|
||||
.filter(|p| p.frame.window == s.frame.window && p.frame.source == s.frame.source
|
||||
&& p.frame.work_ms().is_some_and(|t| t >= SLOW_MS)).take(3).count();
|
||||
if count < 3 { return None; }
|
||||
Rule::LongFrames
|
||||
} else { return None; };
|
||||
Some(Finding { rule, window: s.frame.window, source: s.frame.source, severity: work,
|
||||
evidence: json!({"frame": s.json(), "confidence": "measured work; cause unknown",
|
||||
"next_measurement": "capture update/compositor phases for this window and source"}) })
|
||||
}
|
||||
|
||||
pub fn process(&mut self, now: u64, p: Usage) -> Vec<Finding> {
|
||||
let minute = now / 60_000;
|
||||
let fds = p.fds.map(u64::from);
|
||||
if self.floors.back().is_some_and(|f| minute > f.minute + 1) { self.floors.clear(); }
|
||||
match self.floors.back_mut() {
|
||||
Some(f) if f.minute == minute => {
|
||||
// A missing read invalidates this minute, rather than bridging an evidence gap.
|
||||
f.memory = f.memory.zip(p.footprint).map(|(a,b)| a.min(b));
|
||||
f.fds = f.fds.zip(fds).map(|(a,b)| a.min(b));
|
||||
}
|
||||
_ => {
|
||||
if self.floors.len() == 6 { self.floors.pop_front(); }
|
||||
self.floors.push_back(Floor { minute, memory: p.footprint, fds });
|
||||
}
|
||||
}
|
||||
// Five completed minute floors, excluding the in-progress minute.
|
||||
if self.floors.len() < 6 { return Vec::new(); }
|
||||
let mut out = Vec::new();
|
||||
for (rule, minimum) in [(Rule::MemoryGrowth, 64 << 20), (Rule::FdGrowth, 32)] {
|
||||
let values: Option<Vec<u64>> = self.floors.iter().take(5)
|
||||
.map(|f| if rule == Rule::MemoryGrowth { f.memory } else { f.fds }).collect();
|
||||
let Some(values) = values else { continue };
|
||||
let delta = values[4].saturating_sub(values[0]);
|
||||
if values.windows(2).all(|p| p[1] > p[0]) && delta >= minimum && delta as f64 >= values[0] as f64 * 0.2 {
|
||||
out.push(Finding { rule, window: 0, source: None, severity: values[4] as f64,
|
||||
evidence: json!({"minute_floors": values, "growth": delta,
|
||||
"confidence": "suspected growth, not a proven leak",
|
||||
"next_measurement": "repeat view open/close cycles; check whether footprint and descriptors plateau"}) });
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn admit(&mut self, now: u64, f: &Finding) -> bool {
|
||||
let old = self.sent.iter().find(|s| s.rule == f.rule && s.window == f.window && s.source == f.source);
|
||||
if self.last_sent.is_some_and(|t| now.saturating_sub(t) < 2000)
|
||||
|| old.is_some_and(|s| now.saturating_sub(s.at) < 60_000 || f.severity < s.severity * 1.25) {
|
||||
self.suppressed += 1;
|
||||
return false;
|
||||
}
|
||||
self.sent.retain(|s| !(s.rule == f.rule && s.window == f.window && s.source == f.source));
|
||||
if self.sent.len() == 64 { self.sent.pop_front(); }
|
||||
self.sent.push_back(Sent { rule: f.rule, window: f.window, source: f.source, at: now, severity: f.severity });
|
||||
self.last_sent = Some(now);
|
||||
true
|
||||
}
|
||||
}
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
//! Bounded local diagnostics. Apps explicitly choose a directory and install their hooks.
|
||||
//! No network, global allocator installation, redraws, or per-frame formatting.
|
||||
|
||||
// Unit benchmark `recorder::tests::instrumentation_overhead` calls `GlobalAlloc::alloc`/`dealloc` directly.
|
||||
#![cfg_attr(not(test), forbid(unsafe_code))]
|
||||
#![cfg_attr(target_arch = "wasm32", allow(dead_code))]
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod incident;
|
||||
mod recorder;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod stats;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod store;
|
||||
|
||||
pub use recorder::Recorder;
|
||||
|
||||
use std::{cell::Cell, path::PathBuf, sync::mpsc::SyncSender};
|
||||
|
||||
pub(crate) const QUEUE: usize = 256;
|
||||
pub(crate) const RECENT: usize = 600;
|
||||
pub(crate) const WINDOW_MS: u64 = 60_000;
|
||||
pub(crate) const SLOW_MS: f64 = 1000.0 / 60.0;
|
||||
pub(crate) const LARGE_BYTES: u64 = 8 << 20;
|
||||
|
||||
// rune-perf is native-only and has no rune-core dependency.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[inline]
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
pub(crate) fn now() -> std::time::Instant { std::time::Instant::now() }
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[inline]
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
pub(crate) fn now_ms() -> u64 {
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_millis() as u64
|
||||
}
|
||||
|
||||
/// How long the recorder waits with nothing to write before [`Config::on_idle`] runs.
|
||||
pub const IDLE: std::time::Duration = std::time::Duration::from_secs(10);
|
||||
|
||||
/// Minimum gap between two [`Config::on_idle`] runs on the recorder thread.
|
||||
pub const IDLE_MIN_GAP: std::time::Duration = std::time::Duration::from_secs(180);
|
||||
|
||||
/// One process/launch per directory. Use separate directories for dev and captures.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Config {
|
||||
directory: PathBuf,
|
||||
app: String,
|
||||
build: String,
|
||||
incidents: Option<SyncSender<PathBuf>>,
|
||||
idle: Option<fn()>,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn new(directory: impl Into<PathBuf>, app: impl Into<String>) -> Self {
|
||||
Self { directory: directory.into(), app: app.into(), build: String::new(), incidents: None, idle: None }
|
||||
}
|
||||
|
||||
/// Build identity written into snapshots and incidents, such as a version or commit.
|
||||
pub fn build(mut self, build: impl Into<String>) -> Self {
|
||||
self.build = build.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Runs once per idle spell (at least [`IDLE_MIN_GAP`] after the previous tidy) on the
|
||||
/// recorder's thread after [`IDLE`] with no new samples or pending writes, then the thread
|
||||
/// waits with no timer.
|
||||
pub fn on_idle(mut self, idle: fn()) -> Self {
|
||||
self.idle = Some(idle);
|
||||
self
|
||||
}
|
||||
|
||||
/// Bounded notification queue for incident paths. A full/disconnected receiver loses a
|
||||
/// notification, never the incident file. Consumers may route the path into their own
|
||||
/// task system.
|
||||
pub fn incidents(mut self, tx: SyncSender<PathBuf>) -> Self {
|
||||
self.incidents = Some(tx);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum Outcome {
|
||||
Drawn,
|
||||
Unchanged,
|
||||
#[default]
|
||||
Skipped,
|
||||
}
|
||||
|
||||
impl Outcome {
|
||||
fn name(self) -> &'static str {
|
||||
match self { Self::Drawn => "drawn", Self::Unchanged => "unchanged", Self::Skipped => "skipped" }
|
||||
}
|
||||
}
|
||||
|
||||
/// Fixed-size report; an unset measurement is unavailable, never an invented zero.
|
||||
/// Times describe work, not gaps between frames. The caller owns window/source IDs.
|
||||
/// Each setter takes a value or an `Option`, so a missing measurement passes straight through.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct Frame {
|
||||
window: u64,
|
||||
seq: u64,
|
||||
outcome: Outcome,
|
||||
update_ms: Option<f64>,
|
||||
render_ms: Option<f64>,
|
||||
input_to_frame_ms: Option<f64>,
|
||||
gpu_ms: Option<f64>,
|
||||
allocated_bytes: Option<u64>,
|
||||
source: Option<u64>,
|
||||
}
|
||||
|
||||
impl Frame {
|
||||
pub fn new(window: u64, seq: u64, outcome: Outcome) -> Self {
|
||||
Self { window, seq, outcome, ..Self::default() }
|
||||
}
|
||||
|
||||
pub fn update_ms(mut self, ms: impl Into<Option<f64>>) -> Self {
|
||||
self.update_ms = ms.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Compositor (render and encode) wall time.
|
||||
pub fn render_ms(mut self, ms: impl Into<Option<f64>>) -> Self {
|
||||
self.render_ms = ms.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Input receipt to the encoding boundary, NOT input-to-screen latency.
|
||||
pub fn input_to_frame_ms(mut self, ms: impl Into<Option<f64>>) -> Self {
|
||||
self.input_to_frame_ms = ms.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Resolved GPU timestamp duration, only when the backend supplies one.
|
||||
pub fn gpu_ms(mut self, ms: impl Into<Option<f64>>) -> Self {
|
||||
self.gpu_ms = ms.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Successful Rust allocation requests on the reporting thread since its last report,
|
||||
/// usually [`take_allocated_bytes`].
|
||||
pub fn allocated_bytes(mut self, bytes: impl Into<Option<u64>>) -> Self {
|
||||
self.allocated_bytes = bytes.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Stable numeric source identifier; never user text or content.
|
||||
pub fn source(mut self, id: impl Into<Option<u64>>) -> Self {
|
||||
self.source = id.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Update plus compositor time, when both were measured.
|
||||
pub fn work_ms(self) -> Option<f64> { self.update_ms.zip(self.render_ms).map(|(u, r)| u + r).filter(|v| v.is_finite()) }
|
||||
|
||||
fn sanitize(mut self) -> Self {
|
||||
for t in [&mut self.update_ms, &mut self.render_ms, &mut self.input_to_frame_ms, &mut self.gpu_ms] {
|
||||
*t = t.filter(|v| v.is_finite() && *v >= 0.0);
|
||||
}
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! { static ALLOCATED_AT: Cell<Option<u64>> = const { Cell::new(None) }; }
|
||||
|
||||
/// Bytes this thread asked the allocator for since its previous call, for
|
||||
/// [`Frame::allocated_bytes`]. Needs `procwatch::alloc::Counting` as the global allocator.
|
||||
/// `None` when it isn't installed, and on a thread's first call, which only sets the baseline.
|
||||
/// Never allocates.
|
||||
pub fn take_allocated_bytes() -> Option<u64> {
|
||||
let now = procwatch::alloc::thread_allocated_bytes()?;
|
||||
let last = ALLOCATED_AT.try_with(|at| at.replace(Some(now))).ok()??;
|
||||
Some(now.wrapping_sub(last))
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct Sample { at_ms: u64, frame: Frame }
|
||||
|
||||
impl Sample {
|
||||
fn anomaly(self) -> bool {
|
||||
self.frame.work_ms().is_some_and(|ms| ms >= SLOW_MS)
|
||||
|| self.frame.allocated_bytes.is_some_and(|n| n >= LARGE_BYTES)
|
||||
}
|
||||
fn json(self) -> serde_json::Value {
|
||||
let f = self.frame;
|
||||
serde_json::json!({"at_ms": self.at_ms, "window": f.window, "source": f.source,
|
||||
"seq": f.seq, "outcome": f.outcome.name(), "update_ms": f.update_ms,
|
||||
"render_ms": f.render_ms, "work_ms": f.work_ms(),
|
||||
"input_to_frame_ms": f.input_to_frame_ms, "gpu_ms": f.gpu_ms,
|
||||
"ui_allocated_bytes": f.allocated_bytes})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
use std::io;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use std::{sync::{Arc, atomic::{AtomicBool, AtomicU64, Ordering::Relaxed}, mpsc::{SyncSender, sync_channel}}, thread::JoinHandle, time::Instant};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use crate::{QUEUE, Sample, store};
|
||||
use crate::{Config, Frame};
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Health {
|
||||
pub dropped: AtomicU64,
|
||||
pub errors: AtomicU64,
|
||||
pub stop: AtomicBool,
|
||||
}
|
||||
|
||||
/// Owns one writer. Drop cancels without blocking the UI; `shutdown` drains and joins off-UI.
|
||||
/// Dropping while waiting for a previous process's directory lock cancels that wait too.
|
||||
pub struct Recorder {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
start: Instant,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
out: Option<SyncSender<Sample>>,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
health: Arc<Health>,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
worker: Option<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl Recorder {
|
||||
pub fn start(config: Config) -> io::Result<Self> {
|
||||
if config.app.len() > 128 || config.build.len() > 256 {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "app/build identity too long"));
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
Err(io::Error::new(io::ErrorKind::Unsupported, "local perf files are unsupported on web"))
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let (out, rx) = sync_channel(QUEUE);
|
||||
let start = crate::now();
|
||||
let health = Arc::new(Health::default());
|
||||
let h = health.clone();
|
||||
// All filesystem work, including mkdir/open/locking, belongs to this thread.
|
||||
let worker = std::thread::Builder::new().name("rune-perf".into()).spawn(move || {
|
||||
if let Err(e) = store::run(config, rx, start, &h) {
|
||||
h.errors.fetch_add(1, Relaxed);
|
||||
eprintln!("rune-perf: recorder stopped: {e}");
|
||||
}
|
||||
})?;
|
||||
Ok(Self { start, out: Some(out), health, worker: Some(worker) })
|
||||
}
|
||||
}
|
||||
|
||||
/// Nonblocking, fixed-size send. Returns false when the queue is full or writer stopped.
|
||||
pub fn record(&self, frame: Frame) -> bool {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let _ = frame;
|
||||
false
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let sample = Sample { at_ms: self.start.elapsed().as_millis() as u64, frame: frame.sanitize() };
|
||||
if self.out.as_ref().is_some_and(|out| out.try_send(sample).is_ok()) { return true; }
|
||||
self.health.dropped.fetch_add(1, Relaxed);
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dropped_samples(&self) -> u64 {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
0
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
self.health.dropped.load(Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
/// Call off the UI thread. Cancels lock waits; drains queued frames if already recording.
|
||||
pub fn shutdown(mut self) -> std::thread::Result<()> {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
let _ = &mut self;
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
self.health.stop.store(true, Relaxed);
|
||||
self.out.take();
|
||||
self.worker.take().map_or(Ok(()), |w| w.join())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl Drop for Recorder {
|
||||
fn drop(&mut self) { self.health.stop.store(true, Relaxed); }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,69 @@
|
||||
use super::*;
|
||||
use crate::{Outcome, stats::percentiles};
|
||||
use procwatch::alloc::{Counting, thread_allocated_bytes};
|
||||
use std::{alloc::{GlobalAlloc, Layout, System}, hint::black_box};
|
||||
|
||||
#[test]
|
||||
fn report_path_has_zero_allocations_and_overflow_is_bounded() {
|
||||
let (out, rx) = sync_channel(QUEUE);
|
||||
let r = Recorder { start: crate::now(), out: Some(out), health: Arc::default(), worker: None };
|
||||
r.record(Frame::default());
|
||||
rx.recv().unwrap();
|
||||
// Unwrap: the test binary installs the counting allocator, so this is a real zero.
|
||||
let before = thread_allocated_bytes().unwrap();
|
||||
for n in 0..1000 { r.record(black_box(Frame::new(1, n, Outcome::Drawn).update_ms(1.0).render_ms(1.0))); }
|
||||
assert_eq!(thread_allocated_bytes().unwrap(), before);
|
||||
assert_eq!(r.dropped_samples(), 1000 - QUEUE as u64);
|
||||
assert_eq!(rx.try_iter().count(), QUEUE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "manual paired optimized component benchmark"]
|
||||
#[allow(unsafe_code)]
|
||||
fn instrumentation_overhead() {
|
||||
const N: usize = 200_000;
|
||||
fn allocations(a: &impl GlobalAlloc) -> f64 {
|
||||
let at = crate::now();
|
||||
for _ in 0..N {
|
||||
// SAFETY: valid layout, checked allocation, freed once with the same layout.
|
||||
unsafe {
|
||||
let l = Layout::from_size_align(black_box(128), 8).unwrap();
|
||||
let p = black_box(a.alloc(l));
|
||||
assert!(!p.is_null());
|
||||
std::ptr::write_volatile(p, 42);
|
||||
a.dealloc(p, l);
|
||||
}
|
||||
}
|
||||
black_box(thread_allocated_bytes());
|
||||
at.elapsed().as_nanos() as f64 / N as f64
|
||||
}
|
||||
let (out, rx) = sync_channel(QUEUE);
|
||||
let r = Recorder { start: crate::now(), out: Some(out), health: Arc::default(), worker: None };
|
||||
let mut values: [Vec<f64>; 4] = Default::default();
|
||||
let mut deltas = Vec::new();
|
||||
for round in 0..22 {
|
||||
let mut measured = [0.0; 4];
|
||||
for i in 0..4 {
|
||||
let mode = if round % 2 == 0 { i } else { 3 - i };
|
||||
measured[mode] = match mode {
|
||||
0 => allocations(&System),
|
||||
1 => allocations(&Counting::system()),
|
||||
_ => {
|
||||
let at = crate::now();
|
||||
for _ in 0..N {
|
||||
let f = black_box(Frame::default());
|
||||
if mode == 3 { black_box(r.record(f)); black_box(rx.recv().unwrap()); }
|
||||
else { black_box(f); }
|
||||
}
|
||||
at.elapsed().as_nanos() as f64 / N as f64
|
||||
}
|
||||
};
|
||||
if round > 0 { values[mode].push(measured[mode]); }
|
||||
}
|
||||
if round > 0 { deltas.push(measured[3] - measured[2]); }
|
||||
}
|
||||
for (name, v) in ["system_alloc_free_ns", "counting_alloc_free_ns", "baseline_frame_ns", "report_roundtrip_ns"].into_iter().zip(values) {
|
||||
println!("METRIC {name} {}", percentiles(v));
|
||||
}
|
||||
println!("METRIC paired_report_delta_ns {}", percentiles(deltas));
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
use std::collections::VecDeque;
|
||||
use serde_json::{Value, json};
|
||||
use crate::{RECENT, Sample, WINDOW_MS};
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Stats {
|
||||
pub recent: VecDeque<Sample>,
|
||||
total: u64,
|
||||
anomalies: u64,
|
||||
suppressed: u64,
|
||||
max_work: Option<f64>,
|
||||
max_bytes: Option<u64>,
|
||||
log_second: u64,
|
||||
logged: u32,
|
||||
}
|
||||
|
||||
impl Stats {
|
||||
pub fn accept(&mut self, s: Sample) -> bool {
|
||||
self.total += 1;
|
||||
if let Some(v) = s.frame.work_ms() { self.max_work = Some(self.max_work.map_or(v, |old| old.max(v))); }
|
||||
if let Some(v) = s.frame.allocated_bytes { self.max_bytes = Some(self.max_bytes.map_or(v, |old| old.max(v))); }
|
||||
if self.recent.len() == RECENT { self.recent.pop_front(); }
|
||||
self.recent.push_back(s);
|
||||
self.prune(s.at_ms);
|
||||
if !s.anomaly() { return false; }
|
||||
self.anomalies += 1;
|
||||
if self.log_second != s.at_ms / 1000 { self.log_second = s.at_ms / 1000; self.logged = 0; }
|
||||
if self.logged == 10 { self.suppressed += 1; return false; }
|
||||
self.logged += 1;
|
||||
true
|
||||
}
|
||||
|
||||
pub fn prune(&mut self, now: u64) {
|
||||
while self.recent.front().is_some_and(|s| now.saturating_sub(s.at_ms) > WINDOW_MS) { self.recent.pop_front(); }
|
||||
}
|
||||
|
||||
pub fn json(&self) -> Value {
|
||||
let metric = |f: fn(&Sample) -> Option<f64>| percentiles(self.recent.iter().filter_map(f).collect());
|
||||
json!({"total": self.total, "anomalies": self.anomalies, "log_suppressed": self.suppressed,
|
||||
"lifetime_max_work_ms": self.max_work, "lifetime_max_ui_allocated_bytes": self.max_bytes,
|
||||
"recent_count": self.recent.len(), "timed_count": self.recent.iter().filter(|s| s.frame.work_ms().is_some()).count(),
|
||||
"window_ms": WINDOW_MS, "capacity": RECENT,
|
||||
"work_ms": metric(|s| s.frame.work_ms()),
|
||||
"ui_allocated_bytes": metric(|s| s.frame.allocated_bytes.map(|n| n as f64)),
|
||||
"input_to_frame_ms": metric(|s| s.frame.input_to_frame_ms),
|
||||
"gpu_ms": metric(|s| s.frame.gpu_ms),
|
||||
"latest": self.recent.back().map(|s| s.json()),
|
||||
"recent_anomalies": self.recent.iter().rev().filter(|s| s.anomaly()).take(20).map(|s| s.json()).collect::<Vec<_>>()})
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn percentiles(mut values: Vec<f64>) -> Value {
|
||||
if values.is_empty() { return Value::Null; }
|
||||
values.sort_by(f64::total_cmp);
|
||||
let p = |q: f64| values[((values.len() as f64 * q).ceil() as usize).saturating_sub(1)];
|
||||
json!({"p50": p(0.5), "p95": p(0.95), "max": values.last(), "count": values.len()})
|
||||
}
|
||||
+284
@@ -0,0 +1,284 @@
|
||||
use std::{fs::{File, OpenOptions, TryLockError}, io::{self, Write}, path::Path,
|
||||
sync::{atomic::Ordering::Relaxed, mpsc::{Receiver, RecvTimeoutError}}, time::{Duration, Instant}};
|
||||
use serde_json::{Value, json};
|
||||
use procwatch::Usage;
|
||||
use crate::{Config, LARGE_BYTES, SLOW_MS, Sample, incident::{Detector, Finding}, now, now_ms, recorder::Health, stats::Stats};
|
||||
|
||||
const LOG_BYTES: u64 = 4 << 20;
|
||||
const INCIDENT_BYTES: usize = 256 << 10;
|
||||
/// How often, at most, process memory is checked for incidents: as frames arrive, never on a
|
||||
/// timer of its own, so an idle app wakes nothing.
|
||||
const CHECK_EVERY: Duration = Duration::from_secs(2);
|
||||
/// What was found is kept in memory and written once the app has been this long without
|
||||
/// another slow frame or incident, so a burst (typing in a slow build) is one write, after it.
|
||||
const QUIET: Duration = Duration::from_secs(2);
|
||||
/// Memory lines kept while nothing else is to be written; they go out only beside a finding.
|
||||
const MEMORY_LINES: usize = 20;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum IdleTidy {
|
||||
Parked { last: Option<Instant> },
|
||||
Armed { last: Option<Instant>, due: Instant },
|
||||
}
|
||||
|
||||
impl IdleTidy {
|
||||
fn on_work(self, now: Instant, hooked: bool) -> Self {
|
||||
let last = match self {
|
||||
Self::Parked { last } | Self::Armed { last, .. } => last,
|
||||
};
|
||||
if !hooked {
|
||||
return Self::Parked { last };
|
||||
}
|
||||
let due = last.map_or(now + crate::IDLE, |prev| (prev + crate::IDLE_MIN_GAP).max(now + crate::IDLE));
|
||||
Self::Armed { last, due }
|
||||
}
|
||||
|
||||
fn wait(self, now: Instant) -> Option<Duration> {
|
||||
match self {
|
||||
Self::Parked { .. } => None,
|
||||
Self::Armed { due, .. } => Some(due.saturating_duration_since(now)),
|
||||
}
|
||||
}
|
||||
|
||||
fn take_due(&mut self, now: Instant) -> bool {
|
||||
match *self {
|
||||
Self::Armed { due, .. } if now >= due => {
|
||||
*self = Self::Parked { last: Some(now) };
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn run(config: Config, rx: Receiver<Sample>, start: Instant, health: &Health) -> io::Result<()> {
|
||||
std::fs::create_dir_all(&config.directory)?;
|
||||
let lock = OpenOptions::new().create(true).truncate(false).read(true).write(true)
|
||||
.open(config.directory.join(".perf.lock"))?;
|
||||
if !acquire(&lock, health)? { return Ok(()); }
|
||||
let mut writer = Writer::new(&config, start, health);
|
||||
let mut checked: Option<Instant> = None;
|
||||
let mut tidy = IdleTidy::Parked { last: None };
|
||||
loop {
|
||||
let got = match writer.due {
|
||||
Some(due) => rx.recv_timeout(due.saturating_duration_since(now())),
|
||||
// Nothing due to flush: when a hook is armed after samples, tidy once per idle spell
|
||||
// (at least IDLE_MIN_GAP apart), then wait with no timer.
|
||||
None => match (config.idle, tidy.wait(now())) {
|
||||
(Some(idle), Some(wait)) => match rx.recv_timeout(wait) {
|
||||
Err(RecvTimeoutError::Timeout) => {
|
||||
if tidy.take_due(now()) {
|
||||
idle();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
got => got,
|
||||
},
|
||||
_ => rx.recv().map_err(|_| RecvTimeoutError::Disconnected),
|
||||
},
|
||||
};
|
||||
match got {
|
||||
Ok(s) => {
|
||||
writer.accept(s);
|
||||
tidy = tidy.on_work(now(), config.idle.is_some());
|
||||
if checked.is_none_or(|at| at.elapsed() >= CHECK_EVERY) {
|
||||
writer.check();
|
||||
checked = Some(now());
|
||||
}
|
||||
}
|
||||
Err(RecvTimeoutError::Disconnected) => {
|
||||
writer.check();
|
||||
writer.flush();
|
||||
if writer.wrote { writer.snapshot(); }
|
||||
break;
|
||||
}
|
||||
Err(RecvTimeoutError::Timeout) => writer.flush(),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn acquire(lock: &File, health: &Health) -> io::Result<bool> {
|
||||
loop {
|
||||
if health.stop.load(Relaxed) { return Ok(false); }
|
||||
match lock.try_lock() {
|
||||
Ok(()) => return Ok(true),
|
||||
Err(TryLockError::WouldBlock) => std::thread::park_timeout(Duration::from_millis(100)),
|
||||
Err(TryLockError::Error(e)) if e.kind() == io::ErrorKind::Interrupted => continue,
|
||||
Err(TryLockError::Error(e)) => return Err(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Writer<'a> {
|
||||
config: &'a Config,
|
||||
health: &'a Health,
|
||||
start: Instant,
|
||||
launch: String,
|
||||
started_at: u64,
|
||||
stats: Stats,
|
||||
detector: Detector,
|
||||
log: Log<'a>,
|
||||
memory_at: u64,
|
||||
incidents: u64,
|
||||
hook_dropped: u64,
|
||||
/// Log lines and incident files found since the last flush, and when to write them.
|
||||
lines: Vec<Value>,
|
||||
found: Vec<(String, Value)>,
|
||||
due: Option<Instant>,
|
||||
/// Anything was written this run, so the shutdown snapshot goes out too.
|
||||
wrote: bool,
|
||||
}
|
||||
|
||||
impl<'a> Writer<'a> {
|
||||
fn new(config: &'a Config, start: Instant, health: &'a Health) -> Self {
|
||||
let started_at = now_ms().saturating_sub(start.elapsed().as_millis() as u64);
|
||||
Self { config, health, start, launch: format!("{}-{started_at}", std::process::id()), started_at,
|
||||
stats: Stats::default(), detector: Detector::default(), memory_at: 0, incidents: 0, hook_dropped: 0,
|
||||
log: Log { dir: &config.directory, file: None, size: 0, limit: LOG_BYTES },
|
||||
lines: Vec::new(), found: Vec::new(), due: None, wrote: false }
|
||||
}
|
||||
|
||||
fn accept(&mut self, s: Sample) {
|
||||
if self.stats.accept(s) {
|
||||
self.lines.push(json!({"kind": "frame", "launch": self.launch, "frame": s.json()}));
|
||||
self.due = Some(crate::now() + QUIET);
|
||||
}
|
||||
if let Some(f) = self.detector.frame(s, &self.stats) { self.incident(s.at_ms, f); }
|
||||
}
|
||||
|
||||
fn incident(&mut self, now: u64, f: Finding) {
|
||||
if !self.detector.admit(now, &f) { return; }
|
||||
let value = json!({"schema": 1, "app": self.config.app, "build": self.config.build,
|
||||
"launch": self.launch, "pid": std::process::id(), "created_at_ms": now_ms(),
|
||||
"rule": f.rule.id(), "window": f.window, "source": f.source, "evidence": f.evidence,
|
||||
"history": self.stats.recent.iter().map(|s| s.json()).collect::<Vec<_>>(),
|
||||
"dropped_samples": self.health.dropped.load(Relaxed)});
|
||||
let name = format!("perf-incident-{:02}.json", self.incidents % 16);
|
||||
self.incidents += 1;
|
||||
// A later incident in the same slot replaces this one before it's written: its
|
||||
// notification is lost, as a full receiver's is.
|
||||
let before = self.found.len();
|
||||
self.found.retain(|(n, _)| *n != name);
|
||||
if self.found.len() < before && self.config.incidents.is_some() { self.hook_dropped += 1; }
|
||||
self.found.push((name, value));
|
||||
self.due = Some(crate::now() + QUIET);
|
||||
}
|
||||
|
||||
/// Writes what was found since the last flush: the log lines, then each incident file and a
|
||||
/// snapshot beside them. Nothing when nothing was found; memory lines alone wait.
|
||||
fn flush(&mut self) {
|
||||
self.due = None;
|
||||
let findings = self.lines.iter().any(|l| l["kind"] != "memory") || !self.found.is_empty();
|
||||
if !findings { return; }
|
||||
self.wrote = true;
|
||||
for line in std::mem::take(&mut self.lines) {
|
||||
let result = self.log.append(&line);
|
||||
self.error(result);
|
||||
}
|
||||
let found = std::mem::take(&mut self.found);
|
||||
let any = !found.is_empty();
|
||||
for (name, value) in found {
|
||||
match atomic_json(&self.config.directory, &name, &value, INCIDENT_BYTES) {
|
||||
Ok(()) => {
|
||||
if let Some(hook) = &self.config.incidents
|
||||
&& hook.try_send(self.config.directory.join(name)).is_err() { self.hook_dropped += 1; }
|
||||
}
|
||||
Err(e) => self.error(Err(e)),
|
||||
}
|
||||
}
|
||||
if any { self.write_snapshot(); }
|
||||
}
|
||||
|
||||
/// Writes what is still in memory, then `perf.json`.
|
||||
fn snapshot(&mut self) {
|
||||
self.flush();
|
||||
self.write_snapshot();
|
||||
}
|
||||
|
||||
/// The periodic check: process memory against the incident rules, and a memory line in the
|
||||
/// log every 30 s. No snapshot.
|
||||
fn check(&mut self) {
|
||||
let now = self.start.elapsed().as_millis() as u64;
|
||||
self.stats.prune(now);
|
||||
let memory = procwatch::usage();
|
||||
for f in self.detector.process(now, memory) { self.incident(now, f); }
|
||||
if now >= self.memory_at {
|
||||
let memory_lines = self.lines.iter().filter(|l| l["kind"] == "memory").count();
|
||||
if memory_lines >= MEMORY_LINES && let Some(i) = self.lines.iter().position(|l| l["kind"] == "memory") { self.lines.remove(i); }
|
||||
self.lines.push(json!({"kind": "memory", "at_ms": now, "launch": self.launch, "memory": usage_json(memory)}));
|
||||
self.memory_at = now + 30_000;
|
||||
}
|
||||
}
|
||||
|
||||
/// `perf.json`: beside each flush with incidents, and at shutdown when this run wrote anything.
|
||||
fn write_snapshot(&mut self) {
|
||||
let now = self.start.elapsed().as_millis() as u64;
|
||||
let memory = procwatch::usage();
|
||||
let frames = self.stats.json();
|
||||
let snapshot = json!({"schema": 1, "recorder_version": env!("CARGO_PKG_VERSION"),
|
||||
"app": self.config.app, "version": self.config.build, "launch": self.launch,
|
||||
"pid": std::process::id(), "started_at_ms": self.started_at, "updated_at_ms": now_ms(), "uptime_ms": now,
|
||||
"scope": "work_ms = update + compositor wall time; input_to_frame_ms ends at encoding, not presentation; allocation requests are not retained heap",
|
||||
"slow_ms": SLOW_MS, "large_bytes": LARGE_BYTES, "memory": usage_json(memory),
|
||||
"capabilities": {"process_memory": memory.resident.is_some(), "file_descriptors": memory.fds.is_some(),
|
||||
"ui_allocations": !frames["ui_allocated_bytes"].is_null(),
|
||||
"input_to_frame": !frames["input_to_frame_ms"].is_null(), "gpu_timestamps": !frames["gpu_ms"].is_null(),
|
||||
"presentation": false},
|
||||
"dropped_samples": self.health.dropped.load(Relaxed), "write_errors": self.health.errors.load(Relaxed),
|
||||
"incidents": self.incidents, "incidents_suppressed": self.detector.suppressed,
|
||||
"incident_notifications_dropped": self.hook_dropped, "frames": frames});
|
||||
self.error(atomic_json(&self.config.directory, "perf.json", &snapshot, INCIDENT_BYTES));
|
||||
}
|
||||
|
||||
fn error(&self, result: io::Result<()>) {
|
||||
if let Err(e) = result
|
||||
&& self.health.errors.fetch_add(1, Relaxed) == 0 { eprintln!("rune-perf: write failed: {e}"); }
|
||||
}
|
||||
}
|
||||
|
||||
fn usage_json(u: Usage) -> Value {
|
||||
json!({"resident_bytes": u.resident, "footprint_bytes": u.footprint,
|
||||
"peak_footprint_bytes": u.footprint_peak, "open_fds": u.fds})
|
||||
}
|
||||
|
||||
fn atomic_json(dir: &Path, name: &str, value: &Value, limit: usize) -> io::Result<()> {
|
||||
let bytes = serde_json::to_vec(value)?;
|
||||
if bytes.len() > limit { return Err(io::Error::other("performance record exceeds byte cap")); }
|
||||
let tmp = dir.join(format!(".{name}.tmp"));
|
||||
std::fs::write(&tmp, bytes)?;
|
||||
std::fs::rename(tmp, dir.join(name))
|
||||
}
|
||||
|
||||
/// `perf.log`, kept open for appending: a line costs one write, not an open, a stat and a close.
|
||||
struct Log<'a> { dir: &'a Path, file: Option<File>, size: u64, limit: u64 }
|
||||
impl Log<'_> {
|
||||
fn append(&mut self, value: &Value) -> io::Result<()> {
|
||||
let mut line = serde_json::to_vec(value)?;
|
||||
line.push(b'\n');
|
||||
if line.len() as u64 > self.limit { return Err(io::Error::other("performance record exceeds log limit")); }
|
||||
let path = self.dir.join("perf.log");
|
||||
if self.file.is_none() {
|
||||
let file = OpenOptions::new().create(true).append(true).open(&path)?;
|
||||
self.size = file.metadata()?.len();
|
||||
self.file = Some(file);
|
||||
}
|
||||
if self.size + line.len() as u64 > self.limit {
|
||||
self.file = None;
|
||||
std::fs::rename(&path, self.dir.join("perf.log.1"))?;
|
||||
self.file = Some(OpenOptions::new().create(true).append(true).open(&path)?);
|
||||
self.size = 0;
|
||||
}
|
||||
let Some(file) = self.file.as_mut() else { return Ok(()) };
|
||||
if let Err(e) = file.write_all(&line) {
|
||||
// A partial write (a full disk): the next line reopens and reads the real size.
|
||||
self.file = None;
|
||||
return Err(e);
|
||||
}
|
||||
self.size += line.len() as u64;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
use super::*;
|
||||
use crate::{Frame, Outcome, Recorder};
|
||||
use std::sync::{Arc, mpsc::sync_channel};
|
||||
|
||||
fn frame(at_ms: u64) -> Sample {
|
||||
Sample { at_ms, frame: Frame::new(0, at_ms, Outcome::Drawn).update_ms(300.0).render_ms(1.0) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writer_publishes_snapshot_and_bounded_incidents_even_when_hook_is_full() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (tx, rx) = sync_channel(1);
|
||||
let config = Config::new(dir.path(), "fixture").build("1.0").incidents(tx);
|
||||
let health = Health::default();
|
||||
let mut w = Writer::new(&config, crate::now(), &health);
|
||||
for n in 0..40 {
|
||||
let mut s = frame(n * 2000);
|
||||
s.frame.window = n;
|
||||
w.accept(s);
|
||||
}
|
||||
w.snapshot();
|
||||
assert_eq!(w.incidents, 40);
|
||||
assert_eq!(w.hook_dropped, 39);
|
||||
assert!(rx.try_recv().unwrap().is_file());
|
||||
let files: Vec<_> = std::fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap()).collect();
|
||||
assert_eq!(files.iter().filter(|e| e.file_name().to_string_lossy().starts_with("perf-incident-")).count(), 16);
|
||||
for e in files.iter().filter(|e| e.path().extension().is_some_and(|s| s == "json")) {
|
||||
let bytes = std::fs::read(e.path()).unwrap();
|
||||
assert!(bytes.len() <= INCIDENT_BYTES);
|
||||
let _: Value = serde_json::from_slice(&bytes).unwrap();
|
||||
}
|
||||
let snapshot: Value = serde_json::from_slice(&std::fs::read(dir.path().join("perf.json")).unwrap()).unwrap();
|
||||
assert_eq!(snapshot["frames"]["total"], 40);
|
||||
assert_eq!(snapshot["version"], "1.0");
|
||||
assert!(snapshot["frames"]["ui_allocated_bytes"].is_null());
|
||||
assert_eq!(snapshot["write_errors"], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn logs_rotate_and_failed_writes_are_visible() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut log = Log { dir: dir.path(), file: None, size: 0, limit: 128 };
|
||||
for n in 0..50 { log.append(&json!({"seq": n})).unwrap(); }
|
||||
for name in ["perf.log", "perf.log.1"] {
|
||||
let text = std::fs::read_to_string(dir.path().join(name)).unwrap();
|
||||
assert!(text.len() <= 128);
|
||||
for line in text.lines() { let _: Value = serde_json::from_str(line).unwrap(); }
|
||||
}
|
||||
// Simulate a prior partial write with stale in-memory size accounting.
|
||||
std::fs::write(dir.path().join("perf.log"), vec![b' '; 125]).unwrap();
|
||||
log.size = 0;
|
||||
log.file = None;
|
||||
log.append(&json!({"seq": 51})).unwrap();
|
||||
assert!(std::fs::metadata(dir.path().join("perf.log")).unwrap().len() <= 128);
|
||||
assert_eq!(std::fs::metadata(dir.path().join("perf.log.1")).unwrap().len(), 125);
|
||||
let config = Config::new(dir.path().join("absent"), "fixture");
|
||||
let health = Health::default();
|
||||
let mut w = Writer::new(&config, crate::now(), &health);
|
||||
w.snapshot();
|
||||
assert!(health.errors.load(Relaxed) >= 1);
|
||||
assert!(atomic_json(dir.path(), "big.json", &json!("oversize"), 1).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replacement_wait_is_cancellable_without_touching_owner_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let lock = OpenOptions::new().create(true).truncate(false).read(true).write(true).open(dir.path().join(".perf.lock")).unwrap();
|
||||
lock.lock().unwrap();
|
||||
let recorder = Recorder::start(Config::new(dir.path(), "replacement")).unwrap();
|
||||
for _ in 0..1000 { recorder.record(Frame::default()); }
|
||||
assert!(recorder.dropped_samples() >= 744);
|
||||
recorder.shutdown().unwrap();
|
||||
assert!(!dir.path().join("perf.json").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replacement_acquires_after_old_owner_releases() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let lock = OpenOptions::new().create(true).truncate(false).read(true).write(true).open(dir.path().join(".perf.lock")).unwrap();
|
||||
lock.lock().unwrap();
|
||||
let (tx, rx) = sync_channel(1);
|
||||
let config = Config::new(dir.path(), "replacement").incidents(tx);
|
||||
let recorder = Recorder::start(config).unwrap();
|
||||
recorder.record(frame(0).frame);
|
||||
drop(lock);
|
||||
let path = rx.recv_timeout(Duration::from_secs(5)).unwrap();
|
||||
assert!(path.is_file());
|
||||
recorder.shutdown().unwrap();
|
||||
let snapshot: Value = serde_json::from_slice(&std::fs::read(dir.path().join("perf.json")).unwrap()).unwrap();
|
||||
assert_eq!(snapshot["frames"]["total"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropped_recorder_cancels_lock_wait() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let lock = OpenOptions::new().create(true).truncate(false).read(true).write(true).open(dir.path().join(".perf.lock")).unwrap();
|
||||
lock.lock().unwrap();
|
||||
let health = Arc::new(Health::default());
|
||||
let h = health.clone();
|
||||
let (done, wait) = sync_channel(1);
|
||||
let path = dir.path().join(".perf.lock");
|
||||
let worker = std::thread::spawn(move || {
|
||||
let lock = OpenOptions::new().read(true).write(true).open(path).unwrap();
|
||||
done.send(acquire(&lock, &h).unwrap()).unwrap();
|
||||
});
|
||||
health.stop.store(true, Relaxed);
|
||||
assert!(!wait.recv_timeout(Duration::from_secs(5)).unwrap());
|
||||
worker.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "manual optimized background cost measurement"]
|
||||
fn instrumentation_overhead_writer() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let config = Config::new(dir.path(), "benchmark");
|
||||
let health = Health::default();
|
||||
let mut w = Writer::new(&config, crate::now(), &health);
|
||||
for n in 0..crate::RECENT { w.stats.accept(frame(n as u64)); }
|
||||
let mut times = Vec::new();
|
||||
for round in 0..22 {
|
||||
let at = crate::now();
|
||||
for _ in 0..100 { w.snapshot(); }
|
||||
if round > 0 { times.push(at.elapsed().as_secs_f64() * 10.0); }
|
||||
}
|
||||
println!("METRIC writer_snapshot_ms {}", crate::stats::percentiles(times));
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
use super::*;
|
||||
use crate::{incident::{Detector, Finding, Rule}, stats::Stats};
|
||||
use procwatch::Usage;
|
||||
use std::hint::black_box;
|
||||
|
||||
#[global_allocator]
|
||||
static ALLOCATOR: procwatch::alloc::Counting = procwatch::alloc::Counting::system();
|
||||
|
||||
fn sample(at_ms: u64, work: Option<f64>) -> Sample {
|
||||
Sample { at_ms, frame: Frame::default().update_ms(work).render_ms(work.map(|_| 0.0)) }
|
||||
}
|
||||
|
||||
fn usage(footprint: Option<u64>, fds: Option<u32>) -> Usage {
|
||||
let mut u = Usage::default();
|
||||
u.footprint = footprint;
|
||||
u.fds = fds;
|
||||
u
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optional_counters_stay_unavailable_and_invalid_timings_are_rejected() {
|
||||
let mut stats = Stats::default();
|
||||
stats.accept(sample(0, None));
|
||||
let json = stats.json();
|
||||
for name in ["work_ms", "ui_allocated_bytes", "gpu_ms", "input_to_frame_ms", "lifetime_max_ui_allocated_bytes"] {
|
||||
assert!(json[name].is_null(), "{name}");
|
||||
}
|
||||
let f = Frame::new(1, 1, Outcome::Drawn).update_ms(f64::NAN).render_ms(-1.0).gpu_ms(f64::INFINITY).sanitize();
|
||||
assert!(f.update_ms.is_none() && f.render_ms.is_none() && f.gpu_ms.is_none());
|
||||
assert_eq!(Frame::default().update_ms(f64::MAX).render_ms(f64::MAX).work_ms(), None);
|
||||
assert_eq!(Frame::new(1, 1, Outcome::Drawn).update_ms(2.0).render_ms(1.0).work_ms(), Some(3.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn history_is_bounded_and_idle_is_not_work() {
|
||||
let mut stats = Stats::default();
|
||||
for n in 0..10_000 { stats.accept(sample(n, Some(n as f64))); }
|
||||
let j = stats.json();
|
||||
assert_eq!(j["recent_count"], RECENT);
|
||||
assert_eq!(j["work_ms"]["p50"], 9699.0);
|
||||
assert_eq!(j["work_ms"]["p95"], 9969.0);
|
||||
assert_eq!(j["recent_anomalies"].as_array().unwrap().len(), 20);
|
||||
stats.prune(70_000);
|
||||
assert!(stats.json()["work_ms"].is_null());
|
||||
assert_eq!(stats.json()["lifetime_max_work_ms"], 9999.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anomalies_rate_limit_logs_but_keep_counts() {
|
||||
let mut stats = Stats::default();
|
||||
for _ in 0..10 { assert!(stats.accept(sample(0, Some(20.0)))); }
|
||||
assert!(!stats.accept(sample(999, Some(20.0))));
|
||||
assert!(stats.accept(sample(1000, Some(20.0))));
|
||||
assert_eq!(stats.json()["anomalies"], 12);
|
||||
assert_eq!(stats.json()["log_suppressed"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_frames_require_repetition_and_do_not_mix_windows() {
|
||||
let mut stats = Stats::default();
|
||||
let d = Detector::default();
|
||||
for n in 0..3 {
|
||||
let mut s = sample(n, Some(20.0));
|
||||
s.frame.window = n;
|
||||
stats.accept(s);
|
||||
assert!(d.frame(s, &stats).is_none());
|
||||
}
|
||||
for n in 3..5 { stats.accept(sample(n, Some(20.0))); }
|
||||
assert_eq!(d.frame(sample(5, Some(20.0)), &stats).unwrap().rule, Rule::LongFrames);
|
||||
assert!(d.frame(sample(5000, None), &stats).is_none());
|
||||
assert_eq!(d.frame(sample(5001, Some(250.0)), &stats).unwrap().rule, Rule::Stall);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incident_cooldown_requires_worsening() {
|
||||
let mut d = Detector::default();
|
||||
let mut f = Finding { rule: Rule::Stall, window: 0, source: None, severity: 250.0, evidence: serde_json::Value::Null };
|
||||
assert!(d.admit(0, &f));
|
||||
assert!(!d.admit(60_001, &f));
|
||||
f.severity = 400.0;
|
||||
assert!(!d.admit(59_999, &f));
|
||||
assert!(d.admit(60_001, &f));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn growth_uses_completed_floors_and_rejects_plateaus_spikes_gaps_and_missing_reads() {
|
||||
for case in 0..5 {
|
||||
let mut d = Detector::default();
|
||||
let mut findings = Vec::new();
|
||||
for minute in 0..6 {
|
||||
let base = 100 << 20;
|
||||
let value = match case { 0 => base + minute * (20 << 20), 1 => base,
|
||||
2 => if minute == 2 { base * 3 } else { base }, _ => base + minute * (20 << 20) };
|
||||
let at = if case == 3 && minute > 2 { minute + 2 } else { minute } * 60_000;
|
||||
findings = d.process(at, usage(if case == 4 && minute == 2 { None } else { Some(value) }, Some(100)));
|
||||
}
|
||||
assert_eq!(findings.len(), usize::from(case == 0), "case {case}");
|
||||
if case == 0 { assert_eq!(findings[0].rule, Rule::MemoryGrowth); }
|
||||
}
|
||||
let mut d = Detector::default();
|
||||
for n in 0..5 { assert!(d.process(n * 60_000, usage(None, Some(100 + n as u32 * 10))).is_empty()); }
|
||||
assert_eq!(d.process(300_000, usage(None, Some(150)))[0].rule, Rule::FdGrowth);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allocation_deltas_start_from_a_baseline_and_stay_on_this_thread() {
|
||||
assert_eq!(take_allocated_bytes(), None);
|
||||
drop(black_box(vec![0u8; 4096]));
|
||||
assert_eq!(take_allocated_bytes(), Some(4096));
|
||||
assert_eq!(take_allocated_bytes(), Some(0));
|
||||
std::thread::spawn(|| drop(black_box(vec![0u8; 1 << 20]))).join().unwrap();
|
||||
// Spawning allocates a little here; the other thread's megabyte isn't counted.
|
||||
assert!(take_allocated_bytes().unwrap() < 64 << 10);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//! A binary without `procwatch::alloc::Counting` installed: allocation figures stay unknown.
|
||||
|
||||
#[test]
|
||||
fn allocation_bytes_are_unknown_without_the_counting_allocator() {
|
||||
for _ in 0..3 {
|
||||
drop(std::hint::black_box(vec![0u8; 64]));
|
||||
assert_eq!(rune_perf::take_allocated_bytes(), None);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user