Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
59 commits
Select commit Hold shift + click to select a range
13e40e4
enhancement(tag_cardinality_limit transform): add sliding-window TTL …
kaarolch May 22, 2026
3c9a0bf
Fix tests
kaarolch May 22, 2026
6395814
Add changelog.md
kaarolch May 22, 2026
59e05f8
Fix formating
kaarolch May 22, 2026
7aa7efb
Add missing const
kaarolch May 22, 2026
dde8896
Merge remote-tracking branch 'upstream/master' into tag_cardinality_c…
kaarolch May 22, 2026
b95265e
fix(tag_cardinality_limit transform): address Codex review on TTL imp…
kaarolch May 22, 2026
528561d
fix(tag_cardinality_limit transform): tighten TTL comments, capacity …
kaarolch May 22, 2026
57e3ce8
Merge branch 'master' into tag_cardinality_cache_ttl
kaarolch Jun 3, 2026
44d9f07
fix(tag_cardinality_limit transform): fix TTL window math, expired re…
kaarolch Jun 3, 2026
e13fdd7
Merge branch 'master' into tag_cardinality_cache_ttl
kaarolch Jun 3, 2026
78490bc
Merge upstream/master into tag_cardinality_cache_ttl
kaarolch Jul 31, 2026
9fbb72b
perf(tag_cardinality_limit transform): keep exact-TTL cache hits O(1)
kaarolch Jul 31, 2026
f01dcd3
docs(tag_cardinality_limit transform): state TTL expirations in cache…
kaarolch Jul 31, 2026
c0ed778
fix(tag_cardinality_limit transform): reject ttl_secs in exact_finger…
kaarolch Jul 31, 2026
9a53477
docs(tag_cardinality_limit transform): regenerate component docs for …
kaarolch Jul 31, 2026
aa74bad
fix(tag_cardinality_limit transform): keep rolling-bloom values for t…
kaarolch Jul 31, 2026
199e856
fix(tag_cardinality_limit transform): honor single-generation tumblin…
kaarolch Aug 12, 2026
9ef512a
Merge branch 'master' into tag_cardinality_cache_ttl
kaarolch Aug 12, 2026
795011d
Merge branch 'master' into tag_cardinality_cache_ttl
kaarolch Aug 13, 2026
116434b
Merge branch 'master' into tag_cardinality_cache_ttl
kaarolch Sep 9, 2026
4e84847
Merge branch 'master' into tag_cardinality_cache_ttl
kaarolch Sep 16, 2026
7d5efb1
fix(tag_cardinality_limit transform): address Sep 9 Codex TTL review
kaarolch Sep 16, 2026
700bf9f
Merge upstream/master into tag_cardinality_cache_ttl
kaarolch Sep 16, 2026
e33fabf
test(tag_cardinality_limit transform): trim redundant TTL coverage
kaarolch Sep 16, 2026
a989292
Merge remote-tracking branch 'origin/tag_cardinality_cache_ttl'
kaarolch Sep 16, 2026
66b4bbd
fix(tag_cardinality_limit transform): amortize reclaim and document e…
kaarolch Sep 16, 2026
4510f67
fix(tag_cardinality_limit transform): keep sliding TTL when generatio…
kaarolch Sep 17, 2026
664b5e0
Merge branch 'master' into tag_cardinality_cache_ttl
kaarolch Sep 17, 2026
365a05b
Merge branch 'master' into tag_cardinality_cache_ttl
kaarolch Sep 18, 2026
0446257
Reduce number of test by merging some test together
kaarolch Sep 18, 2026
0604bfd
Merge branch 'master' into tag_cardinality_cache_ttl
kaarolch Sep 21, 2026
605148b
Merge branch 'master' into tag_cardinality_cache_ttl
kaarolch Sep 22, 2026
97363de
Merge upstream/master into tag_cardinality_cache_ttl
kaarolch Oct 16, 2026
fbb4ced
fix(tag_cardinality_limit transform): reject ttl_generations: 0 with …
kaarolch Oct 16, 2026
738f149
Merge branch 'master' into tag_cardinality_cache_ttl
kaarolch Oct 19, 2026
45ece63
Merge branch 'master' into tag_cardinality_cache_ttl
kaarolch Oct 26, 2026
0ee5220
Merge branch 'master' into tag_cardinality_cache_ttl
kaarolch Oct 27, 2026
994a4f3
Merge branch 'master' into tag_cardinality_cache_ttl
kaarolch Oct 27, 2026
eab32a7
Merge branch 'master' into tag_cardinality_cache_ttl
kaarolch Oct 28, 2026
67f46eb
Merge branch 'master' into tag_cardinality_cache_ttl
kaarolch Oct 30, 2026
6ff2c22
Merge branch 'master' into tag_cardinality_cache_ttl
kaarolch Nov 2, 2026
5d5fe9a
Merge branch 'master' into tag_cardinality_cache_ttl
kaarolch Nov 4, 2026
de42499
Merge branch 'master' into tag_cardinality_cache_ttl
kaarolch Nov 5, 2026
fa0e7d1
docs(tag_cardinality_limit): call probabilistic TTL expiry counts app…
kaarolch Nov 5, 2026
ab1e528
fix(tag_cardinality_limit): skip empty-bucket reclaim without TTL and…
kaarolch Nov 5, 2026
2b3430d
fix(tag_cardinality_limit): ignore ttl_secs on excluded metric overrides
kaarolch Nov 5, 2026
4df3db1
fix(tag_cardinality_limit): bound empty-bucket reclaim to one pass pe…
kaarolch Nov 5, 2026
b81eb42
Merge branch 'master' into tag_cardinality_cache_ttl
kaarolch Nov 5, 2026
886a091
fix(tag_cardinality_limit): cap probabilistic ttl_generations at 16
kaarolch Nov 5, 2026
b2acdb0
Merge branch 'master' into tag_cardinality_cache_ttl
kaarolch Nov 6, 2026
e6709e1
Merge branch 'master' into tag_cardinality_cache_ttl
kaarolch Nov 6, 2026
6a49c95
Merge branch 'master' into tag_cardinality_cache_ttl
kaarolch Nov 12, 2026
4b1d9ce
fix(tag_cardinality_limit): rate-limit exact-TTL capacity purge to on…
kaarolch Nov 12, 2026
52b017f
Merge branch 'master' into tag_cardinality_cache_ttl
kaarolch Nov 12, 2026
cf543c7
Merge branch 'master' into tag_cardinality_cache_ttl
kaarolch Nov 16, 2026
0cec23c
Merge branch 'master' into tag_cardinality_cache_ttl
kaarolch Nov 17, 2026
b7530c8
Merge branch 'master' into tag_cardinality_cache_ttl
kaarolch Nov 24, 2026
e83cf8f
Merge branch 'master' into tag_cardinality_cache_ttl
kaarolch Nov 25, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions changelog.d/tag_cardinality_limit_ttl.enhancement.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
The `tag_cardinality_limit` transform gained an optional sliding-window TTL
for tracked tag values. Two new settings — `ttl_secs` and `ttl_generations` —
are available on the global block and each `per_metric_limits` entry; values
not accepted within `ttl_secs` are evicted, freeing room under `value_limit`.
TTL is supported in `exact` and `probabilistic` modes; combining it with
`exact_fingerprint` is rejected at startup because that mode stores no
last-accepted timestamps. In `probabilistic` mode the effective
`ttl_generations` is limited to 16: a cache miss checks every bloom shard,
so a higher count is rejected when `ttl_secs` is long enough to build it.
A new internal counter `tag_cardinality_ttl_expirations_total` reports the
number of cache slots reclaimed by TTL eviction — exact in `exact` mode, an
approximation in `probabilistic` mode (refresh-on-sighting can over-count, and
bloom false positives can under-count). See the transform documentation for
configuration details and mode-specific behavior.

