Shared domain and query toolkit
The shared domain and query toolkit is the common language for HyperDX observability data. It gives the web app, API, alert tasks, CLI, and automation tools the same chart, dashboard, filter, variable, template, and query rules. It also turns those shared inputs into checked ClickHouse or PromQL requests. See Explorer and query experience and Dashboards and visualization for the product flows that use these rules.
System role
The toolkit keeps product behavior aligned across services that create, validate, display, or run observability queries. The web app uses it for editing and display. Server services use it for request checks and query work. Automation tools use the same contracts to read and write dashboards.
Shared package boundary
The package is published as @hyperdx/common-utils. Its public rules are grouped by shared responsibility, so a browser, a Node service, or an automation process can apply the same domain rule instead of defining a local version.
| Area | System purpose |
|---|---|
| Domain types and schemas | Define the shared shape of sources, charts, dashboards, filters, variables, alerts, webhook templates, and display settings. |
| Query helpers | Turn builder charts, raw SQL, search text, variables, and macros into ClickHouse or PromQL requests. |
| Metadata | Connect logical fields to ClickHouse tables, types, indexes, rollups, and value lists. |
| Validation and guards | Reject invalid combinations before they reach a query, saved dashboard, alert, or automation flow. |
| ClickHouse clients | Give browser and Node callers one query contract while keeping transport details separate. |
| Portability helpers | Convert dashboard references and display values into forms that can move between instances. |
| Template helpers | Validate and render the small set of helpers allowed in webhook and link templates. |
References: packages/…/package.json• L1-29 packages/…/types.ts• L187-205 packages/…/types.ts• L1242-1349 packages/…/handlebarsEnv.ts• L1-136
Domain model
The domain model gives every service the same vocabulary for an observability query. A chart can use the visual builder, raw SQL, or PromQL, but each form carries the settings needed to save, validate, run, and display it.
Chart and source contracts
Charts describe a source, time range, display type, expressions, filters, grouping, ordering, and optional formulas or alerts. The contract separates builder, raw SQL, and PromQL charts so each query language receives the rules it needs.
Builder charts support derived series with arithmetic formulas on metric, log, and trace sources. Shared display settings cover number formats, palette tokens, conditional colors, number-tile trends, table row striping, series limits, line interpolation, and row actions. Ratio charts can use per-group values or each group's share of the total. Older numeric color tokens resolve to current named tokens so saved charts keep their meaning.
PromQL charts accept both the older single-expression shape and the newer list of expressions. Each expression can use instant or range evaluation. Number, pie, and bar displays can reduce samples to a last usable value, minimum, maximum, mean, sum, or count. Dashboard label filters become PromQL matchers for the expressions that the display actually queries.
Heatmaps support distribution and series modes. PromQL heatmaps also support histogram buckets. An absent mode keeps the older distribution behavior, so older saved tiles retain their meaning.
Sources describe where logs, traces, metrics, sessions, or Prometheus data live. They also define the expressions that give meaning to time, body, service, trace, duration, and other fields. Log sources can optionally map OpenTelemetry severity numbers and event names when those columns exist, so older or non-OpenTelemetry tables remain valid without those expressions. ClickHouse types map to broad query types such as date, number, string, array, map, JSON, dynamic, and tuple.
Categorical charts use seriesLimit as a row limit after conversion. An explicit order stays in control. When none exists, the toolkit orders by the first value in descending order and uses the group as a stable tie-breaker. Number charts remove time and grouping dimensions. Formula number charts expose the formula result instead of its operand series.
When a source names several timestamp expressions, bucket selection prefers the highest-precision DateTime or DateTime64 column. A day-only column is not used when a more precise time column is available, which prevents a whole day from collapsing into one bucket.
References: packages/…/types.ts• L34-46 packages/…/types.ts• L400-500 packages/…/types.ts• L1242-1349 packages/…/types.ts• L1742-1826 packages/…/types.ts• L2695-2749 packages/…/utils.ts• L83-99 packages/…/utils.ts• L207-333 packages/…/utils.ts• L1007-1108 packages/…/utils.ts• L1588-1645 packages/…/renderChartConfig.ts• L589-655
Dashboard and filter contracts
Dashboards combine saved tiles with shared filters and optional containers. A filter can broadcast its selection into matching tile queries, expose it as a variable, or do both. This makes the effect of each dashboard control explicit.
Filter values can become SQL or Lucene conditions, or they can supply a dashboard variable. Query-expression filters can use ClickHouse fields. Static-list and Prometheus-label filters are variable-only. Ad hoc filters let a user add field conditions for supported SQL or PromQL sources. PromQL ad hoc filters use label matchers and support only the operators PromQL can express.
The toolkit keeps filter state usable across query and display paths. It formats date selections for the ClickHouse type of the target column, preserves stable serialized state for query caching, and parses nested SQL expressions without confusing their inner operators with the outer filter. A pinned filter is accepted only when its full condition can round-trip as one visible sidebar facet, so the displayed filter does not diverge from the executed predicate.
Required filters add a second state check. A tile is blocked only when a required selection is missing and the tile consumes that filter through broadcast, a variable, or a global requirement. Raw SQL and PromQL do not consume broadcast filters in the same way as builder charts.
Dashboard filter state accepts both legacy expression keys and variable keys. Variable entries take precedence, explicit empty selections remain meaningful, and single-select filters honor only the first stored value. Serialization keeps the result stable for URLs and other persisted state.
References: packages/…/types.ts• L1272-1379 packages/…/filters.ts• L63-175 packages/…/filters.ts• L495-648 packages/…/filters.ts• L884-1177 packages/…/filters.ts• L1218-1403 packages/…/dashboardFilterValues.ts• L29-199 packages/…/dashboardFilterValues.ts• L202-317
Variable handling
A dashboard variable is a named set of selected strings derived from a dashboard filter. SQL, regular expression, CSV, Lucene, PromQL, and Markdown formats let the same selection work in the language that consumes it.
Variable expansion is language-aware. SQL receives SQL-safe values and variable macros. Lucene receives Lucene-safe values. PromQL receives matcher-safe values and leaves SQL-only macros unchanged. Markdown receives display-safe text. The scanner respects quoted strings and SQL comments. It expands the source once, so a selected value that looks like another variable or macro cannot change the query structure.
For PromQL, the toolkit also adds dashboard label matchers to every vector selector in the expressions used by the display. It parses the expression before adding the matchers. A parse error is reported instead of silently sending an unfiltered query. Expressions that a display does not query remain unchanged, which lets users keep unfinished expression rows while editing.
The toolkit also finds which variables a chart uses. Consumers can then avoid rerunning a tile when an unrelated dashboard variable changes. Alerts can warn when a tile depends on dashboard variables because alert evaluation uses empty selections. Filter value lookups report variables that must be selected before a query can return useful values.
References: packages/…/variables.ts• L32-117 packages/…/variables.ts• L223-449 packages/…/variables.ts• L453-675 packages/…/variables.ts• L1183-1429 packages/…/macros.ts• L519-612 packages/…/promqlLabelInjection.ts• L34-93 packages/…/variables.test.ts• L571-1122
Query lifecycle
The query lifecycle joins user intent, dashboard state, source metadata, and data execution. The same path supports interactive exploration, dashboard tiles, saved searches, alerts, and CLI queries.
This diagram shows how shared input becomes a checked request and a result or useful error.
flowchart LR
A[Chart, search, or dashboard input] --> B[Shared types and guards]
B --> C[Filters, variables, and macros]
C --> D[Source metadata]
D --> E[SQL or PromQL request]
E --> F[ClickHouse or Prometheus client]
F --> G[Rows, series, or query error]
Query construction
The chart renderer combines a chart definition with its time range, source expressions, filters, grouping, aggregation, formulas, and query settings. It returns a ClickHouse statement with parameter values. Raw SQL uses the same context through time, source, filter, and variable macros.
Display type controls the result shape. Time charts use buckets and intervals. Categorical charts use bounded rows and stable ordering. Number charts remove time and grouping dimensions. Table charts use bounded output. Formula and multi-series rules are shared so the editor, API, and automation surfaces agree on what a chart can represent. A positive series limit can also select the top groups before the final chart query, while zero means no limit. For categorical charts, the converted limit follows the user's order when one exists and otherwise uses a deterministic value-descending order.
Search text follows a separate front end but the same destination. The Lucene parser creates an expression tree. A metadata-aware serializer turns field matches, ranges, arrays, maps, JSON paths, and implicit body searches into ClickHouse predicates. Unknown fields become a non-match rather than a broad query.
PromQL templates expand time macros and variables before the request is sent. Dashboard label filters are added only to expressions selected by the display. PromQL charts query every non-blank expression for time-series displays and only the first queried expression for other displays. Auto-selected steps can use a source minimum granularity, while an explicit tile granularity stays unchanged. Non-finite samples are ignored during reduction, and a series with no usable sample has no value rather than zero.
Metric charts can account for upstream sample weights when the source provides them. The renderer keeps unsupported counter, ratio, formula, and metric-type combinations out of the query path rather than relying on a ClickHouse error.
The renderer also uses source text-index metadata to improve SQL filters on map fields. When a source exposes a matching key-value items column, safe equality and IN predicates can use that indexed representation for faster ClickHouse reads. The original SQL literal is preserved, including escaped quotes, backslashes, and JSON text. The rewrite does not apply when an empty or non-string value could change the meaning of a missing map key, and it leaves unsupported operators or unknown map columns unchanged.
References: packages/…/renderChartConfig.ts• L379-505 packages/…/renderChartConfig.ts• L589-705 packages/…/renderChartConfig.ts• L906-1087 packages/…/renderChartConfig.ts• L1090-1245 packages/…/renderChartConfig.ts• L1332-1469 packages/…/renderChartConfig.ts• L1543-1665 packages/…/renderChartConfig.ts• L2720-2819 packages/…/promql.ts• L20-244 packages/…/macros.ts• L519-612 packages/…/promqlLabelInjection.ts• L34-93 packages/…/utils.ts• L977-1108 packages/…/rewriteSqlFilterWithKvItems.test.ts• L42-260 packages/…/kvItemsRewrite.int.test.ts• L10-147
Metadata-assisted query behavior
Metadata connects a logical source field to the physical ClickHouse table. It caches table and column facts by connection and table, then uses them to resolve types, materialized columns, JSON and map paths, skip indexes, rollups, and related views.
Metadata renders logical key expressions into one physical SQL form for value lookup and filtering. This keeps JSON paths and nested fields aligned when the system selects values, builds constraints, or checks a materialized view. Value discovery uses bounded strategies that prefer indexes and rollups, then use a bounded table read when needed.
Field discovery uses the requested time range when a timestamp expression exists and otherwise uses a short default lookback. Primary-index discovery refuses a path that cannot prove its time range is safe. Complete search remains available when the index cannot prove that its result is complete. Metric-name lookup returns deterministic pages with a truncation signal.
References: packages/…/metadata.ts• L62-157 packages/…/metadata.ts• L253-489 packages/…/metadata.ts• L907-1003 packages/…/metadata.ts• L1005-1367 packages/…/metadata.test.ts• L906-1046 packages/…/metadata.test.ts• L1048-1486
ClickHouse execution
The ClickHouse layer gives all callers a parameterized SQL model. It separates identifiers, strings, and numeric values from SQL text. Shared type helpers classify ClickHouse columns for charts and search, including wrapped, structured, fixed-string, dynamic, numeric variant, and scalar types. They also distinguish integer types from other numeric types when a caller needs integer-specific behavior.
The shared client applies safe defaults, supports cancellation, adapts browser and Node streams, and reports failures with enough query context for diagnosis. It can execute a rendered chart as one request or run an explain request to check chart validity. A rejected server setting can be learned and removed on retry without changing the query identity. Error guards also let callers distinguish missing columns from access denial and show a useful response.
The client can recover result-column relationships from ClickHouse SQL. It preserves aliases and select order when the full statement contains ClickHouse syntax that the parser does not understand, so display code can still map returned values to chart expressions.
Each query can carry bounded attribution. The attribution identifies the product surface and related chart, search, dashboard, source, or alert. It helps operators connect ClickHouse activity to the request that caused it without changing query results or exposing sensitive identity data.
References: packages/…/index.ts• L66-228 packages/…/index.ts• L235-404 packages/…/index.ts• L448-504 packages/…/index.ts• L506-837 packages/…/index.ts• L861-1230 packages/…/types.ts• L470-496 packages/…/utils.ts• L83-99
Query language support
The toolkit treats query text as a contract between an editor and a renderer. It preserves valid syntax while users type, expands shared context, formats SQL for inspection, and reports problems before execution when possible.
SQL macros and formatting
Raw SQL templates use named macros for values that change with the dashboard or query view. Time macros bind the selected range and bucket size. Source macros select the configured table. Filter and variable macros apply dashboard state without creating invalid empty-selection SQL.
Macro expansion resolves nested arguments before the outer macro and does not scan expanded values again. SQL formatting supports ClickHouse text and preserves the macro form expected by the query lexer. If incomplete text cannot be formatted, callers can show the original text.
References: packages/…/macros.ts• L66-511 packages/…/sqlFormatter.ts• L11-43 packages/…/variables.ts• L421-445 packages/…/utils.ts• L1273-1362
Template contracts
Template helpers provide a small, shared language for webhook bodies and row links. The environment removes built-in helpers, permits only registered helpers, and supports strict or lenient handling of missing context keys. Syntax and helper errors are found before delivery, with source locations when the template parser provides them.
Webhook templates use plain text or JSON-oriented output rather than HTML. The shared type contract defines the variables that alert delivery can provide and the default bodies that the app and API show to users. Missing values render according to the template mode, while an unknown helper is an explicit validation error. The shared environment supports the approved default and floor helpers, and it reports helper calls outside that set instead of silently accepting them.
References: packages/…/handlebarsEnv.ts• L1-136 packages/…/handlebarsEnv.ts• L138-193 packages/…/types.ts• L568-663 packages/…/types.ts• L701-742
Validation and dashboard checks
Validation works at several levels. Schemas check data shape. Dashboard validation checks relationships such as unique IDs, valid tile references, usable variable names, filter modes, and formula rules. Query validation checks macro use, time range, interval, source, filter, and variable contracts.
Saved dashboard validation also checks query and filter text during import. It reports malformed SQL or Lucene conditions without pretending that static validation can know every ClickHouse column. Variable references are expanded before a dashboard filter's values query is checked. PromQL conditions are accepted by these static checks because their full validity belongs to the Prometheus query path.
A pinned filter is accepted only when its full condition can round-trip as one visible sidebar facet, so the displayed filter does not diverge from the executed predicate. Empty conditions are treated as no-ops, while variable-keyed saved values have no condition text to validate.
Variable names are checked against the shared token grammar and against sibling filters. Filter value lookups can report empty variables that must be selected before a dropdown query can return a useful set of values.
Raw SQL validation also separates editor feedback from execution. It reports missing time or interval contracts, checks variable references, warns when dashboard tiles omit source or filter macros, and rejects source-table macro forms that do not match the selected source.
References: packages/…/filters.ts• L603-648 packages/…/filters.ts• L689-829 packages/…/filters.ts• L1337-1403 packages/…/utils.ts• L1631-1859 packages/…/dashboardValidation.ts• L35-376 packages/…/filters.test.ts• L514-917
Links and series names
Row link templates turn chart or table data into search, dashboard, or external URLs. Internal targets use known IDs or names. External targets use absolute HTTP or HTTPS URLs. Template values are encoded as URL parts, and missing row values produce a row-specific error.
Series name templates turn Prometheus labels into stable legend names. The renderer applies aliases or templates and adds a fallback when names collide, so distinct series do not merge under one display name.
References: packages/…/linkTemplate.ts• L3-74 packages/…/linkUrlBuilder.ts• L47-293 packages/…/seriesNameTemplate.ts• L3-171
Compatibility boundaries
The toolkit sits between product behavior, ClickHouse behavior, stored data, and external automation. Compatibility rules keep these boundaries from producing different meanings in different services.
Server and stored-data compatibility
ClickHouse version helpers decide whether a server supports an optional query or metadata path. Unknown or old versions use a supported fallback. Shared schemas accept current contracts while selected helpers read older forms.
Legacy color tokens resolve to current palette names. A shared dashboard walker lets app, API, import, and provisioning paths apply the same color migration without changing unrelated tile data. PromQL accepts both expression shapes. PromQL filter conditions stay separate from SQL and Lucene filter conditions. Dashboard filter state accepts both expression and variable addressing. Alert inputs can carry the old singular channel and the current plural channel, but both must agree when both are present.
Display settings also preserve old saved-chart behavior. An absent heatmap mode keeps distribution semantics. An absent line interpolation uses the display default. An unset series limit keeps the normal safety cap, while zero remains an explicit unlimited choice.
Optional log source expressions also preserve older source records. Severity number and event name mappings remain unset unless a source has matching columns, so existing log tables do not gain invalid default fields.
References: packages/…/clickhouseVersion.ts• L1-183 packages/…/types.ts• L1527-1676 packages/…/types.ts• L1711-1818 packages/…/types.ts• L1265-1349 packages/…/types.ts• L1445-1593 packages/…/types.ts• L2695-2749 packages/…/dashboardFilterValues.ts• L26-279
External source compatibility
External source conversion is the boundary between the internal source model and the v2 sources API. It validates source data, supplies the historical session timestamp field when older records omit it, and changes internal granularity names such as 5 minute to API values such as 5m.
The conversion is one-way for API output. It keeps source data JSON-safe and changes materialized-view granularity fields without changing the internal source contract. The inverse granularity mapping is available for callers that receive compact external values.
References: packages/…/externalSource.ts• L1-96
Cross-service contract changes
Shared types are part of the API contract. A schema or enum change can affect the dashboard editor, internal routes, external API validation, alert tasks, CLI charting, and generated API descriptions. Change the shared meaning first, then check every consumer that serializes or executes it.
The same rule applies to helpers. Formula eligibility, heatmap modes, filter state, variable expansion, template helpers, PromQL query shape, PromQL label injection, metadata key rendering, SQL conversion, and query attribution must produce the same answer in the app, API, background tasks, and automation surfaces.
The package build keeps runtime modules and type declarations as separate outputs. Source changes must therefore preserve both the runtime entry points and the declarations consumed by TypeScript callers. The build emits CommonJS and ESM bundles while excluding tests from both the runtime bundle and declaration build.
References: packages/…/types.ts• L187-188 packages/…/types.ts• L1242-1349 packages/…/types.ts• L1641-1776 packages/…/types.ts• L2695-2749 packages/…/utils.ts• L1588-1621 packages/…/variables.ts• L997-1047 packages/…/package.json• L48-62 packages/…/tsup.config.ts• L3-14 packages/…/tsconfig.build.json• L1-7
Change checklist
When these files or sections are changed, remember to consider these:
- When changing a chart, source, filter, variable, display setting, formula, or dashboard schema, check the matching API schema and generated API description. Stored data and external clients must still parse the same fields.
- When changing palette tokens, color rules, background trends, interpolation, heatmap modes, or series limits, keep editor defaults, legacy reads, render behavior, dashboard validation, and external schemas aligned.
- When changing categorical chart limits or ordering, keep the editor, server-side tile queries, explicit user order, default value order, alias quoting, and stable tie-breaking aligned.
- When changing timestamp expressions or bucket selection, preserve precision ordering, Date fallback behavior, metadata lookup failure handling, and the full timestamp expression used for filtering.
- When changing PromQL expressions, query modes, reducers, minimum granularity, macros, or label filters, keep legacy reads, blank-expression handling, queried-expression selection, matcher injection, range reduction, and chart display rules aligned.
- When changing metric rendering, formulas, ratios, sample weights, or top-series selection, keep the displayed ranking, missing-value behavior, aggregate semantics, and single-query result shape aligned.
- When changing dashboard filter state, preserve precedence between variable and expression entries, explicit empty selections, single-select behavior, date type conversion, and required-filter blocking.
- When changing variable scanning, keep comments, quoted strings, nested macro arguments, language-specific escaping, and the no-rescan rule aligned across SQL, Lucene, PromQL, and Markdown.
- When changing template helpers or webhook variables, keep validation, default bodies, delivery rendering, and the app's editor contract aligned. Unknown helpers must fail in the shared validation path.
- When changing metadata key rendering or ClickHouse type mapping, use the same physical expression for selected values and their constraints. Check JSON and map access, index paths, rollup probes, and distributed-table behavior.
- When changing SQL parameter construction or alias extraction, preserve identifier and value separation, parser fallbacks, select order, and the mapping from returned columns to chart series.
- When changing map key-value index rewrites, preserve the exact SQL literal text for escaped strings and JSON values. Keep empty-value bailouts, supported operators, and the ClickHouse version split between
hasAnyand chainedhascalls aligned with metadata lookup. - When changing query attribution or client retry behavior, keep client merge rules, query-log payloads, bounded values, query IDs, and retry identity aligned. Attribution must remain non-sensitive and must never make a query fail.
- When changing metadata discovery limits or lookup paths, preserve bounded reads, deterministic ordering, truncation signals, cache-key inputs, and fallbacks after permission or feature failures.
- When changing palette migration or portable dashboard conversion, keep ID-to-name remapping, legacy token handling, and unresolved-reference behavior aligned across import, export, and write paths.
- When adding or changing optional source field expressions, keep source schemas, source forms, API descriptions, query rendering, and behavior for older tables aligned. Do not introduce a default that makes absent columns look present.
- When changing external source conversion, keep compact granularity names, legacy session defaults, source validation, and JSON-safe output aligned with the v2 sources API.
- When changing ClickHouse numeric type helpers, preserve wrapper handling and keep integer-specific checks separate from the broader numeric classification used by charts.
- When changing package entry points or build settings, keep CommonJS, ESM, declaration output, path aliases, and test exclusion aligned so browser and server consumers receive the same public contract.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A heatmap has a mode and source combination that the renderer does not support | The tile can be accepted with no valid heatmap meaning | Shared mode and source guards keep chart validation and rendering aligned. |
| A raw SQL tile omits its time range or interval contract | The tile or alert can ignore the selected window or fail to form time buckets | Raw SQL validation checks time and interval macros against the display type. |
| A dashboard filter has no broadcast or variable effect | The control collects a value that no tile can use | Dashboard validation rejects filters with no effect. |
| A required filter is empty but the tile does not consume that filter path | A tile can block forever or load without a required selection | Blocking checks distinguish global requirements, variables, broadcasts, and query language. |
| A saved filter contains both old expression state and new variable state | The dashboard can show stale selections or rerun with the wrong value | Parsing gives the variable entry precedence and preserves explicit empty state. |
| A variable macro names a variable absent from the chart context | Query expansion cannot build a meaningful predicate | Expansion raises a typed unknown-variable error. |
| A template calls an unknown helper | Webhook or link output cannot be trusted to match the saved template | The restricted template environment rejects unknown helpers during validation or render. |
| A PromQL chart contains only blank expressions or starts a single-value chart with a blank expression | Prometheus receives an empty or unintended query | Series selection removes blank expressions and limits non-time-series charts to the first expression. |
| A PromQL expression cannot parse when a dashboard label filter must be added | The query fails rather than silently returning unfiltered data | Label injection parses the expression and raises an explicit filter-application error. |
| A PromQL range contains only non-finite samples | A missing value can appear as zero or poison a reduction | Reducers skip non-finite samples and return no value when none remain. |
| A logical JSON or map path is rendered differently in value lookup and filtering | The UI can show values from one field and filter another | Metadata shares one rendered physical expression for both paths. |
| A fast index read cannot prove that the requested time range is covered | Discovery can return values from outside the selected window | Metadata refuses the unprunable path and uses a range-aware fallback. |
| A metric-name page is capped without ordering or a truncation signal | A real metric can disappear without a clear reason | Name lookup orders results, reads one extra row, and reports truncated. |
| A pinned filter contains extra predicates that the sidebar cannot show | The UI and executed query describe different filters | Renderability checks require one complete round-trip facet. |
| A DateTime filter value is compared as a plain string | ClickHouse can reject the predicate or compare it with the wrong type | Filter rendering uses the target column's ClickHouse date type. |
A mixed ClickHouse Variant column is treated as numeric without checking all members | A chart can apply numeric behavior to a value with incompatible members | Type mapping marks only all-numeric variants as numeric and leaves mixed variants unclassified. |
| A wrapped ClickHouse integer is checked only as a plain type name | Integer-specific behavior can fail for nullable or low-cardinality columns | The integer guard removes supported wrappers before it checks the integer family. |
| Full SQL parsing fails on ClickHouse-only syntax while aliases are still needed | Returned columns can lose their chart-series mapping | Alias extraction retries with the outer projection and returns an empty map only when that also fails. |
| A map value contains escaped quotes or JSON text and the key-value rewrite decodes and re-escapes it | The indexed predicate can miss the row returned by the original map expression | The rewrite emits the parsed key and value literals in their original SQL form and integration tests compare results in ClickHouse. |
| A key-value filter uses an empty string, a non-string value, or an unsupported operator | The indexed predicate can change missing-key semantics or fail to match the original condition | The rewrite leaves the condition unchanged unless it is a supported equality or IN expression with non-empty string literals. |
| A package build includes tests or emits only one module format | A consumer can fail at import time or receive declarations that do not match runtime exports | The build config bundles source entry points as CommonJS and ESM and excludes test files from declarations. |
| An external link renders a relative or non-HTTP URL | Navigation can use the wrong origin or an unsafe scheme | Link validation allows only absolute HTTP and HTTPS URLs. |
| An older session source lacks its timestamp expression in the external source payload | Source validation rejects a source that the older system could query | External conversion adds the historical TimestampTime default before schema validation. |
| An internal granularity is sent to the external source API without conversion | The API receives a value outside its compact source contract | External conversion maps supported second, minute, hour, and day values to s, m, h, and d forms. |
| An optional log source expression points to a column missing from an older table | Log display or search can fail for a source that was valid before the field was added | Source contracts keep severity number and event name expressions optional and do not invent defaults. |
Key files
| File | Why to read it |
|---|---|
| packages/…/types.ts | Main contract for sources, chart configs, dashboards, filters, variables, alerts, formulas, display settings, palette migration, and compatibility helpers. |
| packages/…/guards.ts | Type and source guards for chart variants, source needs, and compatibility rules. |
| packages/…/heatmap.ts | Default heatmap mode for older saved tiles. |
| packages/…/index.ts | Shared ClickHouse SQL model, type mapping, client behavior, result handling, attribution, and chart execution boundary. |
| packages/…/renderChartConfig.ts | Central path from a chart definition to a ClickHouse query, including formulas, ratios, time filters, metric translation, series limits, and indexed map-filter rewrites. |
| packages/…/metadata.ts | Metadata boundary for tables, columns, JSON and map paths, indexes, rollups, field discovery, and metric-name lookup. |
| packages/…/utils.ts | Shared time, granularity, chart-shape, SQL parsing, dashboard portability, and validation helpers. |
| packages/…/externalSource.ts | External source validation, legacy session defaults, and compact granularity conversion for the sources API. |
| packages/…/queryParser.ts | Path from Lucene search text to metadata-aware ClickHouse predicates. |
| packages/…/macros.ts | Raw SQL and PromQL macro contracts, source checks, expansion, and dashboard filter application. |
| packages/…/promqlLabelInjection.ts | PromQL selector boundary that applies label matchers without changing unrelated expression text. |
| packages/…/variables.ts | Variable syntax, output formats, language-aware expansion, reference checks, and query dependency selection. |
| packages/…/filters.ts | Filter state conversion, date-aware predicates, pinned-filter checks, query parsing, ad hoc conditions, dashboard variable helpers, and saved-query validation. |
| packages/…/dashboardFilterValues.ts | Compatibility boundary for dashboard filter selections, deterministic serialization, and required-filter blocking. |
| packages/…/dashboardValidation.ts | Cross-field and cross-object dashboard checks. |
| packages/…/handlebarsEnv.ts | Restricted template environment, approved helper behavior, and early template error reporting. |
| packages/…/sqlFormatter.ts | ClickHouse SQL formatting for templates and diagnostics. |
| packages/…/promql.ts | PromQL expression selection, query modes, reducers, macros, and time steps. |
| packages/…/linkUrlBuilder.ts | Search, dashboard, and external link construction from row data. |
| packages/…/clickhouseVersion.ts | Server-version gates for optional ClickHouse capabilities. |
| packages/…/tsup.config.ts | Runtime bundle formats, source entry points, and test exclusion. |
| packages/…/tsconfig.build.json | Declaration-only build scope and test exclusion. |