# stackler
Single-crate Rust library. Runtime stack telemetry: stack bounds discovery, stack-pointer sampling, and stack painting for high-water marks. `no_std`-capable core, relaxed atomics only.
## Commands
```sh
# NOTE: tests share the process-wide registry and reset it, so they MUST run
# single-threaded (`-- --test-threads 1`); parallel runs are flaky.
cargo test -- --test-threads 1 # default features (std)
cargo test --features full -- --test-threads 1 # everything but hook_pthread
cargo test --features full,hook_pthread -- --test-threads 1
cargo test --no-default-features -- --test-threads 1 # no_std API surface only
cargo test --features full --test main_thread # harness-free; runs in `main`
cargo bench # divan benchmarks (custom harness)
cargo run --release --example pool --features full
cargo clippy --all-targets --all-features # clippy::all is deny'd in lib.rs
cargo check --no-default-features --target thumbv7m-none-eabi # no_std build
cargo check --target x86_64-pc-windows-msvc --all-features # never-run platform paths
cargo check --target x86_64-unknown-linux-musl --all-features
cargo +1.85 check --all-features # the declared MSRV; CI has a job for it
cargo doc --no-deps --all-features # docs.rs-style docs
# Intra-doc links break only in the feature combinations that lack the item they
# point at, so the docs are worth building in more than one; CI does four, and this
# sweeps all 64:
for m in $(seq 0 63); do f=; for i in 0 1 2 3 4 5; do [ $((m>>i & 1)) -ne 0 ] && \
```
## Architecture
- `src/lib.rs` — crate docs, `Stackler` config builder, `measure`, `measure_peak`, re-exports
- `src/platform.rs` — `sp()` (inline asm per arch, address-of-local fallback), OS stack bounds (`pthread_getattr_np` / `pthread_get_stackaddr_np` / `GetCurrentThreadStackLimits`), thread id
- `src/stack.rs` — `Stack` (bounds arithmetic), painting and scanning, `Paint`, `Peak`
- `src/registry.rs` — cache-aligned slot array, claim/retire state machine, TLS attach with exit hook, the public measurement functions
- `src/stats.rs` — `Stats` and `ThreadStats`, `stats()` aggregation, `Sub`
- `src/histogram.rs` — `Histogram` (64 power-of-two buckets `[2^k, 2^(k+1))`)
- `src/fmt.rs` — `Display` impls, gated behind `fmt`
- `src/sampler.rs` — background thread calling `poll_all()`, gated behind `sampler`
- `src/hook.rs` — `pthread_create` interposition, gated behind `hook_pthread`
- `src/config.rs` — `paint_depth` / `reserve`, in relaxed atomics
## Design invariants
- **Nothing shared on the observation path — no exceptions.** Every counter a measurement touches, the depth histogram included, lives in the recording thread's own `#[repr(align(64))]` slot; aggregates are computed in `stats()` by walking the slots. This is load-bearing, not stylistic: while the histogram buckets were shared, sixteen threads sampling in lockstep achieved the throughput of one. Do not move anything back out of the slot.
- **All measurement atomics are `Ordering::Relaxed`.** Slot *state* transitions are not: publishing a claimed slot is `Release`, acquiring one to scan is `Acquire`. That pairing is what makes a cross-thread watermark read safe against the owner exiting (`retire` cannot pass `SCANNING`).
- **Cross-thread writes get their own cache line.** `Slot::control` (state + generation) is `#[repr(align(64))]` and therefore 64 bytes wide, so no other field can share a line with it whatever order the compiler picks — `repr(Rust)` reorders freely, so declaration order guarantees nothing. That is what keeps a sampler's compare-exchange on `state` from bouncing the counters an observation writes. A `const` assertion pins the size.
- **A slot outlives its thread, so readers validate.** `Slot::generation` is bumped with `Release` before a slot is torn down *and* before it is re-claimed; `Slot::snapshot` reads it on both sides of the field loads with an `fence(Acquire)` between, and throws the view away if it changed. Without that, a recycled slot can hand out a `base` from one thread and a `limit` from another — a nonsensical `size`. Any new field read from outside the owning thread belongs inside that window.
- **Snapshots are self-consistent by construction where it is free.** `Slot::snapshot` reports `max(peak, depth_last)`: ordering the two writes is not enough to make two relaxed loads agree, and a peak shallower than a depth actually observed would be nonsense.
- **`reset()` never clobbers a concurrent observation.** It lowers peaks and rebases `THREADS_SEEN` with `compare_exchange`, not `store`, so a sample that races in is preserved rather than erased. It is still not coherent field-to-field; that is documented on `reset` itself, and verified — `sample_avg` above `peak_max` does happen under concurrent resets.
- **Only the owner paints.** Anyone may scan. Cross-thread scans are racy by construction and documented as such; never add cross-thread *painting*.
- **A watermark only describes frames created after the paint.** Hence `#[inline(never)]` barriers in `measure_peak` and in every test that burns stack — an inlined callee has no frame of its own.
- **Watermarks understate, never overstate.** `Peak::AtLeast` exists so saturation is visible; keep it that way rather than extrapolating.
- Painting stays a page above `Stack::limit` (guard-page insurance) and `TOP_MARGIN` below the painter's stack pointer (so painting cannot clobber its own callees).
- **Reported stack bounds are not blindly trusted.** On glibc the initial thread's low end comes from `RLIMIT_STACK`, and an unlimited one yields a span reaching past the heap — painting into which segfaults, and guarding against which never fires. `platform::trustworthy_limit` caps it; `tests/main_thread.rs` is the regression test, and it has to be harness-free because libtest never runs on the initial thread.
- **`sp()`'s fallback is deliberately `#[inline(never)]`.** A local in its own frame sits just below the caller's, which bounds the error by that frame instead of the caller's and puts it on the conservative side for `has_headroom`. Verify changes to it by temporarily forcing the fallback on x86-64 and running the suite.
## Conventions
- `#![cfg_attr(not(feature = "std"), no_std)]`; `std` (default) pulls in `libc` on unix and enables the registry
- `#![deny(missing_docs)]` — every public item must be documented
- `#![deny(clippy::all)]` — clippy warnings are hard errors
- `#![deny(rustdoc::broken_intra_doc_links)]` — a dangling link fails the build; prose in the crate-level header names items in backticks rather than linking them, because that narrative spans every feature tier and cannot link into all of them at once. Item docs do link, with `cfg_attr` doc pairs where the target is behind a different feature than the item
- Edition 2024, MSRV 1.85
- `Stats` subtraction uses `saturating_sub` (never panics); counters are diffed, gauges are carried over — `Stats`' own docs are the reference
- `Stats` and `ThreadStats` are `#[non_exhaustive]` so that new metrics are not breaking changes; `Peak` deliberately is not, because it would force a wildcard arm on an enum that is already complete
- Every feature combination must compile warning-free; CI checks them one at a time, and cross-checks Windows and musl because a platform-specific feature that forgets its `cfg` shows up nowhere else
- Tests: `tests/primitives.rs` is the `no_std`-safe surface (no feature gate), `tests/basics.rs` is `#![cfg(feature = "std")]`, `tests/integration.rs` needs `std` + `watermark`, `tests/main_thread.rs` is `harness = false`, and `src/platform.rs` carries unit tests for the bounds arithmetic
- `Cargo.lock` is gitignored (per `.gitignore`)
- Dual-licensed CC0 / MIT