authors: kaarolch
2 changes: 2 additions & 0 deletions lib/vector-common/src/internal_event/metric_name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ pub enum CounterName {
StaleEventsFlushedTotal,
StartedTotal,
StoppedTotal,
TagCardinalityTtlExpirationsTotal,
TagCardinalityUntrackedEventsTotal,
TagValueLimitExceededTotal,
TopologyDiskBufferLifecycleEventsTotal,
Expand Down Expand Up @@ -455,6 +456,7 @@ impl CounterName {
Self::StaleEventsFlushedTotal => "stale_events_flushed_total",
Self::StartedTotal => "started_total",
Self::StoppedTotal => "stopped_total",
Self::TagCardinalityTtlExpirationsTotal => "tag_cardinality_ttl_expirations_total",
Self::TagCardinalityUntrackedEventsTotal => "tag_cardinality_untracked_events_total",
Self::TagValueLimitExceededTotal => "tag_value_limit_exceeded_total",
Self::TopologyDiskBufferLifecycleEventsTotal => {
Expand Down
29 changes: 29 additions & 0 deletions src/internal_events/tag_cardinality_limit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,3 +105,32 @@ impl InternalEvent for TagCardinalityTrackedKeys {
gauge!(GaugeName::TagCardinalityTrackedKeys).set(LossyF64(self.count));
}
}

/// Emitted when TTL eviction reclaims tag values from a tracking bucket.
///
/// The `count` is in cache *slots*, the unit `AcceptedTagValueSet::len`
/// measures when enforcing `value_limit`. For the exact backend a slot holds
/// one distinct value, so the count is exact. For the probabilistic backend it
/// is an approximation of the distinct values that aged out of the retired
/// rolling-bloom shard, not a bound. Refresh-on-sighting can over-count,
/// because a hot value copied into a newer shard is still included when the
/// old shard rotates out. A bloom false positive can under-count, because
/// `BloomFilterStorage::insert` leaves the shard count unchanged when the
/// filter already reports the value as present.
#[derive(NamedInternalEvent)]
pub(crate) struct TagCardinalityTtlExpired {
pub count: u64,
}

impl InternalEvent for TagCardinalityTtlExpired {
fn emit(self) {
if self.count == 0 {
return;
}
debug!(
message = "Expired tag values from cardinality cache.",
count = self.count,
);
counter!(CounterName::TagCardinalityTtlExpirationsTotal).increment(self.count);
}
}
269 changes: 268 additions & 1 deletion src/transforms/tag_cardinality_limit/config.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::collections::HashMap;
use std::{collections::HashMap, time::Duration};

use snafu::Snafu;
use vector_lib::configurable::configurable_component;
Expand Down Expand Up @@ -87,6 +87,71 @@ pub struct Inner {

#[serde(default)]
pub internal_metrics: InternalMetricsConfig,

/// Expire tracked tag values after this many seconds since they were last
/// accepted into the cardinality cache.
///
/// When unset (default) or set to `0`, values persist for the lifetime of the
/// process — the historical behavior. When set to a positive value, the
/// transform behaves like a sliding window: any tag value not accepted within
/// the TTL is dropped, freeing room under `value_limit` for fresh values.
/// Useful for bounding cost on backends (e.g. Datadog custom metrics) that
/// bill on a rolling unique-series window.
///
/// "Accepted" means the value was recorded on an emitted event. With
/// `limit_exceeded_action: drop_tag`, every retained tag sighting refreshes
/// the lease. With `limit_exceeded_action: drop_event`, the pre-check uses a
/// non-refreshing membership test and the record pass runs only when the
/// whole event is kept — so a value present on every *incoming* event can
/// still expire if those events are rejected because another tag is over
/// limit. Size the TTL around the active accepted set, not raw event volume.
///
/// In `exact` mode every value carries a precise last-accepted timestamp; in
/// `probabilistic` mode the underlying bloom filter is split into
/// `ttl_generations` rolling shards, so eviction is approximate to within
/// `ttl_secs / ttl_generations`.
///
/// Not supported in `exact_fingerprint` mode, which keeps only hashes and has
/// nowhere to record a last-accepted time; combining the two is a configuration
/// error rather than a silently ignored setting.
#[serde(default)]
#[configurable(metadata(docs::human_name = "TTL (seconds)"))]
pub ttl_secs: Option<u64>,
Comment thread
kaarolch marked this conversation as resolved.
Resolved

/// Number of time-slices the TTL window is split into.
///
/// In `probabilistic` mode, higher values smooth eviction (closer to a true
/// sliding window) at the cost of `(effective ttl_generations + 1) *
/// cache_size_per_key` memory per (metric, tag-key) pair. The same factor
/// applies to CPU. A cache miss, or a hit that lives only in an older shard,
/// checks every shard, and each check hashes the tag value, so lookup cost
/// grows linearly with the shard count. The effective generation count in
/// this mode is limited to 16; a higher request is rejected when `ttl_secs`
/// is long enough to honor it. A shorter `ttl_secs` still clamps the count
/// first (slices are at least 1s), and the limit applies to that clamped
/// count, so a request above 16 is accepted when the clamp brings it back
/// to 16 or below. The extra shard on top of the effective count is the one
/// currently being written: it covers only part of a slice, so retiring
/// without it would expire values after `ttl_secs - (ttl_secs /
/// ttl_generations)` instead of the full TTL. Explicitly setting `1`
/// produces a one-shard tumbling window: all tracked values are dropped at
/// once every `ttl_secs`, using `cache_size_per_key` memory. When `ttl_secs`
/// is shorter than the requested generation count, generations are clamped
/// but the extra shard is still kept so short TTLs do not silently tumble.
///
/// In `exact` mode this does not change eviction precision (each value still
/// carries its own last-accepted timestamp). It only sets how often the
/// transform may proactively scan the value map (`sweep_interval ≈
/// ttl_secs / ttl_generations`): higher values scan more frequently. Raising
/// it has no benefit for correctness and can increase CPU on large
/// `value_limit` buckets.
///
/// Must be at least `1` when `ttl_secs` is set, and at most 16 effective
/// generations in `probabilistic` mode. Ignored when `ttl_secs` is unset.
/// `exact` mode has no generation cap.
#[serde(default = "default_ttl_generations")]
#[configurable(metadata(docs::human_name = "TTL Generations"))]
pub ttl_generations: u8,
}

/// Controls the approach taken for tracking tag cardinality at the global level.
Expand Down Expand Up @@ -160,6 +225,23 @@ pub struct OverrideInner {

#[serde(default)]
pub internal_metrics: InternalMetricsConfig,

/// Per-metric TTL for tracked tag values. See [`Inner::ttl_secs`] for the
/// full description.
///
/// Per-metric TTL is a **full override** of the global TTL — it does not
/// inherit. Leaving this unset means "no TTL for this metric", *not*
/// "fall back to the global `ttl_secs`". This mirrors how a per-metric
/// `value_limit` fully shadows the global one. If you want a metric to
/// share the global TTL, copy the value explicitly.
#[serde(default)]
#[configurable(metadata(docs::human_name = "TTL (seconds)"))]
pub ttl_secs: Option<u64>,

/// Per-metric override for `ttl_generations`. See [`Inner::ttl_generations`].
#[serde(default = "default_ttl_generations")]
#[configurable(metadata(docs::human_name = "TTL Generations"))]
pub ttl_generations: u8,
}

/// Controls the approach taken for tracking tag cardinality at the per-metric level.
Expand All @@ -185,6 +267,15 @@ pub enum OverrideMode {
Excluded,
}

impl OverrideInner {
/// Whether this override actually applies a TTL. `mode: excluded` ignores
/// every other field and allocates no storage, so a leftover `ttl_secs`
/// there is not a TTL (and must not be validated or counted as one).
pub(crate) fn ttl_active(&self) -> bool {
self.mode.as_mode().is_some() && ttl_duration(self.ttl_secs).is_some()
}
}

impl OverrideMode {
/// Returns the equivalent global `Mode` if this scope is tracked, or `None` if excluded.
#[must_use]
Expand Down Expand Up @@ -313,6 +404,67 @@ pub(crate) const fn default_cache_size() -> usize {
5 * 1024 // 5KB
}

/// Default number of rolling-bloom shards. Four gives a reasonable middle ground:
/// eviction granularity of `ttl/4`, and a 4x memory multiplier on
/// `cache_size_per_key` for users who opt into TTL.
pub(crate) const fn default_ttl_generations() -> u8 {
4
}

/// Largest effective generation count `probabilistic` mode will build.
///
/// A cache miss, and a hit that lives only in an older shard, runs a bloom
/// membership test per shard, and each test hashes the tag value. Sliding
/// windows keep one extra shard, so this allows at most 17 probes. That is
/// four times the default and still splits the TTL into slices of about 6%.
/// `exact` mode does not probe shards and is not limited by this.
///
/// The number is also written out in the `ttl_generations` field docs and the
/// transform's TTL section; keep those in step with this constant.
pub(crate) const MAX_TTL_GENERATIONS: u8 = 16;

/// Resolve `ttl_secs` to a window, treating both `None` and `0` as "no expiry".
///
/// Backend selection and config validation both go through this so they can
/// never disagree about whether a config has TTL enabled.
pub(crate) fn ttl_duration(ttl_secs: Option<u64>) -> Option<Duration> {
ttl_secs.filter(|secs| *secs > 0).map(Duration::from_secs)
}

/// Compute time-slice count and duration so `slice * generations == ttl` exactly.
///
/// Caps `generations` to at most one slice per second of TTL (so each slice is
/// `>= 1s` when `ttl >= 1s`) and to the caller's `ttl_generations` request.
/// Uses `Duration` division for `slice` so non-divisible TTLs (e.g. 10s / 4)
/// still sum to the configured window. The per-second cap saturates at
/// `u8::MAX` rather than wrapping, so a TTL of `>= 2^8` seconds never clamps
/// the requested generation count.
///
/// This is the generation count the storage backends build, so validation
/// applies [`MAX_TTL_GENERATIONS`] to this result rather than to the raw
/// request: a request of 255 with `ttl_secs: 10` builds 10 generations.
pub(crate) fn compute_ttl_slices(ttl: Duration, ttl_generations: u8) -> (u8, Duration) {
let requested = ttl_generations.max(1);
let max_for_ttl = u8::try_from(ttl.as_secs().max(1)).unwrap_or(u8::MAX);
let generations = requested.min(max_for_ttl);
let slice = ttl / u32::from(generations);
(generations, slice)
}

impl Config {
/// Whether the global config or any tracked per-metric override enables a TTL.
///
/// Without a TTL nothing can empty a bucket (apart from intentional
/// `value_limit: 0` ones), so reclaiming empty buckets can be skipped.
pub(crate) fn any_ttl_enabled(&self) -> bool {
ttl_duration(self.global.ttl_secs).is_some()
|| self
.per_metric_limits
.values()
.any(|per_metric| per_metric.config.ttl_active())
}
}

// =============================================================================
// Transform plumbing
// =============================================================================
Expand All @@ -325,6 +477,8 @@ impl GenerateConfig for Config {
value_limit: default_value_limit(),
limit_exceeded_action: default_limit_exceeded_action(),
internal_metrics: InternalMetricsConfig::default(),
ttl_secs: None,
ttl_generations: default_ttl_generations(),
},
tracking_scope: TrackingScope::default(),
max_tracked_keys: None,
Expand All @@ -342,6 +496,31 @@ pub enum BuildError {
`probabilistic`, where it has no effect. Remove the field or switch to `probabilistic` mode."
))]
CacheSizeRequiresProbabilistic { tag_key: String },

#[snafu(display(
"ttl_secs set on {scope} but mode is `exact_fingerprint`, which stores fingerprints \
without last-accepted timestamps and so cannot expire them. Remove ttl_secs or switch to \
`exact` or `probabilistic` mode."
))]
TtlUnsupportedInFingerprintMode { scope: String },

