@mastra/core
Version:
209 lines • 13.3 kB
TypeScript
import { TRACE_AGGREGATE_COUNT_DISTINCT_PREFIX } from './trace-aggregate.js';
import type { NormalizedTraceAggregateRequest, TraceAggregateInterval } from './trace-aggregate.js';
import type { TraceAggregateCanonicalMeasure, TraceAggregateCountDistinctField, TraceAggregateDimension } from './trace-aggregate-registry.js';
import type { TraceQueryComparisonOperator, TraceQueryIssue, TraceQueryMembershipOperator, TraceQueryPlanOptions, TraceQueryScalarPredicate, TraceQueryTenantScope, TrustedTraceQueryPredicate } from './trace-query.js';
/**
* Trusted, backend-independent plan for `aggregateTraces()`.
*
* `planTraceAggregate` enforces everything the request schema leaves to the planner: the
* groupable-dimension allowlist, `countDistinct` targets, `having` / `orderBy` referencing
* requested measures or dimensions, the 365-day window, the 1000-bucket cap, and the 10,000-row
* cap. Only allowlisted identifiers and finite numeric literals reach the plan.
*/
export declare const TRACE_AGGREGATE_MAX_BUCKETS = 1000;
/** Upper bound on `limit × bucket count` when `interval` is present. */
export declare const TRACE_AGGREGATE_MAX_ROWS = 10000;
export declare const TRACE_AGGREGATE_INTERVAL_MS: Record<TraceAggregateInterval, number>;
/** A trusted measure whose `countDistinct` target is one of the scope's fields `F`. */
export type TrustedAggregateMeasure<F extends string> = {
type: 'canonical';
name: TraceAggregateCanonicalMeasure;
} | {
type: 'countDistinct';
name: `${typeof TRACE_AGGREGATE_COUNT_DISTINCT_PREFIX}${F}`;
field: F;
};
export type TrustedTraceAggregateMeasure = TrustedAggregateMeasure<TraceAggregateCountDistinctField>;
/** A measure name that survived allowlisting; narrower than the request-level `TraceAggregateMeasure`. */
export type TrustedTraceAggregateMeasureName = TrustedTraceAggregateMeasure['name'];
/**
* Predicate over a group's whole-window measures. `measure` is a requested measure or `count`
* (always available); when `count` is not in `measures`, backends compute it for
* filtering without projecting it into the response.
*
* Token, cost and time-to-first measures can be null, so `having` uses SQL three-valued logic: a comparison or
* membership test against null is UNKNOWN, `not` of UNKNOWN is UNKNOWN, `and` / `or` follow
* Kleene logic, and a group whose predicate is not TRUE is removed.
*/
export type TrustedTraceAggregateHavingPredicate<M extends string = TrustedTraceAggregateMeasureName> = {
type: 'comparison';
measure: M;
operator: TraceQueryComparisonOperator;
value: number;
} | {
type: 'membership';
measure: M;
operator: TraceQueryMembershipOperator;
values: number[];
} | {
type: 'boolean';
operator: 'and' | 'or';
args: TrustedTraceAggregateHavingPredicate<M>[];
} | {
type: 'not';
arg: TrustedTraceAggregateHavingPredicate<M>;
};
export type TrustedTraceAggregateOrderBy<M extends string = TrustedTraceAggregateMeasureName, D extends string = TraceAggregateDimension> = {
target: 'measure';
/**
* A requested measure, or `count` (always available). When `count` is not in
* `measures`, backends compute it for ordering without projecting it into the response.
*/
measure: M;
direction: 'asc' | 'desc';
} | {
target: 'dimension';
dimension: D;
direction: 'asc' | 'desc';
};
/**
* Group semantics every evaluator and store compiler must implement:
*
* - A **group** is one distinct tuple of `dimensions` values (null values form their own group).
* `having`, `orderBy`, and `limit` operate on groups, never on individual bucket rows.
* - `having` and `orderBy` are evaluated on each group's measures computed over the **whole**
* `timeRange`, even when `interval` is present. `having` applies after grouping and before
* ordering and `limit`. `orderBy` ties break on dimension values ascending. `bucket` is never
* an ordering target.
* - Null dimension values sort last in both directions; compilers emit an explicit `NULLS LAST`
* where the backend default differs.
* - An empty population returns `rows: []` with no synthesised zero row, including ungrouped
* requests and a `having` that removes every group.
* - `limit` counts groups. `truncated` is `true` when more groups survived `having` than `limit`.
* - When `interval` is present, each surviving group expands to one row per non-empty UTC-aligned
* bucket (`floor(startedAt / interval)`), emitted in `bucket` ascending order within the group;
* empty buckets are omitted, and buckets are never dropped from the middle of a series.
* - The planner alone enforces the bucket cap and the row cap (`limit × buckets ≤ 10,000`);
* backends trust the plan and do not re-check them.
* - Null measure values (see below) sort last in both directions; a `having` predicate over a
* null measure is UNKNOWN and removes the group (see `TrustedTraceAggregateHavingPredicate`).
*
* Time to first token/chunk semantics:
*
* - `timeToFirstToken.*` and `timeToFirstChunk.*` read the nullable `timeToFirstTokenMs` /
* `timeToFirstChunkMs` of the root span (`aggregateTraces`) or of each span (`aggregateSpans`).
* Rows without a value are skipped, never read as 0. `avg`, `min`, `max` and the percentiles are
* null when no row in the group has a value; `.count` is the number of rows that have one (0 when
* none does).
*
* Token and cost semantics:
*
* - **Usage stage.** Usage is aggregated per candidate trace before grouping, so fan-out from
* several metric rows per model call never reaches the group stage. A metric row belongs to
* candidate trace T when its `traceId` is T, its `name` is in
* `TRACE_AGGREGATE_USAGE_METRIC_NAMES`, its `timestamp >= timeRange.from` (no upper bound; a
* trace that starts in the window may finish after it), and it matches `scope` when present.
* The `from` bound is for pruning: rows recorded before `from` never count, even for a trace
* whose current root is in the window (for example, spend before a suspend that happened
* before `from`). Within that bound there is no current-span or current-attempt filter: every
* row for the trace counts, including spend before a suspend/resume and rows whose `spanId` has
* no span row. Rows sharing a `metricId` are exporter retries of one emission and carry
* identical values, so they collapse to one row and which copy survives does not matter;
* ClickHouse dedupes inside this stage without relying on merges. Grouping, `where`, and
* `interval` still use the current root.
* - **Tokens.** A trace is usage-bearing when at least one metric row belongs to it. Its
* `tokens.<x>` value is the sum of `value` over the rows named by the measure's
* `metricNames` (0 when there are none); a trace that is not usage-bearing has no token value.
* `tokens.<x>.sum` sums over the group's usage-bearing traces, `tokens.<x>.avg` divides by
* their count, and both are null when the group has none.
* - **Cost.** Only `TRACE_AGGREGATE_COST_METRIC_NAMES` rows carry cost. Such a row is priced when
* it has an `estimatedCost`, a `costUnit`, and either no `costMetadata.error` or
* `costMetadata.error = 'partial_cost'` (the SDK priced some token types of the call and the cost
* covers those). It failed to price when `costMetadata.error` is set (including `partial_cost`)
* or it has a cost without a unit, so a `partial_cost` row is both priced and failed. A row with
* neither a cost nor an error is neither: when the provider reports cost, only one of the call's
* total rows carries it. A trace's cost is the sum of its priced rows' `estimatedCost`; rows
* that are not priced contribute nothing to cost or cost unit. `cost.sum` sums over traces with
* at least one priced row, `cost.avg` divides by their count.
* - **Row cost.** Whenever any `cost.*` measure is requested, every row also carries
* `cost.coverage` and `cost.unit`. A trace is covered when it has at least one priced row and
* no row that failed to price; `cost.coverage` is covered traces ÷ usage-bearing traces, null
* when the group has no usage-bearing traces. A trace with a `partial_cost` row adds that cost to
* `cost.sum` but is not covered. `cost.unit` is the priced rows' single `costUnit`, `'mixed'`
* when they use more than one, and null exactly when there are no priced rows. `cost.sum` and
* `cost.avg` are null when the group has no priced rows or `cost.unit` is `'mixed'`. Row cost
* fields are not measures: they cannot be requested, filtered on, or ordered by.
* - Measures are computed independently for the whole-window group (for `having` / `orderBy`) and
* for each bucket row.
*/
export interface TrustedTraceAggregatePlan {
result: 'aggregate';
timeRange: {
from: string;
to: string;
};
where?: TrustedTraceQueryPredicate;
scope?: TraceQueryTenantScope;
/** Normalized dimensions in request order (at most two). */
dimensions: TraceAggregateDimension[];
interval?: TraceAggregateInterval;
/** Requested measures in request order; `countDistinct` names are normalized. */
measures: TrustedTraceAggregateMeasure[];
having?: TrustedTraceAggregateHavingPredicate;
orderBy: TrustedTraceAggregateOrderBy;
/** Maximum number of groups (not rows) in the response. */
limit: number;
}
/**
* Number of UTC-aligned buckets a `[from, to)` range touches. A range that does not
* start on a bucket boundary touches one more bucket than `(to - from) / interval`.
*/
export declare function countTraceAggregateBuckets(fromMs: number, toMs: number, interval: TraceAggregateInterval): number;
/**
* Converts a structurally valid aggregate request into the canonical plan consumed by
* observability storage adapters.
*
* @internal This is a trusted server/storage boundary, not a client-side query builder.
*/
export declare function planTraceAggregate(request: NormalizedTraceAggregateRequest, options?: Pick<TraceQueryPlanOptions, 'scope' | 'allowTokenSearch'>): TrustedTraceAggregatePlan;
/** @internal The parts of an aggregate request that trace and span scopes share. */
export interface AggregateGroupsRequest {
timeRange: {
from: string;
to: string;
};
groupBy: string[];
interval?: TraceAggregateInterval;
measures: string[];
having?: TraceQueryScalarPredicate;
orderBy: {
field: string;
direction: 'asc' | 'desc';
};
limit: number;
}
/** @internal How a scope allowlists dimensions and `countDistinct` targets. */
export interface AggregateScopePolicy<D extends string, F extends string> {
isDimension(path: string): path is D;
parseMeasure(name: string): {
type: 'canonical';
measure: TraceAggregateCanonicalMeasure;
} | {
type: 'countDistinct';
field: F;
} | undefined;
}
/** @internal Window, bucket and row caps, dimensions, measures, `having` and `orderBy` for any scope. */
export declare function planAggregateGroups<D extends string, F extends string>(request: AggregateGroupsRequest, issues: TraceQueryIssue[], policy: AggregateScopePolicy<D, F>): {
timeRange: {
from: string;
to: string;
};
dimensions: D[];
interval: "15m" | "1d" | "1h" | "1m" | "5m" | undefined;
measures: TrustedAggregateMeasure<F>[];
having: TrustedTraceAggregateHavingPredicate<"cost.avg" | "cost.sum" | "count" | "duration.avg" | "duration.max" | "duration.min" | "duration.p50" | "duration.p90" | "duration.p95" | "duration.p99" | "errorCount" | "errorRate" | "timeToFirstChunk.avg" | "timeToFirstChunk.count" | "timeToFirstChunk.max" | "timeToFirstChunk.min" | "timeToFirstChunk.p50" | "timeToFirstChunk.p90" | "timeToFirstChunk.p95" | "timeToFirstChunk.p99" | "timeToFirstToken.avg" | "timeToFirstToken.count" | "timeToFirstToken.max" | "timeToFirstToken.min" | "timeToFirstToken.p50" | "timeToFirstToken.p90" | "timeToFirstToken.p95" | "timeToFirstToken.p99" | "tokens.cached.avg" | "tokens.cached.sum" | "tokens.input.avg" | "tokens.input.sum" | "tokens.output.avg" | "tokens.output.sum" | "tokens.reasoning.avg" | "tokens.reasoning.sum" | "tokens.total.avg" | "tokens.total.sum" | `countDistinct.${F}`> | undefined;
orderBy: TrustedTraceAggregateOrderBy<"cost.avg" | "cost.sum" | "count" | "duration.avg" | "duration.max" | "duration.min" | "duration.p50" | "duration.p90" | "duration.p95" | "duration.p99" | "errorCount" | "errorRate" | "timeToFirstChunk.avg" | "timeToFirstChunk.count" | "timeToFirstChunk.max" | "timeToFirstChunk.min" | "timeToFirstChunk.p50" | "timeToFirstChunk.p90" | "timeToFirstChunk.p95" | "timeToFirstChunk.p99" | "timeToFirstToken.avg" | "timeToFirstToken.count" | "timeToFirstToken.max" | "timeToFirstToken.min" | "timeToFirstToken.p50" | "timeToFirstToken.p90" | "timeToFirstToken.p95" | "timeToFirstToken.p99" | "tokens.cached.avg" | "tokens.cached.sum" | "tokens.input.avg" | "tokens.input.sum" | "tokens.output.avg" | "tokens.output.sum" | "tokens.reasoning.avg" | "tokens.reasoning.sum" | "tokens.total.avg" | "tokens.total.sum" | `countDistinct.${F}`, D>;
limit: number;
};
//# sourceMappingURL=trace-aggregate-planner.d.ts.map