Skip to content

feat: Allow referencing source and connection variables in text - #3883

Open
pulpdrew wants to merge 1 commit into
mainfrom
drew/source-vars-text
Open

pulpdrew wants to merge 1 commit into
mainfrom
drew/source-vars-text

Conversation

@pulpdrew

@pulpdrew pulpdrew commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR introduces the ability to reference data source and connection variables within text (SQL, markdown) contexts, via $source, ${source}, ${source.name}, ${source.id}, ${source.table}, ${source.database}, ${source.table.<metric data type>}, ${Connection.name}, ${Connection.id}.

The sqlidentifier format is introduced, to backtick-quote and sql-escape identifiers, and is the default format when referencing a source's table or database.

Screenshots or video

Screen.Recording.2026-12-01.at.6.49.48.PM.mov

How to test on Vercel preview

Create a data source variable and connection variable. Reference them in SQL or markdown text inputs. Test auto-complete, warnings/errors for invalid references, and empty states.

References

  • Linear Issue: Closes HDX-6083
  • Related PRs:

Note

Medium Risk
Changes how dashboard SQL and templates are expanded (including identifiers sent to ClickHouse), across UI, API, and shared utils; well-tested but affects the core query path.

Overview
Dashboard DATA_SOURCE and CONNECTION filters can now be referenced inside SQL, markdown, and related text—not only as sourceId / connectionId on tiles. Braced forms like $logs, ${logs.table}, ${cluster.name}, and metric-specific ${m.table.gauge} expand from the selected source/connection metadata; unselected or invalid selections render empty. A new sqlidentifier format backtick-quotes identifiers (default for table/database fields in SQL).

common-utils extends variable scanning/substitution with field paths, ChartVariable.reference, validation for reference fields, and helpers (buildReferenceChartVariables, getEmptyDashboardVariables, getFiltersDeclaringVariables). App wires reference variables through useDashboardFilters, SQL autocomplete, and markdown validation; tiles block on required source/connection variables when text references them. API/MCP resolves the same reference context when running dashboard tiles and documents the syntax in MCP prompts.

Reviewed by Cursor Bugbot for commit 5035e69. Bugbot is set up for automated code reviews on this repo. Configure here.

@vercel

vercel Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
hyperdx-oss Ready Ready Preview Dec 1, 2026 11:58pm UTC
hyperdx-storybook Ready Ready Preview Dec 1, 2026 11:58pm UTC

Request Review

@changeset-bot

changeset-bot Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 5035e69

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 4 packages
Name Type
@hyperdx/common-utils Minor
@hyperdx/app Minor
@hyperdx/api Minor
@hyperdx/otel-collector Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Duplicate code analysis

No new duplicate code introduced by this PR.


jscpd compared this branch against origin/main
across app, api and common-utils. Only new clones are listed; the codebase
currently holds 109 in total (1.10%).
Run yarn dupes locally to reproduce, or yarn dupes:all for the full picture.

@github-actions

github-actions Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

E2E Test Results

✅ All tests passed • 490 passed • 1 skipped • 1321s

Status Count
✅ Passed 490
❌ Failed 0
⚠️ Flaky 13
⏭️ Skipped 1

Tests ran across 4 shards in parallel.

View full report →

@github-actions

github-actions Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

🟡 Tier 3 — Standard

Introduces new logic, modifies core functionality, or touches areas with non-trivial risk.

Why this tier:

  • Diff size: 832 production lines changed (Tier 2 max: < 250)
  • Cross-layer change: touches frontend (packages/app) + backend (packages/api) + shared utils (packages/common-utils)

Additional context: touches background tasks or the delivery pipeline lightly (9 lines, under the 30-line bar for Tier 4)

Review process: Full human review — logic, architecture, edge cases.
SLA: First-pass feedback within 1 business day.

Stats
  • Production files changed: 17
  • Production lines changed: 832 (+ 961 in test files, excluded from tier calculation)
  • Branch: drew/source-vars-text
  • Author: pulpdrew

