@whotracksme/reporting 7.12.2 → 8.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/communication/test/helpers/in-memory-database.js +45 -0
  3. package/package.json +2 -2
  4. package/reporting/src/hash-detector-v2/index.js +164 -0
  5. package/reporting/src/hash-detector-v2/prob.js +599 -0
  6. package/reporting/src/hash-detector-v2.js +18 -0
  7. package/reporting/src/observable.js +43 -0
  8. package/reporting/src/pages.js +11 -12
  9. package/reporting/src/paused-domains-reporter.js +50 -0
  10. package/reporting/src/persisted-counters.js +158 -0
  11. package/reporting/src/popularity-estimator.js +625 -0
  12. package/reporting/src/popularity-vote-handler.js +219 -0
  13. package/reporting/src/popularity-vote-sanitizer.js +384 -0
  14. package/reporting/src/random.js +90 -1
  15. package/reporting/src/reporting.js +98 -13
  16. package/reporting/src/utils.js +41 -1
  17. package/reporting/test/activity-estimator.spec.js +3 -2
  18. package/reporting/test/alive-check.spec.js +2 -2
  19. package/reporting/test/country-provider.spec.js +2 -2
  20. package/reporting/test/index.js +6 -0
  21. package/reporting/test/job-scheduler.spec.js +2 -2
  22. package/reporting/test/observable.spec.js +72 -0
  23. package/reporting/test/page-aggregator.spec.js +3 -0
  24. package/reporting/test/patterns-updater.spec.js +2 -2
  25. package/reporting/test/persisted-counters.spec.js +132 -0
  26. package/reporting/test/popularity-estimator.spec.js +710 -0
  27. package/reporting/test/popularity-vote-handler.spec.js +420 -0
  28. package/reporting/test/popularity-vote-sanitizer.spec.js +635 -0
  29. package/reporting/test/random.spec.js +157 -0
  30. package/reporting/test/reporting.spec.js +202 -180
  31. package/reporting/test/utils.spec.js +42 -0
