diff --git a/web/ui/mantine-ui/src/pages/query/ExplainViews/Aggregation.tsx b/web/ui/mantine-ui/src/pages/query/ExplainViews/Aggregation.tsx new file mode 100644 index 0000000000..3db2d4c0f5 --- /dev/null +++ b/web/ui/mantine-ui/src/pages/query/ExplainViews/Aggregation.tsx @@ -0,0 +1,109 @@ +import { FC } from "react"; +import ASTNode, { Aggregation, aggregationType } from "../../../promql/ast"; +import { labelNameList } from "../../../promql/format"; +import { parsePrometheusFloat } from "../../../lib/formatFloatValue"; +import { Card, Text } from "@mantine/core"; + +const describeAggregationType = ( + aggrType: aggregationType, + param: ASTNode | null +) => { + switch (aggrType) { + case "sum": + return "sums over the sample values of the input series"; + case "min": + return "takes the minimum of the sample values of the input series"; + case "max": + return "takes the maximum of the sample values of the input series"; + case "avg": + return "calculates the average of the sample values of the input series"; + case "stddev": + return "calculates the population standard deviation of the sample values of the input series"; + case "stdvar": + return "calculates the population standard variation of the sample values of the input series"; + case "count": + return "counts the number of input series"; + case "group": + return "groups the input series by the supplied grouping labels, while setting the sample value to 1"; + case "count_values": + if (param === null) { + throw new Error( + "encountered count_values() node without label parameter" + ); + } + if (param.type !== "stringLiteral") { + throw new Error( + "encountered count_values() node without string literal label parameter" + ); + } + return ( + <> + outputs one time series for each unique sample value in the input + series (each counting the number of occurrences of that value and + indicating the original value in the {labelNameList([param.val])}{" "} + label) + + ); + case "bottomk": + return "returns the bottom K series by value"; + case "topk": + return "returns the top K series by value"; + case "quantile": + if (param === null) { + throw new Error( + "encountered quantile() node without quantile parameter" + ); + } + if (param.type === "numberLiteral") { + return `calculates the ${param.val}th quantile (${ + parsePrometheusFloat(param.val) * 100 + }th percentile) over the sample values of the input series`; + } + return "calculates a quantile over the sample values of the input series"; + + case "limitk": + return "limits the output to K series"; + case "limit_ratio": + return "limits the output to a ratio of the input series"; + default: + throw new Error(`invalid aggregation type ${aggrType}`); + } +}; + +const describeAggregationGrouping = (grouping: string[], without: boolean) => { + if (without) { + return ( + <>aggregating away the [{labelNameList(grouping)}] label dimensions + ); + } + + if (grouping.length === 1) { + return <>grouped by their {labelNameList(grouping)} label dimension; + } + + if (grouping.length > 1) { + return <>grouped by their [{labelNameList(grouping)}] label dimensions; + } + + return "aggregating away any label dimensions"; +}; + +interface AggregationExplainViewProps { + node: Aggregation; +} + +const AggregationExplainView: FC = ({ node }) => { + return ( + + + Aggregation + + + This node {describeAggregationType(node.op, node.param)},{" "} + {describeAggregationGrouping(node.grouping, node.without)}. + + + ); +}; + +export default AggregationExplainView; diff --git a/web/ui/mantine-ui/src/pages/query/ExplainViews/BinaryExpr/BinaryExpr.tsx b/web/ui/mantine-ui/src/pages/query/ExplainViews/BinaryExpr/BinaryExpr.tsx new file mode 100644 index 0000000000..837b84da31 --- /dev/null +++ b/web/ui/mantine-ui/src/pages/query/ExplainViews/BinaryExpr/BinaryExpr.tsx @@ -0,0 +1,106 @@ +import { FC } from "react"; +import { BinaryExpr } from "../../../../promql/ast"; +import serializeNode from "../../../../promql/serialize"; +import VectorScalarBinaryExprExplainView from "./VectorScalar"; +import VectorVectorBinaryExprExplainView from "./VectorVector"; +import ScalarScalarBinaryExprExplainView from "./ScalarScalar"; +import { nodeValueType } from "../../../../promql/utils"; +import { useSuspenseAPIQuery } from "../../../../api/api"; +import { InstantQueryResult } from "../../../../api/responseTypes/query"; +import { Card, Text } from "@mantine/core"; + +interface BinaryExprExplainViewProps { + node: BinaryExpr; +} + +const BinaryExprExplainView: FC = ({ node }) => { + const { data: lhs } = useSuspenseAPIQuery({ + path: `/query`, + params: { + query: serializeNode(node.lhs), + }, + }); + const { data: rhs } = useSuspenseAPIQuery({ + path: `/query`, + params: { + query: serializeNode(node.rhs), + }, + }); + + if ( + lhs.data.resultType !== nodeValueType(node.lhs) || + rhs.data.resultType !== nodeValueType(node.rhs) + ) { + // This can happen for a brief transitionary render when "node" has changed, but "lhs" and "rhs" + // haven't switched back to loading yet (leading to a crash in e.g. the vector-vector explain view). + return null; + } + + // Scalar-scalar binops. + if (lhs.data.resultType === "scalar" && rhs.data.resultType === "scalar") { + return ( + + + Scalar-to-scalar binary operation + + + + ); + } + + // Vector-scalar binops. + if (lhs.data.resultType === "scalar" && rhs.data.resultType === "vector") { + return ( + + + Scalar-to-vector binary operation + + + + ); + } + if (lhs.data.resultType === "vector" && rhs.data.resultType === "scalar") { + return ( + + + Vector-to-scalar binary operation + + + + ); + } + + // Vector-vector binops. + if (lhs.data.resultType === "vector" && rhs.data.resultType === "vector") { + return ( + + + Vector-to-vector binary operation + + + + ); + } + + throw new Error("invalid binary operator argument types"); +}; + +export default BinaryExprExplainView; diff --git a/web/ui/mantine-ui/src/pages/query/ExplainViews/BinaryExpr/ScalarScalar.tsx b/web/ui/mantine-ui/src/pages/query/ExplainViews/BinaryExpr/ScalarScalar.tsx new file mode 100644 index 0000000000..874d824486 --- /dev/null +++ b/web/ui/mantine-ui/src/pages/query/ExplainViews/BinaryExpr/ScalarScalar.tsx @@ -0,0 +1,54 @@ +import { FC } from "react"; +import { BinaryExpr } from "../../../../promql/ast"; +import { scalarBinOp } from "../../../../promql/binOp"; +import { Table } from "@mantine/core"; +import { SampleValue } from "../../../../api/responseTypes/query"; +import { + formatPrometheusFloat, + parsePrometheusFloat, +} from "../../../../lib/formatFloatValue"; + +interface ScalarScalarBinaryExprExplainViewProps { + node: BinaryExpr; + lhs: SampleValue; + rhs: SampleValue; +} + +const ScalarScalarBinaryExprExplainView: FC< + ScalarScalarBinaryExprExplainViewProps +> = ({ node, lhs, rhs }) => { + const [lhsVal, rhsVal] = [ + parsePrometheusFloat(lhs[1]), + parsePrometheusFloat(rhs[1]), + ]; + + return ( + + + + Left value + Operator + Right value + + Result + + + + + {lhs[1]} + + {node.op} + {node.bool && " bool"} + + {rhs[1]} + = + + {formatPrometheusFloat(scalarBinOp(node.op, lhsVal, rhsVal))} + + + +
+ ); +}; + +export default ScalarScalarBinaryExprExplainView; diff --git a/web/ui/mantine-ui/src/pages/query/ExplainViews/BinaryExpr/VectorScalar.tsx b/web/ui/mantine-ui/src/pages/query/ExplainViews/BinaryExpr/VectorScalar.tsx new file mode 100644 index 0000000000..3a0652f818 --- /dev/null +++ b/web/ui/mantine-ui/src/pages/query/ExplainViews/BinaryExpr/VectorScalar.tsx @@ -0,0 +1,104 @@ +import { FC } from "react"; +import { BinaryExpr } from "../../../../promql/ast"; +// import SeriesName from '../../../../utils/SeriesName'; +import { isComparisonOperator } from "../../../../promql/utils"; +import { vectorElemBinop } from "../../../../promql/binOp"; +import { + InstantSample, + SampleValue, +} from "../../../../api/responseTypes/query"; +import { Alert, Table, Text } from "@mantine/core"; +import { + formatPrometheusFloat, + parsePrometheusFloat, +} from "../../../../lib/formatFloatValue"; +import SeriesName from "../../SeriesName"; + +interface VectorScalarBinaryExprExplainViewProps { + node: BinaryExpr; + scalar: SampleValue; + vector: InstantSample[]; + scalarLeft: boolean; +} + +const VectorScalarBinaryExprExplainView: FC< + VectorScalarBinaryExprExplainViewProps +> = ({ node, scalar, vector, scalarLeft }) => { + if (vector.length === 0) { + return ( + + One side of the binary operation produces 0 results, no matching + information shown. + + ); + } + + return ( + + + + {!scalarLeft && Left labels} + Left value + Operator + {scalarLeft && Right labels} + Right value + + Result + + + + {vector.map((sample: InstantSample, idx) => { + if (!sample.value) { + // TODO: Handle native histograms or show a better error message. + throw new Error("Native histograms are not supported yet"); + } + + const vecVal = parsePrometheusFloat(sample.value[1]); + const scalVal = parsePrometheusFloat(scalar[1]); + + let { value, keep } = scalarLeft + ? vectorElemBinop(node.op, scalVal, vecVal) + : vectorElemBinop(node.op, vecVal, scalVal); + if (isComparisonOperator(node.op) && scalarLeft) { + value = vecVal; + } + if (node.bool) { + value = Number(keep); + keep = true; + } + + const scalarCell = {scalar[1]}; + const vectorCells = ( + <> + + + + {sample.value[1]} + + ); + + return ( + + {scalarLeft ? scalarCell : vectorCells} + + {node.op} + {node.bool && " bool"} + + {scalarLeft ? vectorCells : scalarCell} + = + + {keep ? ( + formatPrometheusFloat(value) + ) : ( + dropped + )} + + + ); + })} + +
+ ); +}; + +export default VectorScalarBinaryExprExplainView; diff --git a/web/ui/mantine-ui/src/pages/query/ExplainViews/BinaryExpr/VectorVector.tsx b/web/ui/mantine-ui/src/pages/query/ExplainViews/BinaryExpr/VectorVector.tsx new file mode 100644 index 0000000000..0b0854409e --- /dev/null +++ b/web/ui/mantine-ui/src/pages/query/ExplainViews/BinaryExpr/VectorVector.tsx @@ -0,0 +1,686 @@ +import React, { FC, useState } from "react"; +import { BinaryExpr, vectorMatchCardinality } from "../../../../promql/ast"; +import { InstantSample, Metric } from "../../../../api/responseTypes/query"; +import { isComparisonOperator, isSetOperator } from "../../../../promql/utils"; +import { + VectorMatchError, + BinOpMatchGroup, + MatchErrorType, + computeVectorVectorBinOp, + filteredSampleValue, +} from "../../../../promql/binOp"; +import { formatNode, labelNameList } from "../../../../promql/format"; +import { + Alert, + Anchor, + Box, + Button, + Group, + List, + Switch, + Table, + Text, +} from "@mantine/core"; +import { useLocalStorage } from "@mantine/hooks"; +import { IconAlertTriangle } from "@tabler/icons-react"; +import SeriesName from "../../SeriesName"; + +// We use this color pool for two purposes: +// +// 1. To distinguish different match groups from each other. +// 2. To distinguish multiple series within one match group from each other. +const colorPool = [ + "#1f77b4", + "#ff7f0e", + "#2ca02c", + "#d62728", + "#9467bd", + "#8c564b", + "#e377c2", + "#7f7f7f", + "#bcbd22", + "#17becf", + "#393b79", + "#637939", + "#8c6d31", + "#843c39", + "#d6616b", + "#7b4173", + "#ce6dbd", + "#9c9ede", + "#c5b0d5", + "#c49c94", + "#f7b6d2", + "#c7c7c7", + "#dbdb8d", + "#9edae5", + "#393b79", + "#637939", + "#8c6d31", + "#843c39", + "#d6616b", + "#7b4173", + "#ce6dbd", + "#9c9ede", + "#c5b0d5", + "#c49c94", + "#f7b6d2", + "#c7c7c7", + "#dbdb8d", + "#9edae5", + "#17becf", + "#393b79", + "#637939", + "#8c6d31", + "#843c39", + "#d6616b", + "#7b4173", + "#ce6dbd", + "#9c9ede", + "#c5b0d5", + "#c49c94", + "#f7b6d2", +]; + +const rhsColorOffset = colorPool.length / 2 + 3; +const colorForIndex = (idx: number, offset?: number) => + `${colorPool[(idx + (offset || 0)) % colorPool.length]}80`; + +const seriesSwatch = (color: string) => ( + +); +interface VectorVectorBinaryExprExplainViewProps { + node: BinaryExpr; + lhs: InstantSample[]; + rhs: InstantSample[]; +} + +const noMatchLabels = ( + metric: Metric, + on: boolean, + labels: string[] +): Metric => { + const result: Metric = {}; + for (const name in metric) { + if (!(labels.includes(name) === on && (on || name !== "__name__"))) { + result[name] = metric[name]; + } + } + return result; +}; + +const explanationText = (node: BinaryExpr): React.ReactNode => { + const matching = node.matching!; + const [oneSide, manySide] = + matching.card === vectorMatchCardinality.oneToMany + ? ["left", "right"] + : ["right", "left"]; + + return ( + <> + + {isComparisonOperator(node.op) ? ( + <> + This node filters the series from the left-hand side based on the + result of a " + {node.op}" + comparison with matching series from the right-hand side. + + ) : ( + <> + This node calculates the result of applying the " + {node.op}" + operator between the sample values of matching series from two sets + of time series. + + )} + + + {(matching.labels.length > 0 || matching.on) && + (matching.on ? ( + + on( + {labelNameList(matching.labels)}):{" "} + {matching.labels.length > 0 ? ( + <> + series on both sides are matched on the labels{" "} + {labelNameList(matching.labels)} + + ) : ( + <> + all series from one side are matched to all series on the + other side. + + )} + + ) : ( + + ignoring( + {labelNameList(matching.labels)}): series on both sides are + matched on all of their labels, except{" "} + {labelNameList(matching.labels)}. + + ))} + {matching.card === vectorMatchCardinality.oneToOne ? ( + + One-to-one match. Each series from the left-hand side is allowed to + match with at most one series on the right-hand side, and vice + versa. + + ) : ( + + + group_{manySide}({labelNameList(matching.include)}) + + : {matching.card} match. Each series from the {oneSide}-hand side is + allowed to match with multiple series from the {manySide}-hand side. + {matching.include.length !== 0 && ( + <> + {" "} + Any {labelNameList(matching.include)} labels found on the{" "} + {oneSide}-hand side are propagated into the result, in addition + to the match group's labels. + + )} + + )} + {node.bool && ( + + bool: Instead of + filtering series based on the outcome of the comparison for matched + series, keep all series, but return the comparison outcome as a + boolean 0 or{" "} + 1 sample value. + + )} + + + ); +}; + +const explainError = ( + binOp: BinaryExpr, + _mg: BinOpMatchGroup, + err: VectorMatchError +) => { + const fixes = ( + <> + + Possible fixes: + + + {err.type === MatchErrorType.multipleMatchesForOneToOneMatching && ( + + + + Allow {err.dupeSide === "left" ? "many-to-one" : "one-to-many"}{" "} + matching + + : If you want to allow{" "} + {err.dupeSide === "left" ? "many-to-one" : "one-to-many"}{" "} + matching, you need to explicitly request it by adding a{" "} + + group_{err.dupeSide}() + {" "} + modifier to the operator: + + + {formatNode( + { + ...binOp, + matching: { + ...(binOp.matching + ? binOp.matching + : { labels: [], on: false, include: [] }), + card: + err.dupeSide === "left" + ? vectorMatchCardinality.manyToOne + : vectorMatchCardinality.oneToMany, + }, + }, + true, + 1 + )} + + + )} + + Update your matching parameters: Consider including + more differentiating labels in your matching modifiers (via{" "} + on() /{" "} + ignoring()) to + split multiple series into distinct match groups. + + + Aggregate the input: Consider aggregating away the + extra labels that create multiple series per group before applying the + binary operation. + + + + ); + + switch (err.type) { + case MatchErrorType.multipleMatchesForOneToOneMatching: + return ( + <> + + Binary operators only allow one-to-one matching by + default, but we found{" "} + multiple series on the {err.dupeSide} side for this + match group. + + {fixes} + + ); + case MatchErrorType.multipleMatchesOnBothSides: + return ( + <> + + We found multiple series on both sides for this + match group. Since many-to-many matching is not + supported, you need to ensure that at least one of the sides only + yields a single series. + + {fixes} + + ); + case MatchErrorType.multipleMatchesOnOneSide: { + const [oneSide, manySide] = + binOp.matching!.card === vectorMatchCardinality.oneToMany + ? ["left", "right"] + : ["right", "left"]; + return ( + <> + + You requested{" "} + + {oneSide === "right" ? "many-to-one" : "one-to-many"} matching + {" "} + via{" "} + + group_{manySide}() + + , but we also found{" "} + multiple series on the {oneSide} side of the match + group. Make sure that the {oneSide} side only contains a single + series. + + {fixes} + + ); + } + default: + throw new Error("unknown match error"); + } +}; + +const VectorVectorBinaryExprExplainView: FC< + VectorVectorBinaryExprExplainViewProps +> = ({ node, lhs, rhs }) => { + // TODO: Don't use Mantine's local storage as a one-off here. + // const [allowLineBreaks, setAllowLineBreaks] = useLocalStorage({ + // key: "queryPage.explain.binaryOperators.breakLongLines", + // defaultValue: true, + // }); + + const [showSampleValues, setShowSampleValues] = useLocalStorage({ + key: "queryPage.explain.binaryOperators.showSampleValues", + defaultValue: false, + }); + + const [maxGroups, setMaxGroups] = useState(100); + const [maxSeriesPerGroup, setMaxSeriesPerGroup] = useState< + number | undefined + >(100); + + const { matching } = node; + if (matching === null) { + // The parent should make sure to only pass in vector-vector binops that have their "matching" field filled out. + throw new Error("missing matching parameters in vector-to-vector binop"); + } + + const { groups: matchGroups, numGroups } = computeVectorVectorBinOp( + node.op, + matching, + node.bool, + lhs, + rhs, + { + maxGroups: maxGroups, + maxSeriesPerGroup: maxSeriesPerGroup, + } + ); + const errCount = Object.values(matchGroups).filter((mg) => mg.error).length; + + return ( + <> + {explanationText(node)} + + {!isSetOperator(node.op) && ( + <> + + {/* + setAllowLineBreaks(event.currentTarget.checked) + } + /> */} + + setShowSampleValues(event.currentTarget.checked) + } + /> + + + {numGroups > Object.keys(matchGroups).length && ( + } + > + Too many match groups to display, only showing{" "} + {Object.keys(matchGroups).length} out of {numGroups} groups. + setMaxGroups(undefined)}> + Show all groups + + + )} + + {errCount > 0 && ( + } + > + Found matching issues in {errCount} match group + {errCount > 1 ? "s" : ""}. See below for per-group error details. + + )} + + + + {Object.values(matchGroups).map((mg, mgIdx) => { + const { + groupLabels, + lhs, + lhsCount, + rhs, + rhsCount, + result, + error, + } = mg; + + const noLHSMatches = lhs.length === 0; + const noRHSMatches = rhs.length === 0; + + const groupColor = colorPool[mgIdx % colorPool.length]; + const noMatchesColor = "#e0e0e0"; + const lhsGroupColor = noLHSMatches + ? noMatchesColor + : groupColor; + const rhsGroupColor = noRHSMatches + ? noMatchesColor + : groupColor; + const resultGroupColor = + noLHSMatches || noRHSMatches ? noMatchesColor : groupColor; + + const matchGroupTitleRow = (color: string) => ( + + + + + + ); + + const matchGroupTable = ( + series: InstantSample[], + seriesCount: number, + color: string, + colorOffset?: number + ) => ( + +
+ + {series.length === 0 ? ( + + + no matching series + + + ) : ( + <> + {matchGroupTitleRow(color)} + {series.map((s, sIdx) => { + if (s.value === undefined) { + // TODO: Figure out how to handle native histograms. + throw new Error( + "Native histograms are not supported yet" + ); + } + + return ( + + + + {seriesSwatch( + colorForIndex(sIdx, colorOffset) + )} + + + + + {showSampleValues && ( + {s.value[1]} + )} + + ); + })} + + )} + {seriesCount > series.length && ( + + + {seriesCount - series.length} more series omitted + – + + + + )} + +
+
+ ); + + const lhsTable = matchGroupTable(lhs, lhsCount, lhsGroupColor); + const rhsTable = matchGroupTable( + rhs, + rhsCount, + rhsGroupColor, + rhsColorOffset + ); + + const resultTable = ( + + + + {noLHSMatches || noRHSMatches ? ( + + + dropped + + + ) : error !== null ? ( + + + error, result omitted + + + ) : ( + <> + {result.map(({ sample, manySideIdx }, resIdx) => { + if (sample.value === undefined) { + // TODO: Figure out how to handle native histograms. + throw new Error( + "Native histograms are not supported yet" + ); + } + + const filtered = + sample.value[1] === filteredSampleValue; + const [lIdx, rIdx] = + matching.card === + vectorMatchCardinality.oneToMany + ? [0, manySideIdx] + : [manySideIdx, 0]; + + return ( + + + + + {seriesSwatch(colorForIndex(lIdx))} + + {seriesSwatch( + colorForIndex(rIdx, rhsColorOffset) + )} + + + + + + {showSampleValues && ( + + {filtered ? ( + + filtered + + ) : ( + {sample.value[1]} + )} + + )} + + ); + })} + + )} + +
+
+ ); + + return ( + + {mgIdx !== 0 && } + + + {error && ( + } + > + {explainError(node, mg, error)} + + )} + + + + + {lhsTable} + + + {node.op} + {node.bool && " bool"} + + + {rhsTable} + + = + + {resultTable} + + + + ); + })} + + + + )} + + ); +}; + +export default VectorVectorBinaryExprExplainView; diff --git a/web/ui/mantine-ui/src/pages/query/ExplainViews/ExplainView.module.css b/web/ui/mantine-ui/src/pages/query/ExplainViews/ExplainView.module.css new file mode 100644 index 0000000000..7cb36c7624 --- /dev/null +++ b/web/ui/mantine-ui/src/pages/query/ExplainViews/ExplainView.module.css @@ -0,0 +1,8 @@ +.funcDoc code { + background-color: light-dark( + var(--mantine-color-gray-1), + var(--mantine-color-dark-5) + ); + padding: 0.05em 0.2em; + border-radius: 0.2em; +} diff --git a/web/ui/mantine-ui/src/pages/query/ExplainViews/ExplainView.tsx b/web/ui/mantine-ui/src/pages/query/ExplainViews/ExplainView.tsx new file mode 100644 index 0000000000..907830757d --- /dev/null +++ b/web/ui/mantine-ui/src/pages/query/ExplainViews/ExplainView.tsx @@ -0,0 +1,198 @@ +import { FC } from "react"; +import { Alert, Text, Anchor, Card, Divider } from "@mantine/core"; +import ASTNode, { nodeType } from "../../../promql/ast"; +// import AggregationExplainView from "./Aggregation"; +// import BinaryExprExplainView from "./BinaryExpr/BinaryExpr"; +// import SelectorExplainView from "./Selector"; +import funcDocs from "../../../promql/functionDocs"; +import { escapeString } from "../../../promql/utils"; +import { formatPrometheusDuration } from "../../../lib/formatTime"; +import classes from "./ExplainView.module.css"; +import SelectorExplainView from "./Selector"; +import AggregationExplainView from "./Aggregation"; +import BinaryExprExplainView from "./BinaryExpr/BinaryExpr"; +interface ExplainViewProps { + node: ASTNode | null; + treeShown: boolean; + setShowTree: () => void; +} + +const ExplainView: FC = ({ + node, + treeShown, + setShowTree, +}) => { + if (node === null) { + return ( + + <> + To use the Explain view,{" "} + {!treeShown && ( + <> + + enable the query tree view + {" "} + (also available via the expression input dropdown) and then + + )}{" "} + select a node in the tree above. + + + ); + } + + switch (node.type) { + case nodeType.aggregation: + return ; + case nodeType.binaryExpr: + return ; + case nodeType.call: + return ( + + + Function call + + + This node calls the{" "} + + + {node.func.name}() + + {" "} + function{node.args.length > 0 ? " on the provided inputs" : ""}. + + + {/* TODO: Some docs, like x_over_time, have relative links pointing back to the Prometheus docs, + make sure to modify those links in the docs extraction so they work from the explain view */} + + {funcDocs[node.func.name]} + + + ); + case nodeType.matrixSelector: + return ; + case nodeType.subquery: + return ( + + + Subquery + + + This node evaluates the passed expression as a subquery over the + last{" "} + + {formatPrometheusDuration(node.range)} + {" "} + at a query resolution{" "} + {node.step > 0 ? ( + <> + of{" "} + + {formatPrometheusDuration(node.step)} + + + ) : ( + "equal to the default rule evaluation interval" + )} + {node.timestamp !== null ? ( + <> + , evaluated relative to an absolute evaluation timestamp of{" "} + + {(node.timestamp / 1000).toFixed(3)} + + + ) : node.startOrEnd !== null ? ( + <> + , evaluated relative to the {node.startOrEnd} of the query range + + ) : ( + <> + )} + {node.offset === 0 ? ( + <> + ) : node.offset > 0 ? ( + <> + , time-shifted{" "} + + {formatPrometheusDuration(node.offset)} + {" "} + into the past + + ) : ( + <> + , time-shifted{" "} + + {formatPrometheusDuration(-node.offset)} + {" "} + into the future + + )} + . + + + ); + case nodeType.numberLiteral: + return ( + + + Number literal + + + A scalar number literal with the value{" "} + {node.val}. + + + ); + case nodeType.parenExpr: + return ( + + + Parentheses + + + Parentheses that contain a sub-expression to be evaluated. + + + ); + case nodeType.stringLiteral: + return ( + + + String literal + + + A string literal with the value{" "} + + "{escapeString(node.val)}" + + . + + + ); + case nodeType.unaryExpr: + return ( + + + Unary expression + + + A unary expression that{" "} + {node.op === "+" + ? "does not affect the expression it is applied to" + : "changes the sign of the expression it is applied to"} + . + + + ); + case nodeType.vectorSelector: + return ; + default: + throw new Error("invalid node type"); + } +}; + +export default ExplainView; diff --git a/web/ui/mantine-ui/src/pages/query/ExplainViews/Selector.tsx b/web/ui/mantine-ui/src/pages/query/ExplainViews/Selector.tsx new file mode 100644 index 0000000000..26f62fb335 --- /dev/null +++ b/web/ui/mantine-ui/src/pages/query/ExplainViews/Selector.tsx @@ -0,0 +1,230 @@ +import { FC, ReactNode } from "react"; +import { + VectorSelector, + MatrixSelector, + nodeType, + LabelMatcher, + matchType, +} from "../../../promql/ast"; +import { escapeString } from "../../../promql/utils"; +import { useSuspenseAPIQuery } from "../../../api/api"; +import { Card, Text, Divider, List } from "@mantine/core"; +import { MetadataResult } from "../../../api/responseTypes/metadata"; +import { formatPrometheusDuration } from "../../../lib/formatTime"; + +interface SelectorExplainViewProps { + node: VectorSelector | MatrixSelector; +} + +const matchingCriteriaList = ( + name: string, + matchers: LabelMatcher[] +): ReactNode => { + return ( + + {name.length > 0 && ( + + The metric name is{" "} + {name}. + + )} + {matchers + .filter((m) => !(m.name === "__name__")) + .map((m) => { + switch (m.type) { + case matchType.equal: + return ( + + + {m.name} + + {m.type} + + "{escapeString(m.value)}" + + : The label{" "} + + {m.name} + {" "} + is exactly{" "} + + "{escapeString(m.value)}" + + . + + ); + case matchType.notEqual: + return ( + + + {m.name} + + {m.type} + + "{escapeString(m.value)}" + + : The label{" "} + + {m.name} + {" "} + is not{" "} + + "{escapeString(m.value)}" + + . + + ); + case matchType.matchRegexp: + return ( + + + {m.name} + + {m.type} + + "{escapeString(m.value)}" + + : The label{" "} + + {m.name} + {" "} + matches the regular expression{" "} + + "{escapeString(m.value)}" + + . + + ); + case matchType.matchNotRegexp: + return ( + + + {m.name} + + {m.type} + + "{escapeString(m.value)}" + + : The label{" "} + + {m.name} + {" "} + does not match the regular expression{" "} + + "{escapeString(m.value)}" + + . + + ); + default: + throw new Error("invalid matcher type"); + } + })} + + ); +}; + +const SelectorExplainView: FC = ({ node }) => { + const baseMetricName = node.name.replace(/(_count|_sum|_bucket)$/, ""); + const { data: metricMeta } = useSuspenseAPIQuery({ + path: `/metadata`, + params: { + metric: baseMetricName, + }, + }); + + return ( + + + {node.type === nodeType.vectorSelector ? "Instant" : "Range"} vector + selector + + + {metricMeta.data === undefined || + metricMeta.data[baseMetricName] === undefined || + metricMeta.data[baseMetricName].length < 1 ? ( + <>No metric metadata found. + ) : ( + <> + Metric help:{" "} + {metricMeta.data[baseMetricName][0].help} +
+ Metric type:{" "} + {metricMeta.data[baseMetricName][0].type} + + )} +
+ + + {node.type === nodeType.vectorSelector ? ( + <> + This node selects the latest (non-stale) sample value within the + last 5m + + ) : ( + <> + This node selects{" "} + + {formatPrometheusDuration(node.range)} + {" "} + of data going backward from the evaluation timestamp + + )} + {node.timestamp !== null ? ( + <> + , evaluated relative to an absolute evaluation timestamp of{" "} + + {(node.timestamp / 1000).toFixed(3)} + + + ) : node.startOrEnd !== null ? ( + <>, evaluated relative to the {node.startOrEnd} of the query range + ) : ( + <> + )} + {node.offset === 0 ? ( + <> + ) : node.offset > 0 ? ( + <> + , time-shifted{" "} + + {formatPrometheusDuration(node.offset)} + {" "} + into the past, + + ) : ( + <> + , time-shifted{" "} + + {formatPrometheusDuration(-node.offset)} + {" "} + into the future, + + )}{" "} + for any series that match all of the following criteria: + + {matchingCriteriaList(node.name, node.matchers)} + + If a series has no values in the last{" "} + + {node.type === nodeType.vectorSelector + ? "5m" + : formatPrometheusDuration(node.range)} + + {node.offset > 0 && ( + <> + {" "} + (relative to the time-shifted instant{" "} + + {formatPrometheusDuration(node.offset)} + {" "} + in the past) + + )} + , the series will not be returned. + +
+ ); +}; + +export default SelectorExplainView; diff --git a/web/ui/mantine-ui/src/pages/query/QueryPanel.tsx b/web/ui/mantine-ui/src/pages/query/QueryPanel.tsx index 628183bd6a..8cddd601a4 100644 --- a/web/ui/mantine-ui/src/pages/query/QueryPanel.tsx +++ b/web/ui/mantine-ui/src/pages/query/QueryPanel.tsx @@ -14,6 +14,7 @@ import { IconChartLine, IconCheckbox, IconGraph, + IconInfoCircle, IconSquare, IconTable, } from "@tabler/icons-react"; @@ -38,6 +39,7 @@ import TreeView from "./TreeView"; import ErrorBoundary from "../../components/ErrorBoundary"; import ASTNode from "../../promql/ast"; import serializeNode from "../../promql/serialize"; +import ExplainView from "./ExplainViews/ExplainView"; export interface PanelProps { idx: number; @@ -153,6 +155,12 @@ const QueryPanel: FC = ({ idx, metricNames }) => { }> Graph + } + > + Explain + @@ -300,6 +308,30 @@ const QueryPanel: FC = ({ idx, metricNames }) => { onSelectRange={onSelectRange} /> + + + + {Array.from(Array(20), (_, i) => ( + + ))} + + } + > + { + dispatch(setShowTree({ idx, showTree: true })); + }} + /> + + + ); diff --git a/web/ui/mantine-ui/src/pages/query/SeriesName.tsx b/web/ui/mantine-ui/src/pages/query/SeriesName.tsx index 4fc3a7df60..66a7856f56 100644 --- a/web/ui/mantine-ui/src/pages/query/SeriesName.tsx +++ b/web/ui/mantine-ui/src/pages/query/SeriesName.tsx @@ -51,14 +51,14 @@ const SeriesName: FC = ({ labels, format }) => { } return ( -
+ {labels ? labels.__name__ : ""} {"{"} {labelNodes} {"}"} -
+ ); }; diff --git a/web/ui/mantine-ui/src/pages/query/TreeNode.tsx b/web/ui/mantine-ui/src/pages/query/TreeNode.tsx index b6a78e9a69..102396f6e4 100644 --- a/web/ui/mantine-ui/src/pages/query/TreeNode.tsx +++ b/web/ui/mantine-ui/src/pages/query/TreeNode.tsx @@ -88,6 +88,13 @@ const TreeNode: FC<{ sortedLabelCards: [], }); + // Deselect node when node is unmounted. + useEffect(() => { + return () => { + setSelectedNode(null); + }; + }, [setSelectedNode]); + const children = getNodeChildren(node); const [childStates, setChildStates] = useState( @@ -236,12 +243,12 @@ const TreeNode: FC<{ // Connector line between this node and its parent. )} - {/* The node itself. */} + {/* The node (visible box) itself. */} + - + ); }; diff --git a/web/ui/mantine-ui/src/pages/query/urlStateEncoding.ts b/web/ui/mantine-ui/src/pages/query/urlStateEncoding.ts index 86b85b3c8a..f948205a12 100644 --- a/web/ui/mantine-ui/src/pages/query/urlStateEncoding.ts +++ b/web/ui/mantine-ui/src/pages/query/urlStateEncoding.ts @@ -39,7 +39,22 @@ export const decodePanelOptionsFromURLParams = (query: string): Panel[] => { panel.showTree = value === "1"; }); decodeSetting("tab", (value) => { - panel.visualizer.activeTab = value === "0" ? "graph" : "table"; + // Numeric values are deprecated (from the old UI), but we still support decoding them. + switch (value) { + case "0": + case "graph": + panel.visualizer.activeTab = "graph"; + break; + case "1": + case "table": + panel.visualizer.activeTab = "table"; + break; + case "explain": + panel.visualizer.activeTab = "explain"; + break; + default: + console.log("Unknown tab", value); + } }); decodeSetting("display_mode", (value) => { panel.visualizer.displayMode = value as GraphDisplayMode; @@ -125,7 +140,7 @@ export const encodePanelOptionsToURLParams = ( panels.forEach((p, idx) => { addParam(idx, "expr", p.expr); addParam(idx, "show_tree", p.showTree ? "1" : "0"); - addParam(idx, "tab", p.visualizer.activeTab === "graph" ? "0" : "1"); + addParam(idx, "tab", p.visualizer.activeTab); if (p.visualizer.endTime !== null) { addParam(idx, "end_input", formatTime(p.visualizer.endTime)); addParam(idx, "moment_input", formatTime(p.visualizer.endTime));