#[snafu(display(
"ttl_generations is 0 on {scope} while ttl_secs is set. Use `1` for a tumbling window \
or a higher value for a sliding window."
))]
ZeroTtlGenerations { scope: String },

#[snafu(display(
"ttl_generations resolves to {effective} on {scope} in probabilistic mode, above the \
limit of {limit}. A cache miss checks every bloom shard and hashes the tag value each \
time, so lower ttl_generations (16 keeps slices of about ttl/16) or use `exact` mode, \
which is not capped."
))]
TtlGenerationsTooHigh {
scope: String,
effective: u8,
limit: u8,
},
}

#[async_trait::async_trait]
Expand Down Expand Up @@ -407,10 +586,98 @@ impl TransformConfig for Config {
}
}

// `exact_fingerprint` keeps only hashes, with nowhere to record a last-seen
// time, so a TTL would silently never fire. Reject rather than mislead.
if ttl_duration(self.global.ttl_secs).is_some()
&& matches!(self.global.mode, Mode::ExactFingerprint)
{
errors.push(
BuildError::TtlUnsupportedInFingerprintMode {
scope: "the global configuration".to_string(),
}
.to_string(),
);
}

if ttl_duration(self.global.ttl_secs).is_some() && self.global.ttl_generations == 0 {
errors.push(
BuildError::ZeroTtlGenerations {
scope: "the global configuration".to_string(),
}
.to_string(),
);
}

