Skip to content
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
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
195 changes: 195 additions & 0 deletions crates/analyzer/src/timeline/binned/distribution.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Binned timelines of weighted distributions over (state, dimension) pairs.
//!
//! A distribution timeline describes, per opaque series (e.g. an operator in a
//! query engine), how some weighted quantity (a "measure", e.g. an entity
//! count) is distributed over the states of a finite state machine and an
//! application-defined dimension (e.g. which resource holds the entity's
//! data), for each time bin of a window.
//!
//! This module is application-agnostic: series, measures, states, and
//! dimension keys are all opaque to the aggregation. Downstream analyzers
//! decide what they mean and are expected to keep dimension keys a small
//! enumerable set.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: I was thrown off a bit about what this does because "distribution" might imply a probability distribution, but the values within each bin are absolute bin time weighted measures and not normalized to sum to 1. Perhaps we could name this "categorical" or something?


use std::hash::Hash;

use rustc_hash::FxHashMap as HashMap;

use quent_time::{SpanNanoSec, bin::BinnedSpan};

use crate::{
AnalyzerResult,
timeline::binned::{BinnedTimelineAggregator, KeyedAggregator},
};

/// Identity of one aggregation cell of a distribution timeline.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct DistributionKey<'a, S> {
/// Opaque series the sample belongs to (e.g. an operator id downstream).
pub series: S,
/// The measure this weight contributes to (e.g. an entity count).
pub measure: &'a str,
/// The FSM state name during the span.
pub state: &'a str,
/// Application-defined dimension key (opaque to the aggregation).
pub dimension: &'a str,
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would be nice to make this more generic:

Suggested change
/// Identity of one aggregation cell of a distribution timeline.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct DistributionKey<'a, S> {
/// Opaque series the sample belongs to (e.g. an operator id downstream).
pub series: S,
/// The measure this weight contributes to (e.g. an entity count).
pub measure: &'a str,
/// The FSM state name during the span.
pub state: &'a str,
/// Application-defined dimension key (opaque to the aggregation).
pub dimension: &'a str,
}
/// Identity of one aggregation cell of a distribution timeline.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct DistributionKey<S, M, St, D> {
/// Opaque series the sample belongs to (e.g. an operator id downstream).
pub series: S,
/// The measure this weight contributes to (e.g. an entity count).
pub measure: M,
/// The FSM state name during the span.
pub state: St,
/// Application-defined dimension key (opaque to the aggregation).
pub dimension: D,
}

?

This way the DistributionTimelineBuilder would only require Eq + Hash bounds and we wouldn't always need stringification.


/// A binned timeline of weighted (state, dimension) distributions for
/// multiple series and measures.
#[derive(Clone, Debug)]
pub struct DistributionTimeline<'a, S> {
pub config: BinnedSpan,
pub data: HashMap<DistributionKey<'a, S>, Vec<f64>>,
}

/// Builds a [`DistributionTimeline`] from weighted samples.
///
/// Aggregation is span-weighted: each sample contributes
/// `weight * overlap_fraction` to every bin its span intersects, so bin values
/// are time-weighted averages over the bin, not instantaneous snapshots.
pub struct DistributionTimelineBuilder<'a, S> {
aggregator: KeyedAggregator<DistributionKey<'a, S>>,
}

impl<'a, S> DistributionTimelineBuilder<'a, S>
where
S: Eq + Hash + Clone,
{
pub fn new(config: BinnedSpan) -> Self {
Self {
aggregator: KeyedAggregator::new(config),
}
}

/// Return the configuration of the binned timeline.
pub fn config(&self) -> BinnedSpan {
self.aggregator.config()
}

/// Attempt to push one weighted sample spanning `span` into the timeline.
pub fn try_push(
&mut self,
key: DistributionKey<'a, S>,
span: SpanNanoSec,
weight: f64,
) -> AnalyzerResult<()> {
self.aggregator.try_push(span, (key, weight))
}

pub fn build(self) -> DistributionTimeline<'a, S> {
DistributionTimeline {
config: self.aggregator.config(),
data: self.aggregator.finish(),
}
}
}

#[cfg(test)]
mod tests {
use std::num::NonZero;

use super::*;

fn test_config() -> BinnedSpan {
BinnedSpan::try_new(
SpanNanoSec::try_new(0, 1000).unwrap(),
NonZero::try_from(10).unwrap(),
)
.unwrap()
}

fn key<'a>(
series: u32,
measure: &'a str,
state: &'a str,
dimension: &'a str,
) -> DistributionKey<'a, u32> {
DistributionKey {
series,
measure,
state,
dimension,
}
}

