-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathtelemetry.test.ts
More file actions
2263 lines (2017 loc) · 81.5 KB
/
telemetry.test.ts
File metadata and controls
2263 lines (2017 loc) · 81.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @ts-nocheck
import { describe, expect, test, mock, afterEach, beforeEach, spyOn } from "bun:test"
import { Telemetry } from "../../src/telemetry"
// ---------------------------------------------------------------------------
// 1. categorizeToolName
// ---------------------------------------------------------------------------
describe("telemetry.categorizeToolName", () => {
test("returns 'mcp' for mcp tools regardless of name", () => {
expect(Telemetry.categorizeToolName("anything", "mcp")).toBe("mcp")
expect(Telemetry.categorizeToolName("sql_query", "mcp")).toBe("mcp")
})
test("returns 'sql' for sql-related tools", () => {
expect(Telemetry.categorizeToolName("sql_execute", "standard")).toBe("sql")
expect(Telemetry.categorizeToolName("run_query", "standard")).toBe("sql")
})
test("returns 'schema' for schema-related tools", () => {
expect(Telemetry.categorizeToolName("schema_inspector", "standard")).toBe("schema")
expect(Telemetry.categorizeToolName("list_columns", "standard")).toBe("schema")
expect(Telemetry.categorizeToolName("describe_table", "standard")).toBe("schema")
})
test("returns 'dbt' for dbt tools", () => {
expect(Telemetry.categorizeToolName("dbt_build", "standard")).toBe("dbt")
expect(Telemetry.categorizeToolName("dbt_run", "standard")).toBe("dbt")
})
test("returns 'finops' for cost/finops tools", () => {
expect(Telemetry.categorizeToolName("cost_analysis", "standard")).toBe("finops")
expect(Telemetry.categorizeToolName("finops_report", "standard")).toBe("finops")
expect(Telemetry.categorizeToolName("warehouse_usage_stats", "standard")).toBe("finops")
})
test("returns 'warehouse' for warehouse/connection tools", () => {
expect(Telemetry.categorizeToolName("warehouse_list", "standard")).toBe("warehouse")
expect(Telemetry.categorizeToolName("connection_test", "standard")).toBe("warehouse")
})
test("returns 'lineage' for lineage/dag tools", () => {
expect(Telemetry.categorizeToolName("lineage_trace", "standard")).toBe("lineage")
expect(Telemetry.categorizeToolName("dag_viewer", "standard")).toBe("lineage")
})
test("returns 'file' for file operation tools", () => {
for (const tool of ["read", "write", "edit", "glob", "grep", "bash"]) {
expect(Telemetry.categorizeToolName(tool, "standard")).toBe("file")
}
})
test("returns 'standard' for unknown tools", () => {
expect(Telemetry.categorizeToolName("unknown_tool", "standard")).toBe("standard")
expect(Telemetry.categorizeToolName("some_custom_thing", "standard")).toBe("standard")
})
test("is case insensitive", () => {
expect(Telemetry.categorizeToolName("SQL_EXECUTE", "standard")).toBe("sql")
expect(Telemetry.categorizeToolName("DBT_Build", "standard")).toBe("dbt")
expect(Telemetry.categorizeToolName("Read", "standard")).toBe("file")
})
})
// ---------------------------------------------------------------------------
// 2. bucketCount
// ---------------------------------------------------------------------------
describe("telemetry.bucketCount", () => {
test("returns '0' for zero or negative", () => {
expect(Telemetry.bucketCount(0)).toBe("0")
expect(Telemetry.bucketCount(-5)).toBe("0")
})
test("returns '1-10' for 1-10", () => {
expect(Telemetry.bucketCount(1)).toBe("1-10")
expect(Telemetry.bucketCount(10)).toBe("1-10")
})
test("returns '10-50' for 11-50", () => {
expect(Telemetry.bucketCount(11)).toBe("10-50")
expect(Telemetry.bucketCount(50)).toBe("10-50")
})
test("returns '50-200' for 51-200", () => {
expect(Telemetry.bucketCount(51)).toBe("50-200")
expect(Telemetry.bucketCount(200)).toBe("50-200")
})
test("returns '200+' for >200", () => {
expect(Telemetry.bucketCount(201)).toBe("200+")
expect(Telemetry.bucketCount(1000)).toBe("200+")
})
})
// ---------------------------------------------------------------------------
// 3. track — buffering behavior
// ---------------------------------------------------------------------------
describe("telemetry.track", () => {
test("track is a function", () => {
expect(typeof Telemetry.track).toBe("function")
})
test("track does not throw when called with valid events before init", () => {
expect(() => {
Telemetry.track({
type: "session_start",
timestamp: Date.now(),
session_id: "test-session",
model_id: "test-model",
provider_id: "test-provider",
agent: "test-agent",
project_id: "test-project",
os: "linux",
arch: "x64",
node_version: "v22.0.0",
})
}).not.toThrow()
})
test("pre-init events are buffered, not dropped", async () => {
// Ensure clean state
await Telemetry.shutdown()
// Track before init — should buffer
Telemetry.track({
type: "mcp_server_status",
timestamp: Date.now(),
session_id: "pre-init",
server_name: "test",
transport: "stdio",
status: "connected",
})
Telemetry.track({
type: "engine_started",
timestamp: Date.now(),
session_id: "pre-init",
engine_version: "1.0",
python_version: "3.12",
status: "started",
duration_ms: 100,
})
// init() with telemetry disabled via env var — should clear buffer
const origEnv = process.env.ALTIMATE_TELEMETRY_DISABLED
process.env.ALTIMATE_TELEMETRY_DISABLED = "true"
try {
await Telemetry.init()
// After init disables, track should drop
Telemetry.track({
type: "session_start",
timestamp: Date.now(),
session_id: "post-disable",
model_id: "m",
provider_id: "p",
agent: "a",
project_id: "x",
os: "linux",
arch: "x64",
node_version: "v22.0.0",
})
} finally {
process.env.ALTIMATE_TELEMETRY_DISABLED = origEnv
await Telemetry.shutdown()
}
})
test("init() is idempotent — second call returns same promise", async () => {
await Telemetry.shutdown()
const origEnv = process.env.ALTIMATE_TELEMETRY_DISABLED
process.env.ALTIMATE_TELEMETRY_DISABLED = "true"
try {
const p1 = Telemetry.init()
const p2 = Telemetry.init()
expect(p1).toBe(p2) // same promise object
await p1
} finally {
process.env.ALTIMATE_TELEMETRY_DISABLED = origEnv
await Telemetry.shutdown()
}
})
})
// ---------------------------------------------------------------------------
// 4. setContext / getContext
// ---------------------------------------------------------------------------
describe("telemetry.context", () => {
test("setContext and getContext work together", () => {
Telemetry.setContext({ sessionId: "sess-123", projectId: "proj-456" })
const ctx = Telemetry.getContext()
expect(ctx.sessionId).toBe("sess-123")
expect(ctx.projectId).toBe("proj-456")
})
test("getContext returns empty strings initially after shutdown", async () => {
await Telemetry.shutdown()
const ctx = Telemetry.getContext()
expect(ctx.sessionId).toBe("")
expect(ctx.projectId).toBe("")
})
})
// ---------------------------------------------------------------------------
// 5. Event type completeness — all 33 event types
// ---------------------------------------------------------------------------
// Shared event type list — single source of truth for completeness and naming tests
const ALL_EVENT_TYPES: Telemetry.Event["type"][] = [
"session_start",
"session_end",
"generation",
"tool_call",
"native_call",
"error",
"command",
"context_overflow_recovered",
"compaction_triggered",
"tool_outputs_pruned",
"auth_login",
"auth_logout",
"mcp_server_status",
"provider_error",
"engine_started",
"engine_error",
"upgrade_attempted",
"session_forked",
"permission_denied",
"doom_loop_detected",
"environment_census",
"context_utilization",
"agent_outcome",
"error_recovered",
"mcp_server_census",
"mcp_discovery",
"memory_operation",
"memory_injection",
"warehouse_connect",
"warehouse_query",
"warehouse_introspection",
"warehouse_discovery",
"warehouse_census",
"skill_used",
"first_launch",
"skill_created",
"skill_installed",
"skill_removed",
"plan_revision",
"sql_execute_failure",
"feature_suggestion",
"core_failure",
"sql_pre_validation",
]
describe("telemetry.event-types", () => {
test("all event types are valid", () => {
expect(ALL_EVENT_TYPES.length).toBe(43)
})
})
// ---------------------------------------------------------------------------
// 6. Privacy validation
// ---------------------------------------------------------------------------
describe("telemetry.privacy", () => {
test("error events truncate messages to 500 chars", () => {
const longError = "x".repeat(1000)
const event: Telemetry.Event = {
type: "provider_error",
timestamp: Date.now(),
session_id: "test",
provider_id: "test",
model_id: "test",
error_type: "test",
error_message: longError.slice(0, 500),
}
expect(event.error_message.length).toBe(500)
})
test("engine_error truncates error_message", () => {
const longError = "y".repeat(1000)
const event: Telemetry.Event = {
type: "engine_error",
timestamp: Date.now(),
session_id: "test",
phase: "startup",
error_message: longError.slice(0, 500),
}
expect(event.error_message.length).toBe(500)
})
test("tool_call event does NOT include tool arguments", () => {
const event: Telemetry.Event = {
type: "tool_call",
timestamp: Date.now(),
session_id: "test",
message_id: "msg-1",
tool_name: "sql_execute",
tool_type: "standard",
tool_category: "sql",
status: "success",
duration_ms: 100,
sequence_index: 0,
previous_tool: null,
}
expect("input" in event).toBe(false)
expect("output" in event).toBe(false)
expect("args" in event).toBe(false)
expect("arguments" in event).toBe(false)
})
test("environment_census does NOT include hostnames or credentials", () => {
const event: Telemetry.Event = {
type: "environment_census",
timestamp: Date.now(),
session_id: "test",
warehouse_types: ["snowflake", "bigquery"],
warehouse_count: 2,
dbt_detected: true,
dbt_adapter: "snowflake",
dbt_model_count_bucket: "10-50",
dbt_source_count_bucket: "1-10",
dbt_test_count_bucket: "1-10",
connection_sources: ["configured", "dbt-profile"],
mcp_server_count: 3,
skill_count: 0,
os: "darwin",
feature_flags: ["plan_mode"],
}
expect("hostname" in event).toBe(false)
expect("password" in event).toBe(false)
expect("connection_string" in event).toBe(false)
expect("host" in event).toBe(false)
expect("port" in event).toBe(false)
expect(event.dbt_model_count_bucket).toMatch(/^(0|1-10|10-50|50-200|200\+)$/)
})
})
// ---------------------------------------------------------------------------
// 7. Naming convention validation
// ---------------------------------------------------------------------------
describe("telemetry.naming-convention", () => {
test("all event types use snake_case", () => {
for (const t of ALL_EVENT_TYPES) {
expect(t).toMatch(/^[a-z][a-z0-9_]*$/)
}
})
})
// ---------------------------------------------------------------------------
// 8. parseConnectionString (tested indirectly via init + flush)
// ---------------------------------------------------------------------------
describe("telemetry.parseConnectionString (indirect)", () => {
afterEach(async () => {
await Telemetry.shutdown()
mock.restore()
})
test("valid connection string enables telemetry and produces correct endpoint in flush", async () => {
const origEnv = process.env.ALTIMATE_TELEMETRY_DISABLED
const origCs = process.env.APPLICATIONINSIGHTS_CONNECTION_STRING
const fetchCalls: { url: string; body: string }[] = []
const fetchMock = spyOn(global, "fetch").mockImplementation(async (input: any, init: any) => {
fetchCalls.push({ url: String(input), body: String(init?.body ?? "") })
return new Response("", { status: 200 })
})
try {
delete process.env.ALTIMATE_TELEMETRY_DISABLED
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING =
"InstrumentationKey=test-key-123;IngestionEndpoint=https://example.com"
await Telemetry.init()
Telemetry.track({
type: "session_start",
timestamp: 1000,
session_id: "s1",
model_id: "m1",
provider_id: "p1",
agent: "a1",
project_id: "proj1",
os: "linux",
arch: "x64",
node_version: "v22.0.0",
})
await Telemetry.flush()
expect(fetchCalls.length).toBe(1)
expect(fetchCalls[0].url).toBe("https://example.com/v2/track")
const body = JSON.parse(fetchCalls[0].body)
expect(body[0].iKey).toBe("test-key-123")
} finally {
process.env.ALTIMATE_TELEMETRY_DISABLED = origEnv
if (origCs !== undefined) process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = origCs
else delete process.env.APPLICATIONINSIGHTS_CONNECTION_STRING
fetchMock.mockRestore()
}
})
test("missing InstrumentationKey in connection string disables telemetry", async () => {
const origEnv = process.env.ALTIMATE_TELEMETRY_DISABLED
const origCs = process.env.APPLICATIONINSIGHTS_CONNECTION_STRING
const fetchMock = spyOn(global, "fetch").mockImplementation(async () => {
return new Response("", { status: 200 })
})
try {
delete process.env.ALTIMATE_TELEMETRY_DISABLED
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = "IngestionEndpoint=https://example.com"
await Telemetry.init()
Telemetry.track({
type: "session_start",
timestamp: 1000,
session_id: "s1",
model_id: "m1",
provider_id: "p1",
agent: "a1",
project_id: "proj1",
os: "linux",
arch: "x64",
node_version: "v22.0.0",
})
await Telemetry.flush()
// fetch should NOT be called — telemetry disabled due to invalid connection string
expect(fetchMock).not.toHaveBeenCalled()
} finally {
process.env.ALTIMATE_TELEMETRY_DISABLED = origEnv
if (origCs !== undefined) process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = origCs
else delete process.env.APPLICATIONINSIGHTS_CONNECTION_STRING
fetchMock.mockRestore()
}
})
test("trailing slash on IngestionEndpoint is handled correctly", async () => {
const origEnv = process.env.ALTIMATE_TELEMETRY_DISABLED
const origCs = process.env.APPLICATIONINSIGHTS_CONNECTION_STRING
const fetchCalls: { url: string }[] = []
const fetchMock = spyOn(global, "fetch").mockImplementation(async (input: any) => {
fetchCalls.push({ url: String(input) })
return new Response("", { status: 200 })
})
try {
delete process.env.ALTIMATE_TELEMETRY_DISABLED
// Trailing slash — should not double-up
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING =
"InstrumentationKey=key-456;IngestionEndpoint=https://example.com/"
await Telemetry.init()
Telemetry.track({
type: "session_start",
timestamp: 1000,
session_id: "s1",
model_id: "m1",
provider_id: "p1",
agent: "a1",
project_id: "proj1",
os: "linux",
arch: "x64",
node_version: "v22.0.0",
})
await Telemetry.flush()
expect(fetchCalls.length).toBe(1)
// Should be /v2/track, not //v2/track
expect(fetchCalls[0].url).toBe("https://example.com/v2/track")
} finally {
process.env.ALTIMATE_TELEMETRY_DISABLED = origEnv
if (origCs !== undefined) process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = origCs
else delete process.env.APPLICATIONINSIGHTS_CONNECTION_STRING
fetchMock.mockRestore()
}
})
test("empty connection string disables telemetry", async () => {
const origEnv = process.env.ALTIMATE_TELEMETRY_DISABLED
const origCs = process.env.APPLICATIONINSIGHTS_CONNECTION_STRING
const fetchMock = spyOn(global, "fetch").mockImplementation(async () => {
return new Response("", { status: 200 })
})
try {
delete process.env.ALTIMATE_TELEMETRY_DISABLED
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = ""
await Telemetry.init()
Telemetry.track({
type: "session_start",
timestamp: 1000,
session_id: "s1",
model_id: "m1",
provider_id: "p1",
agent: "a1",
project_id: "proj1",
os: "linux",
arch: "x64",
node_version: "v22.0.0",
})
await Telemetry.flush()
expect(fetchMock).not.toHaveBeenCalled()
} finally {
process.env.ALTIMATE_TELEMETRY_DISABLED = origEnv
if (origCs !== undefined) process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = origCs
else delete process.env.APPLICATIONINSIGHTS_CONNECTION_STRING
fetchMock.mockRestore()
}
})
})
// ---------------------------------------------------------------------------
// 9. toAppInsightsEnvelopes (tested indirectly via track + flush)
// ---------------------------------------------------------------------------
describe("telemetry.toAppInsightsEnvelopes (indirect)", () => {
afterEach(async () => {
await Telemetry.shutdown()
mock.restore()
})
async function initWithMockedFetch(): {
fetchCalls: { url: string; body: string }[]
fetchMock: ReturnType<typeof spyOn>
cleanup: () => void
} {
const origEnv = process.env.ALTIMATE_TELEMETRY_DISABLED
const origCs = process.env.APPLICATIONINSIGHTS_CONNECTION_STRING
delete process.env.ALTIMATE_TELEMETRY_DISABLED
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING =
"InstrumentationKey=test-ikey;IngestionEndpoint=https://test.endpoint.com"
const fetchCalls: { url: string; body: string }[] = []
const fetchMock = spyOn(global, "fetch").mockImplementation(async (_input: any, init: any) => {
fetchCalls.push({ url: String(_input), body: String(init?.body ?? "") })
return new Response("", { status: 200 })
})
await Telemetry.init()
return {
fetchCalls,
fetchMock,
cleanup: () => {
process.env.ALTIMATE_TELEMETRY_DISABLED = origEnv
if (origCs !== undefined) process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = origCs
else delete process.env.APPLICATIONINSIGHTS_CONNECTION_STRING
fetchMock.mockRestore()
},
}
}
test("basic event is converted to envelope format", async () => {
const { fetchCalls, cleanup } = await initWithMockedFetch()
try {
Telemetry.setContext({ sessionId: "sess-abc", projectId: "proj-xyz" })
Telemetry.track({
type: "session_start",
timestamp: 1700000000000,
session_id: "sess-abc",
model_id: "claude-3",
provider_id: "anthropic",
agent: "builder",
project_id: "proj-xyz",
os: "linux",
arch: "x64",
node_version: "v22.0.0",
})
await Telemetry.flush()
expect(fetchCalls.length).toBe(1)
const envelopes = JSON.parse(fetchCalls[0].body)
expect(envelopes.length).toBe(1)
const env = envelopes[0]
expect(env.name).toBe("Microsoft.ApplicationInsights.test-ikey.Event")
expect(env.iKey).toBe("test-ikey")
expect(env.time).toBe(new Date(1700000000000).toISOString())
expect(env.tags["ai.session.id"]).toBe("sess-abc")
expect(env.tags["ai.cloud.role"]).toBe("altimate")
expect(env.data.baseType).toBe("EventData")
expect(env.data.baseData.ver).toBe(2)
expect(env.data.baseData.name).toBe("session_start")
// String fields go to properties
expect(env.data.baseData.properties.model_id).toBe("claude-3")
expect(env.data.baseData.properties.provider_id).toBe("anthropic")
expect(env.data.baseData.properties.agent).toBe("builder")
} finally {
cleanup()
}
})
test("numeric fields go to measurements, string fields go to properties", async () => {
const { fetchCalls, cleanup } = await initWithMockedFetch()
try {
Telemetry.track({
type: "session_end",
timestamp: 1700000000000,
session_id: "sess-1",
total_cost: 0.05,
total_tokens: 1500,
tool_call_count: 10,
duration_ms: 30000,
})
await Telemetry.flush()
const envelopes = JSON.parse(fetchCalls[0].body)
const baseData = envelopes[0].data.baseData
// Numeric fields in measurements
expect(baseData.measurements.total_cost).toBe(0.05)
expect(baseData.measurements.total_tokens).toBe(1500)
expect(baseData.measurements.tool_call_count).toBe(10)
expect(baseData.measurements.duration_ms).toBe(30000)
} finally {
cleanup()
}
})
test("flat token fields appear in measurements", async () => {
const { fetchCalls, cleanup } = await initWithMockedFetch()
try {
Telemetry.track({
type: "generation",
timestamp: 1700000000000,
session_id: "sess-1",
message_id: "msg-1",
model_id: "claude-3",
provider_id: "anthropic",
agent: "builder",
finish_reason: "end_turn",
tokens_input: 100,
tokens_output: 200,
tokens_reasoning: 50,
tokens_cache_read: 10,
tokens_cache_write: 5,
cost: 0.01,
duration_ms: 2000,
})
await Telemetry.flush()
const envelopes = JSON.parse(fetchCalls[0].body)
const measurements = envelopes[0].data.baseData.measurements
expect(measurements.tokens_input).toBe(100)
expect(measurements.tokens_output).toBe(200)
expect(measurements.tokens_reasoning).toBe(50)
expect(measurements.tokens_cache_read).toBe(10)
expect(measurements.tokens_cache_write).toBe(5)
} finally {
cleanup()
}
})
test("fallback sessionId when none set on event", async () => {
const { fetchCalls, cleanup } = await initWithMockedFetch()
try {
// Set context with a session ID
Telemetry.setContext({ sessionId: "fallback-sess", projectId: "p" })
// Track event without session_id in the actual event payload is not possible
// since all events require session_id. But we can verify the tags use event's session_id.
// If the event session_id is empty, the module falls back to the context sessionId.
Telemetry.track({
type: "error",
timestamp: 1700000000000,
session_id: "",
error_name: "TestError",
error_message: "test",
context: "test",
})
await Telemetry.flush()
const envelopes = JSON.parse(fetchCalls[0].body)
// Empty session_id falls back to "startup" (since "" is falsy)
// Actually, looking at the code: `const sid = fields.session_id ?? sessionId`
// "" is not null/undefined, so sid = "". Then `sid || "startup"` = "startup"
expect(envelopes[0].tags["ai.session.id"]).toBe("startup")
} finally {
cleanup()
}
})
test("timestamp is included as ISO string", async () => {
const { fetchCalls, cleanup } = await initWithMockedFetch()
try {
const ts = 1700000000000
Telemetry.track({
type: "session_start",
timestamp: ts,
session_id: "s1",
model_id: "m",
provider_id: "p",
agent: "a",
project_id: "proj",
os: "linux",
arch: "x64",
node_version: "v22.0.0",
})
await Telemetry.flush()
const envelopes = JSON.parse(fetchCalls[0].body)
expect(envelopes[0].time).toBe(new Date(ts).toISOString())
} finally {
cleanup()
}
})
})
// ---------------------------------------------------------------------------
// 10. flush
// ---------------------------------------------------------------------------
describe("telemetry.flush", () => {
afterEach(async () => {
await Telemetry.shutdown()
mock.restore()
})
test("flush sends buffered events via fetch", async () => {
const origEnv = process.env.ALTIMATE_TELEMETRY_DISABLED
const origCs = process.env.APPLICATIONINSIGHTS_CONNECTION_STRING
let fetchCallCount = 0
const fetchMock = spyOn(global, "fetch").mockImplementation(async () => {
fetchCallCount++
return new Response("", { status: 200 })
})
try {
delete process.env.ALTIMATE_TELEMETRY_DISABLED
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = "InstrumentationKey=k;IngestionEndpoint=https://e.com"
await Telemetry.init()
Telemetry.track({
type: "session_start",
timestamp: Date.now(),
session_id: "s1",
model_id: "m",
provider_id: "p",
agent: "a",
project_id: "proj",
os: "linux",
arch: "x64",
node_version: "v22.0.0",
})
await Telemetry.flush()
expect(fetchCallCount).toBe(1)
} finally {
process.env.ALTIMATE_TELEMETRY_DISABLED = origEnv
if (origCs !== undefined) process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = origCs
else delete process.env.APPLICATIONINSIGHTS_CONNECTION_STRING
fetchMock.mockRestore()
}
})
test("flush clears the buffer after success", async () => {
const origEnv = process.env.ALTIMATE_TELEMETRY_DISABLED
const origCs = process.env.APPLICATIONINSIGHTS_CONNECTION_STRING
let fetchCallCount = 0
const fetchMock = spyOn(global, "fetch").mockImplementation(async () => {
fetchCallCount++
return new Response("", { status: 200 })
})
try {
delete process.env.ALTIMATE_TELEMETRY_DISABLED
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = "InstrumentationKey=k;IngestionEndpoint=https://e.com"
await Telemetry.init()
Telemetry.track({
type: "session_start",
timestamp: Date.now(),
session_id: "s1",
model_id: "m",
provider_id: "p",
agent: "a",
project_id: "proj",
os: "linux",
arch: "x64",
node_version: "v22.0.0",
})
await Telemetry.flush()
expect(fetchCallCount).toBe(1)
// Second flush should not call fetch — buffer is empty
await Telemetry.flush()
expect(fetchCallCount).toBe(1)
} finally {
process.env.ALTIMATE_TELEMETRY_DISABLED = origEnv
if (origCs !== undefined) process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = origCs
else delete process.env.APPLICATIONINSIGHTS_CONNECTION_STRING
fetchMock.mockRestore()
}
})
test("flush re-adds events to buffer on network error", async () => {
const origEnv = process.env.ALTIMATE_TELEMETRY_DISABLED
const origCs = process.env.APPLICATIONINSIGHTS_CONNECTION_STRING
let fetchCallCount = 0
const fetchMock = spyOn(global, "fetch").mockImplementation(async () => {
fetchCallCount++
throw new Error("Network error")
})
try {
delete process.env.ALTIMATE_TELEMETRY_DISABLED
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = "InstrumentationKey=k;IngestionEndpoint=https://e.com"
await Telemetry.init()
Telemetry.track({
type: "session_start",
timestamp: Date.now(),
session_id: "s1",
model_id: "m",
provider_id: "p",
agent: "a",
project_id: "proj",
os: "linux",
arch: "x64",
node_version: "v22.0.0",
})
// First flush — network error, events re-added to buffer
await Telemetry.flush()
expect(fetchCallCount).toBe(1)
// Second flush should attempt again (events were re-added with _retried flag)
await Telemetry.flush()
expect(fetchCallCount).toBe(2)
// Third flush — events had _retried=true, so after second failure they are
// filtered out by `events.filter(e => !e._retried)` and NOT re-added.
// Buffer is now empty, so third flush is a no-op.
await Telemetry.flush()
expect(fetchCallCount).toBe(2)
} finally {
process.env.ALTIMATE_TELEMETRY_DISABLED = origEnv
if (origCs !== undefined) process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = origCs
else delete process.env.APPLICATIONINSIGHTS_CONNECTION_STRING
fetchMock.mockRestore()
}
})
test("flush handles AbortController timeout", async () => {
const origEnv = process.env.ALTIMATE_TELEMETRY_DISABLED
const origCs = process.env.APPLICATIONINSIGHTS_CONNECTION_STRING
const fetchMock = spyOn(global, "fetch").mockImplementation(async (_input: any, init: any) => {
// Verify that signal is passed
expect(init?.signal).toBeDefined()
expect(init.signal).toBeInstanceOf(AbortSignal)
return new Response("", { status: 200 })
})
try {
delete process.env.ALTIMATE_TELEMETRY_DISABLED
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = "InstrumentationKey=k;IngestionEndpoint=https://e.com"
await Telemetry.init()
Telemetry.track({
type: "session_start",
timestamp: Date.now(),
session_id: "s1",
model_id: "m",
provider_id: "p",
agent: "a",
project_id: "proj",
os: "linux",
arch: "x64",
node_version: "v22.0.0",
})
await Telemetry.flush()
expect(fetchMock).toHaveBeenCalled()
} finally {
process.env.ALTIMATE_TELEMETRY_DISABLED = origEnv
if (origCs !== undefined) process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = origCs
else delete process.env.APPLICATIONINSIGHTS_CONNECTION_STRING
fetchMock.mockRestore()
}
})
test("droppedEvents counter is included in flush and reset after", async () => {
const origEnv = process.env.ALTIMATE_TELEMETRY_DISABLED
const origCs = process.env.APPLICATIONINSIGHTS_CONNECTION_STRING
const fetchBodies: string[] = []
const fetchMock = spyOn(global, "fetch").mockImplementation(async (_input: any, init: any) => {
fetchBodies.push(String(init?.body ?? ""))
return new Response("", { status: 200 })
})
try {
delete process.env.ALTIMATE_TELEMETRY_DISABLED
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = "InstrumentationKey=k;IngestionEndpoint=https://e.com"
await Telemetry.init()
// Fill buffer beyond MAX_BUFFER_SIZE (200) to trigger drops
for (let i = 0; i < 210; i++) {
Telemetry.track({
type: "session_start",
timestamp: Date.now(),
session_id: "s1",
model_id: "m",
provider_id: "p",
agent: "a",
project_id: "proj",
os: "linux",
arch: "x64",
node_version: "v22.0.0",
})
}
await Telemetry.flush()
expect(fetchBodies.length).toBe(1)
const envelopes = JSON.parse(fetchBodies[0])
// Should include a TelemetryBufferOverflow error event
const overflowEvent = envelopes.find(
(e: any) =>
e.data?.baseData?.name === "error" && e.data?.baseData?.properties?.error_name === "TelemetryBufferOverflow",
)
expect(overflowEvent).toBeDefined()
expect(overflowEvent.data.baseData.properties.error_message).toContain("10 events dropped")
// Second flush — no more dropped events counter
Telemetry.track({
type: "session_start",
timestamp: Date.now(),
session_id: "s1",
model_id: "m",
provider_id: "p",
agent: "a",
project_id: "proj",
os: "linux",
arch: "x64",
node_version: "v22.0.0",
})
await Telemetry.flush()
const envelopes2 = JSON.parse(fetchBodies[1])
const overflowEvent2 = envelopes2.find(
(e: any) => e.data?.baseData?.properties?.error_name === "TelemetryBufferOverflow",
)
expect(overflowEvent2).toBeUndefined()
} finally {
process.env.ALTIMATE_TELEMETRY_DISABLED = origEnv
if (origCs !== undefined) process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = origCs
else delete process.env.APPLICATIONINSIGHTS_CONNECTION_STRING
fetchMock.mockRestore()
}
})
})
// ---------------------------------------------------------------------------
// 11. shutdown
// ---------------------------------------------------------------------------
describe("telemetry.shutdown", () => {
afterEach(async () => {
await Telemetry.shutdown()
mock.restore()
})
test("shutdown flushes remaining events", async () => {
const origEnv = process.env.ALTIMATE_TELEMETRY_DISABLED
const origCs = process.env.APPLICATIONINSIGHTS_CONNECTION_STRING
let fetchCallCount = 0
const fetchMock = spyOn(global, "fetch").mockImplementation(async () => {
fetchCallCount++
return new Response("", { status: 200 })
})
try {
delete process.env.ALTIMATE_TELEMETRY_DISABLED
process.env.APPLICATIONINSIGHTS_CONNECTION_STRING = "InstrumentationKey=k;IngestionEndpoint=https://e.com"
await Telemetry.init()
Telemetry.track({
type: "session_start",
timestamp: Date.now(),
session_id: "s1",
model_id: "m",
provider_id: "p",
agent: "a",
project_id: "proj",
os: "linux",
arch: "x64",
node_version: "v22.0.0",
})