@@ -0,0 +1,710 @@
1
+ /**
2
+ * WhoTracks.Me
3
+ * https://whotracks.me/
4
+ *
5
+ * Copyright 2017-present Ghostery GmbH. All rights reserved.
6
+ *
7
+ * This Source Code Form is subject to the terms of the Mozilla Public
8
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
9
+ * file, You can obtain one at http://mozilla.org/MPL/2.0
10
+ */
11
+
12
+ import { expect, assert } from 'chai';
13
+ import sinon from 'sinon';
14
+ import * as fc from 'fast-check';
15
+
16
+ import PopularityEstimator from '../src/popularity-estimator.js';
17
+
18
+ import { randomSafeIntBetween } from '../src/random.js';
19
+ import { createInMemoryJobScheduler } from './helpers/in-memory-job-scheduler.js';
20
+ import InMemoryDatabase from './helpers/in-memory-database.js';
21
+
22
+ const SECOND = 1000;
23
+ const MINUTE = 60 * SECOND;
24
+ const HOUR = 60 * MINUTE;
25
+ const DAY = 24 * HOUR;
26
+ const WEEK = 7 * DAY;
27
+ const MONTH = 30 * DAY;
28
+ const YEAR = 365 * DAY;
29
+
30
+ function mockStorage(storageKey) {
31
+ return {
32
+ async get(key) {
33
+ expect(key).to.equal(storageKey);
34
+ return this._content;
35
+ },
36
+ async set(key, obj) {
37
+ expect(key).to.equal(storageKey);
38
+ this._content = obj;
39
+ },
40
+ };
41
+ }
42
+
43
+ describe('#PopularityEstimator', function () {
44
+ let uut;
45
+ let clock;
46
+
47
+ let storage;
48
+ let storageKey;
49
+ let inMemoryDatabases;
50
+ let connectDatabase;
51
+
52
+ let jobScheduler;
53
+ let jobsRegistered;
54
+
55
+ async function passesSelfChecks() {
56
+ const checks = await uut.selfChecks();
57
+ if (!checks.allPassed()) {
58
+ const fullReport = JSON.stringify(checks.report(), null, 2);
59
+ const shortReport = JSON.stringify(checks.report().log.failures, null, 2);
60
+ assert.fail(
61
+ `self checks failed:\n${fullReport}:\n\nThis is the error:\n${shortReport}`,
62
+ );
63
+ }
64
+ }
65
+
66
+ function initMocks() {
67
+ clock?.restore();
68
+ clock = sinon.useFakeTimers(new Date('2026-01-01'));
69
+
70
+ // Unless a timer was set at least once, clock.jump will fail
71
+ // TODO: we can remove this workaround if this fix is shipped with @sinon:
72
+ // https://github.com/sinonjs/fake-timers/pull/541
73
+ setTimeout(() => {}, 0);
74
+
75
+ storageKey = 'some-key';
76
+ storage = mockStorage(storageKey);
77
+ inMemoryDatabases = new Map();
78
+ connectDatabase = (name) => {
79
+ let db = inMemoryDatabases.get(name);
80
+ if (!db) {
81
+ db = new InMemoryDatabase();
82
+ inMemoryDatabases.set(name, db);
83
+ }
84
+ return db;
85
+ };
86
+
87
+ jobsRegistered = [];
88
+
89
+ // do not write into the active jobsRegistered array
90
+ const _jobsRegistered = jobsRegistered;
91
+
92
+ jobScheduler = createInMemoryJobScheduler();
93
+ jobScheduler.addObserver('jobRegistered', (job) => {
94
+ expect(job.type).to.eql('popularity-estimator:prepare-voting:v1');
95
+ expect(job.args).to.have.all.keys(
96
+ 'urlProjection',
97
+ 'countType',
98
+ 'intervalType',
99
+ 'sample',
100
+ );
101
+ expect(job.args.sample).to.have.all.keys('value', 'count');
102
+ expect(job.args.sample.value).to.be.a('string');
103
+ expect(job.args.sample.count).to.be.a('number').greaterThan(0);
104
+
105
+ _jobsRegistered.push(job);
106
+ });
107
+
108
+ uut = newPopularityEstimator();
109
+ }
110
+
111
+ function newPopularityEstimator() {
112
+ return new PopularityEstimator({
113
+ storage,
114
+ storageKey,
115
+ connectDatabase,
116
+ jobScheduler,
117
+ });
118
+ }
119
+
120
+ function tearDown() {
121
+ clock?.restore();
122
+ clock = null;
123
+ uut = null;
124
+ storage = null;
125
+ storageKey = null;
126
+ inMemoryDatabases = null;
127
+ connectDatabase = null;
128
+ jobScheduler = null;
129
+ jobsRegistered = null;
130
+ }
131
+
132
+ // Helper that simulates an event like a restart of the service worker/background script:
133
+ // it keeps the storage, but purges everything that was in memory.
134
+ async function simulateRestart() {
135
+ for (const [name, db] of [...inMemoryDatabases]) {
136
+ inMemoryDatabases.set(name, db._clone());
137
+ }
138
+ uut = newPopularityEstimator();
139
+ }
140
+
141
+ beforeEach(initMocks);
142
+ afterEach(tearDown);
143
+
144
+ function navigateTo(location, { isHistoryNavigation = false } = {}) {
145
+ let url;
146
+ if (location.startsWith('http://') || location.startsWith('https://')) {
147
+ url = location;
148
+ } else {
149
+ url = `https://${location}`;
150
+ }
151
+
152
+ const event = {
153
+ type: 'safe-page-navigation',
154
+ url,
155
+ isHistoryNavigation,
156
+ };
157
+ uut.onPageEvent(event);
158
+ }
159
+
160
+ async function ensureAllRotationsStarted() {
161
+ await uut.runRotationChecks();
162
+ await clock.tickAsync(1 * YEAR);
163
+ await clock.runToLastAsync();
164
+ }
165
+
166
+ async function ensureAllRotationsFinished() {
167
+ await clock.tickAsync(1 * YEAR);
168
+ await clock.runToLastAsync();
169
+ }
170
+
171
+ async function endTestByForcingRotation() {
172
+ // This sequence triggers the processing. Note that after this point,
173
+ // there should be no more interactions; otherwise the dummy test
174
+ // might be drawn as a sample.
175
+ await uut.init();
176
+ await ensureAllRotationsFinished();
177
+ navigateTo('dummy-location-to-force-rotation.test');
178
+ }
179
+
180
+ async function expectNoPreparedVotes() {
181
+ await clock.runToLastAsync();
182
+ expect(jobsRegistered).to.eql([]);
183
+ }
184
+
185
+ async function expectPreparedVotes(condition = {}) {
186
+ await clock.runToLastAsync();
187
+ expect(jobsRegistered).to.be.not.empty;
188
+
189
+ const { matchesDomain } = condition;
190
+ if (matchesDomain) {
191
+ for (const job of jobsRegistered) {
192
+ if (
193
+ job.args.sample.value !== matchesDomain &&
194
+ !job.args.sample.value.startsWith(`${matchesDomain}/`)
195
+ ) {
196
+ const job_ = JSON.stringify(job, null, 2);
197
+ assert.fail(
198
+ `Expected all jobs to match the domain ${matchesDomain}. Stopped at:\n${job_}`,
199
+ );
200
+ }
201
+ }
202
+ }
203
+ }
204
+
205
+ describe('#init', function () {
206
+ it('load + unload should not fail', async () => {
207
+ expect(uut.active).to.be.false;
208
+ await uut.init();
209
+ expect(uut.active).to.be.true;
210
+ uut.unload();
211
+ expect(uut.active).to.be.false;
212
+ });
213
+
214
+ it('should support multiple init and unload calls', async function () {
215
+ await uut.init();
216
+ await uut.init();
217
+ uut.unload();
218
+ uut.unload();
219
+ });
220
+
221
+ it('should support concurrent init calls', async function () {
222
+ const pending = [uut.init(), uut.init(), uut.init()];
223
+ await Promise.all([pending]);
224
+ uut.unload();
225
+ });
226
+ });
227
+
228
+ describe('when not initialized', function () {
229
+ it('should ignore events when not active (no waiting)', async () => {
230
+ expect(uut.active).to.be.false;
231
+
232
+ navigateTo('example.test');
233
+ await expectNoPreparedVotes();
234
+ });
235
+
236
+ it('should ignore events when not active (with waiting)', async () => {
237
+ expect(uut.active).to.be.false;
238
+
239
+ await ensureAllRotationsStarted();
240
+ for (let i = 0; i < 100; i += 1) {
241
+ navigateTo('example.test');
242
+ await clock.tickAsync(10 * MINUTE);
243
+ }
244
+
245
+ await endTestByForcingRotation();
246
+ await expectNoPreparedVotes();
247
+ });
248
+ });
249
+
250
+ describe('when initialized', function () {
251
+ beforeEach(async () => {
252
+ await uut.init(); // this initializes only lazily
253
+ navigateTo('some-random-visit-to-trigger-a-full-initialization.test');
254
+ await clock.runToLastAsync();
255
+ });
256
+
257
+ afterEach(() => uut?.unload());
258
+
259
+ it('should pass health checks once initialized', async () => {
260
+ await passesSelfChecks();
261
+ });
262
+
263
+ describe('#flush', function () {
264
+ describe('it should not lose state after an extension restart', function () {
265
+ it('when flush is explicitly called', async () => {
266
+ await ensureAllRotationsStarted();
267
+
268
+ navigateTo('example.test');
269
+ await uut.flush();
270
+
271
+ simulateRestart();
272
+
273
+ await endTestByForcingRotation();
274
+ await expectPreparedVotes({ matchesDomain: 'example.test' });
275
+ });
276
+
277
+ it('after the automatic triggering of flush', async () => {
278
+ await ensureAllRotationsStarted();
279
+
280
+ navigateTo('example.test');
281
+ await clock.runToLastAsync();
282
+
283
+ simulateRestart();
284
+
285
+ await endTestByForcingRotation();
286
+ await expectPreparedVotes({ matchesDomain: 'example.test' });
287
+ });
288
+ });
289
+ });
290
+
291
+ /**
292
+ * Returns an ES6 map from unique URLs to a visit counter, for example:
293
+ *
294
+ * Map(2) { 'https://foo.test/' => 42, 'https://bar.test/' => 17 }
295
+ */
296
+ function arbitraryVisitedUrlDistribution({
297
+ // unless there are clashes, a batch is roughly a visited URL
298
+ minNumberOfBatches = 1,
299
+ maxNumberOfBatches = 10,
300
+
301
+ // controls how often a visited URL (in one batch) should be counted
302
+ minVisitsPerBatch = 1,
303
+ maxVisitsPerBatch = 1000,
304
+ } = {}) {
305
+ return fc
306
+ .array(
307
+ fc.record({
308
+ url: fc.webUrl(),
309
+ numVisits: fc.integer({
310
+ min: minVisitsPerBatch,
311
+ max: maxVisitsPerBatch,
312
+ }),
313
+ }),
314
+ { minLength: minNumberOfBatches, maxLength: maxNumberOfBatches },
315
+ )
316
+ .map((batches) => {
317
+ const distribution = new Map();
318
+ batches.forEach(({ url, numVisits }) => {
319
+ distribution.set(url, (distribution.get(url) || 0) + numVisits);
320
+ });
321
+ return distribution;
322
+ });
323
+ }
324
+
325
+ describe('[property based testing]', function () {
326
+ it('should not crash on arbitrary URLs', async function () {
327
+ this.timeout(20 * SECOND);
328
+ await fc.assert(
329
+ fc
330
+ .asyncProperty(
331
+ fc.record({
332
+ urlDistribution: arbitraryVisitedUrlDistribution({
333
+ maxNumberOfBatches: 32,
334
+ maxVisitsPerBatch: 4,
335
+ }),
336
+ quickDelayInMs: fc.integer({ min: 0, max: 20 * SECOND }),
337
+ slowDelayInMs: fc.integer({
338
+ min: 20 * SECOND,
339
+ max: 15 * MINUTE,
340
+ }),
341
+ firstHistoryNavigation: fc.integer({ min: 1, max: 2 }),
342
+ withDailyRestarts: fc.boolean(),
343
+ }),
344
+ async ({
345
+ urlDistribution,
346
+ quickDelayInMs,
347
+ slowDelayInMs,
348
+ firstHistoryNavigation,
349
+ withDailyRestarts,
350
+ }) => {
351
+ await uut.init();
352
+ await passesSelfChecks();
353
+
354
+ for (let outer = 0; outer < 4; outer += 1) {
355
+ // so we reach at least one real monthly rotation (cooldown + one month)
356
+ await passesSelfChecks();
357
+ clock.jump(1 * WEEK);
358
+
359
+ if (withDailyRestarts) {
360
+ await clock.runToLastAsync();
361
+ simulateRestart();
362
+ await uut.init();
363
+ }
364
+
365
+ for (let inner = 0; inner < 3; inner += 1) {
366
+ for (const [url, count] of urlDistribution) {
367
+ for (
368
+ let sameVisit = 0;
369
+ sameVisit < count;
370
+ sameVisit += 1
371
+ ) {
372
+ // simulate quick navigations to the same URL
373
+ navigateTo(url, {
374
+ isHistoryNavigation:
375
+ sameVisit >= firstHistoryNavigation,
376
+ });
377
+ if (quickDelayInMs > 0) {
378
+ clock.tick(quickDelayInMs);
379
+ }
380
+ }
381
+
382
+ // longer time between navigations to a different URL
383
+ await clock.tickAsync(slowDelayInMs);
384
+ await passesSelfChecks();
385
+ }
386
+ }
387
+ }
388
+ await clock.runToLastAsync();
389
+ await passesSelfChecks();
390
+
391
+ const mustExist = (expectedField, expectedValue) => {
392
+ const found = jobsRegistered.some(
393
+ (job) => job.args[expectedValue] !== expectedValue,
394
+ );
395
+ if (!found) {
396
+ const jobs_ = JSON.stringify(jobsRegistered, null, 2);
397
+ assert.fail(
398
+ `Expected at least one job with ${expectedValue}=${expectedValue}. Instead got:\n${jobs_}`,
399
+ );
400
+ }
401
+ };
402
+
403
+ expect(jobsRegistered).to.be.not.empty;
404
+ mustExist('intervalType', '1d');
405
+ mustExist('intervalType', '1w');
406
+ mustExist('intervalType', '4w');
407
+ mustExist('countType', 'visits');
408
+ mustExist('urlProjection', 'domain');
409
+ mustExist('urlProjection', 'hostname');
410
+ mustExist('urlProjection', 'hostnamePath');
411
+ },
412
+ )
413
+ .beforeEach(initMocks)
414
+ .afterEach(tearDown),
415
+ { numRuns: 3, endOnFailure: true },
416
+ );
417
+ });
418
+
419
+ it('given enough samples, it should support eventually learn the distribution', async function () {
420
+ this.timeout(20 * SECOND);
421
+
422
+ await fc.assert(
423
+ fc
424
+ .asyncProperty(
425
+ // Only consider distributions where there is a significant
426
+ // increase from element to element, but also not too much.
427
+ // Otherwise, we need either too many samples or risk that the
428
+ // test becomes flakey.
429
+ //
430
+ // Note: the problem is that the JavaScript tests are extremely slow.
431
+ // I was not able to track it down; it is suprisingly not CPU bound,
432
+ // but seems related with the time mocking. In simulations, I can
433
+ // confirm that theoretically, it converts reliably for any number great
434
+ // than 1. But in this test environment, everything is so slow that
435
+ // the number of samples that we can work with is tiny. Therefore, we
436
+ // have to pick examples that lead to fast convergence.
437
+ //
438
+ // The design that we use to construct the distribution:
439
+ // - pick any starting value for the base weight (theoretically, it
440
+ // should not mattern and practically keep it small, before we are
441
+ // using intentionally a slow, but simple mechanism to pick samples
442
+ // based on their weight.
443
+ fc.integer({ min: 1, max: 100 }),
444
+ // - Based on the starting weight, we compute the next one by scaling
445
+ // the previous one and ensuring that it is at least one larger.
446
+ //
447
+ // Theoretically, max could be anything and min could be any number > 1.0.
448
+ // But remember that if you create distributions like these
449
+ //
450
+ // - [1, 10000000000]
451
+ // - [10000000000, 10000000001]
452
+ // - [1, 2, 10000000000, 10000000001]
453
+ //
454
+ // ... they will converge, but you will need easily millions of samples.
455
+ // In this current test setup, it will be impractical, since you will get
456
+ // only a few samples per second.
457
+ fc.array(
458
+ fc.double({
459
+ min: 1.5,
460
+ max: 4,
461
+ noDefaultInfinity: true,
462
+ noNaN: true,
463
+ }),
464
+ {
465
+ // To make it easier to pass on CI.
466
+ // increase this number locally to make it much harder
467
+ minLength: 1,
468
+ maxLength: 3,
469
+ },
470
+ ),
471
+
472
+ // Simulates a huge clock jump:
473
+ fc.integer({
474
+ // The round where it happens. On CI, we force it to be almost instantly
475
+ // to get rid of all cooldowns, speeding up the tests. Locally, you use
476
+ // arbitrary integers here, or let it use negative values to turn off
477
+ // the jump completely.
478
+ //
479
+ min: 0, // locally, you can use negative values. But for CI, enforce the jump.
480
+ max: 10,
481
+ }),
482
+ fc.integer({
483
+ // this ensures that the cooldowns are practically skipped.
484
+ min: 4 * WEEK - 1 * DAY,
485
+ max: 3 * MONTH,
486
+ }),
487
+ async (
488
+ startingWeight,
489
+ factors,
490
+ hugeClockJumpAt,
491
+ hugeClockJumpInMs,
492
+ ) => {
493
+ const distributionWeights = [startingWeight];
494
+ for (const factor of factors) {
495
+ const nextWeight = distributionWeights.at(-1) * factor;
496
+ distributionWeights.push(1 + Math.round(nextWeight));
497
+ }
498
+
499
+ const toUrl = (id) =>
500
+ `https://sub${id}.domain${id}.com/path/${id}`;
501
+
502
+ // Reverse mapping: "value" can be any of the following:
503
+ // - domain: domain123.com
504
+ // - hostname: sub123.domain123.com
505
+ // - hostnamePath: sub123.domain123.com/123
506
+ //
507
+ // By construction, we can just look at the first number.
508
+ const sampleToId = (value) => {
509
+ const match = value.match(/[0-9]+/);
510
+ if (!match) {
511
+ assert.fail(`Bad sample received: <<${value}>>`);
512
+ }
513
+ const id = Number.parseInt(match[0], 10);
514
+ expect(id)
515
+ .to.be.at.least(0)
516
+ .and.lessThan(distributionWeights.length);
517
+ return id;
518
+ };
519
+
520
+ // id: 0 (lowest weight)
521
+ // ...
522
+ // id: N (highest weight, most likely)
523
+ //
524
+ // where
525
+ // N = distributionWeights.length - 1;
526
+ const urlDistribution = distributionWeights.map(
527
+ (weight, id) => [toUrl(id), weight],
528
+ );
529
+
530
+ const expandedUrls = urlDistribution.flatMap(([url, weight]) =>
531
+ Array(weight).fill(url),
532
+ );
533
+ const randomPageVisit = () => {
534
+ const pos = randomSafeIntBetween(0, expandedUrls.length - 1);
535
+ navigateTo(expandedUrls[pos]);
536
+ };
537
+
538
+ const toKey = ({ countType, intervalType, urlProjection }) =>
539
+ JSON.stringify([countType, intervalType, urlProjection]);
540
+ const unpackKey = (key) => {
541
+ const [countType, intervalType, urlProjection] =
542
+ JSON.parse(key);
543
+ return { countType, intervalType, urlProjection };
544
+ };
545
+
546
+ const idsSeen = {};
547
+ for (const countType of ['visits']) {
548
+ for (const intervalType of ['1d', '1w', '4w']) {
549
+ for (const urlProjection of [
550
+ 'domain',
551
+ 'hostname',
552
+ 'hostnamePath',
553
+ ]) {
554
+ const key = toKey({
555
+ countType,
556
+ intervalType,
557
+ urlProjection,
558
+ });
559
+ idsSeen[key] = Array(distributionWeights.length).fill(0);
560
+ }
561
+ }
562
+ }
563
+
564
+ // Since the lowest ID represents the most unlikely URL and the
565
+ // highest ID the most likely, we are done if the number of hits
566
+ // are strictly increasing.
567
+ const matchesRealDistributionOrder = (hits) => {
568
+ expect(hits.length).to.eql(distributionWeights.length);
569
+ for (let i = 0; i < hits.length - 1; i += 1) {
570
+ if (hits[i] >= hits[i + 1]) {
571
+ return false;
572
+ }
573
+ }
574
+ return true;
575
+ };
576
+
577
+ await uut.init();
578
+
579
+ const stepSizeInMs = 10 * MINUTE;
580
+ for (let run = 0; run < 1_000_000; run += 1) {
581
+ randomPageVisit();
582
+ clock.tick(stepSizeInMs);
583
+
584
+ // This is critical to get the async operations being processed.
585
+ for (let i = 0; i < 100; i += 1) {
586
+ await Promise.resolve();
587
+ }
588
+
589
+ if (run === hugeClockJumpAt) {
590
+ await clock.runToLastAsync();
591
+ clock.jump(hugeClockJumpInMs);
592
+ }
593
+
594
+ // Simulate weekends, but also has the side-effect that we
595
+ // are advancing faster to the 4-week period, which are
596
+ // the most difficult to approximate.
597
+ if (run % Math.round(WEEK / stepSizeInMs) === 0) {
598
+ clock.jump(2 * DAY);
599
+ }
600
+ if (run % Math.round((3 * WEEK) / stepSizeInMs) === 0) {
601
+ clock.jump(2 * WEEK);
602
+ }
603
+ if (run % Math.round((8 * WEEK) / stepSizeInMs) === 0) {
604
+ clock.jump(6 * WEEK);
605
+ }
606
+
607
+ if (jobsRegistered.length > 0) {
608
+ while (jobsRegistered.length > 0) {
609
+ const job = jobsRegistered.shift();
610
+ const { countType, intervalType, urlProjection, sample } =
611
+ job.args;
612
+
613
+ const key = toKey({
614
+ countType,
615
+ intervalType,
616
+ urlProjection,
617
+ });
618
+ if (!idsSeen[key]) {
619
+ const job_ = JSON.stringify(job, null, 2);
620
+ assert.fail(
621
+ `Unexpected values detected in job:\n${job_}`,
622
+ );
623
+ }
624
+ idsSeen[key][sampleToId(sample.value)] += sample.count;
625
+ }
626
+ if (
627
+ Object.values(idsSeen).every(matchesRealDistributionOrder)
628
+ ) {
629
+ // Example: [10, 27, 63] -> [0.1, 0.27, 0.63]
630
+ const normalizeDistribution = (arr) => {
631
+ const sum = arr.reduce((acc, val) => acc + val, 0);
632
+ return arr.map((val) => val / sum);
633
+ };
634
+
635
+ // 1 = perfect alignment (same direction), 0 = orthogonal
636
+ const cosineSimilarity = (v1, v2) => {
637
+ let dot = 0;
638
+ let mag1 = 0;
639
+ let mag2 = 0;
640
+ for (let i = 0; i < v1.length; i++) {
641
+ dot += v1[i] * v2[i];
642
+ mag1 += v1[i] * v1[i];
643
+ mag2 += v2[i] * v2[i];
644
+ }
645
+ return dot / (Math.sqrt(mag1) * Math.sqrt(mag2));
646
+ };
647
+
648
+ const realDist =
649
+ normalizeDistribution(distributionWeights);
650
+ for (const [key, hits] of Object.entries(idsSeen)) {
651
+ const empiricDist = normalizeDistribution(hits);
652
+ const similarity = cosineSimilarity(
653
+ empiricDist,
654
+ realDist,
655
+ );
656
+ const { intervalType } = unpackKey(key);
657
+ const expectedSimilarity = (() => {
658
+ switch (intervalType) {
659
+ case '1d':
660
+ return 0.85;
661
+ case '1w':
662
+ return 0.8;
663
+ case '4w':
664
+ return 0.75;
665
+ default:
666
+ throw new Error(
667
+ `Internal error: did not expect to see ${intervalType}`,
668
+ );
669
+ }
670
+ })();
671
+ if (similarity < expectedSimilarity) {
672
+ console.error(
673
+ 'Failed to approximate the distribution:\n',
674
+ 'Failed at:',
675
+ key,
676
+ 'distributionWeights:\n',
677
+ JSON.stringify(distributionWeights, null, 2),
678
+ '\n\nidsSeen:\n',
679
+ JSON.stringify(idsSeen, null, 2),
680
+ '\n\nSimilarity is',
681
+ similarity,
682
+ 'but expected at least',
683
+ expectedSimilarity,
684
+ );
685
+ return false;
686
+ }
687
+ }
688
+ return true; // test passed
689
+ }
690
+ }
691
+ }
692
+
693
+ console.error(
694
+ 'Run out of iterations before learning the order of the real distribution:\n',
695
+ 'distributionWeights:\n',
696
+ JSON.stringify(distributionWeights, null, 2),
697
+ '\n\nidsSeen:\n',
698
+ JSON.stringify(idsSeen, null, 2),
699
+ );
700
+ return false;
701
+ },
702
+ )
703
+ .beforeEach(initMocks)
704
+ .afterEach(tearDown),
705
+ { numRuns: 3, endOnFailure: true },
706
+ );
707
+ });
708
+ });
709
+ });
710
+ });