#[test]
fn span_weighting_across_bin_boundaries() -> AnalyzerResult<()> {
let mut builder = DistributionTimelineBuilder::new(test_config());

// Spans [0, 300) and [250, 450) of weight 1 each.
builder.try_push(
key(1, "count", "a", "x"),
SpanNanoSec::try_new(0, 300).unwrap(),
1.0,
)?;
builder.try_push(
key(1, "count", "a", "x"),
SpanNanoSec::try_new(250, 450).unwrap(),
1.0,
)?;

let timeline = builder.build();
let bins = timeline.data.get(&key(1, "count", "a", "x")).unwrap();
assert_eq!(bins[..], [1.0, 1.0, 1.5, 1.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.0]);
Ok(())
}

#[test]
fn distinct_series_measures_states_dimensions() -> AnalyzerResult<()> {
let mut builder = DistributionTimelineBuilder::new(test_config());
let span = SpanNanoSec::try_new(0, 1000).unwrap();

builder.try_push(key(1, "count", "a", "x"), span, 1.0)?;
builder.try_push(key(2, "count", "a", "x"), span, 1.0)?;
builder.try_push(key(1, "bytes", "a", "x"), span, 100.0)?;
builder.try_push(key(1, "count", "b", "x"), span, 1.0)?;
builder.try_push(key(1, "count", "a", "y"), span, 1.0)?;

let timeline = builder.build();
assert_eq!(timeline.data.len(), 5);
assert_eq!(
timeline.data.get(&key(1, "bytes", "a", "x")).unwrap()[..],
[100.0; 10]
);
assert_eq!(
timeline.data.get(&key(2, "count", "a", "x")).unwrap()[..],
[1.0; 10]
);
Ok(())
}

#[test]
fn zero_duration_span_is_noop() -> AnalyzerResult<()> {
let mut builder = DistributionTimelineBuilder::new(test_config());
builder.try_push(
key(1, "count", "a", "x"),
SpanNanoSec::try_new(500, 500).unwrap(),
1.0,
)?;

let timeline = builder.build();
// The key exists (aggregator was created) but all bins remain zero.
let bins = timeline.data.get(&key(1, "count", "a", "x")).unwrap();
assert_eq!(bins[..], [0.0; 10]);
Ok(())
}

#[test]
fn out_of_window_span_contributes_nothing() -> AnalyzerResult<()> {
let mut builder = DistributionTimelineBuilder::new(test_config());
builder.try_push(
key(1, "count", "a", "x"),
SpanNanoSec::try_new(2000, 3000).unwrap(),
1.0,
)?;

let timeline = builder.build();
let bins = timeline.data.get(&key(1, "count", "a", "x")).unwrap();
assert_eq!(bins[..], [0.0; 10]);
Ok(())
}
}
1 change: 1 addition & 0 deletions crates/analyzer/src/timeline/binned/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use quent_time::{SpanNanoSec, bin::BinnedSpan};

use crate::AnalyzerResult;

pub mod distribution;
pub mod resource;

/// A trait for types that can aggregate items into a sequence of time bins.
Expand Down
80 changes: 80 additions & 0 deletions crates/ui/src/timeline/distribution.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Requests and responses for distribution timelines: binned timelines of a
//! weighted distribution over (FSM state, application-defined dimension)
//! pairs, for one or more application-declared measures.
//!
//! All semantics are declared by the downstream analyzer: which FSM the states
//! belong to, what the dimension keys mean, and which measures exist. The UI
//! renders the declared names verbatim.

use std::collections::HashMap;

use serde::{Deserialize, Serialize};
use ts_rs::TS;

use crate::{quantity::CapacityKind, timeline::request::TimelineConfig};

/// Request for a distribution timeline.
#[derive(TS, Debug, Clone, Serialize, Deserialize)]
pub struct DistributionTimelineRequest<GlobalParams> {
/// Names of the measures to compute. Empty means all declared measures.
pub measures: Vec<String>,
/// The configuration of the window and number of bins.
pub config: TimelineConfig,
/// Global application-specific parameters, e.g. filters.
pub app_params: GlobalParams,
}

/// A measure declared by the downstream analyzer for a distribution timeline,
/// e.g. an entity count or a number of bytes.
#[derive(TS, Debug, Clone, Serialize)]
pub struct MeasureDecl {
/// Unique name; key into [`DistributionSeries::values`].
pub name: String,
/// Human-friendly display name.
pub display_name: String,
/// Key into the application's quantity specs map for unit formatting.
pub quantity: String,
/// Display semantics of a bin value (Occupancy = time-weighted level).
pub kind: CapacityKind,
}

