返回 CodeWhale
schema.ts
根目录 / telemetry-ingest / src / schema.ts
1 /**
2 * The published Codewhale telemetry schema, transcribed from `docs/TELEMETRY.md`
3 * and enforced as a **closed** field set.
4 *
5 * The doc is the promise; this file is the enforcement. `test/schema-doc.test.ts`
6 * parses the field names and enum spellings back out of `docs/TELEMETRY.md` and
7 * asserts set equality against the constants below, so a doc that grows a field
8 * this validator does not know — or a validator that grows a field the doc does
9 * not publish — fails the build rather than quietly accepting new data.
10 *
11 * Why closed rather than "ignore what we don't recognise": a future client bug
12 * that starts attaching a path, a prompt, or a provider table name must be
13 * refused by the server, not stored. Unknown key anywhere in the batch rejects
14 * the whole batch. There is no sanitising path — a payload the schema cannot
15 * account for is not made safe by editing it, which is the same rule
16 * `Event::is_bounded` applies on the client's drain path.
17 */
18
19 /** `SCHEMA_VERSION` in `crates/telemetry/src/event.rs`. */
20 export const SCHEMA_VERSION = 4;
21
22 /** Notice-v5 batches without `model_usage`, `tool_usage` or the `ci` source. */
23 export const V3_SCHEMA_VERSION = 3;
24
25 export const V6_SCHEMA_VERSION = 6;
26
27 export const FUNNEL_SCHEMA_VERSION = 5;
28 export const FUNNEL_NOTICE_VERSION = 7;
29 export const FUNNEL_COUNTER_FIELDS = [
30 "home_view", "install_view", "quickstart_view", "contribute_view",
31 "install_intent", "install_confirmed", "star_exit", "issue_exit",
32 "help_wanted_exit", "guide_exit", "docs_search", "docs_search_empty",
33 "docs_search_result", "quickstart_confirmed",
34 ] as const;
35
36 /** Disclosed default-on policy, not a record of human acceptance. */
37 export const NOTICE_VERSION = 6;
38
39 export const V6_NOTICE_VERSION = 8;
40
41 /** The notice version schema v3 batches carry. */
42 export const V3_NOTICE_VERSION = 5;
43
44 export const CONSENT_VERSION = 4;
45
46 /** `BATCH_MAX_EVENTS` in `crates/telemetry/src/actor.rs`. */
47 export const BATCH_MAX_EVENTS = 200;
48
49 /** `BATCH_MAX_BYTES` in `crates/telemetry/src/actor.rs` — the event budget. */
50 export const BATCH_MAX_BYTES = 64 * 1024;
51
52 /**
53 * Hard body cap, computed rather than guessed.
54 *
55 * The client assembles at most `BATCH_MAX_EVENTS` (200) buffered lines totalling
56 * at most `BATCH_MAX_BYTES` (65536) bytes — `actor::parse_events` breaks
57 * *before* appending a line that would cross either bound, so both are ceilings,
58 * and the batch is re-serialized by the same `serde` impl that wrote the lines,
59 * so the event bytes on the wire equal the bytes on disk. On top of that the
60 * envelope costs:
61 *
62 * - ~200 bytes of fixed keys and JSON punctuation,
63 * - ~175 bytes of envelope values (`sent_at` 20, `install_id` 36,
64 * `app_version` <= 64, `git_sha` 12, and four short enums),
65 * - 199 commas between the 200 events.
66 *
67 * 65536 + 200 + 175 + 199 = 66110 bytes is therefore the true maximum a
68 * conforming client can send. 72 KiB leaves ~11% headroom for a future envelope
69 * field without leaving room for a payload that is a different shape entirely.
70 *
71 * The disk rings (`buffer::MAX_EVENTS` = 512, `buffer::MAX_BYTES` = 256 KiB) are
72 * larger, but they are the *storage* cap: a 512-record ring drains as three
73 * batches, never as one 256 KiB POST.
74 */
75 export const MAX_BODY_BYTES = 72 * 1024;
76
77 /**
78 * Server-side length ceiling for the two version strings.
79 *
80 * `docs/TELEMETRY.md` pins their *shape*
81 * (`^\d+\.\d+\.\d+(-[0-9A-Za-z.]+)?$`) but not their length — a pre-release
82 * suffix is unbounded in the published regex. INFERRED, not published: 64 bytes
83 * is far past any real Cargo version and stops the one envelope field with an
84 * open tail from becoming a free-form string slot.
85 */
86 export const MAX_VERSION_LEN = 64;
87
88 /**
89 * Server-side length ceiling for a reduced panic site. INFERRED: the published
90 * rule is a charset, not a length. Real sites are well under 120 bytes.
91 */
92 export const MAX_PANIC_SITE_LEN = 256;
93
94 /**
95 * Server-side cardinality ceiling for `providers`. INFERRED: the published rule
96 * closes the *value* space via `ProviderKind::as_str()`, not the array length.
97 */
98 export const MAX_PROVIDERS = 32;
99
100 // ------------------------------------------------------------- enum spellings
101
102 /** `Surface::as_str` — the surface that produced the batch. */
103 export const SURFACES = [
104 "tui",
105 "exec",
106 "cli",
107 "app-server",
108 "mcp-server",
109 "serve",
110 "website",
111 "web-app",
112 "desktop",
113 "control-plane",
114 // A VS Code-family extension client: deliberately generic, the way "web-app"
115 // and "desktop" are. The editor's own name and version are not collected.
116 // Appended, never inserted: `LEGACY_SURFACES` below is `slice(0, 6)`, and v1
117 // must keep refusing every surface that was not in the runtime whitelist.
118 "vscode-extension",
119 ] as const;
120
121 const LEGACY_SURFACES = SURFACES.slice(0, 6);
122
123 /** `Os::as_str`. */
124 export const OSES = [
125 "linux",
126 "macos",
127 "windows",
128 "freebsd",
129 "android",
130 "other",
131 ] as const;
132
133 /** `Arch::as_str`. */
134 export const ARCHES = ["x86_64", "aarch64", "other"] as const;
135
136 /** `Libc::as_str`. */
137 export const LIBCS = ["gnu", "musl", "none"] as const;
138
139 /** `InstallKind::as_str`. */
140 export const INSTALL_KINDS = ["install", "upgrade", "downgrade"] as const;
141
142 /** `SessionSource::as_str`. */
143 export const SESSION_SOURCES = [
144 "interactive",
145 "resume",
146 "fork",
147 "api",
148 "unknown",
149 "ci",
150 ] as const;
151
152 export const V6_ONLY_SESSION_SOURCES = ["fleet_worker", "agent", "scripted"] as const;
153 export const V6_SESSION_SOURCES = [...SESSION_SOURCES, ...V6_ONLY_SESSION_SOURCES] as const;
154
155 export const INSTALL_AGES = ["new_today", "under_week", "older"] as const;
156
157 /** `DurationBucket` wire spellings. */
158 export const DURATION_BUCKETS = [
159 "lt_1m",
160 "1m_10m",
161 "10m_60m",
162 "gt_60m",
163 ] as const;
164
165 /** `ExitClass::as_str`. */
166 export const EXIT_CLASSES = ["clean", "signal", "panic", "error"] as const;
167
168 export const V6_EXIT_CLASSES = [...EXIT_CLASSES, "unclean"] as const;
169
170 /** `ColdStartBucket` wire spellings. */
171 export const COLD_START_BUCKETS = [
172 "lt_250",
173 "250_1000",
174 "1000_3000",
175 "gte_3000",
176 ] as const;
177
178 // ------------------------------------------------------------------ field sets
179
180 /** `Batch::FIELDS`, in declaration order. */
181 export const ENVELOPE_FIELDS = [
182 "schema_version",
183 "notice_version",
184 "sent_at",
185 "install_id",
186 "app_version",
187 "git_sha",
188 "surface",
189 "os",
190 "arch",
191 "libc",
192 "tty",
193 "events",
194 ] as const;
195
196 /** The unchanged v1 contract never establishes processor consent. */
197 export const LEGACY_ENVELOPE_FIELDS = ENVELOPE_FIELDS.filter((field) => field !== "notice_version");
198 /** V2 retains its original explicit-consent meaning and closed field set. */
199 export const V2_ENVELOPE_FIELDS = [...LEGACY_ENVELOPE_FIELDS, "consent_version"];
200
201 /** Aggregate product interactions; no page, account, session, or tool identifiers. */
202 export const PRODUCT_COUNTER_FIELDS = [
203 "page_view", "docs_view", "install_copy", "download", "signup", "login",
204 "session_create", "session_resume", "turn_submit", "turn_complete",
205 "settings_open", "integration_connect", "error_shown",
206 ] as const;
207
208 /** Anonymous operator-consented service health aggregates. */
209 export const OPERATIONS_FIELDS = [
210 "requests", "errors", "duration_ms_total", "duration_ms_max", "probes", "probes_failed",
211 ] as const;
212
213 /** `ModelCounters::FIELDS`; turn counts are u32, token counts u64. */
214 export const MODEL_COUNTER_FIELDS = [
215 "turns_ok",
216 "turns_failed",
217 "turns_interrupted",
218 "input_tokens",
219 "output_tokens",
220 "cache_read_tokens",
221 "cache_write_tokens",
222 ] as const;
223
224 export const MODEL_COUNTER_FIELDS_V6_EXTRA = [
225 "requests",
226 "reasoning_tokens",
227 "generation_secs",
228 ] as const;
229
230 export const V6_MODEL_COUNTER_FIELDS = [
231 ...MODEL_COUNTER_FIELDS,
232 ...MODEL_COUNTER_FIELDS_V6_EXTRA,
233 ] as const;
234
235 export const CONTEXT_FIELDS = ["lt_32k", "32k_128k", "128k_256k", "gte_256k"] as const;
236
237 /** Every name a shipped `event::TOOL_NAMES` held, plus the `mcp` and `other` buckets. */
238 export const TOOL_NAMES = [
239 "agent", "apply_patch", "authenticate", "automation_adopt", "automation_create",
240 "automation_delete", "automation_list", "automation_pause", "automation_read",
241 "automation_resume", "automation_run", "automation_update", "bash",
242 "code_execution", "context_archive_get", "context_archive_search", "create_goal",
243 "diagnostics", "edit", "edit_file", "exec_shell", "execute_tools", "fetch_url",
244 "file_search", "fim_edit", "finance", "get_goal", "git_blame", "git_commit_plan",
245 "git_diff", "git_fetch", "git_log", "git_merge_tree", "git_review_scope",
246 "git_show", "git_status", "github_close_issue", "github_close_pr", "github_comment",
247 "github_issue_context", "github_pr_context", "github_report_draft",
248 "github_report_read", "grep_files", "handle_read", "image_ocr", "js_execution",
249 "list_dir", "load_skill", "lsp", "memory_get", "memory_search", "note", "notify",
250 "pandoc_convert", "pr_attempt_list", "pr_attempt_preflight", "pr_attempt_read",
251 "pr_attempt_record", "present", "project_map", "read", "read_file", "read_media",
252 "remember", "request_plugin_install", "request_user_input", "retrieve_tool_result",
253 "revert_turn", "review", "rlm", "run_tests", "run_verifiers", "send_later",
254 "session_get", "session_search", "show_data", "speech", "start_mcp_server",
255 "task_cancel", "task_create", "task_gate_run", "task_list", "task_read",
256 "task_shell_wait", "terminal_cancel", "terminal_reset", "terminal_run",
257 "terminal_send", "terminal_wait", "todo_write", "tool_search", "tui_help",
258 "update_goal", "update_plan", "validate_data", "verify", "wait_for_dev_server",
259 "web.run", "web_search", "workflow", "write", "write_file", "mcp", "other",
260 ] as const;
261
262 /** `Counters::FIELDS`, in declaration order. */
263 export const COUNTER_FIELDS = [
264 "turns",
265 "tool_calls",
266 "fleet_dispatch",
267 "workflow_run",
268 "subagent_spawn",
269 "mcp_server_connected",
270 "memory_search",
271 "approval_modal_shown",
272 "approval_auto_allowed",
273 "command_palette_open",
274 ] as const;
275
276 /** `Errors::FIELDS`, in declaration order. */
277 export const ERROR_FIELDS = [
278 "auth_preflight_failed",
279 "provider_http_4xx",
280 "provider_http_5xx",
281 "tool_denied_by_policy",
282 "tool_timeout",
283 "network_error",
284 ] as const;
285
286 /** `TurnWall::FIELDS`, in wire spelling and declaration order. */
287 export const TURN_WALL_FIELDS = [
288 "lt_5s",
289 "5_30s",
290 "30_120s",
291 "gte_120s",
292 ] as const;
293
294 /**
295 * Every event variant's complete key set, `event` tag included.
296 *
297 * `serde(tag = "event")` makes the wire form flat, so the tag is a key like any
298 * other and the variant set is closed.
299 */
300 export const EVENT_FIELDS: Readonly<Record<string, readonly string[]>> = {
301 install_or_upgrade: ["event", "kind", "previous_version"],
302 session_start: ["event", "source"],
303 session_end: [
304 "event",
305 "duration_bucket",
306 "exit_class",
307 "cold_start_bucket",
308 "providers",
309 "counters",
310 "errors",
311 "turn_wall",
312 ],
313 panic: ["event", "site"],
314 product_usage: ["event", "counters"],
315 model_usage: ["event", "provider", "model", "counters", "turn_wall"],
316 tool_usage: ["event", "tool", "calls", "errors"],
317 operations_summary: ["event", ...OPERATIONS_FIELDS],
318 funnel_usage: ["event", "counters"],
319 };
320
321 export const V6_EVENT_FIELDS: Readonly<Record<string, readonly string[]>> = {
322 ...EVENT_FIELDS,
323 session_start: ["event", "source", "install_age"],
324 model_usage: ["event", "provider", "model", "counters", "turn_wall", "context"],
325 };
326
327 /** Every event discriminant, for the doc-match test. */
328 export const EVENT_NAMES = Object.keys(EVENT_FIELDS);
329
330 // -------------------------------------------------------------------- matchers
331
332 /** RFC3339 UTC at second precision — exactly `to_rfc3339_opts(Secs, true)`. */
333 const SENT_AT_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/;
334
335 /**
336 * A canonical lowercase v4 UUID.
337 *
338 * `docs/TELEMETRY.md` and `envelope.rs` both say v4, and `Uuid::new_v4()` only
339 * ever produces this form. The client's own read path accepts any parseable
340 * UUID, so this is marginally stricter than the client — deliberately: an
341 * `install_id.json` hand-written by something other than Codewhale is exactly
342 * the input this endpoint should refuse, and refusing costs the user nothing
343 * because the client drops rejected batches silently.
344 */
345 const INSTALL_ID_RE =
346 /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
347
348 /** `^\d+\.\d+\.\d+(-[0-9A-Za-z.]+)?$`, plus the inferred length ceiling. */
349 const VERSION_RE = /^\d+\.\d+\.\d+(-[0-9A-Za-z.]+)?$/;
350
351 /** First 12 lowercase hex chars — `envelope::short_hex_sha`. */
352 const GIT_SHA_RE = /^[0-9a-f]{12}$/;
353
354 /** `event::is_reduced_panic_site` — the literal `<dep>`, or a `crates/…` site. */
355 const PANIC_SITE_RE = /^crates\/[A-Za-z0-9_/.-]+\.rs:\d+:\d+$/;
356
357 /**
358 * `ProviderKind::as_str()` shape.
359 *
360 * This is the one field whose *value* space the endpoint cannot close: the
361 * authoritative list is `codewhale_config::provider::all_providers()`, a Rust
362 * registry with no generated artifact to read, and hard-coding a copy here
363 * would drift into silently dropping a real user's route. The client closes it
364 * with `Event::is_bounded` -> `is_known_provider_id` before the POST is made;
365 * the server enforces the shape a closed `&'static str` enum can produce
366 * (lowercase, hyphen-joined, bounded) and the doc's sorted-and-deduplicated
367 * rule, which is what catches a client that started sending the customer's own
368 * `[providers.<name>]` table key.
369 */
370 const PROVIDER_RE = /^[a-z0-9]([a-z0-9-]{0,30}[a-z0-9])?$/;
371
372 const U32_MAX = 4294967295;
373
374 /**
375 * `event::is_reported_model_id` shape: a lowercased bundled-catalog id or
376 * `other`. The client closes the value against its catalog; the server bounds
377 * the shape, as it does for providers.
378 */
379 const MODEL_RE = /^[a-z0-9][a-z0-9._:/@+-]{0,127}$/;
380
381 /** Derived contract for CWC's product-only ingress; runtime events stay here. */
382 export const CWC_PRODUCT_SCHEMA = {
383 $schema: "http://json-schema.org/draft-07/schema#",
384 $id: "https://codewhale.net/schemas/cwc-product-telemetry-v3.json",
385 title: "Codewhale CWC aggregate telemetry v3, notice v5",
386 description: "Generated from telemetry-ingest/src/schema.ts; do not edit the JSON artifact. No content or identity fields.",
387 type: "object",
388 additionalProperties: false,
389 required: ENVELOPE_FIELDS,
390 properties: {
391 schema_version: { const: V3_SCHEMA_VERSION },
392 notice_version: { const: V3_NOTICE_VERSION },
393 sent_at: { type: "string", pattern: SENT_AT_RE.source },
394 install_id: { type: "string", pattern: INSTALL_ID_RE.source },
395 app_version: { type: "string", maxLength: MAX_VERSION_LEN, pattern: VERSION_RE.source },
396 git_sha: { const: null },
397 surface: { enum: SURFACES.filter((surface) => surface === "web-app" || surface === "desktop") },
398 os: { const: "other" },
399 arch: { const: "other" },
400 libc: { const: "none" },
401 tty: { const: false },
402 events: {
403 type: "array",
404 minItems: 1,
405 maxItems: 1,
406 items: {
407 type: "object",
408 additionalProperties: false,
409 required: EVENT_FIELDS.product_usage,
410 properties: {
411 event: { const: "product_usage" },
412 counters: {
413 type: "object",
414 additionalProperties: false,
415 required: PRODUCT_COUNTER_FIELDS,
416 properties: Object.fromEntries(PRODUCT_COUNTER_FIELDS.map((field) => [
417 field, { type: "integer", minimum: 0, maximum: U32_MAX },
418 ])),
419 },
420 },
421 },
422 },
423 },
424 } as const;
425
426 const aggregateEventSchema = (event: string, fields: readonly string[]) => ({
427 type: "object", additionalProperties: false, required: ["event", "counters"],
428 properties: {
429 event: { const: event },
430 counters: {
431 type: "object", additionalProperties: false, required: fields,
432 properties: Object.fromEntries(fields.map((field) => [field, { type: "integer", minimum: 0, maximum: U32_MAX }])),
433 },
434 },
435 });
436
437 export const WEBSITE_FUNNEL_SCHEMA = {
438 ...CWC_PRODUCT_SCHEMA,
439 $id: "https://codewhale.net/schemas/website-funnel-telemetry-v5.json",
440 title: "Codewhale website aggregate telemetry v5, notice v7",
441 properties: {
442 ...CWC_PRODUCT_SCHEMA.properties,
443 schema_version: { const: FUNNEL_SCHEMA_VERSION },
444 notice_version: { const: FUNNEL_NOTICE_VERSION },
445 surface: { const: "website" },
446 events: {
447 type: "array", minItems: 1, maxItems: BATCH_MAX_EVENTS,
448 items: { oneOf: [aggregateEventSchema("product_usage", PRODUCT_COUNTER_FIELDS), aggregateEventSchema("funnel_usage", FUNNEL_COUNTER_FIELDS)] },
449 },
450 },
451 } as const;
452
453 // ------------------------------------------------------------------ validation
454
455 /** A rejection carries a reason for the tests. It is never sent to a client. */
456 export type Rejection = { ok: false; reason: string };
457
458 /** A batch that satisfies every published rule. */
459 export type Accepted = { ok: true; batch: Batch };
460
461 export type Counters = Record<(typeof COUNTER_FIELDS)[number], number>;
462 export type Errors = Record<(typeof ERROR_FIELDS)[number], number>;
463 export type TurnWall = Record<(typeof TURN_WALL_FIELDS)[number], number>;
464
465 export type ProductCounters = Record<(typeof PRODUCT_COUNTER_FIELDS)[number], number>;
466
467 export type FunnelCounters = Record<(typeof FUNNEL_COUNTER_FIELDS)[number], number>;
468
469 export type Event =
470 | { event: "install_or_upgrade"; kind: string; previous_version: string | null }
471 | { event: "session_start"; source: string; install_age?: string | null }
472 | {
473 event: "session_end";
474 duration_bucket: string;
475 exit_class: string;
476 cold_start_bucket: string | null;
477 providers: string[];
478 counters: Counters;
479 errors: Errors;
480 turn_wall: TurnWall;
481 }
482 | { event: "panic"; site: string }
483 | { event: "product_usage"; counters: ProductCounters }
484 | { event: "funnel_usage"; counters: FunnelCounters }
485 | {
486 event: "model_usage";
487 provider: string;
488 model: string;
489 counters: Record<(typeof MODEL_COUNTER_FIELDS)[number], number> &
490 Partial<Record<(typeof MODEL_COUNTER_FIELDS_V6_EXTRA)[number], number>>;
491 turn_wall: TurnWall;
492 context?: Record<(typeof CONTEXT_FIELDS)[number], number>;
493 }
494 | { event: "tool_usage"; tool: string; calls: number; errors: number }
495 | ({ event: "operations_summary" } & Record<(typeof OPERATIONS_FIELDS)[number], number>);
496
497 export interface Batch {
498 schema_version: number;
499 consent_version?: number;
500 notice_version?: number;
501 sent_at: string;
502 install_id: string;
503 app_version: string;
504 git_sha: string | null;
505 surface: string;
506 os: string;
507 arch: string;
508 libc: string;
509 tty: boolean;
510 events: Event[];
511 }
512
513 function isPlainObject(value: unknown): value is Record<string, unknown> {
514 return (
515 typeof value === "object" && value !== null && !Array.isArray(value)
516 );
517 }
518
519 /** Exact key-set equality. Missing keys and extra keys are both fatal. */
520 function keysExactly(
521 value: Record<string, unknown>,
522 expected: readonly string[],
523 where: string,
524 ): string | null {
525 const actual = Object.keys(value);
526 if (actual.length !== expected.length) {
527 const extra = actual.filter((key) => !expected.includes(key));
528 if (extra.length > 0) return `${where}: unexpected key ${extra[0]}`;
529 const missing = expected.filter((key) => !actual.includes(key));
530 return `${where}: missing key ${missing[0]}`;
531 }
532 for (const key of actual) {
533 if (!expected.includes(key)) return `${where}: unexpected key ${key}`;
534 }
535 return null;
536 }
537
538 function enumString(
539 value: unknown,
540 allowed: readonly string[],
541 where: string,
542 ): string | null {
543 if (typeof value !== "string" || !allowed.includes(value)) {
544 return `${where}: not one of the documented values`;
545 }
546 return null;
547 }
548
549 function countMap(
550 value: unknown,
551 fields: readonly string[],
552 where: string,
553 max: number,
554 ): string | null {
555 if (!isPlainObject(value)) return `${where}: not an object`;
556 const keyError = keysExactly(value, fields, where);
557 if (keyError) return keyError;
558 for (const field of fields) {
559 const item = value[field];
560 if (typeof item !== "number" || !Number.isInteger(item) || item < 0 || item > max) {
561 return `${where}.${field}: not a count`;
562 }
563 }
564 return null;
565 }
566
567 function u32Map(
568 value: unknown,
569 fields: readonly string[],
570 where: string,
571 ): string | null {
572 if (!isPlainObject(value)) return `${where}: not an object`;
573 const keyError = keysExactly(value, fields, where);
574 if (keyError) return keyError;
575 for (const field of fields) {
576 const item = value[field];
577 if (
578 typeof item !== "number" ||
579 !Number.isInteger(item) ||
580 item < 0 ||
581 item > U32_MAX
582 ) {
583 return `${where}.${field}: not a u32`;
584 }
585 }
586 return null;
587 }
588
589 function u32Fields(
590 value: Record<string, unknown>,
591 fields: readonly string[],
592 where: string,
593 ): string | null {
594 for (const field of fields) {
595 const item = value[field];
596 if (typeof item !== "number" || !Number.isInteger(item) || item < 0 || item > U32_MAX) {
597 return `${where}.${field}: not a u32`;
598 }
599 }
600 return null;
601 }
602
603 function validateEvent(value: unknown, where: string, v6 = false): string | null {
604 if (!isPlainObject(value)) return `${where}: not an object`;
605 const name = value.event;
606 const eventFields = v6 ? V6_EVENT_FIELDS : EVENT_FIELDS;
607 if (typeof name !== "string" || !Object.hasOwn(eventFields, name)) {
608 return `${where}: unknown event discriminant`;
609 }
610 const keyError = keysExactly(value, eventFields[name], `${where}(${name})`);
611 if (keyError) return keyError;
612
613 switch (name) {
614 case "install_or_upgrade": {
615 const kindError = enumString(
616 value.kind,
617 INSTALL_KINDS,
618 `${where}.kind`,
619 );
620 if (kindError) return kindError;
621 const previous = value.previous_version;
622 if (previous !== null) {
623 if (
624 typeof previous !== "string" ||
625 previous.length > MAX_VERSION_LEN ||
626 !VERSION_RE.test(previous)
627 ) {
628 return `${where}.previous_version: not a release version string`;
629 }
630 }
631 return null;
632 }
633 case "session_start": {
634 const sourceError = enumString(
635 value.source,
636 v6 ? V6_SESSION_SOURCES : SESSION_SOURCES,
637 `${where}.source`,
638 );
639 if (sourceError || !v6 || value.install_age === null) return sourceError;
640 return enumString(value.install_age, INSTALL_AGES, `${where}.install_age`);
641 }
642 case "session_end": {
643 const bucketError = enumString(
644 value.duration_bucket,
645 DURATION_BUCKETS,
646 `${where}.duration_bucket`,
647 );
648 if (bucketError) return bucketError;
649 const exitError = enumString(
650 value.exit_class,
651 v6 ? V6_EXIT_CLASSES : EXIT_CLASSES,
652 `${where}.exit_class`,
653 );
654 if (exitError) return exitError;
655 if (value.cold_start_bucket !== null) {
656 const coldError = enumString(
657 value.cold_start_bucket,
658 COLD_START_BUCKETS,
659 `${where}.cold_start_bucket`,
660 );
661 if (coldError) return coldError;
662 }
663 const providers = value.providers;
664 if (!Array.isArray(providers)) return `${where}.providers: not an array`;
665 if (providers.length > MAX_PROVIDERS) {
666 return `${where}.providers: too many entries`;
667 }
668 let previous: string | null = null;
669 for (const provider of providers) {
670 if (typeof provider !== "string" || !PROVIDER_RE.test(provider)) {
671 return `${where}.providers: not a provider id`;
672 }
673 // The doc says "sorted, deduplicated". A client that started shipping
674 // the customer's own `[providers.<name>]` table key would land here
675 // first, because an unsorted or repeated list is the cheapest signal
676 // that this array stopped coming from `ProviderKind::as_str()`.
677 if (previous !== null && provider <= previous) {
678 return `${where}.providers: not sorted and deduplicated`;
679 }
680 previous = provider;
681 }
682 return (
683 u32Map(value.counters, COUNTER_FIELDS, `${where}.counters`) ??
684 u32Map(value.errors, ERROR_FIELDS, `${where}.errors`) ??
685 u32Map(value.turn_wall, TURN_WALL_FIELDS, `${where}.turn_wall`)
686 );
687 }
688 case "operations_summary": {
689 const { event: _event, ...counts } = value;
690 return u32Map(counts, OPERATIONS_FIELDS, where);
691 }
692 case "product_usage":
693 return u32Map(value.counters, PRODUCT_COUNTER_FIELDS, `${where}.counters`);
694 case "funnel_usage":
695 return u32Map(value.counters, FUNNEL_COUNTER_FIELDS, `${where}.counters`);
696 case "model_usage": {
697 if (typeof value.provider !== "string" || !PROVIDER_RE.test(value.provider)) {
698 return `${where}.provider: not a provider id`;
699 }
700 if (typeof value.model !== "string" || !MODEL_RE.test(value.model)) {
701 return `${where}.model: not a catalogued model id`;
702 }
703 const counterError = v6
704 ? countMap(value.counters, V6_MODEL_COUNTER_FIELDS, `${where}.counters`, Number.MAX_SAFE_INTEGER) ??
705 u32Fields(value.counters as Record<string, unknown>, ["requests", "generation_secs"], `${where}.counters`)
706 : countMap(value.counters, MODEL_COUNTER_FIELDS, `${where}.counters`, Number.MAX_SAFE_INTEGER);
707 return (
708 counterError ??
709 u32Map(value.turn_wall, TURN_WALL_FIELDS, `${where}.turn_wall`) ??
710 (v6 ? u32Map(value.context, CONTEXT_FIELDS, `${where}.context`) : null)
711 );
712 }
713 case "tool_usage":
714 return (
715 enumString(value.tool, TOOL_NAMES, `${where}.tool`) ??
716 countMap({ calls: value.calls, errors: value.errors }, ["calls", "errors"], where, U32_MAX)
717 );
718 case "panic": {
719 const site = value.site;
720 if (typeof site !== "string" || site.length > MAX_PANIC_SITE_LEN) {
721 return `${where}.site: not a string`;
722 }
723 if (site !== "<dep>" && !PANIC_SITE_RE.test(site)) {
724 return `${where}.site: not a reduced panic site`;
725 }
726 return null;
727 }
728 default:
729 return `${where}: unknown event discriminant`;
730 }
731 }
732
733 /**
734 * Validate one decoded batch against the published schema.
735 *
736 * Returns the batch on success. On failure the reason is for tests and local
737 * reasoning only — the handler answers with a bare status and no body, because
738 * echoing a parse error back is a way to learn what the endpoint stores.
739 */
740 export function validateBatch(value: unknown): Accepted | Rejection {
741 if (!isPlainObject(value)) return { ok: false, reason: "batch: not an object" };
742
743 const legacy = value.schema_version === 1;
744 const explicitConsent = value.schema_version === 2;
745 const v3 = value.schema_version === V3_SCHEMA_VERSION;
746 const v4 = value.schema_version === SCHEMA_VERSION;
747 const funnel = value.schema_version === FUNNEL_SCHEMA_VERSION;
748 const v6 = value.schema_version === V6_SCHEMA_VERSION;
749 const preUsage = legacy || explicitConsent || v3;
750 if (!legacy && !explicitConsent && !v3 && !v4 && !funnel && !v6) {
751 return { ok: false, reason: "batch.schema_version: unsupported" };
752 }
753 const fields = legacy ? LEGACY_ENVELOPE_FIELDS : explicitConsent ? V2_ENVELOPE_FIELDS : ENVELOPE_FIELDS;
754 const keyError = keysExactly(value, fields, "batch");
755 if (keyError) return { ok: false, reason: keyError };
756 if (explicitConsent && value.consent_version !== CONSENT_VERSION) {
757 return { ok: false, reason: "batch.consent_version: explicit current consent required" };
758 }
759 if (
760 !legacy &&
761 !explicitConsent &&
762 value.notice_version !== (funnel ? FUNNEL_NOTICE_VERSION : v6 ? V6_NOTICE_VERSION : preUsage ? V3_NOTICE_VERSION : NOTICE_VERSION)
763 ) {
764 return { ok: false, reason: "batch.notice_version: current policy required" };
765 }
766 if (typeof value.sent_at !== "string" || !SENT_AT_RE.test(value.sent_at)) {
767 return { ok: false, reason: "batch.sent_at: not RFC3339 UTC seconds" };
768 }
769 if (
770 typeof value.install_id !== "string" ||
771 !INSTALL_ID_RE.test(value.install_id)
772 ) {
773 return { ok: false, reason: "batch.install_id: not a v4 uuid" };
774 }
775 if (
776 typeof value.app_version !== "string" ||
777 value.app_version.length > MAX_VERSION_LEN ||
778 !VERSION_RE.test(value.app_version)
779 ) {
780 return { ok: false, reason: "batch.app_version: not a release version" };
781 }
782 if (value.git_sha !== null) {
783 if (typeof value.git_sha !== "string" || !GIT_SHA_RE.test(value.git_sha)) {
784 return { ok: false, reason: "batch.git_sha: not 12 hex chars or null" };
785 }
786 }
787 if (funnel && (value.surface !== "website" || value.git_sha !== null || value.os !== "other" || value.arch !== "other" || value.libc !== "none" || value.tty !== false)) {
788 return { ok: false, reason: "batch: schema v5 requires the website no-fingerprint envelope" };
789 }
790 const enumErrors =
791 enumString(value.surface, legacy ? LEGACY_SURFACES : SURFACES, "batch.surface") ??
792 enumString(value.os, OSES, "batch.os") ??
793 enumString(value.arch, ARCHES, "batch.arch") ??
794 enumString(value.libc, LIBCS, "batch.libc");
795 if (enumErrors) return { ok: false, reason: enumErrors };
796
797 if (typeof value.tty !== "boolean") {
798 return { ok: false, reason: "batch.tty: not a boolean" };
799 }
800 if (!Array.isArray(value.events)) {
801 return { ok: false, reason: "batch.events: not an array" };
802 }
803 if (value.events.length > BATCH_MAX_EVENTS) {
804 return { ok: false, reason: "batch.events: over BATCH_MAX_EVENTS" };
805 }
806 if (funnel && value.events.length === 0) return { ok: false, reason: "events: schema v5 requires an aggregate" };
807 for (let index = 0; index < value.events.length; index += 1) {
808 const event = value.events[index];
809 if (isPlainObject(event)) {
810 if (funnel && event.event !== "funnel_usage" && event.event !== "product_usage") {
811 return { ok: false, reason: "events: schema v5 website accepts aggregate product/funnel events only" };
812 }
813 if (event.event === "funnel_usage" && (!funnel || value.surface !== "website")) {
814 return { ok: false, reason: "events: funnel_usage requires schema v5 website" };
815 }
816 if (legacy && (event.event === "product_usage" || event.event === "operations_summary")) {
817 return { ok: false, reason: "events: aggregate product/operations events require schema v2 or v3" };
818 }
819 if (preUsage && (event.event === "model_usage" || event.event === "tool_usage")) {
820 return { ok: false, reason: "events: model_usage and tool_usage require schema v4 or later" };
821 }
822 if (preUsage && event.event === "session_start" && event.source === "ci") {
823 return { ok: false, reason: "events: the ci session source requires schema v4" };
824 }
825 if (event.event === "operations_summary" && value.surface !== "control-plane") {
826 return { ok: false, reason: "events: operations_summary requires control-plane surface" };
827 }
828 }
829 const eventError = validateEvent(event, `events[${index}]`, v6);
830 if (eventError) return { ok: false, reason: eventError };
831 }
832
833 return { ok: true, batch: value as unknown as Batch };
834 }
835
835 lines TYPESCRIPT