@whotracksme/reporting 11.0.1 β†’ 11.1.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.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,27 @@
1
+ # v11.1.0 (Mon Aug 10 2026)
2
+
3
+ #### πŸš€ Enhancement
4
+
5
+ - wtm.popularity with activity [#219](https://github.com/whotracksme/webextension-packages/pull/219) ([@philipp-classen](https://github.com/philipp-classen))
6
+
7
+ #### Authors: 1
8
+
9
+ - Philipp Claßen ([@philipp-classen](https://github.com/philipp-classen))
10
+
11
+ ---
12
+
13
+ # v11.0.2 (Sat Jul 18 2026)
14
+
15
+ #### πŸ› Bug Fix
16
+
17
+ - Fix: undo offscreen window size attributes [#217](https://github.com/whotracksme/webextension-packages/pull/217) ([@chrmod](https://github.com/chrmod))
18
+
19
+ #### Authors: 1
20
+
21
+ - Krzysztof Modras ([@chrmod](https://github.com/chrmod))
22
+
23
+ ---
24
+
1
25
  # v11.0.1 (Wed Jul 08 2026)
2
26
 
3
27
  #### πŸ› Bug Fix
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@whotracksme/reporting",
3
- "version": "11.0.1",
3
+ "version": "11.1.0",
4
4
  "type": "module",
5
5
  "description": "",
6
6
  "scripts": {
@@ -316,37 +316,6 @@ async function tryCloseOffscreenDocument() {
316
316
 
317
317
  const OFFSCREEN_DOCUMENT_PREFIX = 'offscreen/doublefetch';
318
318
  const OFFSCREEN_DOCUMENT_INDEX_HTML = `${OFFSCREEN_DOCUMENT_PREFIX}/index.html`;
319
- const OFFSCREEN_DOCUMENT_FIXES_JS = `${OFFSCREEN_DOCUMENT_PREFIX}/offscreen-fix.js`;
320
-
321
- async function tryRegisterOffscreenFixes(domain) {
322
- if (!chrome?.scripting?.registerContentScripts) {
323
- logger.warn('Skipping offscreen-fixes (chrome.scripting API unavailable)');
324
- return () => {};
325
- }
326
-
327
- logger.debug('Installing offscreen fixes for domain:', domain);
328
- const id = 'offscreen-fix';
329
- await chrome.scripting.registerContentScripts([
330
- {
331
- id,
332
- matches: [`https://*.${domain}/*`, `https://${domain}/*`],
333
- js: [OFFSCREEN_DOCUMENT_FIXES_JS],
334
- runAt: 'document_start',
335
- allFrames: true,
336
- world: 'MAIN',
337
- },
338
- ]);
339
-
340
- return () => {
341
- logger.debug('Removing offscreen fixes for domain:', domain);
342
- chrome.scripting.unregisterContentScripts({ ids: [id] }).catch((e) => {
343
- logger.error(
344
- 'cleanup failed: unable to remove offscreen fixes content script:',
345
- e,
346
- );
347
- });
348
- };
349
- }
350
319
 
351
320
  async function withOffscreenDocumentReady(url, headers, asyncCallback) {
352
321
  const cleanups = [];
@@ -371,9 +340,6 @@ async function withOffscreenDocumentReady(url, headers, asyncCallback) {
371
340
  const undoDNRChange = await addDNRSessionRule(rule);
372
341
  cleanups.push(undoDNRChange);
373
342
 
374
- const undoOffscreenFixes = await tryRegisterOffscreenFixes(domain);
375
- cleanups.push(undoOffscreenFixes);
376
-
377
343
  const undoHeaderOverride = await headerOverride({
378
344
  headers,
379
345
  url,
@@ -78,9 +78,14 @@ export default class PersistedCounters {
78
78
  /**
79
79
  * Draws random samples.
80
80
  *
81
+ * Output: {
82
+ * samples: [...], (e.g. ['foo', 'foo', 'bar'])
83
+ * populationSize: <int> (the sum of all counts, not the number of distinct keys)
84
+ * }
85
+ *
81
86
  * Options:
82
87
  * - "group": Aggregates identical samples together
83
- * Example: ['foo', 'foo', 'bar'] ==> [['foo', 2], ['bar', 1]]
88
+ * Example: `samples: ['foo', 'foo', 'bar'] ==> [['foo', 2], ['bar', 1]]`
84
89
  */
85
90
  async sample(numSamples = 1, { group = false } = {}) {
86
91
  // Flush pending counters, so the database becomes the only source of truth.
@@ -89,48 +94,47 @@ export default class PersistedCounters {
89
94
  await this.flush();
90
95
 
91
96
  let samples = [];
92
- if (numSamples > 0) {
93
- await this.db.transaction({ readonly: true }, async (tx) => {
94
- // Initial pass to learn how many counts we had in total
95
- let cursor = await tx.scan();
96
- let totalSum = 0;
97
- while (cursor) {
98
- totalSum += cursor.value;
99
- cursor = await cursor.next();
97
+ let populationSize = 0;
98
+
99
+ await this.db.transaction({ readonly: true }, async (tx) => {
100
+ // Initial pass to learn how many counts we had in total
101
+ let cursor = await tx.scan();
102
+ while (cursor) {
103
+ populationSize += cursor.value;
104
+ cursor = await cursor.next();
105
+ }
106
+ if (populationSize > 0) {
107
+ // Draw the position of the random samples
108
+ const picks = [];
109
+ for (let i = 0; i < numSamples; i += 1) {
110
+ picks.push(randomSafeIntBetween(0, populationSize - 1));
100
111
  }
101
- if (totalSum > 0) {
102
- // Draw the position of the random samples
103
- const picks = [];
104
- for (let i = 0; i < numSamples; i += 1) {
105
- picks.push(randomSafeIntBetween(0, totalSum - 1));
106
- }
107
112
 
108
- // Second pass to identify the chosen samples
109
- cursor = await tx.scan();
110
- let currentSum = 0;
111
- while (cursor && samples.length < numSamples) {
112
- currentSum += cursor.value;
113
- for (let i = 0; i < picks.length; i += 1) {
114
- if (currentSum > picks[i]) {
115
- samples.push(cursor.key);
116
- picks[i] = Number.MAX_VALUE;
117
- }
113
+ // Second pass to identify the chosen samples
114
+ cursor = await tx.scan();
115
+ let currentSum = 0;
116
+ while (cursor && samples.length < numSamples) {
117
+ currentSum += cursor.value;
118
+ for (let i = 0; i < picks.length; i += 1) {
119
+ if (currentSum > picks[i]) {
120
+ samples.push(cursor.key);
121
+ picks[i] = Number.MAX_VALUE;
118
122
  }
119
- cursor = await cursor.next();
120
123
  }
124
+ cursor = await cursor.next();
121
125
  }
122
- });
123
-
124
- if (group) {
125
- // Group identical values together (['foo', 'foo'] => [['foo', 2]]).
126
- // By design, identical values are always next to each other.
127
- samples = groupConsecutive(samples);
128
126
  }
127
+ });
128
+
129
+ if (group) {
130
+ // Group identical values together (['foo', 'foo'] => [['foo', 2]]).
131
+ // By design, identical values are always next to each other.
132
+ samples = groupConsecutive(samples);
129
133
  }
130
134
 
131
135
  // Do a final shuffle to randomize the order; otherwise, the implicit
132
136
  // order of the database may leak through.
133
- return shuffleInPlace(samples);
137
+ return { samples: shuffleInPlace(samples), populationSize };
134
138
  }
135
139
 
136
140
  /*
@@ -56,6 +56,13 @@ export function chooseNumSamplesPerInterval(intervalType) {
56
56
  }
57
57
  }
58
58
 
59
+ // To avoid storing a full history, clients can already do local sampling.
60
+ const LOCAL_SAMPLING_BY_INTERVAL = {
61
+ '1d': 1, // no local sampling
62
+ '1w': 10, // count every 10th visit
63
+ '4w': 100,
64
+ };
65
+
59
66
  export function isLegalVoteCount({ numVotes, intervalType }) {
60
67
  requireInt(numVotes);
61
68
  return numVotes >= 0 && numVotes <= chooseNumSamplesPerInterval(intervalType);
@@ -231,11 +238,9 @@ export default class PopularityEstimator {
231
238
  }
232
239
 
233
240
  const hostnamePath = hostname + pathname;
234
- for (const [interval, samplingSize] of [
235
- ['1d', 1],
236
- ['1w', 10],
237
- ['4w', 100],
238
- ]) {
241
+ for (const [interval, samplingSize] of Object.entries(
242
+ LOCAL_SAMPLING_BY_INTERVAL,
243
+ )) {
239
244
  if (randomSafeIntBetween(1, samplingSize) === 1) {
240
245
  this._popularityBy.domain.visits[interval].count(domain);
241
246
  this._popularityBy.hostname.visits[interval].count(hostname);
@@ -513,9 +518,13 @@ export default class PopularityEstimator {
513
518
  (async () => {
514
519
  // 1) draw samples from the now expired period
515
520
  const numSamples = chooseNumSamplesPerInterval(intervalType);
516
- const groupedSamples = await persistedCounter.sample(numSamples, {
517
- group: true, // helps to avoid unnecessary, duplicated quorum calls
518
- });
521
+ const { samples: groupedSamples, populationSize } =
522
+ await persistedCounter.sample(numSamples, {
523
+ group: true, // helps to avoid unnecessary, duplicated quorum calls
524
+ });
525
+ const activity = requireInt(
526
+ populationSize * LOCAL_SAMPLING_BY_INTERVAL[intervalType],
527
+ );
519
528
 
520
529
  // 2) reset counters (destructive action to enter the new period)
521
530
  await persistedCounter.clear();
@@ -523,7 +532,7 @@ export default class PopularityEstimator {
523
532
  // 3) prepare jobs (but delay registration until all operations
524
533
  // succeeded, which indicates that the system is healthy)
525
534
  return groupedSamples.map(([value, count]) => ({
526
- type: 'popularity-estimator:prepare-voting:v1',
535
+ type: 'popularity-estimator:prepare-voting:v2',
527
536
  args: {
528
537
  urlProjection,
529
538
  countType,
@@ -531,6 +540,7 @@ export default class PopularityEstimator {
531
540
  sample: {
532
541
  value,
533
542
  count,
543
+ activity,
534
544
  },
535
545
  },
536
546
  config: {
@@ -10,7 +10,7 @@
10
10
  */
11
11
 
12
12
  import logger from './logger';
13
- import { random32Bit } from './random';
13
+ import { randomBetween, random32Bit } from './random';
14
14
  import { requireParam, requireString } from './utils';
15
15
  import { BadJobError } from './errors';
16
16
 
@@ -53,7 +53,7 @@ export default class PopularityVoteHandler {
53
53
  this.pauseState = pauseState; // optional
54
54
 
55
55
  jobScheduler.registerHandler(
56
- 'popularity-estimator:prepare-voting:v1',
56
+ 'popularity-estimator:prepare-voting:v2',
57
57
  async (job) => {
58
58
  const { urlProjection, countType, intervalType, sample } = job.args;
59
59
  const validate = (actual, allowed) => {
@@ -72,7 +72,13 @@ export default class PopularityVoteHandler {
72
72
  // Validate the vote. First structurally ...
73
73
  const unmaskedVote = sample?.value;
74
74
  const numVotes = sample?.count;
75
- if (typeof unmaskedVote !== 'string' || !Number.isInteger(numVotes)) {
75
+ const activity = sample?.activity;
76
+ if (
77
+ typeof unmaskedVote !== 'string' ||
78
+ !Number.isInteger(numVotes) ||
79
+ !Number.isInteger(activity) ||
80
+ activity < 0
81
+ ) {
76
82
  throwBadJobError('Corrupted vote sample in job', job);
77
83
  }
78
84
 
@@ -84,22 +90,46 @@ export default class PopularityVoteHandler {
84
90
  );
85
91
  }
86
92
 
87
- const vote = await this.prepareVote(
93
+ const preparedVote = await this.prepareVote(
88
94
  urlProjection,
89
95
  countType,
90
96
  intervalType,
91
97
  unmaskedVote,
92
98
  );
93
- logger.info('Vote ready:', `${numVotes}x for`, vote);
94
-
95
- const sendVoteJob = {
96
- type: 'popularity-estimator:send-vote:v1',
97
- args: { vote },
98
- config: {
99
- readyIn: { min: 2 * SECOND, max: 20 * MINUTE },
100
- },
101
- };
102
- return Array(numVotes).fill(sendVoteJob);
99
+ logger.info(
100
+ 'Vote ready:',
101
+ `${numVotes}x for`,
102
+ preparedVote,
103
+ `with activity=${activity} (before noise)`,
104
+ );
105
+
106
+ const messages = [];
107
+ for (let i = 0; i < numVotes; i += 1) {
108
+ messages.push({
109
+ type: 'popularity-estimator:send-vote:v2',
110
+ args: {
111
+ payload: {
112
+ ...preparedVote,
113
+
114
+ // We can apply some noise as long as it keeps the mean.
115
+ // Since we are using a uniform distribution for the noise,
116
+ // it works if "(A + B) / 2 = 1" holds.
117
+ //
118
+ // Notes:
119
+ // - Why 75%? - There are diminishing returns for higher values,
120
+ // but we would need much more samples.
121
+ // - How important is the noise? - Perhaps not so much, but
122
+ // the noise makes it a bit harder to link votes from the
123
+ // same client in the same round.
124
+ activity: (randomBetween(0.25, 1.75) * activity).toString(),
125
+ },
126
+ },
127
+ config: {
128
+ readyIn: { min: 2 * SECOND, max: 20 * MINUTE },
129
+ },
130
+ });
131
+ }
132
+ return messages;
103
133
  },
104
134
  {
105
135
  priority: -100, // preparing the vote can be delayed
@@ -109,10 +139,10 @@ export default class PopularityVoteHandler {
109
139
  );
110
140
 
111
141
  jobScheduler.registerHandler(
112
- 'popularity-estimator:send-vote:v1',
142
+ 'popularity-estimator:send-vote:v2',
113
143
  async (job) => {
114
- const { vote } = job.args;
115
- if (!vote) {
144
+ const { payload } = job.args;
145
+ if (!payload) {
116
146
  throwBadJobError('Vote missing in job', job);
117
147
  }
118
148
 
@@ -122,11 +152,11 @@ export default class PopularityVoteHandler {
122
152
  // filtering them out would introduce bias.
123
153
  await this.communication.send({
124
154
  action: 'wtm.popularity',
125
- payload: vote,
126
- ver: 3, // Note: no need to keep this number in sync among messages
155
+ payload,
156
+ ver: 4, // Note: no need to keep this number in sync among messages
127
157
  'anti-duplicates': random32Bit(),
128
158
  });
129
- logger.info('Voted successfully for:', vote);
159
+ logger.info('Voted successfully for:', payload);
130
160
  },
131
161
  {
132
162
  priority: 100, // prioritize sending the final message out
@@ -9,6 +9,19 @@
9
9
  * file, You can obtain one at http://mozilla.org/MPL/2.0
10
10
  */
11
11
 
12
+ import * as fc from 'fast-check';
13
+ import * as tldts from 'tldts-experimental';
14
+
15
+ /**
16
+ * Not every URL that fast-check generates can exist in the real world.
17
+ * For instance, "https://a.pg" looks fine, but "a.pg" is itself a public
18
+ * suffix (the rule in the public suffix list is "*.pg"), so it cannot be
19
+ * registered.
20
+ */
21
+ export const arbitraryUrlWithDomain = fc
22
+ .webUrl()
23
+ .filter((url) => tldts.getDomain(url) !== null);
24
+
12
25
  /**
13
26
  * fast-check will find edge cases for keys like "__proto__".
14
27
  * Yet in most use cases, the keys will be simple enough to work
@@ -35,12 +35,15 @@ describe('#PersistedCounters', function () {
35
35
 
36
36
  describe('#sample', function () {
37
37
  it('should return an empty array if nothing has been counted yet', async function () {
38
- expect(await uut.sample()).to.eql([]);
38
+ expect(await uut.sample()).to.eql({ samples: [], populationSize: 0 });
39
39
  });
40
40
 
41
41
  it('should pick only element', async function () {
42
42
  uut.count('foo');
43
- expect(await uut.sample()).to.eql(['foo']);
43
+ expect(await uut.sample()).to.eql({
44
+ samples: ['foo'],
45
+ populationSize: 1,
46
+ });
44
47
  });
45
48
 
46
49
  it('should pick elements based on their counts', async function () {
@@ -50,7 +53,7 @@ describe('#PersistedCounters', function () {
50
53
 
51
54
  let foo = 0;
52
55
  let bar = 0;
53
- const samples = await uut.sample(1000);
56
+ const { samples } = await uut.sample(1000);
54
57
  for (const sample of samples) {
55
58
  if (sample === 'foo') {
56
59
  foo += 1;
@@ -78,12 +81,16 @@ describe('#PersistedCounters', function () {
78
81
  fc.nat(100),
79
82
  async (keys, numSamples) => {
80
83
  keys.forEach((key) => uut.count(key));
81
- const result = await uut.sample(numSamples);
84
+ const { samples, populationSize } = await uut.sample(
85
+ numSamples,
86
+ );
87
+ expect(populationSize).to.eql(keys.length);
88
+
82
89
  if (keys.length === 0) {
83
- expect(result).to.eql([]);
90
+ expect(samples).to.eql([]);
84
91
  } else {
85
- expect(result).to.have.lengthOf(numSamples);
86
- for (const key of result) {
92
+ expect(samples).to.have.lengthOf(numSamples);
93
+ for (const key of samples) {
87
94
  expect(keys).to.include(key);
88
95
  }
89
96
  }
@@ -104,13 +111,18 @@ describe('#PersistedCounters', function () {
104
111
  fc.nat(100),
105
112
  async (keys, numSamples) => {
106
113
  keys.forEach((key) => uut.count(key));
107
- const result = await uut.sample(numSamples, { group: true });
114
+ const { samples, populationSize } = await uut.sample(
115
+ numSamples,
116
+ { group: true },
117
+ );
118
+ expect(populationSize).to.eql(keys.length);
119
+
108
120
  if (keys.length === 0) {
109
- expect(result).to.eql([]);
121
+ expect(samples).to.eql([]);
110
122
  } else {
111
123
  let sum = 0;
112
124
  const keysSeen = new Set();
113
- for (const [key, count] of result) {
125
+ for (const [key, count] of samples) {
114
126
  expect(keys).to.include(key);
115
127
  expect(count).to.be.a('number').greaterThan(0);
116
128
  sum += count;
@@ -18,6 +18,7 @@ import PopularityEstimator from '../src/popularity-estimator.js';
18
18
  import { randomSafeIntBetween } from '../src/random.js';
19
19
  import { createInMemoryJobScheduler } from './helpers/in-memory-job-scheduler.js';
20
20
  import InMemoryDatabase from './helpers/in-memory-database.js';
21
+ import { arbitraryUrlWithDomain } from './helpers/fast-check-utils.js';
21
22
 
22
23
  const SECOND = 1000;
23
24
  const MINUTE = 60 * SECOND;
@@ -91,18 +92,19 @@ describe('#PopularityEstimator', function () {
91
92
 
92
93
  jobScheduler = createInMemoryJobScheduler();
93
94
  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
-
95
+ // Nasty pitfall: it would be nice to run assertions here, but they
96
+ // will not be visible in the console when the user runs them.
97
+ // Instead, they must be validated later (Hint: use ensureValidJob).
105
98
  _jobsRegistered.push(job);
99
+
100
+ // We can still try since there is no downside, but it will only
101
+ // have an effect if console.error is visible. So, it is a best-efforts
102
+ // attempt to get better logging.
103
+ try {
104
+ ensureValidJob(job);
105
+ } catch (e) {
106
+ console.error('Corrupted job detected:', e);
107
+ }
106
108
  });
107
109
 
108
110
  uut = newPopularityEstimator();
@@ -177,6 +179,23 @@ describe('#PopularityEstimator', function () {
177
179
  navigateTo('dummy-location-to-force-rotation.test');
178
180
  }
179
181
 
182
+ function ensureValidJob(job) {
183
+ expect(job.type).to.eql('popularity-estimator:prepare-voting:v2');
184
+ expect(job.args).to.have.all.keys(
185
+ 'urlProjection',
186
+ 'countType',
187
+ 'intervalType',
188
+ 'sample',
189
+ );
190
+ expect(job.args.sample).to.have.all.keys('value', 'count', 'activity');
191
+ expect(job.args.sample.value).to.be.a('string');
192
+ expect(job.args.sample.count).to.be.a('number').greaterThan(0);
193
+ expect(job.args.sample.activity)
194
+ .to.satisfy(Number.isInteger)
195
+ .and.at.least(0);
196
+ return job;
197
+ }
198
+
180
199
  async function expectNoPreparedVotes() {
181
200
  await clock.runToLastAsync();
182
201
  expect(jobsRegistered).to.eql([]);
@@ -185,6 +204,7 @@ describe('#PopularityEstimator', function () {
185
204
  async function expectPreparedVotes(condition = {}) {
186
205
  await clock.runToLastAsync();
187
206
  expect(jobsRegistered).to.be.not.empty;
207
+ jobsRegistered.forEach(ensureValidJob);
188
208
 
189
209
  const { matchesDomain } = condition;
190
210
  if (matchesDomain) {
@@ -305,7 +325,7 @@ describe('#PopularityEstimator', function () {
305
325
  return fc
306
326
  .array(
307
327
  fc.record({
308
- url: fc.webUrl(),
328
+ url: arbitraryUrlWithDomain,
309
329
  numVisits: fc.integer({
310
330
  min: minVisitsPerBatch,
311
331
  max: maxVisitsPerBatch,
@@ -401,6 +421,7 @@ describe('#PopularityEstimator', function () {
401
421
  };
402
422
 
403
423
  expect(jobsRegistered).to.be.not.empty;
424
+ jobsRegistered.forEach(ensureValidJob);
404
425
  mustExist('intervalType', '1d');
405
426
  mustExist('intervalType', '1w');
406
427
  mustExist('intervalType', '4w');
@@ -606,7 +627,7 @@ describe('#PopularityEstimator', function () {
606
627
 
607
628
  if (jobsRegistered.length > 0) {
608
629
  while (jobsRegistered.length > 0) {
609
- const job = jobsRegistered.shift();
630
+ const job = ensureValidJob(jobsRegistered.shift());
610
631
  const { countType, intervalType, urlProjection, sample } =
611
632
  job.args;
612
633
 
@@ -705,6 +726,212 @@ describe('#PopularityEstimator', function () {
705
726
  { numRuns: 3, endOnFailure: true },
706
727
  );
707
728
  });
729
+
730
+ describe('"activity" field: total visits are more important than number of users', function () {
731
+ // Scenario:
732
+ // Most "normal" users favor a site, which generates relatively few visits ...
733
+ const MANY_USERS_FEW_VISITS = {
734
+ url: 'https://streaming.test/watch',
735
+ domain: 'streaming.test',
736
+ timePerVisit: 10 * MINUTE,
737
+ };
738
+ // ... but another, small group ("power users") favors a site that generates a lot of visits
739
+ const FEW_USERS_MANY_VISITS = {
740
+ url: 'https://many-clicks.test/',
741
+ domain: 'many-clicks.test',
742
+ timePerVisit: 10 * SECOND,
743
+ };
744
+
745
+ // A group of "numClients" clients, where each of them makes
746
+ // "numVisits" visits (both given as ranges). Every visit goes either to
747
+ // the site of the normal users ("true") or to the site of the power
748
+ // users ("false").
749
+ function arbitraryClients({
750
+ numClients,
751
+ numVisits,
752
+ chanceOfNormalVisit,
753
+ }) {
754
+ const weight = Math.round(1000 * chanceOfNormalVisit);
755
+ const oneVisit = fc.oneof(
756
+ { weight, arbitrary: fc.constant(true) },
757
+ { weight: 1000 - weight, arbitrary: fc.constant(false) },
758
+ );
759
+ const oneClient = fc.array(oneVisit, numVisits);
760
+ return fc.array(oneClient, numClients);
761
+ }
762
+
763
+ async function simulateClient(visits) {
764
+ initMocks();
765
+ await uut.init();
766
+ await ensureAllRotationsStarted();
767
+
768
+ for (const isNormalUser of visits) {
769
+ const site = isNormalUser
770
+ ? MANY_USERS_FEW_VISITS
771
+ : FEW_USERS_MANY_VISITS;
772
+ navigateTo(site.url);
773
+ clock.tick(site.timePerVisit);
774
+ }
775
+
776
+ await endTestByForcingRotation();
777
+ await clock.runToLastAsync();
778
+ return [...jobsRegistered];
779
+ }
780
+
781
+ // Computes two rankings:
782
+ // - "byVotes": every vote counts once (approximates users per site)
783
+ // - "byActivity": votes are weighted by the activity of the client
784
+ // that sent them (approximates visits per site)
785
+ function rankSites(jobs, intervalType) {
786
+ const byVotes = new Map();
787
+ const byActivity = new Map();
788
+ const matches = ({ args }) =>
789
+ args.intervalType === intervalType &&
790
+ args.urlProjection === 'domain';
791
+
792
+ for (const { args } of jobs.map(ensureValidJob).filter(matches)) {
793
+ const { value, count, activity } = args.sample;
794
+ byVotes.set(value, (byVotes.get(value) || 0) + count);
795
+ byActivity.set(
796
+ value,
797
+ (byActivity.get(value) || 0) + count * activity,
798
+ );
799
+ }
800
+ const winner = (scorePerSite) =>
801
+ [...scorePerSite].sort((x, y) => y[1] - x[1])[0]?.[0];
802
+ return {
803
+ byVotes: winner(byVotes),
804
+ byActivity: winner(byActivity),
805
+ details: JSON.stringify({
806
+ byVotes: [...byVotes],
807
+ byActivity: [...byActivity],
808
+ }),
809
+ };
810
+ }
811
+
812
+ async function expectPowerUsersWinByActivityAndNormalUsersByVotes({
813
+ normalClients,
814
+ powerClients,
815
+ intervalType,
816
+ }) {
817
+ const jobs = [];
818
+ for (const visits of [...normalClients, ...powerClients]) {
819
+ jobs.push(...(await simulateClient(visits)));
820
+ }
821
+
822
+ const { byVotes, byActivity, details } = rankSites(
823
+ jobs,
824
+ intervalType,
825
+ );
826
+ expect(byVotes, details).to.eql(MANY_USERS_FEW_VISITS.domain);
827
+ expect(byActivity, details).to.eql(FEW_USERS_MANY_VISITS.domain);
828
+ }
829
+
830
+ // 0 means that clients are always pure "normal users" or "power users".
831
+ // But the noise here simulates scenarios where users also sometimes visit
832
+ // the other websites (switching the roles).
833
+ const ROLE_NOISE = [0, 0.02, 0.05];
834
+
835
+ // The power users have to stay the smaller group (or they would already
836
+ // win by counting votes), while their visits have to outnumber the ones
837
+ // of the normal group (or there would be nothing for the activity to
838
+ // reveal). Both hold for any combination of the ranges below.
839
+ const NUM_NORMAL_CLIENTS = { minLength: 9, maxLength: 10 };
840
+ const NUM_POWER_CLIENTS = { minLength: 3, maxLength: 4 };
841
+
842
+ for (const {
843
+ intervalType,
844
+ numNormalVisits,
845
+ numPowerVisits,
846
+ numRuns,
847
+ } of [
848
+ {
849
+ intervalType: '1d',
850
+ numNormalVisits: { minLength: 5, maxLength: 8 },
851
+ numPowerVisits: { minLength: 100, maxLength: 150 },
852
+ numRuns: 3,
853
+ },
854
+ {
855
+ // Note that for higher intervals, local sampling introduces more variance.
856
+ // Thus, we need more samples to mitigate the resulting randomness.
857
+ intervalType: '4w',
858
+ numNormalVisits: { minLength: 300, maxLength: 350 },
859
+ numPowerVisits: { minLength: 4000, maxLength: 5000 },
860
+ numRuns: 2,
861
+ },
862
+ ]) {
863
+ it(`should rank by visits, which the votes alone cannot (${intervalType})`, async function () {
864
+ this.timeout(60 * SECOND);
865
+
866
+ await fc.assert(
867
+ fc
868
+ .asyncProperty(
869
+ fc.oneof(
870
+ ...ROLE_NOISE.map((roleNoise) =>
871
+ fc.record({
872
+ normalClients: arbitraryClients({
873
+ numClients: NUM_NORMAL_CLIENTS,
874
+ numVisits: numNormalVisits,
875
+ chanceOfNormalVisit: 1 - roleNoise,
876
+ }),
877
+ powerClients: arbitraryClients({
878
+ numClients: NUM_POWER_CLIENTS,
879
+ numVisits: numPowerVisits,
880
+ chanceOfNormalVisit: roleNoise,
881
+ }),
882
+ }),
883
+ ),
884
+ ),
885
+ (population) =>
886
+ expectPowerUsersWinByActivityAndNormalUsersByVotes({
887
+ ...population,
888
+ intervalType,
889
+ }),
890
+ )
891
+ .beforeEach(initMocks)
892
+ .afterEach(tearDown),
893
+ { numRuns, endOnFailure: true },
894
+ );
895
+ });
896
+ }
897
+
898
+ it('should correct "activity" for the local sampling', async function () {
899
+ this.timeout(60 * SECOND);
900
+
901
+ const numClients = 10;
902
+ const numVisits = 1300;
903
+ const totalVisits = numClients * numVisits;
904
+
905
+ // A client that only visits the site of the power users. Since those
906
+ // visits are short, it stays inside one period - even for "1d".
907
+ const powerUserVisits = Array(numVisits).fill(false);
908
+ expect(numVisits * FEW_USERS_MANY_VISITS.timePerVisit).to.be.lessThan(
909
+ 1 * DAY,
910
+ );
911
+
912
+ // Staying inside one period means a client votes at most once per
913
+ // interval. Thus, each job can be added as it comes.
914
+ const totalActivity = { '1d': 0, '1w': 0, '4w': 0 };
915
+ for (let i = 0; i < numClients; i += 1) {
916
+ const jobs = await simulateClient(powerUserVisits);
917
+ for (const { args } of jobs) {
918
+ if (args.urlProjection === 'domain') {
919
+ totalActivity[args.intervalType] += args.sample.activity;
920
+ }
921
+ }
922
+ }
923
+
924
+ expect(totalActivity['1d'], '1d').to.eql(totalVisits);
925
+ expect(totalActivity['1w'], '1w').to.be.closeTo(
926
+ totalVisits,
927
+ 0.1 * totalVisits,
928
+ );
929
+ expect(totalActivity['4w'], '4w').to.be.closeTo(
930
+ totalVisits,
931
+ 0.3 * totalVisits,
932
+ );
933
+ });
934
+ });
708
935
  });
709
936
  });
710
937
  });
@@ -23,6 +23,7 @@ import {
23
23
  createInMemoryJobScheduler,
24
24
  runClockUntilJobQueueIsEmpty,
25
25
  } from './helpers/in-memory-job-scheduler.js';
26
+ import { arbitraryUrlWithDomain } from './helpers/fast-check-utils.js';
26
27
 
27
28
  const SECOND = 1000;
28
29
 
@@ -180,9 +181,25 @@ describe('#PopularityVoteHandler', function () {
180
181
  let actualPayloads = messagesSent.map(({ message }) => {
181
182
  const { action, payload, ver } = message;
182
183
  expect(action).to.eql('wtm.popularity');
183
- expect(ver).to.eql(3);
184
- return payload;
184
+ expect(ver).to.eql(4);
185
+
186
+ // "payload.activity" is an edge case, because random noise will be applied.
187
+ // The best that we can do is a sanity check here, and then ignoring the field.
188
+ const { activity, ...rest } = payload;
189
+ const activityBeforeNoise = prepareVotingJob.args.sample.activity;
190
+
191
+ // We could make the test stricter, but the conservative estimation here
192
+ // will hold even if the scaling factor changes in the production code.
193
+ expect(activity).to.be.a('string');
194
+ expect(Number(activity)).to.be.within(0, 2 * activityBeforeNoise);
195
+
196
+ return { ...rest, activity: '<ignore>' };
185
197
  });
198
+ expectedPayloads = expectedPayloads.map((payload) => ({
199
+ ...payload,
200
+ activity: '<ignore>',
201
+ }));
202
+
186
203
  if (ignoreMasking) {
187
204
  actualPayloads = actualPayloads.map((payload) => ({
188
205
  ...payload,
@@ -193,6 +210,7 @@ describe('#PopularityVoteHandler', function () {
193
210
  vote: '<ignore>',
194
211
  }));
195
212
  }
213
+
196
214
  try {
197
215
  expect(actualPayloads).to.have.deep.members(expectedPayloads);
198
216
  } catch (e) {
@@ -219,7 +237,7 @@ describe('#PopularityVoteHandler', function () {
219
237
  const intervalType = '1d';
220
238
 
221
239
  const prepareVotingJob = {
222
- type: 'popularity-estimator:prepare-voting:v1',
240
+ type: 'popularity-estimator:prepare-voting:v2',
223
241
  args: {
224
242
  urlProjection,
225
243
  countType,
@@ -227,6 +245,7 @@ describe('#PopularityVoteHandler', function () {
227
245
  sample: {
228
246
  value: 'example.com',
229
247
  count,
248
+ activity: 42,
230
249
  },
231
250
  },
232
251
  };
@@ -263,7 +282,7 @@ describe('#PopularityVoteHandler', function () {
263
282
  const intervalType = '1d';
264
283
 
265
284
  const prepareVotingJob = {
266
- type: 'popularity-estimator:prepare-voting:v1',
285
+ type: 'popularity-estimator:prepare-voting:v2',
267
286
  args: {
268
287
  urlProjection,
269
288
  countType,
@@ -271,6 +290,7 @@ describe('#PopularityVoteHandler', function () {
271
290
  sample: {
272
291
  value: 'example.com',
273
292
  count,
293
+ activity: 42,
274
294
  },
275
295
  },
276
296
  };
@@ -304,7 +324,7 @@ describe('#PopularityVoteHandler', function () {
304
324
  await fc.assert(
305
325
  fc
306
326
  .asyncProperty(
307
- fc.webUrl(),
327
+ arbitraryUrlWithDomain,
308
328
  fc.constantFrom('domain', 'hostname', 'hostnamePath'),
309
329
  fc.constantFrom('1d', '1w', '4w'),
310
330
  fc.integer({ min: 1, max: 3 }),
@@ -313,7 +333,7 @@ describe('#PopularityVoteHandler', function () {
313
333
  const countType = 'visits';
314
334
 
315
335
  const prepareVotingJob = {
316
- type: 'popularity-estimator:prepare-voting:v1',
336
+ type: 'popularity-estimator:prepare-voting:v2',
317
337
  args: {
318
338
  urlProjection,
319
339
  countType,
@@ -321,6 +341,7 @@ describe('#PopularityVoteHandler', function () {
321
341
  sample: {
322
342
  value: vote,
323
343
  count,
344
+ activity: 42,
324
345
  },
325
346
  },
326
347
  };
@@ -359,7 +380,7 @@ describe('#PopularityVoteHandler', function () {
359
380
  await fc.assert(
360
381
  fc
361
382
  .asyncProperty(
362
- fc.webUrl(),
383
+ arbitraryUrlWithDomain,
363
384
  fc.constantFrom('domain', 'hostname'),
364
385
  fc.constantFrom('1d', '1w', '4w'),
365
386
  async (url, urlProjection, intervalType) => {
@@ -384,7 +405,7 @@ describe('#PopularityVoteHandler', function () {
384
405
  countryProvider._ctry = 'de';
385
406
 
386
407
  const prepareVotingJob = {
387
- type: 'popularity-estimator:prepare-voting:v1',
408
+ type: 'popularity-estimator:prepare-voting:v2',
388
409
  args: {
389
410
  urlProjection,
390
411
  countType,
@@ -392,6 +413,7 @@ describe('#PopularityVoteHandler', function () {
392
413
  sample: {
393
414
  value: unmaskedVote,
394
415
  count: 1,
416
+ activity: 42,
395
417
  },
396
418
  },
397
419
  };
@@ -415,6 +437,103 @@ describe('#PopularityVoteHandler', function () {
415
437
  { numRuns: 10 },
416
438
  );
417
439
  });
440
+
441
+ /**
442
+ * Sends "numJobs" identical vote jobs through the scheduler and returns
443
+ * the "activity" values of all messages that ended up being sent.
444
+ */
445
+ async function collectNoisyActivities(prepareVotingJob, numJobs) {
446
+ // If we register too many jobs at once, the jobScheduler will start
447
+ // dropping them. So why not flush after each job? Unfortunately, that
448
+ // slows down the test setup too much.
449
+ const flushJobs = 32; // even with 3 votes, it is 3 * 32 < 100
450
+
451
+ await jobScheduler.init();
452
+ try {
453
+ for (let i = 0; i < numJobs; i += 1) {
454
+ await jobScheduler.registerJob(prepareVotingJob);
455
+ if ((i + 1) % flushJobs === 0) {
456
+ await runClockUntilJobQueueIsEmpty(jobScheduler, clock);
457
+ }
458
+ }
459
+ await runClockUntilJobQueueIsEmpty(jobScheduler, clock);
460
+ return communication._messagesSent.map(({ message }) =>
461
+ Number(message.payload.activity),
462
+ );
463
+ } finally {
464
+ jobScheduler.unload();
465
+ }
466
+ }
467
+
468
+ it('should preserve the mean of "activity" when applying noise', async function () {
469
+ this.timeout(60 * SECOND);
470
+
471
+ await fc.assert(
472
+ fc
473
+ .asyncProperty(
474
+ fc.integer({ min: 1, max: 10000 }),
475
+ async (activity) => {
476
+ quorumChecker._everythingReachesQuorum();
477
+
478
+ // trade-off: do not set too high, or the test will be too slow.
479
+ // But also it must be high enough, so it is not flakey.
480
+ const numJobs = 80;
481
+ const votesPerJob = 3; // the most that a client may send
482
+
483
+ const activities = await collectNoisyActivities(
484
+ {
485
+ type: 'popularity-estimator:prepare-voting:v2',
486
+ args: {
487
+ urlProjection: 'domain',
488
+ countType: 'visits',
489
+ intervalType: '1d',
490
+ sample: {
491
+ value: 'example.com',
492
+ count: votesPerJob,
493
+ activity,
494
+ },
495
+ },
496
+ },
497
+ numJobs,
498
+ );
499
+ expect(activities).to.have.lengthOf(numJobs * votesPerJob);
500
+
501
+ const mean =
502
+ activities.reduce((x, y) => x + y, 0) / activities.length;
503
+ expect(mean).to.be.closeTo(activity, 0.1 * activity);
504
+
505
+ return true;
506
+ },
507
+ )
508
+ .beforeEach(initMocks)
509
+ .afterEach(tearDown),
510
+ { numRuns: 2, endOnFailure: true },
511
+ );
512
+ });
513
+
514
+ it('should apply the noise to each message individually', async function () {
515
+ // Otherwise, votes of the same client would remain trivially linkable.
516
+ // Note that one job is enough: it is the noise within a single job that
517
+ // could be lost (e.g. by drawing it once instead of once per message).
518
+ quorumChecker._everythingReachesQuorum();
519
+ const activities = await collectNoisyActivities(
520
+ {
521
+ type: 'popularity-estimator:prepare-voting:v2',
522
+ args: {
523
+ urlProjection: 'domain',
524
+ countType: 'visits',
525
+ intervalType: '1d',
526
+ sample: { value: 'example.com', count: 3, activity: 42 },
527
+ },
528
+ },
529
+ 1,
530
+ );
531
+
532
+ // Note: there is a theoretical potential for getting the
533
+ // identical random numbers, but practically it is so
534
+ // unlikely that we can ignore it here.
535
+ expect(new Set(activities).size).to.eql(3);
536
+ });
418
537
  });
419
538
  });
420
539
  });
@@ -1,13 +0,0 @@
1
- if (window.outerWidth === 0) {
2
- Object.defineProperty(window, 'outerWidth', {
3
- get: () => 1920,
4
- configurable: true,
5
- });
6
- }
7
-
8
- if (window.outerHeight === 0) {
9
- Object.defineProperty(window, 'outerHeight', {
10
- get: () => 1080,
11
- configurable: true,
12
- });
13
- }