API services and background tasks
The API application is the control plane for HyperDX. It accepts product and automation requests, keeps team-owned configuration in MongoDB, reads telemetry through ClickHouse or Prometheus-compatible connections, manages collectors through OpAMP, and runs work that must continue outside a request. See observability platform architecture for the wider system, telemetry ingestion and storage for the data path, deployment topology for runtime placement, external interfaces and automation for automation clients, and identity, teams, and configuration for team-owned settings.
API application
The API application presents one Express request surface for the web product and external clients. It connects those requests to team-scoped domain actions while keeping product state and telemetry queries in their proper systems.
Server entrypoints
The normal server starts a main API listener and a separate OpAMP listener for supervised OpenTelemetry Collectors. It checks token-encryption support before database work, waits for MongoDB with retry, runs startup migrations, and can create local-mode defaults. Liveness can report before MongoDB is ready, but readiness stays unavailable until the database connection is usable. A serverless entrypoint reuses the same Express application with a warm MongoDB connection, but does not start OpAMP or recurring task timers.
flowchart LR
Process[API process] --> Main[Main HTTP server]
Process --> OpAMP[OpAMP HTTP server]
Main --> Express[Express application]
OpAMP --> OpAMPApp[OpAMP application]
Express --> Mongo[(MongoDB)]
OpAMPApp --> Mongo
Function[Serverless function] --> Express
References: packages/…/index.ts• L1-45 packages/…/server.ts• L51-121 packages/…/serverless.ts• L1-95 packages/…/index.ts• L55-137
Request pipeline
The request pipeline prepares a common service boundary before route work starts. It handles body formats, sessions, cross-origin rules, compression, and request logging. Browser requests use a session. External API and MCP requests use a bearer access key. Local mode supplies a local user and team for single-container use.
Validation stays at the route boundary. Controllers then apply team ownership checks and carry out domain actions. Final error handling returns safe client errors and records unexpected failures for operations.
References: packages/…/api-app.ts• L25-140 packages/…/auth.ts• L82-165 packages/…/error.ts• L42-114 packages/…/passport.ts• L10-58
Router groups
Routers divide the API by audience and product area. Internal product routes normally use session authentication. The versioned external v2 surface reports its version and user identity at its root, then exposes resource routers for alerts, charts, connections, dashboards, sources, saved searches, search, webhooks, and team operations. Every external resource group uses bearer access-key validation and the shared per-key rate limit before controller work starts.
| Route group | Product role |
|---|---|
/ | Health, readiness, login, registration, installation, and team joining |
/me, /team | User, team, access-key, onboarding, member, invitation, and tag actions |
/connections, /sources | Team-owned telemetry destinations and signal descriptions |
/dashboards, /saved-search, /favorites, /pinned-filters | Saved investigation and visualization state |
/alerts, /webhooks | Alert rules, evaluation views, state changes, and notification targets |
/clickhouse-proxy | Protected browser access to a selected ClickHouse connection |
/ai | Natural-language chart and search configuration |
/iac, /mcp, /v1/prometheus | Specialized automation and Prometheus-compatible interfaces |
/api/v2 | Versioned access-key API for alerts, charts, connections, dashboards, sources, saved searches, search, webhooks, and team operations |
The /sources interface manages the signal descriptions that connect product queries to telemetry tables. It lists, creates, updates, and deletes team-owned sources. Requests validate the source kind and its kind-specific fields, then validate that the chosen connection belongs to the same team. Source updates replace the current kind-specific shape, so fields from an old kind do not remain when a source changes kind. The source model supports logs, traces, sessions, metrics, and PromQL. PromQL sources can read ClickHouse time-series data or a Prometheus-compatible connection, and external source creation or update requires the PromQL feature to be enabled. Metric sources can map metric kinds to separate tables.
The MCP source tools give automation clients a staged discovery and management path. clickstack_list_sources returns a light catalog. clickstack_describe_source adds table details and a source configuration that can be sent back to clickstack_save_source. Its schema discovery has a 30-second deadline and a short backstop. If sampling stops after the schema loads, the result keeps completed data and marks the missing stages as partial instead of waiting without a bound. If the schema itself does not load, the tool returns a timeout error. Metric sources can expose metric names and kinds, including exponential histograms; summary metrics remain discoverable but direct query guidance points to SQL. Results stay team-scoped and report partial discovery failures instead of presenting incomplete data as an empty result.
References: packages/…/api-app.ts• L91-138 packages/…/index.ts• L1-19 packages/…/index.ts• L16-76 packages/…/sources.ts• L19-128 packages/…/sources.ts• L24-127 packages/…/sources-crud.int.test.ts• L288-335 packages/…/index.ts• L1-19 packages/…/schemas.ts• L6-261 packages/…/listSources.ts• L218-345 packages/…/describeSource.ts• L73-85 packages/…/saveSource.ts• L25-72 packages/…/listMetrics.ts• L248-315 packages/…/describeMetric.ts• L494-746 packages/…/sources.int.test.ts• L86-210 packages/…/sources.int.test.ts• L107-141 packages/…/sources.int.test.ts• L446-505 packages/…/sources.int.test.ts• L920-947
External dashboard and search contracts
The external v2 dashboard and search routes give automation clients a team-scoped way to manage saved views and retrieve raw telemetry rows. The dashboard contract separates the wire shape from the stored shape so clients can create, validate, read, update, and delete dashboards without knowing the internal document format.
Dashboard validation checks source and connection ownership, filter references, link targets, supported source kinds, formulas, heatmaps, and container or tab references before persistence. The /validate route runs the same checks without saving and returns either normalized input or structured errors for plan-time clients. Reads normalize legacy or malformed data so a missing container reference, stale aggregation field, or unsupported PromQL tile does not silently change into a different chart during a round trip. PromQL tiles now have an explicit external variant for supported chart types, including heatmaps. They use a PromQL source and are available only when the feature is enabled. Unsupported stored forms are not silently converted into another chart.
The search route turns a source and time window into a bounded ClickHouse search. Clients can choose Lucene or SQL row filters and selected expressions. The route rejects semicolons and subqueries in selected expressions, applies source-aware ordering when the client does not provide one, and maps source or connection failures to stable client errors. Results include rows only, not a total match count, and support bounded offset paging.
This flow shows how an external client moves from a saved dashboard or source definition to a safe product response.
flowchart LR
Client[External client] --> Dashboard[Dashboard validation or CRUD]
Client --> Search[Raw search request]
Dashboard --> Scope[Team and reference checks]
Scope --> Mongo[(MongoDB dashboard state)]
Search --> Source[Team-owned source]
Source --> Query[Bounded ClickHouse query]
Mongo --> DashboardResponse[External dashboard shape]
Query --> SearchResponse[Rows and safe errors]
References: packages/…/dashboards.ts• L2558-2809 packages/…/dashboards.ts• L2949-3010 packages/…/dashboards.ts• L3158-3281 packages/…/dashboards.ts• L3325-3347 packages/…/dashboards.ts• L161-224 packages/…/dashboards.ts• L668-729 packages/…/dashboards.ts• L1424-1599 packages/…/dashboards.ts• L1706-1728 packages/…/search.ts• L160-247 packages/…/search.ts• L368-457 packages/…/search.ts• L81-171 packages/…/dashboards.int.test.ts• L226-367 packages/…/dashboards.int.test.ts• L875-965 packages/…/dashboards.ts• L1511-1950 packages/…/dashboards.ts• L242-330 packages/…/dashboards.ts• L433-435 packages/…/dashboards.ts• L920-1230 packages/…/dashboards.ts• L1706-1728 packages/…/dashboards.ts• L1424-1599 packages/…/dashboards.test.ts• L345-648
MCP dashboard automation
MCP dashboard tools let an automation client discover source schemas, create or replace dashboards, query saved tiles, and link summary rows to search, another dashboard, or an external HTTP service. Builder tiles cover common aggregations. Raw SQL remains an option for questions that the builder cannot express.
The dashboard contract keeps filters, formulas, metric annotations, and per-series display rules aligned with the renderer. It rejects unsupported tile-level filters for aggregation tiles, and clients must query every tile after saving because schema validity does not prove that a source query will run.
References: packages/…/content.ts• L16-31 packages/…/content.ts• L55-75 packages/…/schemas.ts• L217-347 packages/…/schemas.ts• L397-600 packages/…/schemas.ts• L1069-1167
MCP tool observability
MCP tool calls use one traced boundary for the full handler. That boundary records the tool, caller, client, duration, query attribution, and error category so operators can connect a slow or failed tool to its request and downstream ClickHouse work. A tool error carries its message into the trace without allowing an oversized response to dominate the span.
References: packages/…/tracing.ts• L52-64 packages/…/tracing.ts• L76-139 packages/…/tracing.ts• L140-160
MCP trace investigations
The trace MCP tools answer two related questions. clickstack_trace_top_time_consuming_operations ranks child operations across many traces that match a parent operation. clickstack_trace_waterfall returns one concrete trace as a parent-child tree and can include logs linked by trace and span identity.
The aggregate tool finds where cumulative time goes in slow requests. The waterfall tool inspects one example after the aggregate result identifies a suspicious operation. Both use the selected trace source and its configured field expressions, and both cap work or report incomplete results instead of presenting partial data as an empty result.
flowchart LR
Question[Trace investigation] --> Aggregate[Many matching traces]
Aggregate --> Ranking[Rank child operations by total time]
Ranking --> Waterfall[Inspect one concrete trace]
Waterfall --> Logs[Correlate linked logs]
References: packages/…/breakdown.ts• L57-267 packages/…/breakdownSchema.ts• L3-110 packages/…/shared.ts• L13-67 packages/…/waterfall.ts• L303-347 packages/…/waterfall.ts• L500-666 packages/…/waterfall.ts• L668-803
Infrastructure-as-code manifest
The IaC manifest gives automation clients a small team-scoped view of resources that they can import or manage. It lists dashboards, alerts, saved searches, sources, connections, and webhooks without returning full product documents.
The manifest uses a fixed per-resource limit and a request time budget. It marks or omits resources that cannot survive an import round trip, such as machine-managed dashboards, unsupported source kinds, or tile alerts that the external tool cannot address. Truncation and omitted resources remain visible through metrics so a partial export is not mistaken for a complete inventory.
References: packages/…/iac.ts• L22-73 packages/…/iac.ts• L97-151 packages/…/iac.ts• L153-277
Domain and persistence services
The API stores control-plane state in MongoDB. Controllers connect HTTP actions to that state and enforce relationships that a single document cannot enforce. Most records belong to a team, so the team is part of the read, write, and reference checks.
Controller services
Controllers turn product actions into domain operations. They preserve links between dashboards, saved searches, sources, connections, alerts, and webhooks instead of treating each request as an isolated document write.
Dashboard changes synchronize tile alerts with the current set of tiles. A dashboard read also resolves alert display fields and repairs legacy chart color tokens at the API boundary. Dashboard and alert writes record onboarding progress only when the product action represents a usable dashboard or alert.
Saved-search deletion removes its dependent alerts before removing the search, then performs a best-effort second sweep for a concurrent alert create. Alert creation accepts three query origins: a saved search, a dashboard tile, or an inline chart configuration. Each origin must be valid for the team and for the alert types the worker can evaluate.
Inline raw SQL alerts use the selected connection and may use a source only when that source belongs to the same connection. Builder alerts allow formulas only for source kinds that the evaluator supports. Alert updates preserve omitted schedule fields, clear stale range bounds, and keep a canonical multi-channel list with a first-channel mirror for older readers.
Alert list work is separate from alert rule validation. It applies team, creator, tag, source, state, and name filters before it walks pages. The response resolves names and tags from the saved search or dashboard when older records do not store those display fields. A single-alert response can include the full inline chart configuration, while list rows use only the references needed to render them.
References: packages/…/dashboard.ts• L32-66 packages/…/dashboard.ts• L84-131 packages/…/dashboard.ts• L150-276 packages/…/alerts.ts• L60-237 packages/…/alerts.ts• L241-379 packages/…/alerts.ts• L417-553 packages/…/alertsPage.ts• L67-169 packages/…/alerts.ts• L41-123 packages/…/alertsPage.test.ts• L19-226 packages/…/alerts.int.test.ts• L139-211 packages/…/alertsPagination.int.test.ts• L92-147 packages/…/alertsPagination.int.test.ts• L233-374
Webhook management
Webhook management gives internal product routes and external v2 clients one team-scoped lifecycle for alert destinations. The shared controller validates and persists webhook creation, replacement, and deletion while each router applies its own authentication and response contract.
External clients can list webhooks with stable offset pagination, validate a configuration without saving it, and create, replace, or delete a stored destination. Read responses do not expose write-only headers or query parameters. Updates replace readable fields, preserve omitted secret fields when the destination is unchanged, and clear those fields when the URL or service changes. A concurrent destination change returns a conflict instead of applying a stale update. Deletion is blocked while an alert still refers to the webhook.
The internal route masks the URL path and secret map values while preserving their keys. A later update or test can reuse masked values only for the stored destination. A destination change rejects masked secrets and clears omitted secret maps, so stored secrets cannot move to a new URL or service. The internal route also lets operators test a destination with the same enriched alert fields used during delivery. Its response masks stored URL paths and secret values, so a client can keep a configured destination without reading its credentials back.
References: packages/…/webhook.ts• L19-144 packages/…/webhooks.ts• L43-75 packages/…/webhooks.ts• L134-223 packages/…/webhooks.ts• L225-405 packages/…/webhooks.ts• L407-521 packages/…/webhooks.ts• L332-360 packages/…/webhooks.ts• L527-562 packages/…/webhooks.ts• L604-841 packages/…/webhooks.int.test.ts• L75-1010
Persistent models
MongoDB is the durable store for identity, team settings, telemetry connections, query definitions, dashboards, alert state, and delivery targets. These records coordinate the web application, external API, OpAMP service, and background tasks.
| Model area | Durable purpose |
|---|---|
| Users and teams | Identity, membership, access keys, onboarding state, collector keys, team query settings, and collector policy |
| Connections and sources | How a team reaches telemetry and how each signal is interpreted |
| Saved searches and dashboards | Reusable query definitions, chart layouts, filters, and view state |
| Alerts and alert history | Rules, schedules, state, evaluation values, errors, diagnostics, and retention-limited history |
| Webhooks and invitations | Notification destinations and pending team membership actions |
Users have one personal access key and a small onboarding record. Onboarding writes are safe for local synthetic users and do not delay the product write that caused them. Alert history stores both evaluation results and useful timing data, such as query time, delivery time, backfilled windows, and per-target delivery results. History expires after about 30 days and has indexes for recent alert and group views.
Dashboards retain both user view state and a server-owned provisioning marker. Their filters can support query values, static choices, Prometheus labels, and selection requirements. Sources use one shared team and connection identity with kind-specific descriptions for logs, traces, sessions, metrics, and PromQL. Source metric-table and metadata subdocuments do not add unstable nested identifiers to API responses.
Alerts can use one or more webhook channels. The canonical channel list remains compatible with older single-channel records. Alert state distinguishes normal, firing, pending, disabled, insufficient-data, and failed evaluation outcomes. Failed evaluation history does not count as a completed window, so the task can retry it. Alert display names and tags can be stored on the alert or derived from its referenced resource for older records. The alert model supports both unpaged team lists and the name-ordered pages used by the alerts surface.
References: packages/…/index.ts• L21-137 packages/…/user.ts• L12-71 packages/…/dashboard.ts• L7-65 packages/…/source.ts• L18-134 packages/…/source.ts• L136-304 packages/…/alert.ts• L13-134 packages/…/alert.ts• L138-309 packages/…/alertHistory.ts• L17-139 packages/…/webhook.ts• L17-78 packages/…/user.ts• L10-95 packages/…/dashboard.int.test.ts• L82-155 packages/…/sources.int.test.ts• L386-526 packages/…/sources.int.test.ts• L1174-1339
Team records
Team records hold the settings that bind product state to a customer boundary. They include access and collector policy, ClickHouse query settings, and feature choices such as the metrics series table. Local app mode uses a fixed in-process team so the same API routes can serve a single-container installation.
The team service builds the set of tags shown to a team by combining tags from dashboards, saved searches, and alerts. The team API can return all of those tags or limit the result to one resource type, while keeping the result inside the caller's team.
References: packages/…/team.ts• L16-123 packages/…/team.ts• L126-167 packages/…/team.ts• L110-137 packages/…/team.ts• L312-333 packages/…/team.int.test.ts• L55-157
Team scope
Team scope is the main isolation rule in the API. Authenticated context supplies a team, and controller queries include that team when they load or change shared product records.
The rule also applies across references. A source cannot use another team's connection. An alert cannot use another team's dashboard, source, saved search, or webhook. A Prometheus or ClickHouse request cannot resolve a connection outside the caller's team.
References: packages/…/auth.ts• L153-165 packages/…/alerts.ts• L73-231 packages/…/connection.ts• L24-35 packages/…/prometheus.ts• L465-497 packages/…/helpers.ts• L463-487 packages/…/sources.int.test.ts• L131-210 packages/…/webhooks.int.test.ts• L1380-1403 packages/…/alertsPagination.int.test.ts• L407-413
ClickHouse access
ClickHouse is the analytics store for telemetry and the API's main query target. MongoDB stores the connection details and team ownership. The API-level client gives server-side work one query boundary while shared query rules remain in the shared domain and query toolkit.
Query client
Server-side chart work creates a ClickHouse client from a team-owned connection. Alert evaluation, usage reporting, AI metadata lookup, and other services use this boundary to query telemetry without treating ClickHouse as a configuration store.
The AI service selects a configured Anthropic or OpenAI-compatible model and can read source metadata and sample values before it builds a chart configuration. The assistant accepts a natural-language request for a team-owned source, gives the model source fields and example values, then converts the structured result into the platform's chart format. Provider selection supports Anthropic and OpenAI, with optional custom endpoints and OpenAI request headers; a legacy Anthropic key remains supported.
MCP query tools use the same connection boundary, apply a short execution ceiling and request deadline, check metric fields against the source kind, and return bounded results with hints for common query failures. MCP metric discovery uses the same connection boundary after it confirms that the source is a metric source owned by the team. It reads metric names from the source's metric tables and can return units or descriptions when the table provides them. It keeps each query and the whole discovery request within fixed time and result limits.
References: packages/…/clickhouse.ts• L1-26 packages/…/usageStats.ts• L57-127 packages/…/default.ts• L682-700 packages/…/ai.ts• L45-162 packages/…/ai.ts• L248-352 packages/…/ai.ts• L25-133 packages/…/ai.test.ts• L61-257 packages/…/ai.test.ts• L259-297 packages/…/helpers.ts• L74-99 packages/…/helpers.ts• L320-378 packages/…/helpers.ts• L400-684 packages/…/listMetrics.ts• L138-231 packages/…/listMetrics.ts• L302-461
Trace query access
Trace investigations use source-configured expressions to find trace, span, parent, service, operation, duration, and status values. A shared trace access layer keeps connection lookup, time filtering, duration conversion, and ClickHouse safety settings consistent across aggregate and waterfall queries.
The aggregate path selects matching parent trace IDs, then ranks child operations by cumulative time. The waterfall path selects or receives one trace ID, bounds the fetch to the trace extent, and returns a readable tree with optional linked logs. Both paths cap work and report incomplete or truncated results instead of presenting them as complete.
References: packages/…/shared.ts• L13-67 packages/…/breakdown.ts• L102-221 packages/…/waterfall.ts• L500-666 packages/…/waterfall.ts• L668-803
Prometheus-compatible query access
The /v1/prometheus surface gives clients one Prometheus-shaped contract across two backends. A Prometheus-compatible connection forwards supported requests to its configured service. A ClickHouse connection prefers its Prometheus HTTP handler when the server supports it. Older servers use ClickHouse time-series table functions as a fallback. Both paths return the same vector, matrix, and label shapes.
The surface supports range queries, instant queries, exemplars, label names, and label values. It accepts standard GET and POST query forms where the endpoint supports both. It bounds query time, result size, resolution, and exemplar windows. Label lookups can narrow results by time range and series selectors when the ClickHouse time-series table supports the required bounds. ClickHouse-backed exemplar requests return an empty result because metric chart queries obtain those exemplars from metric data directly.
The proxy keeps connection-owned path and query settings while allowing normal Prometheus request parameters to define the query. It returns safe Prometheus-shaped errors and does not expose connection credentials in those errors. Upstream bodies are streamed through the API with a JSON content type so a member-configured endpoint cannot make the browser treat a response as active content.
Browser requests can carry dashboard or search attribution so the resulting ClickHouse query can be tied to the product view that caused it. The API accepts the browser's surface and resource identifiers, but replaces the route label and trace identity with values from the server request context. This keeps query logs useful without allowing a client to claim a trace that did not run.
flowchart LR
Client[Prometheus client] --> API[/v1/prometheus]
API --> Select{Connection backend}
Select -->|Prometheus-compatible| Upstream[Prometheus service]
Select -->|ClickHouse HTTP handler| HTTP[ClickHouse Prometheus API]
Select -->|Older or unconfigured ClickHouse| Query[ClickHouse time-series query]
Upstream --> Shape[Prometheus response]
HTTP --> Shape
Query --> Shape
Shape --> Client
References: packages/…/prometheus.ts• L61-81 packages/…/prometheus.ts• L136-219 packages/…/prometheus.ts• L234-435 packages/…/prometheus.ts• L461-579 packages/…/prometheus.ts• L588-692 packages/…/prometheus.ts• L724-832 packages/…/prometheus.ts• L918-1055 packages/…/timeseriesEngine.ts• L15-25 packages/…/timeseriesEngine.ts• L37-255 packages/…/timeseriesEngine.ts• L257-408 packages/…/timeseriesEngine.test.ts• L6-47 packages/…/prometheus.test.ts• L20-261 packages/…/prometheus.int.test.ts• L704-809 packages/…/prometheus.int.test.ts• L1019-1070 packages/…/queryAttribution.int.test.ts• L114-249
ClickHouse proxy
The /clickhouse-proxy route lets an authenticated browser use a team-selected ClickHouse connection without exposing its credentials. The connection test accepts only HTTP or HTTPS hosts, rejects private IP targets, uses a short timeout, and returns safe connection errors. Query forwarding accepts only GET and POST requests, resolves the connection inside the caller's team, sanitizes the forwarded path, adds connection credentials server-side, and records proxy outcomes separately because proxy errors are handled locally.
References: packages/…/api-app.ts• L106-112 packages/…/clickhouseProxy.ts• L18-24 packages/…/clickhouseProxy.ts• L36-79 packages/…/clickhouseProxy.ts• L86-161 packages/…/clickhouseProxy.ts• L165-237 packages/…/clickhouseProxy.ts• L267-327
OpAMP integration
OpAMP is the management link between HyperDX and supervised OpenTelemetry Collectors. A collector reports status to the API. The API keeps the latest process-local agent view and can return a remote collector configuration built from team settings.
Agent management
The OpAMP listener accepts protobuf messages at /v1/opamp. It tracks an agent by instance UID and exposes current status such as health, capabilities, sequence state, effective configuration, and remote-configuration results. The agent view is not a durable inventory. A process restart clears it until the collector reports again.
References: packages/…/app.ts• L7-44 packages/…/opampController.ts• L413-562 packages/…/agentService.ts• L31-147 packages/…/agent.ts• L34-92
Remote collector configuration
When a collector supports remote configuration, the API combines the team's collector keys and authentication policy into a configuration response. The collector applies that response and sends telemetry through the ingestion path. An opt-in Datadog intake can use the same collector pipelines.
This creates a control-plane loop: team settings define access, OpAMP distributes the collector view, and the collector sends logs, traces, metrics, and sessions toward storage. See telemetry ingestion and storage for the downstream path.
sequenceDiagram
participant Collector
participant OpAMP as OpAMP service
participant Mongo as MongoDB
participant Storage as Telemetry storage
Collector->>OpAMP: Agent status
OpAMP->>Mongo: Save latest agent view
OpAMP->>Mongo: Read team keys and policy
OpAMP-->>Collector: Remote configuration
Collector->>Storage: Send telemetry
References: packages/…/opampController.ts• L175-410 packages/…/opampController.ts• L417-639 packages/…/README.md• L1-11
Scheduled task execution
The task runner handles work that must run without a browser request. It validates task input, creates the selected task, runs it with tracing and metrics, records the result, and releases task resources. In-process mode repeats work on a UTC schedule without overlapping a prior run. External scheduling mode runs one task and exits.
Task lifecycle
The runner supports alert checks, dashboard provisioning, and a simple ping-pong task. Each run records duration and outcome. An uncaught process error causes the task process to exit so an external supervisor can retry or replace it.
flowchart TD
Args[Task arguments] --> Validate[Validate task and options]
Validate --> Select[Create task]
Select --> Run[Execute task]
Run --> Outcome{Outcome}
Outcome -->|success| Success[Record success]
Outcome -->|failure| Failure[Record failure]
Success --> Dispose[Release resources]
Failure --> Dispose
Dispose --> Mode{Execution mode}
Mode -->|in-process| Wait[Wait for next UTC run]
Mode -->|external scheduler| Exit[Exit with result]
References: packages/…/types.ts• L3-107 packages/…/index.ts• L20-105 packages/…/metrics.ts• L12-69
Alert evaluation
The alert task turns persisted rules into ClickHouse evaluations. It loads the query context for saved-search, dashboard-tile, or inline alerts, groups work by connection, evaluates completed time windows, compares values with thresholds, and stores state and history.
The task aligns windows by interval, a schedule start, or an offset. It can backfill missed windows, track groups separately, and wait for several consecutive violating windows before firing. A query or processing failure records an error without marking the window complete. A later run can therefore retry the same window. Evaluation history also records query time, notification time, backfilled windows, and per-target delivery timing so slow parts of the alert path remain visible.
This flow turns a stored rule into a state change and an optional notification.
flowchart LR
Rule[Stored alert rule] --> Context[Load query context and history]
Context --> Batch[Group by connection]
Batch --> Query[Evaluate completed windows]
Query --> Compare[Compare values and groups]
Compare --> State[Store state and evaluation history]
State --> Notify[Render and deliver firing or recovery notices]
Alert sources support saved searches, dashboard tiles, and detached inline chart configurations. Builder charts can use supported line, stacked-bar, and number forms. Raw SQL alerts use the display types that the evaluator can interpret. PromQL chart configurations are not evaluated as alerts.
References: packages/…/alerts.ts• L75-236 packages/…/index.ts• L1044-1269 packages/…/index.ts• L1436-1761 packages/…/index.ts• L1842-2002 packages/…/index.ts• L2004-2188 packages/…/alert.ts• L72-134 packages/…/alerts.int.test.ts• L139-173 packages/…/alerts.int.test.ts• L1444-1531
Notification rendering
Notification rendering converts alert context into a title, body, link, and structured delivery message. It can include the query result for saved-search alerts and exposes stable fields such as status, comparator, threshold, value, group, group values, source query, team, and note to generic webhook templates.
Configured channels are resolved first. Message mentions can add webhook targets by ID or name prefix. Duplicate targets are sent once. A maximum of 20 targets is allowed for one event, while configured channels keep priority over message mentions. Remaining targets are dispatched concurrently. Missing targets, unsupported mentions, cap skips, render failures, and delivery failures stay attached to the alert execution result.
The message contract carries raw numeric values as well as safe string values. It also identifies the alert source, comparator, query text, team, note, tags, group key, and group values. Group values are available by column name for receiver-side routing. Query text is bounded before it enters a webhook body, and range alerts carry an upper bound only when their comparator uses one. Test sends use the same enriched fields as real alert events so a receiver can validate its template before an alert fires.
References: packages/…/template.ts• L180-258 packages/…/template.ts• L291-337 packages/…/template.ts• L414-518 packages/…/template.ts• L607-768 packages/…/template.ts• L770-881 packages/…/template.ts• L948-1016 packages/…/types.ts• L7-52 packages/…/generic.ts• L74-111 packages/…/renderAlertTemplate.int.test.ts• L475-725
Webhook delivery
Generic and incident webhook delivery turns the structured alert message into a user-defined JSON body and sends it to a validated destination. When a body is not set, it uses the default shape for the selected service. Each attempt has a configurable timeout with a 30-second fallback, retries get fresh timeout budgets, redirects are disallowed, and an idempotency key helps receivers reduce duplicate effects in the at-least-once delivery model.
The template contract supports alert identity, state, source type, condition, value, group, source query, team, note, tags, and both Unix and ISO time values. String values are escaped for JSON while numeric values remain usable in JSON number fields. Invalid templates, timeouts, redirects, and non-success responses fail the target without hiding the result of other targets.
Webhook configuration can be tested from the API with the same message fields used during a real firing. Stored secrets remain masked in responses. The API restores them only when the request still points to the stored destination. A destination change requires new secret values.
References: packages/…/generic.ts• L73-153 packages/…/generic.ts• L173-285 packages/…/generic.test.ts• L38-201 packages/…/generic.test.ts• L204-295 packages/…/types.ts• L7-52 packages/…/webhooks.ts• L43-117 packages/…/webhooks.ts• L225-374 packages/…/webhooks.ts• L407-521 packages/…/webhooks.int.test.ts• L777-1217 packages/…/webhooks.int.test.ts• L1220-1361
Dashboard provisioning
The dashboard task imports dashboard definitions for one team or all teams. It validates definitions and updates only machine-managed dashboards. User-created dashboards remain separate. The request API removes the server-owned machine marker so a normal user update cannot hand a dashboard to the provisioner.
References: packages/…/index.ts• L18-190 packages/…/dashboards.ts• L99-123 packages/…/dashboards.ts• L137-216
Usage reporting
When enabled, the long-lived API starts a four-hour usage report timer. The report combines high-level instance data, host facts, and ClickHouse usage before sending an aggregate to the configured usage service. Serverless mode does not start this timer.
References: packages/…/api-app.ts• L82-87 packages/…/usageStats.ts• L130-187 packages/…/serverless.ts• L20-23
Change checklist
When these files or sections are changed, remember to consider these:
- Changes to the external v2 router must preserve its version probe, resource paths, per-access-key rate limit, and access-key validation on every resource group.
- Changes to external dashboard conversion must preserve GET-to-validate-to-PUT round trips, builder, Raw SQL, and PromQL chart variants, legacy reference healing, metric select fields, stale aggregation fields, palette normalization, and the three states of series limits.
- Changes to external dashboard validation must keep source and connection ownership, container and tab references, heatmap and formula source gates, filter source rules, link-out targets, and PromQL feature gating aligned across create, update, validate, and MCP save paths.
- Changes to the external dashboard
/validatecontract must keep normalized defaults and structured error paths separate from persistence and must preserve the same validation rules as create and update. - Changes to external dashboard update behavior must account for the lack of optimistic concurrency control and for alert cleanup after tile changes.
- Changes to external search must preserve source-scoped ordering, Lucene and SQL filter handling, selected-expression restrictions, result bounds, offset behavior, and safe ClickHouse error mapping.
- Changes to source kinds or source fields must stay aligned across the common source contract, Express validation, Mongoose discriminators, kind changes, MCP flattening, MCP round-trip output, and metric discovery guidance.
- Changes to source connection or team handling must preserve same-team connection checks in both HTTP and MCP paths, including local app mode.
- Changes to source feature gates must preserve the rule that PromQL sources are rejected on disabled deployments while other source kinds remain available.
- Changes to source nested data must preserve stable response shapes. In particular, embedded configuration must not gain transient identifiers that change response bodies or ETags.
- Changes to metric discovery must preserve the split between discoverable metric kinds and queryable metric kinds, the representative table choice, partial-failure signals, and the next-step guidance for SQL.
- Changes to dashboard MCP schemas or prompts must preserve the split between builder and raw SQL tiles, per-series filters, filter variables, source-aware metric fields, and post-save tile validation.
- Changes to time-series label filters must preserve backend selection, native-handler fallback, Prometheus response shape, bounds, selectors, and ClickHouse table capabilities.
- Changes to trace MCP tools or source expressions must preserve the aggregate-versus-waterfall distinction, duration conversion, bounded time windows, parent filters, trace caps, linked logs, and partial-result notes.
- Changes to alert sources, chart limits, schedules, comparators, or channels must stay aligned across route validation, durable alert records, task loading, query evaluation, message rendering, and delivery.
- Changes to alert schedule starts or offsets must preserve the same window calculation for due checks, backfill ranges, consecutive-window history, and alert evaluation.
- Changes to inline raw SQL alert references must preserve the same-team and same-connection rule between the chart connection and optional source.
- Changes to alert history states or analytics must preserve the rule that failed windows do not count as evaluated windows. This affects retry, backfill, consecutive-window firing, and evaluation views.
- Changes to alert display names, tags, or list sorting must stay aligned across derived response fields, stored-field filters, cursor encoding, the
_idtie-break, and the alert list index. - Changes to dashboard tiles or saved-search deletion must preserve dependent alert cleanup, display-field derivation, color-token normalization, and the team ownership boundary.
- Changes to dashboard filters, colors, source kinds, or source-specific fields must stay aligned across request validation, response normalization, kind changes, JSON import, external API conversion, and scheduled provisioning.
- Changes to AI provider or source metadata handling must preserve provider and key checks, custom endpoint and header parsing, team-owned connection lookup, field discovery, telemetry attribution, and chart configuration mapping.
- Changes to team settings must preserve local app behavior and the link between collector policy, ClickHouse settings, and downstream queries.
- Changes to user access keys or onboarding state must preserve session ownership, immediate key revocation, local synthetic-user behavior, and fire-and-forget onboarding writes.
- Changes to the IaC manifest must preserve its per-type cap, time budget, truncation signal, and rules for withholding resources that cannot round-trip.
- Changes to MCP source discovery must preserve the schema-first deadline, backstop snapshot, partial-result and skipped-stage signals, metric-kind guidance, source ownership check, and whole-operation timeout.
- Changes to MCP tracing must preserve query attribution, caller and client identity, duration and error metrics, bounded span messages, and the distinction between returned tool errors and thrown failures.
- Changes to webhook message fields must update the shared delivery message, test payloads, generic template variables, and receiver-facing contracts together. Preserve bounded source-query text, comparator-gated range bounds, group-value variables, tag forms, and JSON-safe optional values.
- Changes to webhook lifecycle routes must preserve shared team scope, service-and-name uniqueness, external pagination and validation results, write-only secret handling, destination-change clearing, concurrent-update conflicts, and the alert-reference delete guard.
- Changes to internal webhook redaction must preserve masked URL and map values, same-destination secret reuse, destination or service change clearing, and the enriched test payload.
- Changes to webhook destination or secret handling must preserve masking, same-destination secret reuse, destination-change clearing, redirect blocking, and the per-attempt delivery timeout and retry contract.
- Changes to the ClickHouse proxy must preserve HTTP/HTTPS and non-private-host checks for connection tests, encoded-path sanitization, team-scoped connection lookup, credential injection, user attribution settings, and locally recorded proxy outcomes.
- Changes to Prometheus proxy parameter merging must keep caller-settable Prometheus parameters separate from connection-pinned tenant parameters and must keep secrets out of error bodies.
- Changes to Prometheus request attribution must preserve browser surface and resource identifiers while keeping the server-owned route label and trace identity in ClickHouse query logs.
- Changes to team collector keys or authentication policy must update both OpAMP remote configuration and the collector ingestion path. See telemetry ingestion and storage.
- Changes to task names or execution modes must stay aligned with scheduler commands, run metrics, resource disposal, and serverless startup.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| MongoDB is not ready after process start | Liveness can work while API and OpAMP traffic cannot be served | Readiness reports failure until connection succeeds, and the long-lived server retries the first connection |
| Request has no valid session or bearer key | The route returns 401 before domain work runs | Authentication is applied at router boundaries |
| External v2 client exceeds its per-key request limit | The resource request is throttled before controller work runs | Each external v2 resource group uses the shared access-key rate limiter |
| External dashboard read returns a stale container or tab reference | A client cannot send the returned dashboard back through validation | Read conversion drops orphan or empty references and validation checks effective containers |
| External dashboard contains a stale aggregation field | GET output fails the next PUT or import plan | Conversion removes fields that the selected aggregation cannot use |
| External dashboard contains an unsupported or disabled PromQL tile | The client cannot query or safely round-trip the tile | PromQL variants declare their source and feature requirements, and unsupported stored forms are not silently downgraded |
| PromQL source is created or updated while the feature is disabled | The source cannot be queried by the deployment | External source writes reject PromQL with a clear 400 response before persistence |
| Dashboard validation rules differ between plan and apply | An IaC client can pass validation but fail during create or update | The validate route and write routes call the shared tile and reference validator |
| Concurrent external dashboard PUTs edit the same document | One update can silently overwrite the other and leave stale tile references | Clients must serialize edits; the route has no optimistic concurrency control |
| Dashboard request references a wrong team source or connection | The dashboard could query data outside its team | Validation loads references through the team boundary and checks source-to-connection agreement |
| Dashboard uses a heatmap or formula with an unsupported source kind | The saved tile cannot render or can bypass the editor's source rules | Create and changed-tile validation applies source-kind gates |
| Search request contains a subquery or semicolon in selected expressions | Client input could expand the intended row query | The external search schema rejects those expressions before ClickHouse work |
| Search source or connection is missing | The client receives a stable not-found result instead of a query | Search resolves both records inside the caller's team before creating the client |
| Search query returns an unsafe or unexpected ClickHouse error | Internal details could leak or a client could misread a server failure | User query errors map to 400 and other ClickHouse failures use a safe 500 message |
| Referenced connection or product record belongs to another team | The request could read or query data outside its team | Team scope is included in record lookups and cross-record validation |
| Source update changes kind but leaves old kind fields | A source can describe the wrong telemetry shape or expose stale metric tables | Source updates replace kind-specific data and tests check that old fields are removed |
| Source request names a connection outside the team | The source could read telemetry through another team's connection | HTTP and MCP paths validate the connection against the caller's team |
| Source configuration is accepted by request validation but missing from the model | The field disappears on write without a clear client error | Source contracts and discriminator persistence are checked by round-trip tests |
| Source response contains a generated nested identifier | Equivalent reads have different bodies and ETags | Nested configuration schemas disable generated identifiers and MCP output strips stored ones |
| MCP metric discovery fails for one metric kind | Results can be incomplete even when other kinds succeed | The response names partial failures and gives the client a retry or narrowing hint |
| Summary metrics are treated as queryable builder metrics | Automation receives a query path that cannot render the metric | Discovery keeps summary data visible but directs queries to clickstack_sql |
| Dashboard builder select fields do not match the source kind | The renderer can produce a query against the wrong metric shape | MCP validation rejects metric annotations on non-metric sources and requires them on metric sources |
| MCP query exceeds its execution or request limit | The tool fails or returns a bounded result instead of completing | Fixed ClickHouse settings, request timeout, result trimming, and error hints bound the work |
| Trace breakdown scans a wide window or too many parent traces | The aggregate query can time out before it ranks child operations | The tool caps parent traces and top results and reports a shorter-window recovery path |
| Trace waterfall exceeds its span or fetch-window cap | The returned tree may omit spans or early parts of a long trace | The response reports span truncation or a clamped fetch window |
| Trace waterfall cannot resolve its linked log source | The trace result has no correlated logs | The response keeps the trace and reports the log-source or connection problem |
| AI provider, key, model, or header configuration is invalid | Natural-language chart generation cannot start or cannot call the intended endpoint | Provider, key, model, endpoint, and JSON header requirements are checked before model creation |
| ClickHouse time-series tags lack bounds while a selector is requested | Label lookup cannot answer the requested series filter | The API rejects match[] for tables without the required time bounds |
| ClickHouse lacks the Prometheus HTTP handler | Native proxying is unavailable, but supported queries can still use the fallback table functions | The API checks the server version and handler before selecting the fallback |
| MCP source discovery reaches its deadline after schema loading | The client receives a usable but incomplete description instead of an unbounded wait | Abortable sampling, a backstop snapshot, partial, and skippedStages expose the missing discovery work |
| MCP source discovery cannot load the column schema before the backstop | The tool returns a timeout error without schema details | The deadline path distinguishes a snapshot from a failure before the schema stage |
| An MCP tool returns an error result or throws | Operators may miss the cause or confuse a user error with a server failure | The tracing boundary records bounded status text, error category, duration, and separate returned-error or exception metrics |
| ClickHouse proxy test receives a non-HTTP host or private IP | The API could make a server-side request to an unsafe target | The test route allows only HTTP or HTTPS and rejects private IP addresses before fetch |
| ClickHouse proxy path contains encoded query delimiters or a host injection | The browser proxy could forward a request outside the intended ClickHouse path | Recursive decoding, URL parsing, and host checks constrain the rewritten path |
| Alert query fails or times out | Alert state does not advance and the window remains eligible for retry | The task stores an error history row that scheduling ignores |
| Alert schedule start is in the future or its window is not complete | The task can create a false firing from data that is not due | The evaluator skips future starts and incomplete anchored windows |
| Alert changes from a range comparator without clearing its upper bound | Messages or clients can report a range that the alert no longer uses | Alert updates unset the range bound for single-bound comparators, and rendering gates it by comparator |
| Alert references a deleted webhook | That target is skipped and the execution reports a notification failure | Targets are resolved at delivery time and failures are kept per target |
| One alert event has too many configured or mentioned targets | Some notifications are not sent | Duplicate targets are removed, configured channels run first, and a bounded fan-out cap records skipped targets |
| Webhook destination redirects or does not respond | Delivery fails instead of following an unsafe redirect or holding the task forever | URL validation, manual redirect handling, per-attempt timeout, and retry protect delivery |
| Webhook update changes destination while retaining masked secrets | Stored secrets could be sent to a new destination | The API rejects masked secrets on destination changes and clears omitted secret maps |
| Webhook update races with another destination change | The client could apply a stale replacement or attach fields to the wrong destination | The shared update uses the snapshotted destination as a write condition and returns 409 on a conflict |
| A persisted webhook cannot match the external response schema | A create or update succeeds in storage but the client cannot treat the response as a normal resource | The API logs only safe identifiers, increments a serialization metric, and returns the persisted ID with a 500 |
| An external webhook row is malformed during list pagination | meta.total can exceed the number of returned resources | The list reports the stored count and omits records that cannot pass the external schema |
| Prometheus connection has an invalid or unsafe host | The request fails before any upstream call or returns a safe upstream error | Host schemes are checked, path prefixes are joined safely, and error messages omit credentials and query secrets |
| Connection-pinned Prometheus parameter is treated as caller-settable | A request could widen or change the connection's intended scope | Only the bounded Prometheus parameter set can replace host query values |
| Browser attribution supplies a client trace or route label | ClickHouse query logs could claim a request or trace that did not run the query | The router keeps browser surface and IDs but removes client trace and label values before query execution |
| Serverless entrypoint starts a recurring task or OpAMP listener | The function can stay alive or expose an unsupported long-lived service | Serverless startup only loads the API application and reuses its database connection |
Key files
| File | Why to read it |
|---|---|
| packages/…/server.ts | Shows the long-lived API and OpAMP server lifecycle |
| packages/…/serverless.ts | Shows the serverless API boundary and its limits |
| packages/…/api-app.ts | Shows middleware order and route boundaries |
| packages/…/auth.ts | Shows session, access-key, local-mode, and team context rules |
| packages/…/index.ts | Shows the versioned external API resource groups and their shared access controls |
| packages/…/dashboards.ts | Shows external dashboard CRUD, plan-time validation, normalization, and team-scoped persistence |
| packages/…/dashboards.ts | Shows dashboard wire conversion, round-trip healing, reference checks, and source-kind gates |
| packages/…/search.ts | Shows the external raw-search contract, bounds, and safe error mapping |
| packages/…/search.ts | Shows source lookup, ordering, ClickHouse query setup, and result bounds |
| packages/…/sources.ts | Shows source CRUD, request validation, and connection ownership checks |
| packages/…/sources.ts | Shows external source conversion, granularity mapping, and PromQL feature gating |
| packages/…/sources.ts | Shows source persistence, kind changes, and team-scoped source operations |
| packages/…/source.ts | Shows durable source kinds, metric table mappings, and query settings |
| packages/…/ai.ts | Shows AI provider selection, source metadata lookup, and chart configuration mapping |
| packages/…/ai.ts | Shows the natural-language assistant request and telemetry boundary |
| packages/…/ai.test.ts | Shows supported AI provider and model configuration guarantees |
| packages/…/content.ts | Shows the automation workflow for source discovery, dashboard design, and tile validation |
| packages/…/schemas.ts | Shows the MCP contract for tiles, filters, formulas, metric fields, and row-click links |
| packages/…/helpers.ts | Shows MCP query limits, source-kind checks, result handling, and error hints |
| packages/…/tracing.ts | Shows the shared MCP tracing, query attribution, metrics, and error boundary |
| packages/…/shared.ts | Shows common trace client, time filter, duration, and ClickHouse safety rules |
| packages/…/breakdown.ts | Shows aggregate child-operation ranking across matching traces |
| packages/…/breakdownSchema.ts | Shows the trace breakdown input contract and investigation guidance |
| packages/…/waterfall.ts | Shows single-trace selection, tree construction, fetch bounds, and linked logs |
| packages/…/describeSourceTimeout.test.ts | Shows the deadline contract for complete, partial, backstop, and timeout outcomes |
| packages/…/alerts.ts | Shows alert source validation, schedule normalization, channel persistence, and ownership rules |
| packages/…/alertsPage.ts | Shows alert list filters, derived display fields, and cursor paging |
| packages/…/alert.ts | Shows durable alert sources, state, schedules, channels, and list indexes |
| packages/…/alertHistory.ts | Shows evaluation history retention, indexes, errors, and timing data |
| packages/…/webhook.ts | Shows shared webhook creation, replacement, deletion, ownership, and alert-reference guards |
| packages/…/webhooks.ts | Shows internal webhook CRUD, secret masking, validation, and test delivery |
| packages/…/webhooks.ts | Shows external webhook pagination, plan-time validation, response shaping, and lifecycle errors |
| packages/…/clickhouseProxy.ts | Shows protected ClickHouse connection tests, path checks, browser forwarding, and proxy outcomes |
| packages/…/prometheus.ts | Shows backend selection, safe proxying, and Prometheus-compatible response handling |
| packages/…/timeseriesEngine.ts | Shows ClickHouse label lookup, PromQL fallback, and time-series limits |
| packages/…/opampController.ts | Shows collector status and remote configuration exchange |
| packages/…/index.ts | Shows task selection, scheduling modes, and run instrumentation |
| packages/…/index.ts | Shows alert windows, state changes, retries, diagnostics, and task execution |
| packages/…/template.ts | Shows alert message context, enriched fields, and notification target handling |
| packages/…/generic.ts | Shows generic webhook rendering, timeout, retry, and redirect rules |
| packages/…/types.ts | Shows the shared alert message and transport contracts |
| packages/…/index.ts | Shows machine-managed dashboard synchronization |