ComparisonPolicy

Struct ComparisonPolicy 

Source
pub struct ComparisonPolicy {
    pub default_percent: Option<f64>,
    pub per_metric_percent: BTreeMap<String, f64>,
}
Expand description

Re-export of the comparison-policy types so downstream crates using ktstr::cli as their public surface don’t need to reach into the internal ktstr::stats module (which is pub(crate) — see lib.rs — and therefore not a stable public path). The policy is the only item in stats that a CLI or external consumer constructs directly; every other item is internal plumbing reached via cli::compare_partitions. Per-metric threshold policy driving compare_rows / compare_partitions.

Resolution priority for a given metric’s relative significance threshold, highest first:

  1. per_metric_percent[metric_name] — explicit override for this metric.
  2. default_percent — uniform override across every metric not listed in the map (equivalent to the old --threshold N CLI flag).
  3. The metric’s built-in default_rel from the METRICS registry — the “no policy” fallback.

Values in the struct are stored as PERCENT (e.g. 10.0 meaning 10%), NOT fractions. Self::rel_threshold does the /100.0 conversion so every caller inside compare_rows reads a fraction without re-deriving the division.

Note on the registry-fallback branch: the default_rel field on MetricDef is already a FRACTION (e.g. 0.25 for 25%), not a percent. rel_threshold returns it verbatim — it does NOT divide by 100. Only the override branches (per-metric map, default_percent) do the percent-to-fraction conversion because their inputs are percents. This asymmetry is deliberate so callers supplying CLI/file-based overrides work in human-intuitive percent units while the registry defaults (which already ship in fraction form) pass through unchanged.

The struct is serde::Serialize / serde::Deserialize so cargo ktstr perf-delta --policy <path> can load a JSON-persisted policy file. Default construction produces an empty policy that uses every registry default; Self::uniform reproduces the old --threshold N behaviour without any per-metric override plumbing at the call site.

Fields§

§default_percent: Option<f64>

Uniform override: when Some(p), every metric whose name is NOT in Self::per_metric_percent uses p / 100.0 as its relative threshold. None falls through to the registry default_rel. Stored as percent (e.g. 10.0 for 10%).

§per_metric_percent: BTreeMap<String, f64>

Per-metric overrides keyed by metric name. Each value is a percent (e.g. 15.0 → 15%). An entry here takes precedence over both Self::default_percent and the registry default_rel.

Implementations§

Source§

impl ComparisonPolicy

Source

pub fn new() -> Self

Empty policy — every metric uses its METRICS registry default. Equivalent to the old --threshold None CLI path.

Source

pub fn uniform(percent: f64) -> Self

Uniform override: every metric uses percent / 100.0. Mirrors the old --threshold N CLI behaviour; the CLI dispatch at cargo ktstr perf-delta --threshold N constructs a policy via this constructor.

Source

pub fn load_json(path: &Path) -> Result<Self>

Load a JSON-persisted policy from a file. Errors propagate the read / parse reason as an anyhow::Error with the file path in the context chain so a malformed --policy path.json surfaces an actionable message rather than a generic “invalid JSON.”

Validates after parsing via Self::validate: rejects negative thresholds (a misconfigured 10 vs -10 would invert the dual-gate logic at the .abs() >= rel_thresh check and silently classify every metric as significant) and rejects per-metric keys not registered in METRICS (a typo like "wrost_spread" would otherwise be silently ignored — the key simply never matches during resolution and the metric falls through to default_percent).

Source

pub fn validate(&self) -> Result<()>

Structural validation separate from parsing so both the load_json path and programmatic constructors (after Self::uniform with a user-supplied percent) can share one set of invariants without re-implementing checks at each call site. Called automatically by Self::load_json; CLI dispatch should call it after constructing via Self::uniform to catch --threshold -10 at the entry point rather than deep inside compare_rows where the dual-gate math silently misbehaves.

Rejects:

  • Negative default_percent (nonsensical — thresholds are absolute-value comparisons).
  • Negative entries in per_metric_percent.
  • Per-metric keys not in the METRICS registry (silent typos would otherwise fall through to default_percent unnoticed).
Source

pub fn from_cli_flags( threshold: Option<f64>, policy: Option<&Path>, ) -> Result<Self>

Resolve the mutually-exclusive --threshold / --policy CLI pair into a policy: --threshold N is sugar for a uniform N% default (validated for sign); --policy PATH loads a per-metric JSON policy; neither falls through to the registry defaults. Shared by every subcommand that accepts the pair (perf-delta) so the resolution rules — and the “exactly one of the two” contract — live in one place.

Both flags set is rejected with an error. At the CLI call sites clap conflicts_with makes that unreachable, but this is a library entry point and must not panic on its inputs; the error is the defence-in-depth backstop.

Source

pub fn rel_threshold(&self, metric_name: &str, default_rel: f64) -> f64

Resolve the relative threshold (as a fraction, e.g. 0.10 for 10%) for metric_name with default_rel as the registry-level fallback. Handles the percent→fraction conversion so compare_rows_by does not need to re-derive p / 100.0 at every call site.

Trait Implementations§

Source§

impl Clone for ComparisonPolicy

Source§

fn clone(&self) -> ComparisonPolicy

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ComparisonPolicy

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for ComparisonPolicy

Source§

fn default() -> ComparisonPolicy

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for ComparisonPolicy

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Serialize for ComparisonPolicy

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

impl<T> PolicyExt for T
where T: ?Sized,

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] only if self and other return Action::Follow. Read more
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

§

impl<T> MaybeSend for T
where T: Send,

§

impl<T> MaybeSend for T
where T: Send,