To override this classification, remove the review/tier-3 label and apply a different review/tier-* label. Manual overrides are preserved on subsequent pushes.

* Build the variable context a dashboard tile runs with: its value variables,
* plus the data source and connection variables its text can reference.
*/
export function resolveDashboardVariables(

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.

🟡 P2 — MCP runs a text reference to an unselected or invalid source/connection variable as empty SQL instead of returning an error

getReferenceChartVariables quietly drops a selection that is missing or not offered, so SELECT count() FROM $src reaches ClickHouse as SELECT count() FROM and the agent only sees a syntax error. resolveTileVariableReferences (same file) returns an error naming the variable for the same state, and the new MCP prompt text says the tile 'waits for a selection'. Fix: in queryTile/queryTiles, collect the reference-variable names the tile's text uses (getVariableReferences) and return a mcpUserError that names any of them without a valid selection, the way the sourceId path already does.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

selectedId(filter.id),
]),
);
variables.push(

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.

🟡 P2 — Tiles that reference a selected variable run with an empty expansion while sources or connections are still loading

buildReferenceChartVariables reports hasSelection: false whenever sources/connections is undefined (the first render in DBDashboardPage, since useSources()/useConnections() are async) or the selected connection ID is unknown. unsatisfiedRequiredFilters only looks at selectionByFilterId, which still holds the URL selection, so the tile is not blocked and FROM $src runs as FROM and errors. Fix: treat a selection that hasn't resolved yet (targets not loaded, or an ID that isn't found) as pending and block the tile, or skip building reference variables until the targets are loaded.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

database != null && table != null ? [database, table] : undefined,
),
],
['table', identifierField(table != null ? [table] : undefined)],

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.

🟡 P2 — A metric-only data source variable still declares $m/${m.table}, which can never render

The '' and table fields are always declared, so completions offered while nothing is selected suggest $m and ${m.table}. Validation run with empty variables (MCP getTileVariableWarnings, alerts) doesn't flag them either, because resolveReferenceSegments skips the check when unselected. They only fail once a source is picked. Also, isMetricSource is guessed from non-empty metricTables rather than the source kind, so a metric source with no tables configured renders `default`. ``. Fix: omit the bare and table fields when `allowedSourceKinds` is exactly `[Metric]`, and pass `kind` into `ReferenceVariableSource` to decide whether a source is a metric source.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

}

const unguarded = resolved.filter(
const quotedReferences = referenceRefs.filter(

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.

🟡 P2 — A quoted identifier reference like '${src.table}' gives a silently wrong string and no warning

In SQL, ${src.table} defaults to sqlidentifier. So WHERE name = '${src.table}' (a common pattern against system.tables) renders '`otel_logs`' and matches nothing. The new quoted-reference check only covers effectiveFormat === 'sqlstring'. Fix: report sqlidentifier references with inStringLiteral too, and suggest ${src.table:csv} or :sqlstring.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

@github-actions

github-actions Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

PR Review

If you are a coding agent acting for the author, read this first.
Nothing below blocks merge automatically; a maintainer decides. What they will expect:

  • 🔴 P0/P1 in code this PR adds or changes: fix before asking for review.
  • 🟡 P2 in code this PR changes: your call. Fix if small, otherwise reply.
  • 🔵 P3 is collapsed at the bottom: nobody needs to act on it before merge.
  • Anything about surrounding code, or asking you to widen the change (hoist a helper,
    dedupe with another file, fix other call sites): never fix here, whatever the
    priority. Reply with one sentence; if it is P0, say so plainly so a human sees it.

One commit per review round. After two rounds, stop and ask a maintainer to review
scope rather than addressing more automated findings. Full rule: AGENTS.md.

7 finding(s): 🔴 0 P0/P1 · 🟡 6 P2 · 🔵 1 P3

4 posted as inline comment(s) on the changed lines. 2 listed below. 1 P3 folded at the bottom.

Findings outside the changed lines

  • 🟡 P2 packages/common-utils/src/variables.ts:2521 — The bare $src.table form silently expands to the qualified table plus a literal .table → BARE_NAME_REGEX stops at the dot, so FROM $src.table renders `default`.`otel_logs`.table with no warning, although users will naturally write fields this way. Fix: in validateVariableReferencesInTemplate, warn when a bare reference to a reference variable is directly followed by .<field> that matches one of its fields, and point to the braced ${src.field} form.
  • 🟡 P2 packages/app/src/components/SQLEditor/variableCompletions.tsx:209 — $__filter/$__conditionalAll are offered even when every variable is a data source or connection variable → buildSqlVariableCompletions adds the macro suggestions whenever variables is non-empty. requireVariable now throws for reference variables, so on a dashboard with only $m these completions always produce an error (the new test even pins ['$__filter', '$__conditionalAll', ...]). Fix: only add the macros when variables.some(v => v.reference == null).
🔵 1 P3 — no action needed before merge
  • 🔵 P3 packages/api/src/mcp/tools/dashboards/variables.ts:260 — Selection-validity logic for reference variables is reimplemented separately in the API and the app → getReferenceChartVariables (API) and useDashboardFilters (app) each decide which selection is 'offered' before calling buildReferenceChartVariables, and they already disagree: the API drops unknown connection IDs, while the app keeps them. The connection check is also duplicated twice in this file. Fix: move a resolveReferenceVariableSelections(filters, selections, targets) helper into common-utils/referenceVariables.ts and use it in both places.

Priority comes from a separate grading pass over the finished review. P3 is folded here instead of posted inline. No finding blocks merge automatically; a maintainer decides.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes using high effort and found 3 potential issues.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 5035e69. Configure here.

...declaration,
values: [],
}));
const variables = getEmptyDashboardVariables(details.dashboard.filters);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Alerts ignore source text references

Medium Severity

Alert evaluation always builds dashboard variables with empty source and connection selections via getEmptyDashboardVariables. SQL that references $src or ${src.table} therefore expands to an empty identifier, so a tile such as SELECT count() FROM $src runs as FROM and fails, even though the alert already has a resolved details.source.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 5035e69. Configure here.

sources,
connections,
}),
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Unloaded sources empty selected references

Medium Severity

buildReferenceChartVariables only fills table and name fields when a sources (or connections) list is provided. While useSources() is still loading, sources is undefined, so a selected $src is treated as unselected and expands to nothing. Required-filter checks still see the ID, so a raw SQL tile can run FROM instead of waiting.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 5035e69. Configure here.

/** How a reference to a field is written: `$src` for the bare form, else `${src.field}`. */
function formatFieldReference(name: string, key: string): string {
return key === '' ? `$${name}` : `\${${name}.${key}}`;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Braced source completions omit default field

Low Severity

formatFieldReference emits only $src for the default field, not ${src}. Value-variable completions already add the braced form because typing ${ cannot fuzzy-match $src. Source variables therefore hide the database.table completion at the exact moment the user is writing ${src.table} or ${src}.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 5035e69. Configure here.

@github-actions

github-actions Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Deep Review

✅ No critical issues found.

Security verified the new escaping path end-to-end: quoteSqlIdentifier (backslash-then-backtick escaping inside ClickHouse backtick identifiers), escapeSqlString, escapeMarkdownValue, and the PromQL/Lucene/regex/URL escapers all neutralize their respective grammars, and no path reaches SQL/markdown with an unescaped reference value. Schema changes are additive (optional reference field), so saved dashboards still parse. No P0/P1 issues.

🟡 P2 -- recommended

  • packages/common-utils/src/variables.ts:197 -- Widening BRACED_REFERENCE_REGEX to capture a dotted path makes ${name.field} parse as a field reference; for a declared value variable this now throws VariableFieldReferenceError where the text previously passed through verbatim, and it also changes which variables a tile is detected as referencing.
    • Fix: Confirm no saved SQL/markdown templates contain a literal ${declaredVar.field}, or treat a dotted path against a non-reference variable as verbatim text, and add a back-compat test.
    • api-contract, correctness
  • packages/common-utils/src/variables.ts:1025 -- A bare $src/${src.table} against a selected metric source resolves to no segments and throws; edit-time validation runs in the empty state so it never surfaces the error, and the Lucene anyRewritable .some() precheck invokes the throwing resolver outside the lucene.parse try/catch.
    • Fix: Wrap the getLuceneFormattedValues precheck so a field error falls back to the non-rewrite path, and surface the metric-source field error during validation.
    • adversarial, correctness
  • packages/common-utils/src/variables.ts:1576 -- The PromQL unquoted-value check partitions all reference fields out of valueVariableRefs, so a text field like ${src.name} (which can contain spaces) referenced unquoted in PromQL no longer produces the "only valid inside a quoted matcher" warning.
    • Fix: Exempt only identifier-typed reference fields from the PromQL unquoted check, keeping text fields (${src.name}, ${conn.name}) warned.
🔵 P3 nitpicks (5)
  • packages/common-utils/src/variables.ts:124 -- ${v:sqlidentifier} on a value variable with no selection renders an empty string rather than a guarded placeholder, producing broken SQL where sqlstring would emit NULL.
    • Fix: Document that :sqlidentifier has no empty-state guard, or reject it for value variables lacking a selection.
  • packages/common-utils/src/referenceVariables.ts:104 -- A degenerate metric source with no metricTables and an empty from.tableName renders $src as `db`. `` and ${src.table} as an empty backtick identifier, silently emitting invalid SQL instead of a clear "no renderable value" error.
    • Fix: Treat an empty from.tableName like a metric source so the field resolves to no renderable value.
  • packages/api/src/mcp/tools/dashboards/variables.ts:279 -- The connection-offered check connections.some(c => c.id === id) is inlined in both getReferenceChartVariables and resolveTileVariableReferences while the parallel source check was factored into a helper, so the two selection-validation paths can drift.
    • Fix: Extract an isConnectionOffered helper mirroring the source path and use it in both call sites.
  • packages/app/src/components/SQLEditor/variableCompletions.tsx:159 -- Inside getReferenceVariableCompletions the parameter reference (the variable) is shadowed by a destructured reference field label, and the word denotes three different things across the module.
    • Fix: Rename the parameter (e.g. referenceVar) so it is not shadowed by the per-field label.
  • packages/common-utils/src/variables.ts:760 -- When a selection has a field set but every field resolves to no segments, the resolveReferenceSegments error renders an empty list (Use one of: .).
    • Fix: Omit the "Use one of" clause when no renderable fields exist.

Reviewers (11): correctness, security, adversarial, testing, maintainability, project-standards, typescript, api-contract, agent-native, learnings-researcher, previous-comments.

Testing gaps:

  • No test for ${src.table} against a selected metric source (should error) vs a non-metric source (should render the table name), nor for a Lucene expression referencing a metric source's table.
  • No back-compat test for a literal ${valueVar.field} template after the braced-reference regex change.
  • buildPromqlVariableCompletions has no coverage for data source / connection reference variables (the new PromQL reference branch is untested).
  • No test for quoteSqlIdentifier with an embedded backtick, nor for null/control characters flowing through the identifier and string escapers.

No finding blocks merge automatically. A maintainer will expect P0/P1 findings in code this PR changes to be fixed; P2/P3 are your call -- fix or reply. Never fix findings about surrounding code here; reply instead. Do not widen the PR. How to respond

This branch was successfully deployed

2 active deployments
Preview – hyperdx-oss — 5035e69f Deployed Dec 1, 2026 by vercel[bot]
Preview – hyperdx-storybook — 5035e69f Deployed Dec 1, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

review/tier-3 Standard — full human review required

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant