Repository navigation
feat(canvas): filter bar and time range for the metrics views that Markdown metrics_sql queries - #10250
feat(canvas): filter bar and time range for the metrics views that Markdown metrics_sql queries#10250nishantmonu51 wants to merge 16 commits into
metrics_sql queries#10250Conversation
…ies select from The parser now reads the FROM of each `metrics_sql` and `metrics_sql_rows` query written as a string literal in a Markdown component's content and adds the metrics view as a ref. The component then reconciles after the metrics view, and the canvas validates `filters.required`, `filters.single_select` and `defaults.filters` against it. - `metricssql.MetricsViewName` reads a query's metrics view without looking it up. - `parser.MetricsSQLMetricsViews` walks a template for the calls, and can also record the queries built when the template resolves.
`ResolveCanvas` adds the metrics views of a Markdown component's queries to `referenced_metrics_views`, with the viewer's security applied, so a Markdown-only canvas gets a filter bar and time range, and a metrics view only Markdown queries gets the canvas filters and measure formatting. Queries built when the template resolves (e.g. with `printf`) are found by resolving it for the viewer with recording `metrics_sql` functions; the text resolver now shares that helper. A query the viewer can't run doesn't remove the Markdown component.
…iews The time controls of a canvas without metrics views never resolve, so its Markdown templates waited forever and the widgets stayed empty. Resolve them right away in that case, over all the data.
…wn queries Remove the limit that a Markdown-only metrics view needs another widget, explain that Markdown's metrics views join the canvas filter bar, time range and filter settings, and recommend writing queries as quoted text.
…s follow the canvas filters
nishantmonu51
left a comment
There was a problem hiding this comment.
Left a few notes on Markdown view discovery.
| if content, ok := props["content"].(string); ok { | ||
| names, _ := MetricsSQLMetricsViews(content, nil) | ||
| for _, name := range names { | ||
| refs = append(refs, ResourceName{Kind: ResourceKindMetricsView, Name: name}) |
There was a problem hiding this comment.
This makes every quoted FROM a required component dependency, even in a branch the viewer never enters. If a Markdown widget has an admin-only branch that names a missing or invalid view, ComponentReconciler now clears the widget’s ValidSpec for everyone and can invalidate the canvas too. Previously, viewers who skipped that branch still got the text. Can we keep these refs for ordering and filter discovery, but let ComponentReconciler serve the Markdown spec when an inferred view fails so the query error only shows when that branch runs?
There was a problem hiding this comment.
Good call, fixed in c5bbf96. ResolveCanvas also drops invalid views now, otherwise the time controls would wait on them.
| user = claims.UserAttributes | ||
| } | ||
| content := validSpec.RendererProperties.Fields["content"].GetStringValue() | ||
| names, complete := parser.MetricsSQLMetricsViews(content, &parser.TemplateData{User: user}) |
There was a problem hiding this comment.
If a Markdown widget uses an if to pick between two views the viewer can access, both views appear in the filter bar even though only one query runs. For example, an analyst can pick a dimension that only exists on the inactive view and see no change in the widget. Could ResolveCanvas use the calls recorded for this viewer when template evaluation completes, and fall back to the static names when the recording can’t resolve the template? The parser can still use all the literal names to validate YAML.
There was a problem hiding this comment.
I'd keep the static names, since the recorded run returns no rows and skips queries inside a range over metrics_sql_rows or behind an if on a result, so those would run without the canvas filters.
| func MetricsViewName(sql string) (string, error) { | ||
| p := parser.New() | ||
| p.SetSQLMode(mysql.ModeANSI | mysql.ModeANSIQuotes) | ||
| stmt, err := parseSelectStmt(p, sql) |
There was a problem hiding this comment.
Could MetricsViewName be a method on Compiler that calls parseSelectStmt(c.p, sql)? New(nil) already configures ANSI quoting, and then MetricsSQLMetricsViews can reuse one TiDB parser for all the queries in the widget instead of allocating one per query.
… compiler `MetricsViewName` is now a `Compiler` method, so `MetricsSQLMetricsViews` parses all the queries of a widget with one TiDB parser.
…nly one branch queries The metrics view refs that the parser links from Markdown queries still order the component after its metrics views and put them on the canvas. A missing or invalid one no longer fails the component, since the query naming it may only run in a branch most viewers never enter; the query fails when it runs instead. `ResolveCanvas` leaves out the invalid ones, which have no filters to offer.
AdityaHegde
left a comment
There was a problem hiding this comment.
Metrics view names that differ only in case can drop or reject default filters.
Metrics view lookups ignore case, but the canvas compares names exactly in a few places, and this PR puts Markdown names in a different form in each of them:
- The parser links Markdown refs as written in the query, since
inferAmbiguousRefskeeps the name as is. So the canvas reconciler'sgetReferencedMetricsViewskeys them by the query's spelling, andvalidateDefaultFilterschecksdefaults.filtersagainst that. ResolveCanvaschanges Markdown names to the resource name (runtime/canvases.go:220), andpruneDefaultFilterscompares against those keys exactly.
This causes two failures:
- A default filter is dropped without any error. The resource is
Sales_MV, the Markdown has{{ metrics_sql "SELECT revenue FROM sales_mv" }}, and the default filter key issales_mv. The reconciler accepts this, butResolveCanvaskeys the metrics view asSales_MV, sopruneDefaultFiltersremoves the filter and viewers see unfiltered numbers. - The canvas fails to reconcile. The resource is
sales_mv, the Markdown saysFROM Sales_MV, and the default filter key issales_mv.validateDefaultFiltersfails withmetrics view "sales_mv" referenced in default filter does not exist, even though the query itself runs.
A smaller effect: a KPI with metrics_view: Sales_MV and Markdown with FROM sales_mv put both keys in ReferencedMetricsViews, so the frontend sees the same metrics view twice.
The exact comparisons were already there for metrics_view properties and custom chart metrics_sql. Markdown is the first place where names are written freely inside text, and the docs now tell users that default filters apply to these metrics views, so mismatched case becomes much more likely. Could we use the resource name for every metrics view the canvas tracks? That would cover getReferencedMetricsViews, the metrics_view and param-bound names in ResolveCanvas, and default filter keys, matched case-insensitively. That fixes all three cases at once.
Existing canvases can stop reconciling after this change.
Markdown metrics views are now component refs, so getReferencedMetricsViews returns them and validateMetricsViewTimeConsistency checks them (runtime/reconcilers/canvas.go:116). A canvas with a KPI on a metrics view whose weeks start on Monday, and Markdown that queries one whose weeks start on Sunday, worked before. It now fails with inconsistent first_day_of_week, even when that query is inside a branch like {{ if .user.admin }} that most viewers never enter. The component reconciler already accepts missing or invalid Markdown refs for this reason, so it seems inconsistent for the canvas to reject them over time settings. If the check is intended, now that the canvas time range applies to these metrics views, it would be good to mention it in the release notes. Otherwise, could Markdown-only refs be left out of this check, or reported as a warning?
Developed in collaboration with Claude Code
…wn-filters # Conflicts: # runtime/parser/parser_test.go
… and skip Markdown-only views in the week check Metrics view names are case-insensitive, and the canvas can spell one metrics view several ways: a `metrics_view` property keeps its spelling, while Markdown queries use the resource name. The canvas reconciler now accepts a default filter that names a referenced metrics view in another case, and `ResolveCanvas` keys each default filter by every name the canvas uses for its metrics view instead of dropping it. Metrics views that only Markdown queries are left out of the canvas's `first_day_of_week` / `first_month_of_year` check, since the query may only run in a branch most viewers never enter.
|
@AdityaHegde Fixed both default filter cases in 7658b94. A default filter now goes to every name the canvas uses for its view, and the reconciler matches it in any case. I'd keep the separate keys when a KPI and Markdown spell the same view differently. Markdown needs the resource name, since the runtime matches its filters and format tokens by it. The frontend looks KPIs up by their |
nishantmonu51
left a comment
There was a problem hiding this comment.
A few things inline on filters and dates.
| res := make(map[string]*runtimev1.DefaultMetricsSQLFilter, len(filters)) | ||
| for mv, filter := range filters { | ||
| for _, key := range keys(mv) { | ||
| if _, ok := res[key]; ok && key != mv { |
There was a problem hiding this comment.
If defaults.filters contains Sales_MV: "region = 'West'" and SALES_MV: "region = 'East'", both pass validation. A Markdown query using the canonical key sales_mv then gets whichever filter this Go map visits first. I saw both results from the loop with the same input. Could validateDefaultFilters reject duplicate keys for the same view after case folding? That gives the author a clear error before a reload can change the dashboard totals.
| for name, mv := range referencedMetricsViews { | ||
| namesByResource[mv.Meta.Name.Name] = append(namesByResource[mv.Meta.Name.Name], name) | ||
| } | ||
| res = pruneDefaultFilters(res, func(name string) []string { |
There was a problem hiding this comment.
The visual editor returns through includeHidden above and skips this mapping. With defaults.filters.SALES_MV and a Markdown query resolved as sales_mv, the filter works in the viewer but disappears from the editor’s default-filter preview because DefaultFilterDisplay looks up filterExpr[key] exactly. Could the preview resolve filters against the referenced view names too, while keeping the original YAML keys for editing?
There was a problem hiding this comment.
Fixed in f75b270. I did it in ResolveCanvas instead of the preview, since the editor canvas looked the filters up the same way.
| maps.DeleteFunc(nonMarkdown, func(_ string, res *runtimev1.Resource) bool { | ||
| return res.GetComponent().GetSpec().GetRenderer() == "markdown" | ||
| }) | ||
| validateErr = r.validateMetricsViewTimeConsistency(r.getReferencedMetricsViews(ctx, nonMarkdown)) |
There was a problem hiding this comment.
A Markdown query on a Sunday-start a_weekly view can put Sunday first in the date picker for a canvas whose KPI uses a Monday-start sales_mv view. CanvasDashboardConfigProvider takes its week start from the first time-series view in referencedMetricsViews, which now includes views skipped by this check. Could it prefer a time-series view from the regular widgets and use Markdown views as a fallback on Markdown-only canvases?
| return res | ||
| } | ||
| unchanged := func(spec *runtimev1.CanvasSpec) bool { | ||
| return maps.EqualFunc(spec.GetDefaultPreset().GetFilterExpr(), rekey(spec), func(a, b *runtimev1.DefaultMetricsSQLFilter) bool { return a == b }) |
There was a problem hiding this comment.
DefaultMetricsSQLFilter values are pointers, so maps.Equal already does the comparison this callback does.
| return maps.EqualFunc(spec.GetDefaultPreset().GetFilterExpr(), rekey(spec), func(a, b *runtimev1.DefaultMetricsSQLFilter) bool { return a == b }) | |
| return maps.Equal(spec.GetDefaultPreset().GetFilterExpr(), rekey(spec)) |
… and key them for the editor too - The canvas reconciler rejects `defaults.filters` keys that differ only in case, since they would set two filters for one metrics view. - `ResolveCanvas` rekeys the default filters in sorted key order, so the result doesn't depend on map order. - The editor gets each default filter under its key as written and under the names the canvas uses for its metrics view, so the canvas and the defaults panel find it.
…arkdown-only ones The canvas check on `first_day_of_week` skips metrics views that only Markdown queries, so one of them could set the date picker's week start for a canvas whose widgets start weeks on another day. The canvas now takes the week start from the first time-series metrics view that a widget names in `metrics_view`, and only falls back to the others.
AdityaHegde
left a comment
There was a problem hiding this comment.
Saving default filters can now produce a canvas that fails to reconcile.
Keeping separate keys for different spellings of one metrics view interacts badly with the new duplicate-key check in validateDefaultFilters. Take a KPI with metrics_view: Sales_MV and Markdown with {{ metrics_sql "SELECT revenue FROM sales_mv" }}. ReferencedMetricsViews then has both Sales_MV and sales_mv. A dimension filter in the filter bar applies to every metrics view that has the dimension, so it is set under both keys. saveDefaultFilters writes defaults.filters from topLevelJoiner.expr, so the YAML gets both Sales_MV and sales_mv, and the reconciler then rejects it with default filters "Sales_MV" and "sales_mv" are for the same metrics view. Before this PR, this needed two non-Markdown widgets that spell the view differently. Now it happens whenever a widget's spelling differs from the resource name.
I think this is a good reason to unify the keys in this PR rather than in a follow-up. If you'd rather keep the follow-up, saveDefaultFilters should at least write one key per metrics view, ignoring case.
The week start can still come from a Markdown-only metrics view.
CanvasDashboardConfigProvider prefers metrics views named by a widget's metrics_view property, but the reconciler checks every non-Markdown component, including custom charts that use metrics_sql and components whose metrics view is bound to a param. On a canvas whose only widgets are custom charts, the date picker can still take its week start from a metrics view that only Markdown queries. Could the frontend prefer every metrics view from non-Markdown components, matching the reconciler?
Nit: in ResolveCanvas, the canvasNames block now sits between the "The visual editor gets the full canvas…" comment and the if includeHidden block that it describes.
Developed in collaboration with Claude Code
…pelling A canvas can list one metrics view under several spellings, such as a widget's `metrics_view` and the resource name a Markdown query uses, and the filter bar sets the same filter under each. "Save as default" now writes one key per metrics view, ignoring case, since the canvas rejects default filters that name one metrics view twice.
…kdown-only ones The canvas preferred metrics views that a widget names in `metrics_view`, so on a canvas of custom charts a metrics view that only Markdown queries could still set the week start. It now leaves out only the metrics views that Markdown components alone reference, read from the components' refs.
… branch it describes
|
@AdityaHegde Went with the smaller fix for the first point in 2862b00. Saving defaults now writes one key per view. The week start now skips only the views that Markdown alone references, in 7a18284, so custom charts and param-bound views come first. Moved the comment in 61b1a63. |
nishantmonu51
left a comment
There was a problem hiding this comment.
A few follow-ups inline.
| .map((name) => [name, this.metricsViewsProvider.specs[name]] as const) | ||
| .filter(([, spec]) => spec?.timeDimension); | ||
| const firstSpecWithTimeSeries = (timeSeriesSpecs.find( | ||
| ([name]) => !markdownOnlyMetricsViews.has(name.toLowerCase()), |
There was a problem hiding this comment.
A Markdown query built with printf can still change the calendar for a canvas with a KPI. If a_sunday only comes from that query and z_monday is the KPI’s view, ResolveCanvas returns both views but the Markdown component has no ref for a_sunday. It passes this check and the calendar starts on Sunday. Could ResolveCanvas return which views are used by non-Markdown widgets from the names it already collects? That would also cover a view shared by Markdown and a custom chart whose metrics_sql adds no ref.
There was a problem hiding this comment.
I'd leave this one, it needs a printf-built query on a view with a different week start, and covering it means a new ResolveCanvas field.
| for (const name of Object.keys(filters)) { | ||
| const key = name.toLowerCase(); | ||
| const current = kept.get(key); | ||
| if (current === undefined || name < current) kept.set(key, name); |
There was a problem hiding this comment.
If the YAML already has defaults.filters.sales_mv and a KPI spells the same view Sales_MV, saving the defaults in the editor rewrites the key to Sales_MV even if the filter value stays the same. Can saveDefaultFilters prefer the spelling that’s already in the YAML and use the sorted fallback only for new entries? That keeps a save from changing the project diff just because a widget uses another spelling.
| const filters = oneFilterPerMetricsView( | ||
| this.expressionFilterManager.topLevelJoiner.expr, | ||
| ); | ||
| const filterNames = filters.map(([name]) => name); |
There was a problem hiding this comment.
Could we have Promise.all return [name, sql] pairs and use those to build filterMap? oneFilterPerMetricsView already gives us pairs, so there’s no need to split them into two arrays and match them up by index.
…efault filters "Save as default" now keys each filter by the spelling `defaults.filters` already uses for its metrics view, so a save doesn't rename the key just because a widget spells the metrics view differently. New filters keep the first spelling in sort order. The filter map is built from name and SQL pairs.
A canvas built only from Markdown widgets that query with
metrics_sql/metrics_sql_rowshad no filter bar and no time range, because the canvas only collected metrics views from themetrics_viewandmetrics_sqlproperties of its other widgets. On a mixed canvas, a metrics view that only Markdown queried got none of the canvas filters, andapply_formattingleft rawRILL__FORMAT(...)tokens. Since #10134, the Markdown widgets of a canvas without metrics views also rendered empty, because its time controls never resolve.FROMof the queries written as string literals in itscontent(parser.MetricsSQLMetricsViews,metricssql.MetricsViewName). The component reconciles after them, and the canvas validatesfilters.required,filters.single_selectanddefaults.filtersagainst them.ResolveCanvas: returns those metrics views inreferenced_metrics_viewswith the viewer's security applied, plus the metrics views of queries built when the template resolves (e.g. withprintf). Those are found by resolving the template for the viewer with recordingmetrics_sqlfunctions, a helper now shared with the text resolver. The filter bar, time range, pinned and required filters andapply_formattingthen work for them, on Markdown-only and mixed canvases.metrics_sql: the static analysis also sees branches the template doesn't run for the viewer, so the widget keeps showing the query's error.Not in this PR: Markdown
time_filtershas been ignored since #10134 (the query reads the canvas's time controls, not the widget's), although the docs describe it. Left for a follow-up.Screenshots (synthetic project, Chrome 1440×900 at 2x)
Checklist: