Skip to main content

Crate beatwise

Crate beatwise 

Source
Expand description

§Beatwise

crates.io · API documentation · repository

Beatwise is a small Rust library for watching long-running work.

A task calls beat() whenever it makes progress. Beatwise tracks that rhythm and reports whether the task is Starting, Learning, Healthy, Late, or Stopped.

It works well for background workers, sync loops, schedulers, queue consumers, device pollers, backups, peer maintenance, and other jobs that should keep moving.

Beatwise can watch a known interval, learn a task’s normal pace, or learn a repeating cycle. It uses only the standard library, starts no threads, and does not require an async runtime.

§Installation

cargo add beatwise

Beatwise supports Rust 1.85 and newer.

§Quick start

Register a task, keep the returned heartbeat handle with the work, and call beat() whenever meaningful progress completes:

use std::time::Duration;
use beatwise::{Monitor, TaskConfig, Timing};

let monitor = Monitor::new();
let heartbeat = monitor.register(TaskConfig::new(
    "worker",
    Timing::fixed(Duration::from_secs(5)),
))?;

heartbeat.beat()?;

let status = monitor
    .status(heartbeat.id())
    .expect("registered task remains retained");
println!("{}: {:?}", status.name, status.health);

A heartbeat should mean that work advanced, not merely that a process or thread still exists. Beatwise reports health when the caller asks; it does not wake, restart, cancel, retry, or schedule the monitored work.

§What it provides

  • Fixed deadlines for predictable work.
  • Learned timing for jobs whose pace changes.
  • A robust model for occasional outliers.
  • Repeating-pattern detection for multi-phase work.
  • Independent transition cursors and aggregate health reports.
  • Bounded memory with no event queue or unbounded history.

All timing stays inside the caller’s process. Fixed heartbeats use atomics and a monotonic clock read. Learned tasks add one small mutex. Stopped tasks remain visible until explicitly purged.

§Choosing a timing model

ModelBest forMain tradeoff
FixedPollers, schedulers, and jobs with a known expected intervalThe caller must choose the interval and grace period
EWMAWorkloads whose normal pace changes graduallyThe trained baseline follows the selected adaptation policy
Robust windowBursty work with occasional extreme pauses or outliersKeeps a small bounded sample window and requires an odd capacity
Repeating patternStable multi-phase work such as short/long processing cyclesRequires several complete cycles before the pattern is trusted

Use fixed timing when the expected interval is part of the task’s contract. Use learned timing when the workload itself is the best source of that expectation.

§Lifecycle and ownership

Every task begins in Starting. Before the first beat, it remains there until its startup grace expires; continued silence then makes it Late. After the first beat, fixed timing can become Healthy, while learned timing enters Learning until enough accepted intervals establish a baseline. Running tasks then move between Healthy and Late as their silence crosses the current deadline.

registered task ──> Starting

fixed first beat ───────────────> Healthy <──> Late
learned first beat ──> Learning ── trained ──> Healthy <──> Late

running task ── explicit stop or final heartbeat drop ──> Stopped
Stopped ── Monitor::purge_stopped() ────────────────────> removed

Heartbeat clones refer to the same task. An explicit stop() is task-wide, so other clones can no longer beat. Dropping the final clone also marks the task as stopped. A stopped record remains observable until Monitor::purge_stopped() removes it, and a stopped handle cannot revive a purged task.

Monitor is cheap to clone and may be shared between observers. Heartbeat clones are safe to move between threads. For learned timing, remember that every call to beat() is treated as the next interval in one logical progress stream; unrelated concurrent producers should usually be registered as separate tasks.

§Learn a task’s normal pace

EWMA is the default learned model. It uses constant memory and adapts gradually as the task changes:

use std::time::Duration;
use beatwise::{Adaptation, LearnedTiming, Monitor, TaskConfig, Timing};

let monitor = Monitor::new();
let timing = LearnedTiming::default()
    .with_minimum_samples(8)
    .with_minimum_grace(Duration::from_millis(25))
    .with_sensitivity(4.0)
    .with_adaptation(Adaptation::Slow);

let heartbeat = monitor.register(TaskConfig::new(
    "database-sync",
    Timing::Learned(timing),
))?;

heartbeat.beat()?;

for status in monitor.snapshot() {
    println!("{}: {:?}", status.name, status.timing);
}

For jobs with occasional long pauses or extreme outliers, use the bounded robust window:

use std::time::Duration;
use beatwise::{Adaptation, LearnedTiming, LearningModel, Monitor, TaskConfig, Timing};

let monitor = Monitor::new();
let timing = LearnedTiming::default()
    .with_minimum_samples(9)
    .with_minimum_grace(Duration::from_millis(25))
    .with_adaptation(Adaptation::Slow)
    .with_model(LearningModel::robust_window(9));
let heartbeat = monitor.register(TaskConfig::new(
    "bursty-worker",
    Timing::Learned(timing),
))?;

let task_id = heartbeat.id();
monitor.retrain(task_id)?;

Robust windows use odd capacities from 5 through 31. Monitor::retrain clears the learned baseline without replacing the task ID or heartbeat handle.

§Learn repeating work

Some healthy jobs alternate between short and long phases. The repeating-pattern model learns that cycle instead of forcing it into one average:

