Skip to content

feat(canvas): filter bar and time range for the metrics views that Markdown metrics_sql queries - #10250

Open
nishantmonu51 wants to merge 16 commits into
mainfrom
nishant/canvas-markdown-filters
Open

nishantmonu51 wants to merge 16 commits into
mainfrom
nishant/canvas-markdown-filters

Conversation

@nishantmonu51

Copy link
Copy Markdown
Collaborator

A canvas built only from Markdown widgets that query with metrics_sql / metrics_sql_rows had no filter bar and no time range, because the canvas only collected metrics views from the metrics_view and metrics_sql properties of its other widgets. On a mixed canvas, a metrics view that only Markdown queried got none of the canvas filters, and apply_formatting left raw RILL__FORMAT(...) tokens. Since #10134, the Markdown widgets of a canvas without metrics views also rendered empty, because its time controls never resolve.

  • Parser: a Markdown component now links the metrics views in the FROM of the queries written as string literals in its content (parser.MetricsSQLMetricsViews, metricssql.MetricsViewName). The component reconciles after them, and the canvas validates filters.required, filters.single_select and defaults.filters against them.
  • ResolveCanvas: returns those metrics views in referenced_metrics_views with the viewer's security applied, plus the metrics views of queries built when the template resolves (e.g. with printf). Those are found by resolving the template for the viewer with recording metrics_sql functions, a helper now shared with the text resolver. The filter bar, time range, pinned and required filters and apply_formatting then work for them, on Markdown-only and mixed canvases.
  • A query the viewer can't run doesn't remove the Markdown widget, unlike a custom chart's 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.
  • Frontend: a Markdown template on a canvas without metrics views resolves right away instead of waiting for time controls that never resolve.
  • Docs: replace the "metrics view needs another widget" limit, and add one line to the AI canvas instructions.

Not in this PR: Markdown time_filters has 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)

Before After
Markdown-only canvas before-markdown-only after-markdown-only
Add-filter menu before-markdown-only-filter-menu after-markdown-only-filter-menu
Rep = Jordan Lee on the Markdown-only canvas No filter to pick after-markdown-only-rep-filter
KPI and Markdown on different metrics views, Region = West before-mixed-region-filter after-mixed-region-filter
Visual editor after-editor

Checklist:

  • Covered by tests
  • Ran it and it works as intended
  • Reviewed the diff before requesting a review
  • Checked for unhandled edge cases
  • Linked the issues it closes
  • Checked if the docs need to be updated. If so, create a separate Linear DOCS issue
  • Intend to cherry-pick into the release branch
  • I'm proud of this work!

…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.
@nishantmonu51 nishantmonu51 added Type:Feature New feature request Size:L Large change: 500-1,999 lines Area:Canvas Canvas dashboards labels Dec 1, 2026

@nishantmonu51 nishantmonu51 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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})

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Good call, fixed in c5bbf96. ResolveCanvas also drops invalid views now, otherwise the time controls would wait on them.

Comment thread runtime/canvases.go
user = claims.UserAttributes
}
content := validSpec.RendererProperties.Fields["content"].GetStringValue()
names, complete := parser.MetricsSQLMetricsViews(content, &parser.TemplateData{User: user})

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Comment on lines +129 to +132
func MetricsViewName(sql string) (string, error) {
p := parser.New()
p.SetSQLMode(mysql.ModeANSI | mysql.ModeANSIQuotes)
stmt, err := parseSelectStmt(p, sql)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in 9f5d083.

… 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 AdityaHegde left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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 inferAmbiguousRefs keeps the name as is. So the canvas reconciler's getReferencedMetricsViews keys them by the query's spelling, and validateDefaultFilters checks defaults.filters against that.
  • ResolveCanvas changes Markdown names to the resource name (runtime/canvases.go:220), and pruneDefaultFilters compares against those keys exactly.

This causes two failures:

  1. 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 is sales_mv. The reconciler accepts this, but ResolveCanvas keys the metrics view as Sales_MV, so pruneDefaultFilters removes the filter and viewers see unfiltered numbers.
  2. The canvas fails to reconcile. The resource is sales_mv, the Markdown says FROM Sales_MV, and the default filter key is sales_mv. validateDefaultFilters fails with metrics 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.
@nishantmonu51

Copy link
Copy Markdown
Collaborator Author

@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 metrics_view spelling, so unifying the keys would mean changing those lookups too. Happy to do that in a follow-up. Markdown-only views are also left out of the week settings check now, since their queries can sit in a branch most viewers never hit.

@nishantmonu51 nishantmonu51 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

A few things inline on filters and dates.

Comment thread runtime/canvases.go
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 {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Good catch, fixed in f75b270.

Comment thread runtime/canvases.go
for name, mv := range referencedMetricsViews {
namesByResource[mv.Meta.Name.Name] = append(namesByResource[mv.Meta.Name.Name], name)
}
res = pruneDefaultFilters(res, func(name string) []string {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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))

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in 0b4e14e.

Comment thread runtime/canvases.go Outdated
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 })

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

DefaultMetricsSQLFilter values are pointers, so maps.Equal already does the comparison this callback does.

Suggested change
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))

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Applied in f75b270.

… 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 AdityaHegde left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.
@nishantmonu51

Copy link
Copy Markdown
Collaborator Author

@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 nishantmonu51 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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()),

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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);

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Good idea, fixed in e7f94bb.

const filters = oneFilterPerMetricsView(
this.expressionFilterManager.topLevelJoiner.expr,
);
const filterNames = filters.map(([name]) => name);

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in e7f94bb.

…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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Area:Canvas Canvas dashboards Size:L Large change: 500-1,999 lines Type:Feature New feature request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants