Expand description
Record causal performance evidence for one KeyHog run.
Start a Session at the beginning of the production operation. Record
macro state changes with Session::transition. Wrap measured work in
span, then call Session::finish to produce a versioned RunProfile.
use keyhog_profile::{RunIdentity, RunState, Session, Stage, span};
let identity = RunIdentity::new(
"0.5.49",
"detector-digest",
"config-digest",
"filesystem",
"small-text",
"auto",
);
let mut session = Session::start(identity).expect("start profile");
session.transition(RunState::Scanning);
{
let _read = span(Stage::SourceRead);
std::hint::black_box(42);
}
let profile = session.finish(RunState::Completed);
assert_eq!(profile.status, RunState::Completed);
assert_eq!(profile.stages[0].stage, Stage::SourceRead);
assert_eq!(profile.stages[0].calls, 1);§Runtime ownership
A session owns an isolated Runtime. The session enters that runtime on
the calling thread. Propagate a clone explicitly when work crosses a thread
boundary. This keeps concurrent runs isolated.
use keyhog_profile::{RunIdentity, RunState, Session, Stage, span};
let identity = RunIdentity::new("0.5.49", "d", "c", "stdin", "stream", "auto");
let session = Session::start(identity).expect("start profile");
let runtime = session.runtime();
std::thread::spawn(move || runtime.scope(|| {
let _scan = span(Stage::BackendDispatch);
}))
.join()
.expect("join worker");
let profile = session.finish(RunState::Completed);
assert_eq!(profile.stages[0].stage, Stage::BackendDispatch);§Recording cost
The disabled span path checks one relaxed atomic and does not read the clock.
Enabled spans update fixed atomic counters indexed by MetricId. They do
not allocate, hash metric names, or format text. Vector construction, JSON
serialization, and report analysis run only when counters are drained or a
session is finished.
cargo bench -p keyhog-profile --bench overhead_budget enforces absolute
median budgets for disabled checks, aggregate spans, and causal spans. The
regular CI workflow runs this gate with an optimized benchmark build.
§Metrics and collectors
METRICS is the static registry for metric names, kinds, and units. A
collector implements SnapshotCollector and reports a
CollectorCapability before sampling. The default process-metrics
feature samples process CPU time, resident memory, virtual memory, and thread
count. Disable default features when you need stage timing without platform
process sampling. The profile then reports the collector as disabled instead
of silently emitting unavailable measurements.
§Persisted records
PROFILE_SCHEMA identifies the profile envelope. Every persisted component
also carries its own numeric version. Missing component versions decode as
version one for compatibility with early records. Compare identity fields,
collector capabilities, workload state, and metric units before comparing
measurements from two profiles.
§Privacy
The profiler records counts, durations, run identity, execution choices, and
process resources. Do not use source content, credentials, raw URLs, or
sensitive paths as identity labels. RunProfile::render_text and
RunProfile::to_json_pretty serialize the labels supplied by the caller.
Re-exports§
pub use insight::BackendAttributionV2;pub use insight::BottleneckKindV2;pub use insight::FindingV2;pub use insight::InsightCoverageV2;pub use insight::MemoryInsightV2;pub use insight::ParallelismInsightV2;pub use insight::PhaseInsightV2;pub use insight::RunInsightV2;pub use insight::SerialRegionV2;pub use insight::SerialScopeV2;pub use insight::StageAttributionV2;pub use insight::StageMemoryV2;pub use insight::ThroughputInsightV2;pub use insight::RUN_INSIGHT_V2_VERSION;
Modules§
- insight
- Turn one recorded profile into the answers an operator asked for.
Structs§
- Allocation
Evidence V2 - Allocator evidence: exact counts when a
crate::TrackingAllocatoris installed, an explicit capability gap otherwise. - Allocation
Slot V2 - Per-slot allocation counters at one instant.
- Allocation
Snapshot V2 - Process-wide allocation counters at one instant, split by owning stage.
- Allocation
Totals V2 - Session-window allocation totals with live and peak levels at the end.
- Annotation
V2 - One bounded typed numeric annotation on the run timeline.
- Artifact
Integrity V2 - Digest protecting the canonical profile artifact.
- Batch
Route V2 - One actual route completed for a measured batch.
- Blocked
Wait Record V2 - Blocked wait time attributed separately from runnable execution for one stage.
- Build
Identity Input - Build-specific values supplied by the final binary crate.
- Build
Identity V2 - Exact executable and toolchain identity used by one run.
- Cache
Effectiveness V2 - Hit and miss counts for one reuse cache.
- Cache
Layer V2 - State and generation identity for one cache layer.
- Causal
Parent - Portable causal parent captured from a runtime’s current span context.
- Causal
Profile V2 - Versioned causal profile envelope and measurements.
- Causal
RunIdentity V2 - Comparison identity joining every timing-relevant dimension.
- Collector
Capability - Host-specific availability report for one collector.
- Comparison
Difference - One identity or workload field that prevents a valid performance comparison.
- Config
Identity Input - Canonical resolved configuration values supplied by the final operator.
- Config
Identity V2 - Canonical resolved configuration and policy identity.
- Context
Guard - Thread context guard returned by
Runtime::enter. - Counter
Span - Time a sub-stage region into a
crate::CounterIdinstead of a stage. - CpuFrequency
Sample V2 - Aggregate CPU frequency across all CPUs at one sample instant.
- Daemon
Identity V2 - Daemon mode and request linkage for one run.
- Decision
Timer - Time a region whose measurement drives a decision, profiled or not.
- Decode
Retention Evidence V2 - Decode expansion and retained-buffer evidence.
- Detector
Identity Input - Detector-specific values supplied after the scanner compiles its effective corpus.
- Detector
Identity V2 - Detector corpus and compiled execution-plan identity.
- Distribution
Bucket V2 - One exact logarithmic bucket of a caller-recorded value distribution.
- Event
Loss Counts - Exact reasons typed timeline records were not retained.
- Event
Stream V2 - Bounded event stream with explicit availability and loss accounting.
- Fault
Evidence V2 - Page-fault deltas across one run from proc stat.
- Hardware
Counter Collector - Linux perf, Windows cycle-time, or stub collector for hardware counters.
- Hardware
Counter Sample V2 - One absolute hardware-counter reading taken by
HardwareCounterCollector. - Hardware
Counter SetV2 - Counter deltas and derived ratios across one run (session-thread scope).
- Hardware
RunEvidence V2 - Complete CPU hardware evidence for one run.
- Host
Identity V2 - Exact host and operating environment used by one run.
- Indexed
Counter Record V2 - One indexed counter family, summed per slot across every worker.
- IoEvidence
V2 - Process IO deltas across one run from
/proc/self/io. - Latency
Bucket V2 - One exact logarithmic latency bucket.
- Latency
Distribution V2 - Allocation-free hot-path call latency distribution for one micro-function.
- Memory
Evidence V2 - Memory levels at the end of one run, including the kernel high water.
- Metric
Descriptor - Static metric metadata. Every string is embedded in the binary.
- Metric
Distribution V2 - Caller-recorded logarithmic distribution for one typed metric.
- Network
Evidence V2 - Network evidence: process-level counters or an explicit gap, plus retry activity aggregated from caller annotations.
- Network
Process Counters V2 - Per-process network counters where the host exposes them.
- Outcome
Identity V2 - Terminal outcome and result identity for one run.
- Point
Event V2 - One bounded instantaneous event with a typed numeric payload.
- Pressure
Evidence V2 - Kernel pressure-stall averages at the end of one run.
- Pressure
Thermal Collector - Pressure-stall and thermal collector backed by
/proc/pressureand sysfs thermal zones on Linux. - Pressure
Thermal Sample V2 - One absolute pressure and thermal reading.
- Producer
Identity V2 - Producer identity for the code that emitted an artifact.
- Profile
Comparison - Deterministic comparison of two profile records.
- Profile
Envelope V2 - Self-describing envelope for a v2 causal profile.
- Queue
Depth V2 - Current depth and high-water mark for one bounded queue slot.
- Queue
Link Loss Counts - Exact reasons queue causality records were not retained.
- Queue
Link V2 - One matched producer enqueue and consumer dequeue through a bounded queue.
- Resource
Sample - Process resource observation associated with a run-state boundary.
- Resource
Snapshot - Process resource observation at a macro boundary.
- Resource
Usage - Resource change across a completed profile session.
- Retry
Record V2 - Retry attempts recorded for one cause.
- Route
Identity V2 - Requested, selected, completed, and recovered backend identity.
- RunIdentity
- Identity and execution choices required to compare two run records honestly.
- RunProfile
- Complete replayable profile record.
- RunSpan
Hardware V2 - Run-level cycle and instruction totals joined from span records.
- Runtime
- Owned fixed-stage metric storage that can be propagated across worker boundaries.
- Sampling
Policy - Deterministic bounded policy for retaining expensive detail events.
- Scheduler
Collector - Context-switch, migration, and runqueue-delay collector.
- Scheduler
Evidence V2 - Scheduler activity deltas across one run with an explicit source per field.
- Scheduler
Sample V2 - One absolute scheduler-activity reading from procfs and perf software events.
- Schema
Version V2 - Independent major and minor version for one schema family.
- Session
- One causal profiling session with isolated owned metric storage.
- Session
Active - Reserved error type for profile-session initialization failures.
- Source
Identity Input - Safe source adapter names and hashed target values supplied by the operator.
- Source
Identity V2 - Safe source adapter and target identity.
- Sourced
Evidence V2 - One measured field plus the facility that produced or was asked for it.
- Span
- Allocation-free stage guard. It contains no start timestamp while disabled.
- Span
Hardware Aggregation V2 - Cold-path CPI aggregation over one drained span set.
- Span
Hardware V2 - Raw per-span cycle and instruction readings attached at span begin and end.
- Span
Record V2 - One nested or linked causal interval.
- Stage
Allocation V2 - Per-stage allocation ownership;
metric_idisNonefor the root slot that owns allocations made outside any recorded span. - Stage
Comparison - Exact aggregate difference for one stage.
- Stage
Concurrency V2 - Wall-clock occupancy of one micro-function across every worker.
- Stage
Hardware V2 - Per-stage cycle and instruction totals joined from span records.
- Stage
Measurement - One aggregate fixed-stage measurement.
- State
Measurement - One completed macro state with its wall time and boundary resource deltas.
- State
Transition - One run-state transition relative to session start.
- System
IoCollector - Faults and process-IO collector backed by
/proc/self/statand/proc/self/ioon Linux. - System
IoSample V2 - One absolute faults-and-IO reading from procfs.
- System
RunEvidence V2 - Complete memory, IO, and system evidence for one run.
- Thermal
Evidence V2 - Thermal state at the end of one run.
- Thread
CpuV2 - One thread’s cumulative CPU consumption at a sample instant.
- Thread
Hardware V2 - Per-thread cycle and instruction totals joined from span records.
- Thread
Utilization Collector - Per-thread CPU utilization and frequency sampler.
- Thread
Utilization Sample V2 - Per-thread CPU census at one instant, bounded with explicit loss.
- Thread
Utilization V2 - Per-thread CPU consumption and utilization across one run.
- Topology
Collector - Static CPU topology, affinity, NUMA, and cgroup limit collector.
- Topology
Evidence V2 - Static CPU topology, affinity, NUMA, and cgroup CPU limits for one run.
- Tracking
Allocator - Global allocator that counts allocations, bytes, and live memory with
per-stage ownership. Install with
#[global_allocator]. Without theallocation-trackingfeature every method inlines to the system allocator. - Typed
Metric Record V2 - One typed counter or gauge materialized from fixed runtime storage.
- Utilization
Evidence V2 - Per-thread utilization, effective parallelism, and frequency series.
- Worker
Imbalance V2 - Work-stealing imbalance evidence merged from every worker shard.
- Worker
Load V2 - Per-worker load observed from one counter shard.
- Worker
Occupancy RowV2 - Busy, blocked, and idle time for one worker across the whole session.
- Worker
Occupancy V2 - Pool-wide busy versus idle accounting merged from every worker shard.
- Workload
Identity Input - Measured byte and unit totals used to classify comparable workload shapes.
- Workload
Identity V2 - Measured workload shape used to classify comparable runs.
- Workload
Measurements - Optional byte domains whose totals distinguish source, expansion, decode, and dispatch work.
Enums§
- Annotation
Id - Stable identifier for a numeric annotation attached to the run timeline.
- Attribution
- Optional attribution for work performed inside a derived input.
- CacheId
- A reuse cache the profiler reports hit and miss counts for.
- Cache
Layer Kind V2 - Cache families whose preparation state changes run cost.
- Cache
State - Cache state that materially changes run cost.
- Collector
Availability - Whether a collector can produce measurements on this host.
- Collector
Id - Stable identity of a profiling data collector.
- Counter
Id - Type-safe identifier for an additive monotonic metric.
- Coverage
State V2 - Whether scanner coverage was complete, partial, or unknown.
- Daemon
State - Daemon state that materially changes startup and resident work.
- Detail
- How much performance measurement this process performs.
- EventId
- Stable identifier for an instantaneous causal event.
- Evidence
- A measured value or an explicit reason why no value exists.
- Evidence
Gap - Why a v2 evidence field has no measured value.
- GaugeId
- Type-safe identifier for a latest-value metric.
- Hardware
Field Source V2 - Exact host facility that produced (or was asked for) one hardware field.
- Indexed
Counter Id - An additive counter that exists once per caller-owned slot.
- IoCache
State V2 - Explicitly observed page-cache state for one source of IO work.
- Macro
Stage Id - Stable identifier for a top-level production pipeline stage.
- Metric
Id - Stable wire identifier for a metric recorded by
keyhog-profile. - Metric
Kind - Measurement behavior associated with a metric.
- Metric
Unit - Stable unit associated with a metric value.
- QueueId
- Bounded fixed set of queue slots for causality links and depth gauges.
- Retry
Cause - Why one operation was attempted again.
- RunState
- Coarse causal state of a profiling run.
- Stage
- Stable micro-function identifier shared by scanner, source, verifier, and reporter paths.
- Work
Origin - Causal origin of the work measured by one span.
Constants§
- CACHE_
EFFECTIVENESS_ V2_ VERSION - CAUSAL_
IDENTITY_ V2_ VERSION - CAUSAL_
PROFILE_ V2_ VERSION - COLLECTOR_
CAPABILITY_ VERSION - COMPARISON_
DIFFERENCE_ VERSION - EVENT_
SCHEMA_ VERSION - EXPORTER_
VERSION - HARDWARE_
EVIDENCE_ V2_ VERSION - INDEXED_
COUNTER_ SLOTS - Number of slots in every indexed counter family.
- INDEXED_
COUNTER_ V2_ VERSION - MAX_
ANNOTATIONS - MAX_
BATCH_ ROUTES - Hard cap on retained batch-route records; further routes count as drops.
- MAX_
POINT_ EVENTS - MAX_
QUEUE_ LINKS - Maximum pending enqueues and completed links retained per runtime.
- MAX_
RECORDED_ SPANS - Maximum number of causal span records retained by one profiling runtime.
- MAX_
SAMPLE_ THREADS - Maximum retained threads per utilization sample; excess is counted.
- MAX_
UTILIZATION_ SAMPLES - Maximum retained utilization samples per session; excess is counted, never stored.
- METRIC_
REGISTRY_ VERSION - PROFILE_
COMPARISON_ VERSION - PROFILE_
ENVELOPE_ V2_ VERSION - PROFILE_
SCHEMA - Stable wire schema for persisted profiling records.
- PROFILE_
SCHEMA_ V2 - PROFILE_
SCHEMA_ V2_ MAJOR - PROFILE_
SCHEMA_ V2_ MINOR - RESOURCE_
SAMPLE_ VERSION - RESOURCE_
SNAPSHOT_ VERSION - RESOURCE_
USAGE_ VERSION - RETRY_
RECORD_ V2_ VERSION - ROOT_
SLOT - Slot index for allocations made outside any recorded span.
- RUN_
IDENTITY_ VERSION - RUN_
PROFILE_ VERSION - SPAN_
HARDWARE_ V2_ VERSION - STAGE_
COMPARISON_ VERSION - STAGE_
CONCURRENCY_ V2_ VERSION - STAGE_
MEASUREMENT_ VERSION - STAGE_
SLOTS - Stage attribution slots: one per
crate::Stageplus one root slot for allocations made outside any recorded span. - STATE_
MEASUREMENT_ VERSION - STATE_
TRANSITION_ VERSION - SYSTEM_
EVIDENCE_ V2_ VERSION - WORKER_
OCCUPANCY_ V2_ VERSION - WORKLOAD_
MEASUREMENTS_ VERSION
Statics§
- METRICS
- Allocation-free registry in numeric
MetricIdorder.
Traits§
- Snapshot
Collector - Portable lifecycle for a collector that snapshots one metric family.
Functions§
- add_
backend_ dispatched_ bytes - Add bytes submitted once to the completed backend route in the current profile.
- add_
counter - Increment one typed monotonic counter in the current profiling runtime.
- add_
derived_ decoder_ bytes - Add bytes produced by accepted decode-through work in the current profile.
- add_
indexed_ counter - Add to one slot of an indexed counter family.
- add_
input_ bytes - Add source bytes processed by the current profile.
- add_
input_ units - Add source units such as files, objects, responses, or chunks.
- add_
stage_ bytes - Attribute bytes to one micro-function so its throughput can be reported.
- aggregate_
span_ hardware - Join span-attached counter readings into per-stage, per-thread, and run CPI.
- allocation_
snapshot - Snapshot the process-wide allocation counters; all zeros when the
allocation-trackingfeature is disabled. - allocation_
tracking_ installed - Whether any tracked allocation has run through a
TrackingAllocator. - blocked
- Record one blocked wait interval separately from runnable execution.
- compare_
profiles - Compare two runs only after checking every identity field that changes timing.
- counter_
span - Start a sub-stage measurement that accumulates into one counter.
- current_
causal_ parent - Capture a portable token naming the current runtime’s causal parent.
- current_
runtime - Return a clone of the runtime current on this thread.
- current_
task_ id - Current thread’s caller-assigned task identity, or zero when unset.
- current_
work_ origin - Current thread’s causal work origin.
- decision_
timer - Start a decision-driving measurement of one micro-function.
- detail
- Return the measurement level requested for this process.
- enabled
- Return whether fixed-stage profiling is active on the calling thread.
- instrument_
future - Propagate the current runtime and causal parent while polling one future.
- instrument_
future_ with_ parent - Propagate the current runtime with an explicit portable causal parent.
- milli_
ratio - Exact integer ratio in thousandths;
Nonewhen the denominator is zero. - record_
annotation - Record one typed numeric annotation on the current run timeline.
- record_
batch_ route - Record the requested, selected, and completed route for one completed batch.
- record_
cache_ hit - Count one consultation of a reuse cache that was served from the cache.
- record_
cache_ miss - Count one consultation of a reuse cache that had to recompute or refetch.
- record_
distribution - Record one observed value into a metric’s bounded logarithmic distribution.
- record_
event - Record one typed instantaneous event with a numeric payload.
- record_
fs_ metadata_ latency_ ns - Record one filesystem metadata (stat/readdir) latency inside a
Stage::SourceWalkinstrumented path. - record_
fs_ open_ latency_ ns - Record one filesystem open latency inside a
Stage::SourceWalkorStage::SourceReadinstrumented path. - record_
fs_ read_ latency_ ns - Record one filesystem read latency inside a
Stage::SourceReadinstrumented path. - record_
io_ cache_ state - Record one explicitly observed page-cache state for IO work.
- record_
network_ bytes - Add network bytes a caller read and wrote; process-level counters are not visible to the profiler on every host, so callers report their own IO.
- record_
network_ latency_ ns - Record one network request latency observed by a caller.
- record_
network_ request - Count one completed network request.
- record_
queue_ depth_ dequeue - Decrement one queue’s depth gauge, saturating at zero.
- record_
queue_ depth_ enqueue - Increment one queue’s depth gauge and refresh its high-water mark.
- record_
queue_ dequeue - Record the consumer dequeue matching one earlier
record_queue_enqueue. - record_
queue_ enqueue - Record one producer enqueue for later matching by
record_queue_dequeue. - record_
retained_ buffer_ bytes - Record the current retained-buffer level in bytes; the runtime keeps the running high water alongside the latest value.
- record_
retry - Count one retry attempt, whether or not the retry eventually succeeded.
- record_
sampled_ event - Record one expensive detail event under a deterministic bounded sampling policy.
- reset
- Discard fixed-stage counters and input totals in the current runtime.
- reset_
allocation_ peaks - Restart peak-live tracking from the current live levels.
- serial_
span - Declare that this region runs with the worker pool idle.
- set_
attribution - Replace this thread’s attribution and return its previous value.
- set_
detail - Set the measurement level for this process and enable or disable the calling thread’s standalone profiling runtime to match.
- set_
enabled - Enable or disable the calling thread’s standalone profiling runtime.
- set_
gauge - Replace one typed latest-value gauge in the current profiling runtime.
- set_
queue_ depth - Replace one queue’s depth gauge and refresh its high-water mark.
- set_
task_ id - Replace this thread’s caller-assigned task identity and return the previous.
- set_
work_ origin - Replace this thread’s causal work origin and return its previous value.
- span
- Start one fixed-stage measurement.
- span_
with_ parent - Start one fixed-stage measurement with an explicit portable causal parent.
- take_
input_ totals - Atomically read and clear aggregate input bytes and units.
- take_
metric_ distributions - Drain caller-recorded value distributions from the current runtime.
- take_
stage_ measurements - Atomically drain fixed counters and materialize stable stage records.
- take_
typed_ metrics - Drain typed counters from the current session or standalone runtime.