use std::time::Duration;
use beatwise::{
    Adaptation, LearnedTiming, LearningModel, Monitor, PatternConfig, TaskConfig, Timing,
};

let monitor = Monitor::new();
let pattern = PatternConfig::new(6, 3)
    .with_tolerance_percent(10)
    .with_minimum_contrast_percent(20);
let timing = LearnedTiming::default()
    .with_minimum_samples(9)
    .with_startup_grace(Duration::from_secs(30))
    .with_minimum_grace(Duration::from_millis(25))
    .with_sensitivity(4.0)
    .with_adaptation(Adaptation::Slow)
    .with_model(LearningModel::RepeatingPattern(pattern));
let heartbeat = monitor.register(TaskConfig::new(
    "phased-worker",
    Timing::Learned(timing),
))?;

heartbeat.beat()?;

Patterns can have two through eight phases and require three through eight cycles. Beatwise learns from at most 64 intervals. An outlier still counts as a heartbeat and advances the phase, but it does not replace the trusted baseline.

§Watch state changes

A transition cursor reports meaningful state changes without callbacks or a shared event queue:

use std::time::Duration;
use beatwise::{HealthState, Monitor, TaskConfig, Timing};

let monitor = Monitor::new();
let heartbeat = monitor.register(TaskConfig::new(
    "worker",
    Timing::fixed(Duration::from_secs(1)),
))?;
let mut transitions = monitor.transition_cursor();

for transition in transitions.poll() {
    assert_eq!(transition.previous, None);
    assert_eq!(transition.current, HealthState::Starting);
}

heartbeat.beat()?;

for transition in transitions.poll() {
    println!(
        "{}: {:?} -> {:?}",
        transition.status.name,
        transition.previous,
        transition.current,
    );
}

Each cursor is independent. poll() returns only state changes, ordered by task ID. A transition’s observation time is when the cursor polled the monitor, not an exact historical timestamp for the instant the state changed. Beatwise does not run callbacks or own an executor.

§Build health endpoints

Use a summary for a lightweight health check or a full report when you need task details:

use std::time::Duration;
use beatwise::{HealthPolicy, HealthVerdict, Monitor, TaskConfig, Timing};

let monitor = Monitor::new();
let heartbeat = monitor.register(TaskConfig::new(
    "api-worker",
    Timing::fixed(Duration::from_secs(1)),
))?;

let readiness = monitor.summary(HealthPolicy::readiness());
assert_eq!(readiness.verdict, HealthVerdict::Degraded);
assert_eq!(readiness.counts.starting, 1);

heartbeat.beat()?;

let liveness = monitor.report(HealthPolicy::liveness());
println!(
    "verdict={:?}, considered={}, ignored={}",
    liveness.summary.verdict,
    liveness.summary.considered_tasks,
    liveness.summary.ignored_tasks,
);
for task in liveness.tasks.iter() {
    println!("{}: {:?}", task.name, task.health);
}

readiness() treats starting and learning tasks as degraded. liveness() allows those states, fails late tasks, and ignores stopped records. strict() accepts only healthy tasks. Custom policies can change how any state affects the verdict.

§Examples

The repository includes runnable examples for fixed timing, learned timing, aggregate health reports, and a standard-library worker thread:

cargo run --example fixed_monitor
cargo run --example learned_monitor
cargo run --example health_report
cargo run --example worker_loop

§Version note

Beatwise 0.2.0 replaces the old Thumper 0.1.x DJ, deck, and output API. The old implementation remains available in Git history.

§Validation

From the repository root:

cargo fmt --all --check
cargo clippy --all-targets -- -D warnings
cargo test
RUSTDOCFLAGS="-D warnings" cargo doc --no-deps
cargo package --list
cargo package

Structs§

FixedTiming
Fixed timing configuration for a task.
HealthCounts
Exact retained-task counts grouped by stable health state.
HealthPolicy
Explicit mapping from task states to aggregate health impacts.
HealthReport
Aggregate summary plus the task snapshots used to build it.
HealthSummary
Compact aggregate observation of a monitor.
HealthTransition
One meaningful health-state change observed by a TransitionCursor.
Heartbeat
Handle used by a monitored task to report meaningful progress.
LearnedTiming
Learned timing configuration for a task.
Monitor
Registry and pull-driven observation point for monitored tasks.
PatternConfig
Configuration for bounded repeating-pattern discovery.
StoppedError
Returned when a heartbeat is sent after a task has stopped.
TaskConfig
Registration configuration for a monitored task.
TaskId
An opaque identifier for a monitored task.
TaskStatus
Compact snapshot of one monitored task.
TransitionCursor
Independent, bounded cursor for observing task health transitions.

Enums§

Adaptation
Controls how a learned model changes after its training phase.
Confidence
Confidence in a learned timing baseline.
ConfigError
A task configuration error.
Health
Current health of a monitored task.
HealthImpact
Effect one task state has on an aggregate health verdict.
HealthState
Stable identity of a task’s current health state.
HealthVerdict
Aggregate health verdict for the tasks considered by a HealthPolicy.
LearningModel
Statistical model used to learn a task’s heartbeat timing.
RegisterError
A task registration error.
RetrainError
Returned when a learned task cannot be retrained.
StopReason
Describes why a task entered the stopped state.
Timing
Timing policy used to determine a task’s health.
TimingStatus
Current public view of a task’s timing policy.