Skip to content
Open
Show file tree
Hide file tree
Changes from 38 commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
73efe53
feat(metrics-pipeline): generic Redis-stream to ClickHouse metrics pi…
ericallam Jul 2, 2026
7c7e9f0
feat(clickhouse): queue metrics tables and read queries
ericallam Jul 2, 2026
dbd725e
feat(run-engine): emit queue depth, throughput, and scheduling-delay …
ericallam Jul 2, 2026
761ebbe
feat(webapp): queue metrics ingestion, admin controls, and emission s…
ericallam Jul 2, 2026
a3d88c1
feat(tsql): opt-in gap-fill for time-bucketed series
ericallam Jul 2, 2026
e44e3ce
feat(webapp): Queues dashboard and per-org metrics UI flag
ericallam Jul 2, 2026
9036161
chore(webapp): add server-changes note for queue metrics
ericallam Jul 2, 2026
a9003c0
chore: apply oxfmt formatting
ericallam Jul 3, 2026
118a18d
chore: use import type for type-only imports
ericallam Jul 3, 2026
79660ad
fix(tsql): avoid polynomial backtracking in ORDER BY direction strip
ericallam Jul 3, 2026
83cb71d
fix(tsql): strip ORDER BY direction without a backtracking regex
ericallam Jul 3, 2026
f2f1921
fix(clickhouse): remove semicolons from queue metrics migration comments
ericallam Jul 3, 2026
f088d4a
test(clickhouse): rewrite queue metrics test for cumulative counters
ericallam Jul 3, 2026
24cdb36
fix(metrics-pipeline): use BigInt order keys and namespaced odometer …
ericallam Jul 3, 2026
28a0c91
fix(clickhouse): filter zero waits from quantile view and accept stri…
ericallam Jul 3, 2026
877519c
fix(webapp): fail open on queue metrics and honor sparkline total ove…
ericallam Jul 3, 2026
7a0f14e
test(run-engine): import describe from vitest in run-queue metrics test
ericallam Jul 3, 2026
a9ac17a
fix(tsql): skip gap-fill on descending bucket order
ericallam Jul 3, 2026
969cf88
fix(metrics-pipeline): widen order_key packing factor to 1e6
ericallam Jul 3, 2026
1f4249e
feat(webapp,clickhouse): standard time filter for queue metrics pages
ericallam Jul 4, 2026
a2ab1dc
fix(tsql): register the deltaSumTimestampMerge aggregate
ericallam Jul 4, 2026
3131fc5
chore(webapp): use shared primitives on the admin queue metrics page
ericallam Jul 4, 2026
aea59d9
feat(webapp): house style hero charts on the queues list
ericallam Jul 4, 2026
42139c2
feat(clickhouse): queue activity ranking queries
ericallam Jul 4, 2026
52ee876
feat(webapp): queue allocation view and relevance-ordered queue list
ericallam Jul 4, 2026
23ea178
fix(tsql): inject time fallbacks into FROM subqueries
ericallam Jul 4, 2026
0a2ce25
feat(clickhouse,tsql): queue metrics rollups and single-scan ranking
ericallam Jul 4, 2026
cde3fa0
feat(webapp): serve queue metrics reads from rollups and fix env totals
ericallam Jul 4, 2026
c29f8bd
feat(clickhouse,webapp): keep 10-second resolution on the env metrics…
ericallam Jul 4, 2026
3991214
fix(webapp): include rollup tables in the queue metrics simulator reset
ericallam Jul 4, 2026
3c59e8b
fix(webapp): update the queue metrics simulator for cumulative counters
ericallam Jul 4, 2026
fc40fa2
feat(webapp): stage fake Redis usage from the queue metrics simulator
ericallam Jul 4, 2026
5851eb7
fix(webapp): keep the search filter on the ranked queue list's tail
ericallam Jul 5, 2026
6ed899a
fix(metrics-pipeline): drop metric emits while the metrics Redis is n…
ericallam Jul 5, 2026
9750ceb
feat(webapp): remove auto-balance from the allocation view
ericallam Jul 5, 2026
e6ae16e
feat(tsql,webapp): reject cross-queue merges of per-queue counter states
ericallam Jul 5, 2026
cbe5444
refactor(clickhouse,webapp): use the stored quantile list in all merg…
ericallam Jul 5, 2026
5511df5
fix(tsql): satisfy the tenant column type in the merge guard test schema
ericallam Jul 5, 2026
f339c97
fix(clickhouse): dedup retried metric batches in the MV target tiers
ericallam Jul 5, 2026
b7f943d
fix(webapp,metrics-pipeline): review hardening for overflow counters,…
ericallam Jul 5, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .server-changes/queue-metrics-dashboard.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
area: webapp
type: feature
---

