Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

monitoring.ts

325 lines11.8 KB

1import * as Alchemy from "alchemy";
2import * as Axiom from "@alchemy.run/axiom";
3import * as Output from "alchemy/Output";
4import * as Effect from "effect/Effect";
5import * as Option from "effect/Option";
6​
7import { relayResourceNameForStage } from "../deploymentConfig.ts";
8import { notifierConfig } from "../monitoring.ts";
9import { isPreviewStage } from "../previewStages.ts";
10​
11const RUNBOOK_URL =
12 "https://github.com/pingdotgg/t3code/blob/main/docs/operations/05_relay-observability.md#mobile-crashes-and-errors";
13​
14// A new dataset has none of these fields until a report carries them, and an
15// unknown field fails the whole query, so every one has a default.
16const field = (name: string, fallback: string) => `column_ifexists('${name}', ${fallback})`;
17const reports = (dataset: string) =>
18 [
19 `['${dataset}']`,
20 `| extend source = tostring(${field("attributes.expo.error.source", "''")}),`,
21 ` fatal = tobool(${field("attributes.expo.error.is_fatal", "false")}),`,
22 ` js_fatal = tobool(${field("attributes.relay.crash.js_fatal", "false")}),`,
23 ` platform = tostring(${field("resource.os.name", "''")}),`,
24 ` install = tostring(${field("resource.expo.eas_client.id", "''")}),`,
25 ` error_type = tostring(${field("attributes.exception.type", "''")}),`,
26 ` message = substring(tostring(${field("attributes.exception.message", "''")}), 0, 140),`,
27 ` version = strcat(tostring(${field("service.version", "''")}), ' (', tostring(${field("resource.expo.app.build_number", "''")}), ')')`,
28 `| where isnotempty(source) and isnotempty(platform)`,
29 // A fatal JS error also ends in a native abort; counting both would double every JS crash.
30 // Android reports every OS kill (low memory, swiped away, background limits) as SIGKILL on next launch.
31 `| extend kind = case(source == 'nativeCrash' and js_fatal, 'abort after JS crash', source == 'nativeCrash' and platform == 'Android' and error_type == 'SIGKILL', 'OS kill', source == 'nativeCrash', 'native crash', fatal, 'JS crash', 'handled error')`,
32 ].join("\n");
33const crashes = (dataset: string) =>
34 `${reports(dataset)}\n| where kind in ('JS crash', 'native crash')`;
35const osKills = (dataset: string) => `${reports(dataset)}\n| where kind == 'OS kill'`;
36const handledErrors = (dataset: string) => `${reports(dataset)}\n| where kind == 'handled error'`;
37const ingest = (traces: string) =>
38 `['${traces}']\n| where name == 'relay.mobile_telemetry.ingest'\n| extend signal = tostring(['attributes.custom']['relay.mobile_telemetry.signal']), outcome = tostring(['attributes.custom']['relay.mobile_telemetry.outcome'])`;
39​
40type Severity = "page" | "warn";
41​
42interface Datasets {
43 readonly logs: string;
44 readonly traces: string;
46​
47interface MobileMonitor {
48 readonly id: string;
49 readonly severity: Severity;
50 readonly name: string;
51 /** Why it fires. The runbook link is appended. */
52 readonly description: string;
53 readonly query: (datasets: Datasets) => string;
54 readonly props: Pick<
55 Axiom.MonitorProps,
56 | "type"
57 | "operator"
58 | "threshold"
59 | "rangeMinutes"
60 | "intervalMinutes"
61 | "compareDays"
62 | "tolerance"
63 | "alertOnNoData"
64 | "triggerFromNRuns"
65 | "triggerAfterNPositiveResults"
66 >;
68​
69// No production baseline exists yet: the spike monitor learns its own, and the
70// thresholds below are starting points to tune after two weeks of data.
71const mobileMonitors: ReadonlyArray<MobileMonitor> = [
72 {
73 id: "MobileCrashSpikeMonitor",
74 severity: "page",
75 name: "T3 Code mobile: crash spike",
76 description:
77 "Crashes (JS and native, each counted once) per 15 min well above the same time over the last 7 days. Usually a bad OTA update or store build: compare app versions on the dashboard.",
78 query: ({ logs }) => `${crashes(logs)}\n| summarize crashes = count() by bin_auto(_time)`,
79 props: {
80 type: "AnomalyDetection",
81 operator: "Above",
82 compareDays: 7,
83 tolerance: 50,
84 rangeMinutes: 15,
85 intervalMinutes: 15,
86 },
87 },
88 {
89 id: "MobileCrashSpreadMonitor",
90 severity: "page",
91 name: "T3 Code mobile: one crash hitting many installs",
92 description:
93 "The most widespread crash reached this many installs in an hour. Its message and versions are at the top of the dashboard's Top crashes table.",
94 query: ({ logs }) =>
95 `${crashes(logs)}\n| summarize installs = dcount(install) by platform, error_type, message\n| summarize worst = max(installs)`,
96 props: {
97 type: "Threshold",
98 operator: "AboveOrEqual",
99 threshold: 25,
100 rangeMinutes: 60,
101 intervalMinutes: 15,
102 },
103 },
104 {
105 id: "MobileOsKillSpikeMonitor",
106 severity: "warn",
107 name: "T3 Code mobile: Android OS kills spike",
108 description:
109 "Android killing the app (low memory, freezes) per hour well above the same time over the last 7 days. Usually a release that leaks memory or blocks the main thread: compare app versions on the dashboard.",
110 query: ({ logs }) => `${osKills(logs)}\n| summarize kills = count() by bin_auto(_time)`,
111 props: {
112 type: "AnomalyDetection",
113 operator: "Above",
114 compareDays: 7,
115 tolerance: 50,
116 rangeMinutes: 60,
117 intervalMinutes: 60,
118 triggerAfterNPositiveResults: 2,
119 triggerFromNRuns: 2,
120 },
121 },
122 {
123 id: "MobileTelemetryStoppedMonitor",
124 severity: "warn",
125 name: "T3 Code mobile: reports stopped",
126 description:
127 "No startup metrics forwarded in an hour. Every launch sends some, so the relay route, the Axiom token, or the app's endpoint is broken, and crashes go unseen too.",
128 query: ({ traces }) =>
129 `${ingest(traces)}\n| where signal == 'metrics' and outcome == 'forwarded'\n| summarize forwarded = count()`,
130 props: {
131 type: "Threshold",
132 operator: "Below",
133 threshold: 1,
134 rangeMinutes: 60,
135 intervalMinutes: 15,
136 alertOnNoData: true,
137 triggerFromNRuns: 2,
138 },
139 },
140 {
141 id: "MobileSymbolicationFailingMonitor",
142 severity: "warn",
143 name: "T3 Code mobile: crash stacks not symbolicated",
144 description:
145 "Share of release JS exceptions over 6 h whose stack stayed minified. Map uploads are failing or the relay cannot read them; relay.symbolication.status says which.",
146 query: ({ logs }) =>
147 [
148 `['${logs}']`,
149 `| extend status = tostring(${field("attributes.relay.symbolication.status", "''")})`,
150 `| where isnotempty(status) and status !in ('no_bundle_id', 'no_bundle_frames')`,
151 `| summarize total = count(), minified = countif(status != 'symbolicated')`,
152 `| project minified_pct = iff(total >= 20, 100.0 * minified / total, 0.0)`,
153 ].join("\n"),
154 props: {
155 type: "Threshold",
156 operator: "Above",
157 threshold: 50,
158 rangeMinutes: 360,
159 intervalMinutes: 60,
160 },
161 },
162];
163​
164interface QueryChart {
165 readonly id: string;
166 readonly name: string;
167 readonly type: "TimeSeries" | "Table" | "Statistic";
168 readonly query: { readonly apl: string };
169 /** Grid columns out of 12. */
170 readonly width: 4 | 6 | 12;
172​
173const chart = (
174 type: QueryChart["type"],
175 width: QueryChart["width"],
176 id: string,
177 name: string,
178 apl: string,
179): QueryChart => ({ id, name, type, width, query: { apl } });
180​
181const mobileDashboardCharts = ({ logs, traces }: Datasets): ReadonlyArray<QueryChart> => [
182 chart("Statistic", 4, "crashes", "Crashes", `${crashes(logs)}\n| summarize count()`),
183 chart(
184 "Statistic",
185 4,
186 "crashed-installs",
187 "Installs that crashed",
188 `${crashes(logs)}\n| summarize dcount(install)`,
189 ),
190 chart(
191 "Statistic",
192 4,
193 "handled-errors",
194 "Handled errors",
195 `${handledErrors(logs)}\n| summarize count()`,
196 ),
197 chart(
198 "TimeSeries",
199 6,
200 "crashes-over-time",
201 "Crashes by platform",
202 `${crashes(logs)}\n| summarize count() by bin_auto(_time), series = strcat(platform, ' ', kind)`,
203 ),
204 chart(
205 "TimeSeries",
206 6,
207 "handled-over-time",
208 "Handled errors by platform",
209 `${handledErrors(logs)}\n| summarize count() by bin_auto(_time), platform`,
210 ),
211 chart(
212 "Table",
213 12,
214 "top-crashes",
215 "Top crashes",
216 `${crashes(logs)}\n| summarize installs = dcount(install), crashes = count(), first_seen = min(_time), last_seen = max(_time), versions = make_set(version, 3) by platform, kind, error_type, message\n| order by installs desc, crashes desc\n| take 15`,
217 ),
218 chart(
219 "Table",
220 12,
221 "top-handled",
222 "Top handled errors",
223 `${handledErrors(logs)}\n| summarize installs = dcount(install), errors = count(), last_seen = max(_time), versions = make_set(version, 3) by platform, error_type, message\n| order by installs desc, errors desc\n| take 15`,
224 ),
225 chart(
226 "Table",
227 6,
228 "by-version",
229 "Crashes by app version",
230 `${crashes(logs)}\n| summarize crashes = count(), installs = dcount(install) by platform, version\n| order by crashes desc\n| take 10`,
231 ),
232 chart(
233 "TimeSeries",
234 6,
235 "symbolication",
236 "JS stacks by symbolication outcome",
237 `['${logs}']\n| extend status = tostring(${field("attributes.relay.symbolication.status", "''")})\n| where isnotempty(status)\n| summarize count() by bin_auto(_time), status`,
238 ),
239 chart(
240 "TimeSeries",
241 12,
242 "os-kills",
243 "Android OS kills by app version",
244 `${osKills(logs)}\n| summarize count() by bin_auto(_time), version`,
245 ),
246 chart(
247 "TimeSeries",
248 12,
249 "ingest",
250 "Reports reaching the relay",
251 `${ingest(traces)}\n| summarize count() by bin_auto(_time), series = strcat(signal, ' ', outcome)`,
252 ),
253];
254​
255/** Lays charts left to right, wrapping at Axiom's 12-column grid. */
256function layout(charts: ReadonlyArray<QueryChart>) {
257 let x = 0;
258 let y = 0;
259 let rowHeight = 0;
260 return charts.map((chart) => {
261 const h = chart.type === "Statistic" ? 3 : 6;
262 if (x + chart.width > 12) {
263 x = 0;
264 y += rowHeight;
265 rowHeight = 0;
266 }
267 const cell = { i: chart.id, x, y, w: chart.width, h };
268 x += chart.width;
269 rowHeight = Math.max(rowHeight, h);
270 return cell;
271 });
273​
274/**
275 * Monitors follow the relay's: a deployment opts in by naming its paging notifier. The
276 * dashboard also comes up on PR previews, so a change to mobile telemetry can be checked
277 * there; the preview's teardown removes it.
278 */
279export const MobileMonitoring = Effect.fn("MobileMonitoring")(function* (
280 logs: Axiom.Dataset,
281 traces: Axiom.Dataset,
282) {
283 const { stage } = yield* Alchemy.Stack;
284 const page = yield* notifierConfig("RELAY_ALERT_NOTIFIER_ID");
285 if (Option.isNone(page) && !isPreviewStage(stage)) return;
286 const datasets = Output.map(Output.all(logs.name, traces.name), ([logs, traces]) => ({
287 logs,
288 traces,
289 }));
290​
291 if (Option.isSome(page)) {
292 const notifiers: Record<Severity, Option.Option<string>> = {
293 page,
294 warn: yield* notifierConfig("RELAY_WARNING_NOTIFIER_ID"),
295 };
296 for (const monitor of mobileMonitors) {
297 yield* Axiom.Monitor(monitor.id, {
298 ...monitor.props,
299 name: stage === "prod" ? monitor.name : `[${stage}] ${monitor.name}`,
300 description: `${monitor.description} Runbook: ${RUNBOOK_URL}`,
301 aplQuery: Output.map(datasets, monitor.query),
302 triggerFromNRuns: monitor.props.triggerFromNRuns ?? 1,
303 alertOnNoData: monitor.props.alertOnNoData ?? false,
304 notifierIds: Option.toArray(notifiers[monitor.severity]),
305 });
306 }
307 }
308​
309 yield* Axiom.Dashboard("MobileHealthDashboard", {
310 dashboard: Output.map(datasets, (names) => {
311 const charts = mobileDashboardCharts(names);
312 return {
313 name: relayResourceNameForStage("t3-code-mobile-health", stage),
314 owner: "X-AXIOM-EVERYONE",
315 description: `T3 Code mobile app crashes and errors. Crashes count JS and native once each. Runbook: ${RUNBOOK_URL}`,
316 refreshTime: 300,
317 schemaVersion: 2,
318 timeWindowStart: "qr-now-7d",
319 timeWindowEnd: "qr-now",
320 charts: charts.map(({ width: _width, ...chart }) => chart),
321 layout: layout(charts),
322 };
323 }),
324 });
325});