/// One key of the application-defined dimension of a distribution timeline.
#[derive(TS, Debug, Clone, Serialize)]
pub struct DimensionKeyDecl {
/// The key used in [`DistributionSeries::values`].
pub key: String,
/// Human-friendly display name.
pub display_name: String,
}

/// Presentation metadata for a distribution timeline, declared by the
/// downstream analyzer.
///
/// Dimension keys are expected to be a small enumerable set; unbounded key
/// cardinality is a downstream misuse.
#[derive(TS, Debug, Clone, Serialize)]
pub struct DistributionDecl {
/// The FSM type whose states are distributed. References an entry in the
/// application's FSM type declarations (e.g. `QueryBundle` fsm_types) for
/// the state graph, names, and ordering.
pub entity_type_name: String,
/// Display name of the dimension, e.g. an application may use a dimension
/// describing where an entity's data resides.
pub dimension_name: String,
/// The dimension keys in stable stacking/legend order.
pub dimension_keys: Vec<DimensionKeyDecl>,
/// The measures present in this response.
pub measures: Vec<MeasureDecl>,
}

/// Binned values of one distribution timeline series:
/// measure name -> state name -> dimension key -> one value per time bin.
///
/// Absent inner entries mean all-zero bins.
#[derive(TS, Debug, Clone, Default, Serialize)]
pub struct DistributionSeries {
pub values: HashMap<String, HashMap<String, HashMap<String, Vec<f64>>>>,
}
1 change: 1 addition & 0 deletions crates/ui/src/timeline/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@
// SPDX-License-Identifier: Apache-2.0

//! Requests and responses for timelines.
pub mod distribution;
pub mod request;
pub mod response;
25 changes: 25 additions & 0 deletions docs/domains/query_engine/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,31 @@ act as [Resource Groups][resource-group], forming a hierarchy through which
resource usages can be aggregated. See [Resource Group][resource-group] for
details.

## Data-flow distribution timeline

The analyzer trait offers an optional `data_flow_timeline` method (HTTP:
`POST /api/engines/{engine_id}/timeline/data-flow`) powering the UI's
data-flow-over-time view of a query plan: for every [Operator][operator] of a
query, a binned timeline of a distribution over
(FSM state × application-defined dimension), for one or more
application-declared measures.

Consistent with Operators having no FSM (see [Operator][operator] notes), all
semantics live in the application's analyzer:

- **Entity**: which FSM type is distributed (e.g. a task or batch entity that
works on behalf of an Operator), referenced by `entity_type_name` into the
query bundle's FSM type declarations for state names and ordering.
- **Dimension**: an opaque, small, enumerable key set declared per response
(e.g. where an entity's data resides), with display names and stable order.
- **Measures**: named weights (e.g. an entity count, resident bytes) with a
quantity spec reference for unit formatting.

Bin values are span-weighted (an entity in a state for a fraction of a bin
contributes that fraction), matching all other timelines. Analyzers that do
not provide the feature return `Unsupported` — the default implementation —
and the UI hides the view.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The intention of this doc is to specify and explain the query engine domain event model, but not to explain the UI or any implementation details (those are not in the current docs/ at all). Let's find a better place for this or remove and create an issue so we can address it when we have some introductory sections / scaffolding in place.

[mutual-exclusion]: ../../modeling/README.md#mutual-exclusion
[engine]: #engine
[entity]: ../../modeling/entity.md
Expand Down
15 changes: 15 additions & 0 deletions domains/query_engine/analyzer/src/ui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use quent_query_engine_ui as ui;
use quent_ui::{
entities::{request::EntityListRequest, response::EntityListResponse},
timeline::{
distribution::DistributionTimelineRequest,
request::{BulkChunkedTimelineRequest, BulkTimelineRequest, SingleTimelineRequest},
response::{
BulkChunkedTimelinesResponse, BulkTimelinesResponse, BulkTimelinesResponseEntry,
Expand Down Expand Up @@ -116,6 +117,20 @@ pub trait UiAnalyzer {

Ok(BulkChunkedTimelinesResponse { entries })
}

/// Return, for every operator of a query, a binned timeline of a
/// distribution over (entity state, analyzer-defined dimension), for one
/// or more analyzer-declared measures. Powers the UI's data-flow-over-time
/// view of the query plan.
///
/// The default implementation reports the feature as unsupported, so
/// existing analyzers keep compiling and the UI hides the view.
fn data_flow_timeline(
&self,
_request: DistributionTimelineRequest<ui::QueryFilter>,
) -> AnalyzerResult<ui::DataFlowTimelineResponse> {
Ok(ui::DataFlowTimelineResponse::Unsupported)
}
}

/// Boxed owned stream of an analyzer's [`UiAnalyzer::Event`] from
Expand Down
Loading
Loading