Queue metrics and health on the Queues page: per-queue depth, throughput, concurrency, throttling, and scheduling-delay charts, plus a per-queue detail view. Off by default; enabled per organization.
8 changes: 6 additions & 2 deletions apps/webapp/app/components/primitives/UsageSparkline.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ export type UsageSparklineProps = {
color?: string;
/** Unit shown in the tooltip (e.g. calls, tokens). */
unitLabel?: UnitLabel;
/** Trailing scalar shown after the chart. Defaults to the sum of buckets (override for gauges, e.g. peak). */
total?: number;
/** Format the trailing total. Defaults to `toLocaleString`. */
formatTotal?: (total: number) => string;
/** Class for the trailing total label. */
Expand All @@ -44,14 +46,16 @@ export function UsageSparkline({
bucketIntervalMs,
color = "#3B82F6",
unitLabel = { singular: "call", plural: "calls" },
total: totalOverride,
formatTotal,
totalClassName = "text-blue-400",
}: UsageSparklineProps) {
if (!data || data.every((v) => v === 0)) {
const hasTotalOverride = totalOverride !== undefined;
if (!data || data.length === 0 || (data.every((v) => v === 0) && !hasTotalOverride)) {
return <span className="text-text-dimmed">–</span>;
}

const total = data.reduce((a, b) => a + b, 0);
const total = totalOverride ?? data.reduce((a, b) => a + b, 0);
const max = Math.max(...data);

// Map each bucket to a dated point so the tooltip can show the window it
Expand Down
2 changes: 1 addition & 1 deletion apps/webapp/app/components/primitives/charts/Chart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ const ChartTooltipContent = React.forwardRef<
)}
<div
className={cn(
"flex flex-1 justify-between leading-none",
"flex flex-1 justify-between gap-3 leading-none",
nestLabel ? "items-end" : "items-center"
)}
>
Expand Down
53 changes: 52 additions & 1 deletion apps/webapp/app/components/primitives/charts/ChartLine.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
CartesianGrid,
Line,
LineChart,
ReferenceLine,
XAxis,
YAxis,
type XAxisProps,
Expand Down Expand Up @@ -48,12 +49,38 @@ export type ChartLineRendererProps = {
tooltipLabelFormatter?: (label: string, payload: any[]) => string;
/** Optional formatter for numeric tooltip values (e.g. bytes, duration) */
tooltipValueFormatter?: (value: number) => string;
/** Draw a dot at each data point. Defaults to true; turn off for dense/compact charts. */
showDots?: boolean;
/** Horizontal reference lines (e.g. limits); the y-domain extends to include them. */
referenceLines?: Array<{ y: number; label?: string; color?: string }>;
/** Width injected by ResponsiveContainer */
width?: number;
/** Height injected by ResponsiveContainer */
height?: number;
};

/** Reference-line label: right-aligned just below the line (recharts injects viewBox). */
function ReferenceLineLabel({
viewBox,
value,
}: {
viewBox?: { x: number; y: number; width: number };
value: string;
}) {
if (!viewBox) return null;
return (
<text
x={viewBox.x + viewBox.width - 4}
y={viewBox.y + 12}
textAnchor="end"
fill="#878C99"
fontSize={10}
>
{value}
</text>
);
}

/**
* Line chart renderer for the compound component system.
* Must be used within a Chart.Root.
Expand All @@ -73,6 +100,8 @@ export function ChartLineRenderer({
stacked = false,
tooltipLabelFormatter,
tooltipValueFormatter,
showDots = true,
referenceLines,
width,
height,
}: ChartLineRendererProps) {
Expand Down Expand Up @@ -176,6 +205,17 @@ export function ChartLineRenderer({
labelFormatter={tooltipLabelFormatter}
/>
{/* Note: Legend is now rendered by ChartRoot outside the chart container */}
{referenceLines?.map((line) => (
<ReferenceLine
key={`ref-${line.y}-${line.label ?? ""}`}
y={line.y}
stroke={line.color ?? "#4D525B"}
strokeDasharray="4 4"
strokeWidth={1}
ifOverflow="extendDomain"
label={line.label ? <ReferenceLineLabel value={line.label} /> : undefined}
/>
))}
{visibleSeries.map((key) => (
<Area
key={key}
Expand Down Expand Up @@ -222,14 +262,25 @@ export function ChartLineRenderer({
labelFormatter={tooltipLabelFormatter}
/>
{/* Note: Legend is now rendered by ChartRoot outside the chart container */}
{referenceLines?.map((line) => (
<ReferenceLine
key={`ref-${line.y}-${line.label ?? ""}`}
y={line.y}
stroke={line.color ?? "#4D525B"}
strokeDasharray="4 4"
strokeWidth={1}
ifOverflow="extendDomain"
label={line.label ? <ReferenceLineLabel value={line.label} /> : undefined}
/>
))}
{visibleSeries.map((key) => (
<Line
key={key}
dataKey={key}
type={lineType}
stroke={config[key]?.color}
strokeWidth={1}
dot={{ r: 1.5, fill: config[key]?.color, strokeWidth: 0 }}
dot={showDots ? { r: 1.5, fill: config[key]?.color, strokeWidth: 0 } : false}
activeDot={{ r: 4 }}
isAnimationActive={false}
/>
Expand Down
3 changes: 3 additions & 0 deletions apps/webapp/app/entry.server.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import * as Worker from "~/services/worker.server";
import { initMollifierDrainerWorker } from "~/v3/mollifierDrainerWorker.server";
import { initMollifierStaleSweepWorker } from "~/v3/mollifierStaleSweepWorker.server";
import { initBillingLimitWorker } from "~/v3/billingLimitWorker.server";
import { initQueueMetricsConsumer, initQueueMetricsEmitter } from "~/v3/queueMetrics.server";
import { bootstrap } from "./bootstrap";
import { LocaleContextProvider } from "./components/primitives/LocaleProvider";
import type { OperatingSystemPlatform } from "./components/primitives/OperatingSystemProvider";
Expand Down Expand Up @@ -234,6 +235,8 @@ Worker.init().catch((error) => {
initMollifierDrainerWorker();
initMollifierStaleSweepWorker();
initBillingLimitWorker();
initQueueMetricsEmitter();
initQueueMetricsConsumer();

bootstrap().catch((error) => {
logError(error);
Expand Down
22 changes: 22 additions & 0 deletions apps/webapp/app/env.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -883,6 +883,28 @@ const EnvironmentSchema = z
RUN_ENGINE_REUSE_SNAPSHOT_COUNT: z.coerce.number().int().default(0),
RUN_ENGINE_MAXIMUM_ENV_COUNT: z.coerce.number().int().optional(),
RUN_ENGINE_RUN_QUEUE_SHARD_COUNT: z.coerce.number().int().default(4),
// Queue metrics ingestion (Redis Stream -> ClickHouse). The runtime on/off is the
// `queue_metrics:enabled` Redis key; these gate emitter construction + consumer boot.
QUEUE_METRICS_EMIT_ENABLED: z.string().default("0"),
QUEUE_METRICS_CONSUMER_ENABLED: z.string().default("0"),
QUEUE_METRICS_STREAM_SHARD_COUNT: z.coerce.number().int().default(4),
QUEUE_METRICS_CONSUMER_BATCH_SIZE: z.coerce.number().int().default(1000),
// Counter stream (exact counts, loss-intolerant). Unset host => the run-queue Redis;
// set it to a dedicated instance so counter backlog never competes with the run queue.
QUEUE_METRICS_REDIS_HOST: z.string().optional(),
QUEUE_METRICS_REDIS_PORT: z.coerce.number().optional(),
QUEUE_METRICS_REDIS_USERNAME: z.string().optional(),
QUEUE_METRICS_REDIS_PASSWORD: z.string().optional(),
QUEUE_METRICS_REDIS_TLS_DISABLED: z.string().default(process.env.REDIS_TLS_DISABLED ?? "false"),
QUEUE_METRICS_COUNTER_STREAM_MAXLEN: z.coerce.number().int().default(8_000_000),
// TTL (seconds) on the per-(queue,op) cumulative odometer key, refreshed on every write.
// Idle-past-TTL queues purge and self-heal (restart from 1) on return; default 7 days.
QUEUE_METRICS_COUNTER_ODOMETER_TTL_SECONDS: z.coerce.number().int().default(604_800),
// Per-env distinct queue_name cap (0 = unlimited); overflow maps to "__overflow__".
QUEUE_METRICS_MAX_QUEUE_NAMES_PER_ENV: z.coerce.number().int().default(1000),
// Fraction (0..1) of ops that emit a gauge; counters are never sampled. Dial below 1
// only if EngineCPU is too high in slow-path-heavy regions (hurts low-traffic queues).
QUEUE_METRICS_GAUGE_SAMPLE_RATE: z.coerce.number().min(0).max(1).default(1),
RUN_ENGINE_WORKER_SHUTDOWN_TIMEOUT_MS: z.coerce.number().int().default(60_000),
RUN_ENGINE_RETRY_WARM_START_THRESHOLD_MS: z.coerce.number().int().default(30_000),
RUN_ENGINE_PROCESS_WORKER_QUEUE_DEBOUNCE_MS: z.coerce.number().int().default(200),
Expand Down
109 changes: 109 additions & 0 deletions apps/webapp/app/hooks/useMetricResourceQuery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useInterval } from "./useInterval";

export type MetricResourceRow = Record<string, number | string | null>;

type MetricResourceResponse =
| { success: true; data: { rows: MetricResourceRow[] } }
| { success: false; error: string };

export type MetricResourceTimeRange = {
period: string | null;
from: string | null;
to: string | null;
};

export type MetricResourceQueryOptions = {
organizationId: string;
projectId: string;
environmentId: string;
timeRange: MetricResourceTimeRange;
defaultPeriod: string;
queues?: string[];
fillGaps?: boolean;
refreshIntervalMs?: number;
};

/**
* Client-fetch a TRQL query from the metric resource route (like the dashboard
* widgets): own loading state, interval + on-focus refresh, abort on change/unmount.
*/
export function useMetricResourceQuery(query: string, opts: MetricResourceQueryOptions) {
const [rows, setRows] = useState<MetricResourceRow[] | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [failed, setFailed] = useState(false);
const abortRef = useRef<AbortController | null>(null);

const {
organizationId,
projectId,
environmentId,
defaultPeriod,
fillGaps,
refreshIntervalMs = 60_000,
} = opts;
const { period, from, to } = opts.timeRange;
const queuesKey = opts.queues && opts.queues.length > 0 ? opts.queues.join(",") : undefined;
Comment thread
coderabbitai[bot] marked this conversation as resolved.

const load = useCallback(() => {
abortRef.current?.abort();
const controller = new AbortController();
abortRef.current = controller;
setIsLoading(true);
fetch("/resources/metric", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
query,
scope: "environment",
period: period ?? (from || to ? null : defaultPeriod),
from,
to,
fillGaps: !!fillGaps,
organizationId,
projectId,
environmentId,
...(queuesKey !== undefined ? { queues: queuesKey.split(",") } : {}),
}),
signal: controller.signal,
})
.then((res) => res.json() as Promise<MetricResourceResponse>)
.then((data) => {
if (controller.signal.aborted) return;
if (data.success) {
setRows(data.data.rows);
setFailed(false);
} else {
setFailed(true);
}
setIsLoading(false);
})
.catch((error) => {
if (error instanceof DOMException && error.name === "AbortError") return;
if (!controller.signal.aborted) {
setFailed(true);
setIsLoading(false);
}
});
}, [
query,
period,
from,
to,
defaultPeriod,
fillGaps,
organizationId,
projectId,
environmentId,
queuesKey,
]);

useEffect(() => {
load();
return () => abortRef.current?.abort();
}, [load]);

useInterval({ interval: refreshIntervalMs, onLoad: false, onFocus: true, callback: load });

return { rows: rows ?? [], isLoading, showLoading: isLoading && !rows, failed };
}
Loading