fix(deps): update rust crate metrics-lib to v2 #5
Loading…
Reference in a new issue
No description provided.
Delete branch "renovate/metrics-lib-2.x"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
This PR contains the following updates:
1.0.0→2.0.0Release Notes
jamesgober/metrics-lib (metrics-lib)
v2.0.0Compare Source
A correctness release. The 2026-10-13 audit found bugs that 1.0 had frozen
into its API: Prometheus/OpenMetrics output that scrapers reject, memory
readings 1024× too high off Linux, a token bucket that stopped refilling
after 49.7 days, unbounded registries and unescaped names. Fixing them
needed breaking changes, so this is a major release. Every breaking change
and its replacement is listed in
docs/MIGRATION-2.0.md.Added
init_with_config(MetricsConfig)andtry_metrics();MetricsConfig(series cap, system sampling interval, health thresholds, eager or lazy
system monitor, process metrics) with
with_*setters.validate_metric_name,validate_label_key,validate_label_value) and repair (sanitize_metric_name,sanitize_label_key) with documented limits;MetricsError::InvalidName/
InvalidLabelfrom everytry_*lookup.metadata-only families;
Registry::remove,remove_series,evict_idle,kind_of,with_cardinality_cap, and the diagnosticsinvalid_inputs,kind_conflictsandexposition_conflicts.MetricsError::KindMismatch.try_counter/try_gauge/ … for unlabeled lookups.UpDownCounter(signed integer) andShardedCounter(striped acrosscache lines for contended counters).
Summary: streaming quantiles from a relative-error sketch(
SummaryConfig, default 2 % relative accuracy), exported as a summary.observe_with_exemplar), emitted in OpenMetrics;with the
tracingfeature,span_exemplarandobserve_with_span_exemplartake the trace context from the currentspan. Exemplars live in
HistogramSnapshot::exemplars(empty andunallocated when none were recorded), so
HistogramBucketkeeps its 1.xshape and exporters that cannot carry exemplars never copy them.
Timer::start_owned,MetricsCore::start_timer,MetricsCore::time; guards are#[must_use]and havediscard().process_*series (process_cpu_seconds_total,process_resident_memory_bytes,process_virtual_memory_bytes,process_open_fds,process_max_fds,process_threads,process_start_time_seconds) viaProcessCollector,render_with_processandrender_core.metrics-rs:MetricsLibRecorderimplements themetrics0.24Recorder, so code instrumented with themetricsfacade records into ametrics-lib registry.
http:MetricsServer(a dependency-free/metricsand/healthendpoint with Prometheus/OpenMetrics content negotiation) and aPushgateway client (
push,push_add,delete). The server serves eachconnection on its own short-lived thread (at most
MAX_CONNECTIONS= 16at once). When all are taken, a new connection evicts a connection still
waiting for its request (the oldest one of the address holding the most
such connections), so idle connections cannot lock scrapers out; only
when every slot is writing a response is it answered 503. Every
client gets a total deadline to send its request head
(
REQUEST_TIMEOUT, 2 s, then 408) and to read the response(
RESPONSE_TIMEOUT, 10 s), and heads overMAX_REQUEST_HEAD(8 KiB) areanswered 431. The Pushgateway client enforces one deadline over
connecting, sending and reading, and tries every resolved address with
an equal share of the time left.
tower:RedLayer, request rate/error/duration middleware forany tower service (axum, tonic, hyper).
OtlpExporterwith cumulative or delta temporality, stable seriesstart times, resource attributes, and protobuf encoding
(
render_protobuf) besides JSON.CounterMode::Delta, the default), prefixand packet-size options, any
ToSocketAddrstarget.counter!,gauge!,up_down_counter!,timer!,histogram!,summary!,rate!andlabels!, in thename, key => valuestyle of themetricscrate.asyncfeature:AsyncTimerExtforArc<Timer>('staticfutures),AsyncMetricsBatcher::start_flusherwith a shutdown handle, andrecord_runtime_metricsfor Tokio runtime gauges.TokenBucket::try_newandtime_until_available;Counter::set_max;try_*variants of everyGaugeread-modify-write method.tests/commonthat everyexposition test runs through, including a property test over random
registries; real-thread stress tests (
tests/concurrency.rs); propertytests that call public methods with arbitrary input.
README.mdanddocs/*.mdis compiled and run as adoctest.
docs/MIGRATION-2.0.md,docs/PERFORMANCE.md,docs/STABILITY.md(the2.x contract) and
docs/release/v2.0.0.md.Changed
portfolio standard and allows sysinfo 0.36.
Apache-2.0 OR MIT(was Apache-2.0), per the portfoliorelease checklist.
system(indefault);histogramno longer enablessample;asynccompiles alone; newhttp,metrics-rsandtower;bench-testsremoved.MetricsCore::new()starts no thread and makes no system call; thesystem monitor starts on first use of
system().metrics()initialiseson first use instead of panicking.
get_or_create_countertocounter, and soon; the 1.x names remain as deprecated aliases);
describe_*andconfigure_histogramreturnResult. The registry is sharded (16 locks)and labeled lookups no longer allocate.
_min/_maxgauges, rate meters a_totalcounter plus a_per_secondgauge, dotted names render with_,# UNITappears only in OpenMetrics and only when the name ends inthe unit, OpenMetrics output ends with
# EOF, floats use the canonicalformat.
RateMeter: sliding-window estimate over the configured window;tick_ntakesu64; counts areu64.TokenBucket: GCRA on nanosecondu64timestamps; capacities and tokencounts are
u64.Timer: the sum is kept in 128 bits (no wrap);RunningTimer::stopreturns the elapsed time.
Optionwhere a platform cannotprovide a value;
HealthConfig::memory_percentreplacesmemory_gb;update_interval()returnsDuration.json::renderreturnsserde_json::Result<String>; schema version 2.#[non_exhaustive].systemfeature reads the OS directly on Linux(
/proc), Windows (six kernel32 calls) and macOS (libSystem:getrusage,proc_pidinfo, Mach host statistics,sysctl), sosysinfois no longercompiled there; it remains (0.29 to 0.36.1) only for targets without an
in-house backend, such as FreeBSD. On Windows that removes 20 transitive
crates and about 15 s of clean build time from the default features, and
sysinfo's MSRV no longer constrains Linux, Windows or macOS. The FFIdeclarations are written by hand (no
windows-sys/libc): 0 cratesinstead of 2 and 1, with every struct layout checked at compile time.
Tokio floor 1.47;
parking_lotandnum_cpusremoved (stdMutexandavailable_parallelism); new optionalpin-project-lite,metrics,tower-layer,tower-serviceandhttp. Dev: criterion0.7, proptest 1.11, axum 0.8;
doc-comment,tokio-test,rand,anyhow,crossbeam-channeland thehalfpin removed.stable and MSRV on Linux/macOS/Windows, a cargo-hack feature matrix, a
coverage gate, a docs.rs build and a semver check;
deny.tomlhas noadvisory ignores. The Miri job is gone: the only
unsafecode is theOS calls of the Windows and macOS system backends, which Miri cannot
execute. Warnings are denied in CI instead of with
#![deny(warnings)], so lints added to future compilers cannot breakdownstream or docs.rs builds.
Deprecated
Registry::get_or_create_*,get_or_create_*_withandtry_get_or_create_*_with: usecounter,counter_with,try_counter_withand the same pattern for the other kinds. Removal in3.0.
Removed
MetricsError::Overloaded,OverLimitandNotInitialized(neverproduced).
CounterStats::total,GaugeStats::updates,RateStats::window_fill,timer::utils::benchmark, thebench-testsfeature,build.rsandtarpaulin.toml.Fixed
Audit IDs refer to the 2026-10-13 audit.
asyncfeature did not compile withoutmeter.returns bytes).
between samples and counts iowait, irq, softirq and steal time.
TokenBucketstopped refilling after about 49.7 days (u32millisecond wrap), and
reset()did not help.timers typed
histogramwithout buckets, rate families,_totalhandling, units, missing
# EOF). Output is checked by strictvalidators in every test run.
ThroughputMeter::record_bytestruncated tou32.StatsD injection).
CircuitBreakerConfig,SamplingStats,TimedFutureandBackpressureGuardcould not be named.clamp, empty bucketlists, zero sampling rates, thread-spawn failure).
/proc/self/statparsing broke on process names containingspaces or
); the parsers are pure functions tested against fixtures.RateMeterignored its window and reported "events since thestart of this wall-clock second".
set_max,set_minandupdate_ema.writes.
MetricsCorestarted a sampler thread.RunningTimercould not be held from a temporaryArc.Gauge::clampskipped small-magnitude clamps.#[non_exhaustive]where STABILITY promised additive growth.+Infbucket bounds and non-finite gauges asnull.are
Nonewhere the platform does not report them.try_newreports invalid input and
MAX_REFILL_PER_SECONDdocuments the limit.AsyncMetricsBatcherwas hard-wired to the global instance.now measured and labelled with its machine (see Performance below).
sampler is now lock-free, and the docs say which paths take locks
(registry lookups and registration).
allow(unsafe_code)replaced bydeny(unsafe_code), allowed only insrc/system/windows.rsandsrc/system/macos.rs(OS calls, each block with aSAFETYcomment andcompile-time layout checks); the pin projection uses
pin-project-lite.the guides compiles and runs; feature tables, paths, test counts, memory
layout and performance figures match the code.
Found by the independent re-audit of the 2.0.0 candidate and fixed before
release (ML2 IDs):
clippy::map_unwrap_orin the Linux-only system code failedCI on current stable; Linux and macOS code is now linted locally too.
MetricsServerforseconds to hours, every scrape waited for a 50 ms accept poll, and an
oversized head was answered 200.
render_coresampled the process through afull process-table scan (hundreds of milliseconds on a busy host), and
the system sampler could take longer than its interval. Windows and
macOS now read the current process and the host directly (about 1 µs for
a process sample on Windows instead of about 30 ms), and the sampler
still backs off so it never samples more than a quarter of the time.
HistogramBucket, whichmade every snapshot several times larger and cloned exemplar labels for
exporters that drop them.
Registry::clearracing with registrations could leave theseries count below the real number of series and so let the cap be
exceeded.
took 28 s against a slow gateway), and only the first resolved address
was tried. Timeouts now surface as
TimedOuton every platform.tand a countert.count, a rateqand a gaugeq.per_second); thefirst family keeps the name, as in the text exporters, and the clash is
counted in
exposition_conflicts.Summary::snapshotcopied the sketch once per quantile; it nowreads it once for all quantiles.
could export a minimum of 584 years.
not start a new OTLP series; the exporter now moves the start time.
MetricsErrorstated the wrong name and label-key rules.metrics off Linux were not disclosed; see Performance below and
docs/PERFORMANCE.md.RedLayerdid not time work done inside the innercall, anda panic there left the in-flight gauge raised.
remove,remove_series,metadataandkind_ofdid notrepair names the way the lookups do;
ScopedRegistrylackeddescribe_summary,describe_up_down_counter,remove*,metadataand
kind_of; a clash between two counter types was reported as"counter versus counter".
[Unreleased]skeleton).serde_json 1.0.154, http 1.5).
docs/STABILITY.mdsays.run, as documented.
every type.
exemplar) is documented behaviour and stays: the hot path never waits.
Found by the final verification and fixed before release:
at 503. A new connection now evicts a connection still waiting for its
request, the oldest one of the address holding the most such
connections, so a flooding client evicts its own connections first; the
request-head deadline is 2 s (was 5 s).
docs/MIGRATION-2.0.mdand the release notes.only type-checked (x86_64 macOS, FreeBSD).
proc_pidinfohelper accepts only the result types of anunsafe traittied to their flavor constants, instead of anyT.addresses, so an unreachable first address leaves time for the next.
sysinfobackend is removed;the Windows backend makes six kernel32 calls, as now documented.
Security
Prometheus, OpenMetrics or StatsD output, and every collection that
grows with input is capped (ML-008, ML-009).
MetricsServercannot be stalled by idle, slow or oversized clients(ML2-002), and the Pushgateway client cannot hang past its timeout
(ML2-006).
#![deny(unsafe_code)]:unsafeexists only in the two OS-call modulesof the
systemfeature, which replace the far larger unsafe surface ofsysinfoand its Windows/macOS dependency tree on those platforms.Performance
Measured on an AMD Ryzen 9 9950X3D, Windows 11, on a machine shared with
other builds;
docs/PERFORMANCE.mdhas the full tables and the method,and
tools/compare-1xreproduces the comparison with 1.0.0.Counter::inc(3.9 ns),Timer::record_ns(7.6 ns),Histogram::observe(12.6 ns). The 1.x claim of about 1.5 ns forCounter::incdid not reproduce with the 1.0.0 code either; it iscorrected everywhere.
longer allocates. With eight threads on one counter,
ShardedCounterfinishes 5 to 9 times sooner than
Counter. Rendering 400 series takes0.14 ms.
shard routing and the kind check);
Histogram::snapshot+5 % (+2 ns, theexemplar vector);
RateMeter::tick+13 % andrate()+41 % (+5 ns and+9 ns: the monotonic clock and the sliding-window estimate that fix
ML-014).
process_*sample takes 0.66 µs on Windows (thesysinfopath took 31 ms on the reference host and up to 500 ms underheavy load); a host-plus-process update 0.14 ms instead of about 32 ms.
render_corewith process metrics costs the same asrender.Configuration
📅 Schedule: (UTC)
🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.
♻ Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.
🔕 Ignore: Close this PR and you won't be reminded about this update again.
This PR has been generated by Mend Renovate.
View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.