push_probabilistic_generation_limit(
&mut errors,
"the global configuration",
matches!(self.global.mode, Mode::Probabilistic(_)),
self.global.ttl_secs,
self.global.ttl_generations,
);

for (metric_name, per_metric) in &self.per_metric_limits {
let ttl_enabled = per_metric.config.ttl_active();
if ttl_enabled && matches!(per_metric.config.mode, OverrideMode::ExactFingerprint) {
errors.push(
BuildError::TtlUnsupportedInFingerprintMode {
scope: format!("`per_metric_limits.{metric_name}`"),
}
.to_string(),
);
}
if ttl_enabled && per_metric.config.ttl_generations == 0 {
Comment thread
kaarolch marked this conversation as resolved.
Resolved
errors.push(
BuildError::ZeroTtlGenerations {
scope: format!("`per_metric_limits.{metric_name}`"),
}
.to_string(),
);
}
push_probabilistic_generation_limit(
&mut errors,
&format!("`per_metric_limits.{metric_name}`"),
matches!(per_metric.config.mode, OverrideMode::Probabilistic(_)),
per_metric.config.ttl_secs,
per_metric.config.ttl_generations,
);
}

if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
}

/// Reject probabilistic configs whose built shard count would make every cache
/// miss hash the tag value once per shard. Uses [`compute_ttl_slices`], the
/// same count the backend builds, so a request that a short TTL clamps under
/// the limit is allowed. `mode: excluded` never reaches here with
/// `probabilistic == true`.
fn push_probabilistic_generation_limit(
errors: &mut Vec<String>,
scope: &str,
probabilistic: bool,
ttl_secs: Option<u64>,
ttl_generations: u8,
) {
if !probabilistic {
return;
}
let Some(ttl) = ttl_duration(ttl_secs) else {
return;
};
let (effective, _) = compute_ttl_slices(ttl, ttl_generations);
if effective > MAX_TTL_GENERATIONS {
errors.push(
BuildError::TtlGenerationsTooHigh {
scope: scope.to_string(),
effective,
limit: MAX_TTL_GENERATIONS,
}
.to_string(),
);
}
}
Loading
Loading