forked from google/pprof-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathtest-time-profiler.ts
More file actions
1225 lines (1083 loc) · 39.8 KB
/
Copy pathtest-time-profiler.ts
File metadata and controls
1225 lines (1083 loc) · 39.8 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
/**
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as sinon from 'sinon';
import {isAsyncContextFrameActive} from '../src/async-context-frame';
import {time, getNativeThreadId} from '../src';
import {profileV2, stopV2} from '../src/time-profiler';
import * as v8TimeProfiler from '../src/time-profiler-bindings';
import * as profileSerializer from '../src/profile-serializer';
import {SourceMapper} from '../src/sourcemapper/sourcemapper';
import {timeProfile, v8TimeProfile} from './profiles-for-tests';
import {hrtime} from 'process';
import {Label, Profile} from 'pprof-format';
import {AssertionError} from 'assert';
import {GenerateTimeLabelsArgs, LabelSet} from '../src/v8-types';
import {satisfies} from 'semver';
import {setTimeout as setTimeoutPromise} from 'timers/promises';
import {fork} from 'child_process';
import assert from 'assert';
const useCPED =
isAsyncContextFrameActive() && satisfies(process.versions.node, '>=22.7.0');
const collectAsyncId = satisfies(process.versions.node, '>=24.0.0');
const unsupportedPlatform =
process.platform !== 'darwin' && process.platform !== 'linux';
const shouldSkipCPEDTests = !useCPED || unsupportedPlatform;
const PROFILE_OPTIONS = {
durationMillis: 500,
intervalMicros: 1000,
};
describe('Time Profiler', () => {
describe('profile', () => {
it('should exclude program and idle time', async () => {
const profile = await time.profile(PROFILE_OPTIONS);
assert.ok(profile.stringTable);
assert.equal(profile.stringTable.strings!.indexOf('(program)'), -1);
});
it('should update state', function shouldUpdateState() {
if (unsupportedPlatform) {
this.skip();
}
const startTime = BigInt(Date.now()) * 1000n;
time.start({
intervalMicros: 20 * 1_000,
durationMillis: PROFILE_OPTIONS.durationMillis,
withContexts: true,
lineNumbers: false,
useCPED,
});
const initialContext: {[key: string]: string} = {};
const kSampleCount = time.constants.kSampleCount;
const state = time.getState();
assert.equal(state[kSampleCount], 0, 'Initial state should be 0');
let checked = false;
// Collect several samples while the context is active, then verify the
// context was associated with them. Two things make this robust against
// the flakiness this test used to exhibit:
// - We establish the context the way production code does: via
// runWithContext when useCPED is enabled, and setContext otherwise.
// A bare setContext under useCPED only takes effect when the current
// continuation already has an AsyncContextFrame, so on its own it
// silently no-ops — which made the result depend on test ordering.
// - We wait for several samples rather than a single one. The first
// sample is taken at profiler start (before any context is set) and
// is skipped during context association, so relying on just one
// sample left nothing reliable to associate the context with.
const minSamples = 5;
function sampleAndVerify() {
const deadline = Date.now() + 5_000;
while (state[kSampleCount] < minSamples) {
if (Date.now() > deadline) {
assert.fail(
`Only ${state[kSampleCount]} sample(s) collected, expected ${minSamples}`,
);
}
}
// Mutate the context object after the samples were taken: the profiler
// stores a live reference to it, so the change must be visible below.
initialContext['aaa'] = 'bbb';
let endTime = 0n;
time.stop(false, ({node, context}: GenerateTimeLabelsArgs) => {
if (node.name === time.constants.NON_JS_THREADS_FUNCTION_NAME) {
return {};
}
assert.ok(context !== null, 'Context should not be null');
if (!endTime) {
endTime = BigInt(Date.now()) * 1000n;
}
assert.deepEqual(
context!.context,
initialContext,
'Unexpected context',
);
assert.ok(context!.timestamp >= startTime);
assert.ok(context!.timestamp <= endTime);
checked = true;
return {...context!.context};
});
}
if (useCPED) {
time.runWithContext(initialContext, sampleAndVerify);
} else {
time.setContext(initialContext);
sampleAndVerify();
}
assert(checked, 'No context found');
});
it('should have labels', function shouldHaveLabels() {
if (unsupportedPlatform) {
this.skip();
}
this.timeout(3000);
const intervalNanos = PROFILE_OPTIONS.intervalMicros * 1_000;
time.start({
intervalMicros: PROFILE_OPTIONS.intervalMicros,
durationMillis: PROFILE_OPTIONS.durationMillis,
withContexts: true,
collectAsyncId: collectAsyncId,
lineNumbers: false,
useCPED,
});
// By repeating the test few times, we also exercise the profiler
// start-stop overlap behavior.
const repeats = 3;
const rootSpanId = '1234';
const endPointLabel = 'trace endpoint';
const rootSpanIdLabel = 'local root span id';
const asyncIdLabel = 'async id';
const endPoint = 'foo';
let enableEndPoint = false;
const label0 = {label: 'value0'};
const label1 = {label: 'value1', [rootSpanIdLabel]: rootSpanId};
for (let i = 0; i < repeats; ++i) {
loop();
enableEndPoint = i % 2 === 0;
validateProfile(
time.stop(
i < repeats - 1,
enableEndPoint || collectAsyncId ? generateLabels : undefined,
),
);
}
function generateLabels({context}: GenerateTimeLabelsArgs) {
if (!context) {
return {};
}
const labels: LabelSet = {};
if (typeof context.asyncId !== 'undefined') {
assert(collectAsyncId);
labels[asyncIdLabel] = context.asyncId;
}
for (const [key, value] of Object.entries(context.context ?? {})) {
if (typeof value === 'string') {
labels[key] = value;
if (
enableEndPoint &&
key === rootSpanIdLabel &&
value === rootSpanId
) {
labels[endPointLabel] = endPoint;
}
}
}
return labels;
}
// Each of fn0, fn1, fn2 loops busily for one or two profiling intervals.
// fn0 resets the label; fn1 and fn2 don't. Label for fn1
// is reset in the loop. This ensures the following invariants that we
// test for:
// label0 can be observed in loop or fn0
// label1 can be observed in loop or fn1
// fn0 might be observed with no label
// fn1 must always be observed with label1
// fn2 must never be observed with a label
function fn0() {
const start = hrtime.bigint();
while (hrtime.bigint() - start < intervalNanos);
time.setContext(undefined);
// With node 22, many deopt events are generated by `setContext` call above.
// On MacOS, `v8::TimeTicks::Now` has a resolution of ~42us because
// `mach_absolute_time` ticks (a tick is ~42ns) conversion to microseconds
// is done in such a way that drops the 3 least significant digits
// (https://github.com/nodejs/node/blob/v22.x/deps/v8/src/base/platform/time.cc#L745-L746).
// This two facts lead to samples having identical timestamps, and
// incorrectly matched contexts.
// Workaround here just ensures that after deopt event caused by `setContext`,
// no sample in `fn1` is immediately taken.
const start2 = hrtime.bigint();
while (hrtime.bigint() - start2 < intervalNanos);
}
function fn1() {
const start = hrtime.bigint();
while (hrtime.bigint() - start < intervalNanos);
}
function fn2() {
const start = hrtime.bigint();
while (hrtime.bigint() - start < intervalNanos);
}
function loop() {
const durationNanos = PROFILE_OPTIONS.durationMillis * 1_000_000;
const start = hrtime.bigint();
while (hrtime.bigint() - start < durationNanos) {
time.setContext(label0);
fn0();
time.setContext(label1);
fn1();
time.setContext(undefined);
fn2();
}
}
function validateProfile(profile: Profile) {
// Get string table indices for strings we're interested in
const stringTable = profile.stringTable;
const [
loopIdx,
fn0Idx,
fn1Idx,
fn2Idx,
hrtimeBigIntIdx,
asyncIdLabelIdx,
] = ['loop', 'fn0', 'fn1', 'fn2', 'hrtimeBigInt', asyncIdLabel].map(x =>
stringTable.dedup(x),
);
function getString(n: number | bigint): string {
if (typeof n === 'number') {
return stringTable.strings[n];
}
throw new AssertionError({message: 'Expected a number'});
}
function labelIs(l: Label, key: string, str: string) {
return getString(l.key) === key && getString(l.str) === str;
}
function idx(n: number | bigint): number {
if (typeof n === 'number') {
// We want a 0-based array index, but IDs start from 1.
return n - 1;
}
throw new AssertionError({message: 'Expected a number'});
}
function labelStr(label: Label) {
return label
? `${getString(label.key)}=${getString(label.str)}`
: 'undefined';
}
function getLabels(labels: Label[]) {
const labelObj: {[key: string]: string} = {};
labels.forEach(label => {
labelObj[getString(label.key)] = getString(label.str);
});
return labelObj;
}
let fn0ObservedWithLabel0 = false;
let fn1ObservedWithLabel1 = false;
let fn2ObservedWithoutLabels = false;
let observedAsyncId = false;
profile.sample.forEach(sample => {
let fnName;
for (const locationId of sample.locationId) {
const locIdx = idx(locationId);
const loc = profile.location[locIdx];
const fnIdx = idx(loc.line[0].functionId);
const fn = profile.function[fnIdx];
fnName = fn.name;
if (fnName !== hrtimeBigIntIdx) {
break;
}
}
const labels = sample.label;
if (collectAsyncId) {
const idx = labels.findIndex(
label => label.key === asyncIdLabelIdx,
);
if (idx !== -1) {
// Remove async ID label so it doesn't confuse the assertions on
// labels further below.
labels.splice(idx, 1);
observedAsyncId = true;
}
}
switch (fnName) {
case loopIdx:
if (enableEndPoint) {
assert(
labels.length < 4,
'loop can have at most two labels and one endpoint',
);
labels.forEach(label => {
assert(
labelIs(label, 'label', 'value0') ||
labelIs(label, 'label', 'value1') ||
labelIs(label, endPointLabel, endPoint) ||
labelIs(label, rootSpanIdLabel, rootSpanId),
'loop can be observed with value0 or value1 or root span id or endpoint',
);
});
} else {
assert(labels.length < 3, 'loop can have at most one label');
labels.forEach(label => {
assert(
labelIs(label, 'label', 'value0') ||
labelIs(label, 'label', 'value1') ||
labelIs(label, rootSpanIdLabel, rootSpanId),
'loop can be observed with value0 or value1 or root span id',
);
});
}
break;
case fn0Idx:
assert(
labels.length < 2,
`fn0 can have at most one label, instead got: ${labels.map(
labelStr,
)}`,
);
labels.forEach(label => {
if (labelIs(label, 'label', 'value0')) {
fn0ObservedWithLabel0 = true;
} else {
throw new AssertionError({
message:
'Only value0 can be observed with fn0. Observed instead ' +
labelStr(label),
});
}
});
break;
case fn1Idx:
if (enableEndPoint) {
assert(
labels.length === 3,
'fn1 must be observed with a label, a root span id and an endpoint',
);
const labelMap = getLabels(labels);
assert.deepEqual(labelMap, {
...label1,
[endPointLabel]: endPoint,
});
} else {
assert(
labels.length === 2,
'fn1 must be observed with a label',
);
labels.forEach(label => {
assert(
labelIs(label, 'label', 'value1') ||
labelIs(label, rootSpanIdLabel, rootSpanId),
'Only value1 can be observed with fn1',
);
});
}
fn1ObservedWithLabel1 = true;
break;
case fn2Idx:
assert(
labels.length === 0,
'fn2 must be observed with no labels. Observed instead with ' +
labelStr(labels[0]),
);
fn2ObservedWithoutLabels = true;
break;
default:
// Make no assumptions about other functions; we can just as well
// capture internals of time-profiler.ts, GC, etc.
}
});
assert(fn0ObservedWithLabel0, 'fn0 was not observed with value0');
assert(fn1ObservedWithLabel1, 'fn1 was not observed with value1');
assert(
fn2ObservedWithoutLabels,
'fn2 was not observed without a label',
);
assert(!collectAsyncId || observedAsyncId, 'Async ID was not observed');
}
});
});
it('should have async IDs when enabled', async function shouldCollectAsyncIDs() {
if (!(collectAsyncId && ['darwin', 'linux'].includes(process.platform))) {
this.skip();
}
this.timeout(3000);
time.start({
intervalMicros: PROFILE_OPTIONS.intervalMicros,
durationMillis: PROFILE_OPTIONS.durationMillis,
withContexts: true,
lineNumbers: false,
collectAsyncId: true,
});
let setDone: () => void;
const done = new Promise<void>(resolve => {
setDone = resolve;
});
const testStart = hrtime.bigint();
const testDurationNanos = PROFILE_OPTIONS.durationMillis * 1_000_000;
setTimeout(loop, 0);
function loop() {
const loopDurationNanos = PROFILE_OPTIONS.intervalMicros * 1_000;
const loopStart = hrtime.bigint();
while (hrtime.bigint() - loopStart < loopDurationNanos);
if (hrtime.bigint() - testStart < testDurationNanos) {
setTimeout(loop, 0);
} else {
setDone();
}
}
await done;
let asyncIdObserved = false;
time.stop(false, ({context}: GenerateTimeLabelsArgs) => {
if (!asyncIdObserved && typeof context?.asyncId === 'number') {
asyncIdObserved = context?.asyncId !== -1;
}
return {};
});
assert(asyncIdObserved, 'Async ID was not observed');
});
describe('profile (w/ stubs)', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const sinonStubs: Array<sinon.SinonStub<any, any>> = [];
const timeProfilerStub = {
start: sinon.stub(),
stop: sinon.stub().returns(v8TimeProfile),
dispose: sinon.stub(),
v8ProfilerStuckEventLoopDetected: sinon.stub().returns(0),
};
before(() => {
sinonStubs.push(
sinon.stub(v8TimeProfiler, 'TimeProfiler').returns(timeProfilerStub),
);
sinonStubs.push(sinon.stub(Date, 'now').returns(0));
});
after(() => {
sinonStubs.forEach(stub => {
stub.restore();
});
});
it('should profile during duration and finish profiling after duration', async () => {
let isProfiling = true;
void time.profile(PROFILE_OPTIONS).then(() => {
isProfiling = false;
});
await setTimeoutPromise(2 * PROFILE_OPTIONS.durationMillis);
assert.strictEqual(false, isProfiling, 'profiler is still running');
});
it('should return a profile equal to the expected profile', async () => {
const profile = await time.profile(PROFILE_OPTIONS);
assert.deepEqual(timeProfile, profile);
});
it('should be able to restart when stopping', async () => {
time.start({intervalMicros: PROFILE_OPTIONS.intervalMicros});
timeProfilerStub.start.resetHistory();
timeProfilerStub.stop.resetHistory();
assert.deepEqual(timeProfile, time.stop(true));
assert.equal(
time.v8ProfilerStuckEventLoopDetected(),
0,
'v8 bug detected',
);
sinon.assert.notCalled(timeProfilerStub.start);
sinon.assert.calledOnce(timeProfilerStub.stop);
timeProfilerStub.start.resetHistory();
timeProfilerStub.stop.resetHistory();
assert.deepEqual(timeProfile, time.stop());
sinon.assert.notCalled(timeProfilerStub.start);
sinon.assert.calledOnce(timeProfilerStub.stop);
});
it('should serialize with the source mapper still set when stopping', () => {
// Regression test: stop() used to tear down the profiler state (via
// handleStopNoRestart, which clears gSourceMapper) *before* serializing,
// so the source mapper passed to start() was dropped and transpiled
// frames were left pointing at the generated files instead of the
// original sources. The third argument to serializeTimeProfile is the
// source mapper; it must still be the one passed to start().
const sourceMapper = {} as unknown as SourceMapper;
const serializeStub = sinon
.stub(profileSerializer, 'serializeTimeProfile')
.returns(timeProfile);
try {
// no-restart path: handleStopNoRestart() clears gSourceMapper, so it
// must run after serialization.
time.start({
intervalMicros: PROFILE_OPTIONS.intervalMicros,
sourceMapper,
});
time.stop();
sinon.assert.calledOnce(serializeStub);
assert.strictEqual(
serializeStub.getCall(0).args[2],
sourceMapper,
'source mapper dropped on stop()',
);
// restart path: the source mapper must be preserved here too.
serializeStub.resetHistory();
time.start({
intervalMicros: PROFILE_OPTIONS.intervalMicros,
sourceMapper,
});
time.stop(true);
assert.strictEqual(
serializeStub.getCall(0).args[2],
sourceMapper,
'source mapper dropped on stop(true)',
);
time.stop(); // finalize: dispose the restarted profiler
} finally {
serializeStub.restore();
}
});
});
describe('profileV2', () => {
it('should exclude program and idle time', async () => {
const profile = await time.profileV2(PROFILE_OPTIONS);
assert.ok(profile.stringTable);
assert.equal(profile.stringTable.strings!.indexOf('(program)'), -1);
});
it('should preserve line-number root children metadata in lazy view', function () {
if (unsupportedPlatform) {
this.skip();
}
function hotPath() {
const end = hrtime.bigint() + 2_000_000n;
while (hrtime.bigint() < end);
}
const profiler = new v8TimeProfiler.TimeProfiler({
intervalMicros: 100,
durationMillis: 200,
lineNumbers: true,
withContexts: false,
workaroundV8Bug: false,
collectCpuTime: false,
collectAsyncId: false,
useCPED: false,
isMainThread: true,
});
profiler.start();
try {
const deadline = Date.now() + 200;
while (Date.now() < deadline) {
hotPath();
}
let sawRootChildren = false;
let sawChildWithNonRootMetadata = false;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
profiler.stopAndCollect(false, (profile: any) => {
const root = profile.topDownRoot as {
name: string;
scriptName: string;
scriptId: number;
children: Array<{
name: string;
scriptName: string;
scriptId: number;
}>;
};
const children = root.children;
sawRootChildren = children.length > 0;
sawChildWithNonRootMetadata = children.some(
child =>
child.name !== root.name ||
child.scriptName !== root.scriptName ||
child.scriptId !== root.scriptId,
);
return undefined;
});
assert(sawRootChildren, 'Expected root to have children');
assert(
sawChildWithNonRootMetadata,
'Line-number lazy root children should not collapse to root metadata',
);
} finally {
profiler.dispose();
}
});
});
describe('profileV2 (w/ stubs)', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const sinonStubs: Array<sinon.SinonStub<any, any>> = [];
const timeProfilerStub = {
start: sinon.stub(),
// stopAndCollect invokes the callback synchronously with the raw profile,
// mirroring what the native binding does.
stopAndCollect: sinon
.stub()
.callsFake(
(_restart: boolean, cb: (p: typeof v8TimeProfile) => unknown) =>
cb(v8TimeProfile),
),
dispose: sinon.stub(),
v8ProfilerStuckEventLoopDetected: sinon.stub().returns(0),
};
before(() => {
sinonStubs.push(
sinon.stub(v8TimeProfiler, 'TimeProfiler').returns(timeProfilerStub),
);
sinonStubs.push(sinon.stub(Date, 'now').returns(0));
});
after(() => {
sinonStubs.forEach(stub => stub.restore());
});
it('should profile during duration and finish profiling after duration', async () => {
let isProfiling = true;
void profileV2(PROFILE_OPTIONS).then(() => {
isProfiling = false;
});
await setTimeoutPromise(2 * PROFILE_OPTIONS.durationMillis);
assert.strictEqual(false, isProfiling, 'profiler is still running');
});
it('should return a profile equal to the expected profile', async () => {
const profile = await profileV2(PROFILE_OPTIONS);
assert.deepEqual(timeProfile, profile);
});
it('should be able to restart when stopping', async () => {
time.start({intervalMicros: PROFILE_OPTIONS.intervalMicros});
timeProfilerStub.start.resetHistory();
timeProfilerStub.stopAndCollect.resetHistory();
assert.deepEqual(timeProfile, stopV2(true));
assert.equal(
time.v8ProfilerStuckEventLoopDetected(),
0,
'v8 bug detected',
);
sinon.assert.notCalled(timeProfilerStub.start);
sinon.assert.calledOnce(timeProfilerStub.stopAndCollect);
timeProfilerStub.start.resetHistory();
timeProfilerStub.stopAndCollect.resetHistory();
assert.deepEqual(timeProfile, stopV2());
sinon.assert.notCalled(timeProfilerStub.start);
sinon.assert.calledOnce(timeProfilerStub.stopAndCollect);
});
});
describe('v8BugWorkaround (w/ stubs)', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const sinonStubs: Array<sinon.SinonStub<any, any>> = [];
const timeProfilerStub = {
start: sinon.stub(),
stop: sinon.stub().returns(v8TimeProfile),
dispose: sinon.stub(),
v8ProfilerStuckEventLoopDetected: sinon.stub().returns(2),
};
before(() => {
sinonStubs.push(
sinon.stub(v8TimeProfiler, 'TimeProfiler').returns(timeProfilerStub),
);
sinonStubs.push(sinon.stub(Date, 'now').returns(0));
});
after(() => {
sinonStubs.forEach(stub => {
stub.restore();
});
});
it('should reset profiler when empty profile is returned and restart is requested', () => {
time.start(PROFILE_OPTIONS);
time.stop(true);
sinon.assert.calledTwice(timeProfilerStub.start);
sinon.assert.calledTwice(timeProfilerStub.stop);
assert.equal(
time.v8ProfilerStuckEventLoopDetected(),
2,
'v8 bug not detected',
);
timeProfilerStub.start.resetHistory();
timeProfilerStub.stop.resetHistory();
time.stop(false);
sinon.assert.notCalled(timeProfilerStub.start);
sinon.assert.calledOnce(timeProfilerStub.stop);
});
});
describe('lowCardinalityLabels', () => {
it('should handle lowCardinalityLabels parameter in stop function', async function testLowCardinalityLabels() {
if (unsupportedPlatform) {
this.skip();
}
this.timeout(3000);
// Set up some contexts with labels that we'll mark as low cardinality
const lowCardLabel = 'service_name';
const highCardLabel = 'trace_id';
const lowCardValues = ['web-service', 'api-service']; // Low cardinality values
const context1 = {
[lowCardLabel]: lowCardValues[0],
[highCardLabel]: '12345',
};
const context2 = {
[lowCardLabel]: lowCardValues[1],
[highCardLabel]: '67890',
};
const context3 = {
[lowCardLabel]: lowCardValues[0],
[highCardLabel]: '54321',
}; // Reuse low card value
time.start({
intervalMicros: PROFILE_OPTIONS.intervalMicros,
durationMillis: PROFILE_OPTIONS.durationMillis,
withContexts: true,
lineNumbers: false,
useCPED,
});
// Run busy loop with context switching for profile duration
const profileStart = Date.now();
let iterationCount = 0;
while (Date.now() - profileStart < PROFILE_OPTIONS.durationMillis) {
const start = hrtime.bigint();
const durationNanos = PROFILE_OPTIONS.intervalMicros * 1000;
while (hrtime.bigint() - start < durationNanos) {
// Busy loop
}
// Cycle through different contexts
const contexts = [context1, context2, context3];
time.setContext(contexts[iterationCount % contexts.length]);
iterationCount++;
// Allow other tasks to run
await new Promise(resolve => setImmediate(resolve));
}
let labelsCollected = false;
const lowCardinalityArray = [lowCardLabel];
const generateLabelsFunc = ({context}: GenerateTimeLabelsArgs) => {
if (!context) {
return {};
}
labelsCollected = true;
// Generate labels from context
const labels: LabelSet = {};
for (const [key, value] of Object.entries(context.context ?? {})) {
if (typeof value === 'string') {
labels[key] = value;
}
}
return labels;
};
const profile = time.stop(false, generateLabelsFunc, lowCardinalityArray);
// Verify that labels were collected and the profile is valid
assert(labelsCollected, 'Labels should have been collected');
assert.ok(profile, 'Profile should be generated');
assert.ok(profile.stringTable, 'Profile should have string table');
assert(profile.sample.length > 0, 'Profile should have samples');
// Check that samples have the expected labels and collect low cardinality labels
let foundLowCardLabel = false;
let foundHighCardLabel = false;
const lowCardinalityLabels: Label[] = [];
profile.sample.forEach(sample => {
if (sample.label && sample.label.length > 0) {
sample.label.forEach(label => {
const keyStr = profile.stringTable.strings[Number(label.key)];
const valueStr = profile.stringTable.strings[Number(label.str)];
if (keyStr === lowCardLabel && lowCardValues.includes(valueStr)) {
foundLowCardLabel = true;
lowCardinalityLabels.push(label);
}
if (keyStr === highCardLabel) {
foundHighCardLabel = true;
}
});
}
});
assert(foundLowCardLabel, 'Should find low cardinality label in samples');
assert(
foundHighCardLabel,
'Should find high cardinality label in samples',
);
// Verify that the lowCardinalityLabels parameter is working correctly
// This tests that the stop() function accepts and processes the lowCardinalityLabels parameter
// Group labels by value and count them
const labelsByValue = new Map<string, Label[]>();
lowCardinalityLabels.forEach(label => {
const valueStr = profile.stringTable.strings[Number(label.str)];
if (!labelsByValue.has(valueStr)) {
labelsByValue.set(valueStr, []);
}
labelsByValue.get(valueStr)!.push(label);
});
// We should have exactly 2 distinct values (web-service and api-service)
assert(
labelsByValue.size === 2,
`Expected exactly 2 distinct low cardinality label values, found ${
labelsByValue.size
}. Values: ${Array.from(labelsByValue.keys()).join(', ')}`,
);
// Verify we found both expected values
assert(
labelsByValue.has('web-service'),
'Should find web-service labels',
);
assert(
labelsByValue.has('api-service'),
'Should find api-service labels',
);
// Verify that the lowCardinalityLabels parameter was properly used
// This tests that labels are being processed with the low cardinality configuration
labelsByValue.forEach((labels, value) => {
assert(
labels.length > 0,
`Should have at least one label with value '${value}'`,
);
// Check that all labels have the same key (service_name)
labels.forEach(label => {
const keyStr = profile.stringTable.strings[Number(label.key)];
assert(
keyStr === lowCardLabel,
`Expected label key to be '${lowCardLabel}', got '${keyStr}'`,
);
});
});
// Test that the Set of all low cardinality labels contains exactly 2 unique values
// This verifies that the lowCardinalityLabels parameter is properly handled
const allUniqueValues = new Set(
lowCardinalityLabels.map(
label => profile.stringTable.strings[Number(label.str)],
),
);
assert(
allUniqueValues.size === 2,
`Expected exactly 2 unique low cardinality label values across all samples, found ${allUniqueValues.size}`,
);
assert(
allUniqueValues.has('web-service') &&
allUniqueValues.has('api-service'),
'Should find both web-service and api-service values in the low cardinality labels',
);
// Verify that low cardinality labels with the same value are the same object
// This tests the deduplication behavior as requested by the user
labelsByValue.forEach((labels, value) => {
const uniqueObjects = new Set(labels);
assert(
uniqueObjects.size === 1,
`All labels with value '${value}' should be the same object, found ${uniqueObjects.size} different objects. ` +
'The lowCardinalityLabels parameter should enable deduplication of Label objects with identical key/value pairs.',
);
});
});
});
describe('Memory comparison', () => {
interface WorkerMemoryResult {
initial: number;
afterTraversal: number;
afterHitCount: number;
}
function measureMemoryInWorker(
version: 'v1' | 'v2',
): Promise<WorkerMemoryResult> {
return new Promise((resolve, reject) => {
const child = fork('./out/test/time-memory-worker.js', [], {
execArgv: ['--expose-gc'],
});
child.on('message', (result: WorkerMemoryResult) => {
resolve(result);
child.kill();
});
child.on('error', reject);
child.send(version);
});
}
it('stopAndCollect should use less memory than stop when profile is large', async function () {
if (unsupportedPlatform) {
this.skip();
}
const v1 = await measureMemoryInWorker('v1');
const v2 = await measureMemoryInWorker('v2');
console.log('v1 : ', v1.initial, v1.afterTraversal, v1.afterHitCount);
console.log('v2 : ', v2.initial, v2.afterTraversal, v2.afterHitCount);
// V2 creates almost nothing upfront — lazy wrappers vs full eager tree.
assert.ok(
v2.initial < v1.initial,
`V2 initial should be less: V1=${v1.initial}, V2=${v2.initial}`,
);
}).timeout(120_000);
});
describe('getNativeThreadId', () => {
it('should return a number', () => {
const threadId = getNativeThreadId();
assert.ok(typeof threadId === 'number');
assert.ok(threadId > 0);
});
});
describe('runWithContext', () => {
it('should throw when profiler is not started', () => {
assert.throws(() => {
time.runWithContext({label: 'test'}, () => {});
}, /Wall profiler is not started/);
});
it('should throw when useCPED is not enabled', function testNoCPED() {
if (unsupportedPlatform) {
this.skip();
}