From 6c3bfec204e7fd075ca7ecc2e2793d5e93a2339d Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Wed, 18 Nov 2026 01:14:32 +0100 Subject: [PATCH] perf(pools): make measurement statistics allocation free (#3412) * perf(pools): make measurement statistics allocation free Compute the average directly from the circular buffer and the median via a guarded quickselect over a shared snapshot instead of `toArray()`+`slice().sort()`: - average: O(H) single pass over the buffer (`CircularBuffer.sum()`), no allocation - median: O(H) quickselect over a shared snapshot (native-sort depth fallback keeps the worst case at O(H log H)), no allocation Results are bit-for-bit identical to `average(history.toArray())` and `median(history.toArray())`, fuzz-tested against reference implementations with `Object.is`. Measured: median path x7.2, average path x1.56 per task completion; +10 % throughput on a 2-core fair-share pool. * [autofix.ci] apply automated fixes * test(pools): make statistics fuzz falsifiable and cover sum() directly Feed the bit-for-bit fuzz with wide-dynamics values (1e-8 to 1e8) so that the float64 summation order becomes observable: a mutation reversing the accumulation order of `sum()` now fails the test (checked by mutation). Add a direct `sum()` unit test (empty, full, wrap, partial drain). * fix(pools): preserve negative zero in single-value measurement average `sum()` folds `- 0` into `+ 0` (`0 + (- 0)`), while the replaced `average()` returned `dataSet[0]` as is. Read the single element from the snapshot instead, and pin the behavior with an `Object.is` test. Also document the remaining known difference of the quickselect median (occurrence sign among equal-comparing `- 0`/`NaN` values, unreachable from measurement producers). * [autofix.ci] apply automated fixes * refactor(pools): name the rank-selection tuning constants Extract the insertion-sort cutoff and the quickselect depth factor of `selectAtRank()` into documented module constants, following the existing private-constant convention. No behavior change. --------- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com> --- src/circular-buffer.ts | 32 ++++++ src/pools/utils.ts | 173 ++++++++++++++++++++++++++++++++- tests/circular-buffer.test.mjs | 40 ++++++++ tests/pools/utils.test.mjs | 88 +++++++++++++++++ 4 files changed, 328 insertions(+), 5 deletions(-) diff --git a/src/circular-buffer.ts b/src/circular-buffer.ts index 7748cf56c..91ea3ee52 100644 --- a/src/circular-buffer.ts +++ b/src/circular-buffer.ts @@ -38,6 +38,22 @@ export class CircularBuffer { this.size = 0 } + /** + * Copies the buffer contents, in logical order, into the given destination. + * The destination must be able to hold the whole buffer. + * @param destination - Destination array. + * @returns The number of numbers copied. + */ + public copyTo (destination: Float32Array): number { + const size = this.size + let currentIdx = this.readIdx + for (let i = 0; i < size; i++) { + destination[i] = this.items[currentIdx] + currentIdx = currentIdx === this.maxArrayIdx ? 0 : currentIdx + 1 + } + return size + } + /** * Checks whether the buffer is empty. * @returns Whether the buffer is empty. @@ -82,6 +98,22 @@ export class CircularBuffer { this.writeIdx = this.writeIdx === this.maxArrayIdx ? 0 : this.writeIdx + 1 } + /** + * Computes the sum of the buffer contents, in logical order. + * Bit-for-bit equivalent to summing `toArray()` in the same order. + * @returns Sum of the buffer numbers, zero if the buffer is empty. + */ + public sum (): number { + let sum = 0 + const size = this.size + let currentIdx = this.readIdx + for (let i = 0; i < size; i++) { + sum += this.items[currentIdx] + currentIdx = currentIdx === this.maxArrayIdx ? 0 : currentIdx + 1 + } + return sum + } + /** * Returns buffer as numbers' array. * @returns Numbers' array. diff --git a/src/pools/utils.ts b/src/pools/utils.ts index 0e45484b8..6f2f63793 100644 --- a/src/pools/utils.ts +++ b/src/pools/utils.ts @@ -9,6 +9,7 @@ import { type WorkerOptions, } from 'node:worker_threads' +import type { CircularBuffer } from '../circular-buffer.js' import type { MessageValue, Task } from '../utility-types.js' import type { TasksQueueOptions } from './pool.js' import type { WorkerChoiceStrategiesContext } from './selection-strategies/worker-choice-strategies-context.js' @@ -17,7 +18,7 @@ import { defaultAgingFactor, defaultLoadExponent, } from '../queues/queue-types.js' -import { average, isPlainObject, max, median, min } from '../utils.js' +import { isPlainObject, max, min } from '../utils.js' import { type MeasurementStatisticsRequirements, WorkerChoiceStrategies, @@ -734,6 +735,168 @@ export const checkWorkerNodeArguments = ( } } +/** + * Reusable snapshot buffer for measurement history statistics. + * The main thread computes statistics sequentially, one history at a time. + */ +let measurementSnapshot = new Float32Array(0) + +/** + * Snapshots the given measurement history, in logical order, into the shared + * snapshot buffer. + * @param history - Measurement history to snapshot. + * @returns The number of snapshot values. + */ +const snapshotMeasurementHistory = (history: CircularBuffer): number => { + const size = history.size + if (measurementSnapshot.length < size) { + measurementSnapshot = new Float32Array(size) + } + history.copyTo(measurementSnapshot) + return size +} + +/** + * Computes the average of the given measurement history. + * Bit-for-bit equivalent to `average(history.toArray())`: same values, same + * summation order, no allocation. + * @param history - Measurement history. + * @returns The average of the history values. + */ +const averageMeasurementHistory = (history: CircularBuffer): number => { + const size = history.size + if (size === 0) { + return 0 + } + if (size === 1) { + // Return the raw element instead of `sum()`: accumulating `0 + value` + // would fold `- 0` into `+ 0`, while `average()` returned `dataSet[0]` + // as is. + snapshotMeasurementHistory(history) + return measurementSnapshot[0] + } + return history.sum() / size +} + +/** + * Swaps two elements of the given array. + * @param data - Array whose elements are swapped. + * @param i - Index of the first element. + * @param j - Index of the second element. + */ +const swap = (data: Float32Array, i: number, j: number): void => { + if (i !== j) { + const value = data[i] + data[i] = data[j] + data[j] = value + } +} + +/** + * Width under which rank selection sorts its slice instead of partitioning. + */ +const SELECTION_INSERTION_CUTOFF = 12 +/** + * Maximum number of quickselect partitions, as a factor of the slice height, + * before rank selection falls back to a native sort. + */ +const SELECTION_DEPTH_FACTOR = 2 + +/** + * Selects the value at rank `k` of `data[0, size)` in place (partial sort). + * Quickselect with median-of-three pivot, insertion cutoff and a depth limit + * falling back to native sort, keeping the worst case at O(size log size). + * @param data - Data to partially sort. + * @param size - Number of leading elements to consider. + * @param k - Rank to select. + * @returns The value at rank `k`. + */ +const selectAtRank = (data: Float32Array, size: number, k: number): number => { + let left = 0 + let right = size - 1 + let depthLeft = SELECTION_DEPTH_FACTOR * Math.ceil(Math.log2(size + 1)) + for (;;) { + const width = right - left + 1 + if (width <= SELECTION_INSERTION_CUTOFF) { + for (let i = left + 1; i <= right; i++) { + const value = data[i] + let j = i - 1 + while (j >= left && data[j] > value) { + data[j + 1] = data[j] + --j + } + data[j + 1] = value + } + return data[k] + } + if (--depthLeft < 0) { + data.subarray(left, right + 1).sort() + return data[k] + } + // Median-of-three pivot, stashed at the right end. + const middle = (left + right) >> 1 + if (data[middle] < data[left]) swap(data, middle, left) + if (data[right] < data[middle]) { + swap(data, middle, right) + if (data[middle] < data[left]) swap(data, middle, left) + } + const pivot = data[middle] + swap(data, middle, right) + let lessEnd = left + for (let i = left; i < right; i++) { + if (data[i] < pivot) { + swap(data, i, lessEnd) + ++lessEnd + } + } + let equalEnd = lessEnd + for (let i = lessEnd; i < right; i++) { + if (data[i] === pivot) { + swap(data, i, equalEnd) + ++equalEnd + } + } + swap(data, right, equalEnd) + if (k < lessEnd) { + right = lessEnd - 1 + } else if (k > equalEnd) { + left = equalEnd + 1 + } else { + return pivot + } + } +} + +/** + * Computes the median of the given measurement history. + * Returns the same two middle values as `median(history.toArray())` for + * finite inputs: the middle values are selected elements, not interpolated + * ones. Inputs no measurement producer can emit (`- 0`, `NaN`) may pick a + * different occurrence among equal-comparing values than the comparator + * based sort did. + * @param history - Measurement history. + * @returns The median of the history values. + */ +const medianMeasurementHistory = (history: CircularBuffer): number => { + const size = snapshotMeasurementHistory(history) + if (size === 0) { + return 0 + } + if (size === 1) { + return measurementSnapshot[0] + } + const upperRank = size >> 1 + const lowerRank = (size - 1) >> 1 + const upper = selectAtRank(measurementSnapshot, size, upperRank) + // After the first selection, the leading `upperRank` elements are the + // smallest ones, so the lower middle value is selected within that prefix. + const lower = + lowerRank === upperRank + ? upper + : selectAtRank(measurementSnapshot, upperRank, lowerRank) + return (lower + upper) / 2 +} + /** * Updates the given measurement statistics. * @param measurementStatistics - The measurement statistics to update. @@ -764,15 +927,15 @@ const updateMeasurementStatistics = ( if (measurementRequirements.average || measurementRequirements.median) { measurementStatistics.history.put(measurementValue) if (measurementRequirements.average) { - measurementStatistics.average = average( - measurementStatistics.history.toArray() + measurementStatistics.average = averageMeasurementHistory( + measurementStatistics.history ) } else if (measurementStatistics.average != null) { measurementStatistics.average = undefined } if (measurementRequirements.median) { - measurementStatistics.median = median( - measurementStatistics.history.toArray() + measurementStatistics.median = medianMeasurementHistory( + measurementStatistics.history ) } else if (measurementStatistics.median != null) { measurementStatistics.median = undefined diff --git a/tests/circular-buffer.test.mjs b/tests/circular-buffer.test.mjs index d86f74418..489ca5c89 100644 --- a/tests/circular-buffer.test.mjs +++ b/tests/circular-buffer.test.mjs @@ -166,6 +166,46 @@ describe('Circular buffer test suite', () => { expect(circularBuffer.toArray()).toStrictEqual([3, 4, 5, 6]) }) + it('Verify that circular buffer copyTo() works as intended', () => { + const circularBuffer = new CircularBuffer(4) + const destination = new Float32Array(8) + expect(circularBuffer.copyTo(destination)).toBe(0) + const values = [1, 2, 3, 4, 5, 6] + const expected = [] + for (const value of values) { + circularBuffer.put(value) + expected.push(value) + if (expected.length > 4) expected.shift() + const size = circularBuffer.copyTo(destination) + expect(size).toBe(expected.length) + expect(Array.from(destination.subarray(0, size))).toStrictEqual(expected) + expect(destination.slice(size)).toStrictEqual(new Float32Array(8 - size)) + } + circularBuffer.get() + circularBuffer.get() + const size = circularBuffer.copyTo(destination) + expect(size).toBe(2) + expect(Array.from(destination.subarray(0, size))).toStrictEqual([5, 6]) + circularBuffer.clear() + expect(circularBuffer.copyTo(destination)).toBe(0) + }) + + it('Verify that circular buffer sum() works as intended', () => { + const circularBuffer = new CircularBuffer(4) + expect(circularBuffer.sum()).toBe(0) + for (const value of [1, 2, 3, 4]) { + circularBuffer.put(value) + } + expect(circularBuffer.sum()).toBe(10) + circularBuffer.put(5) + expect(circularBuffer.sum()).toBe(14) + circularBuffer.get() + expect(circularBuffer.sum()).toBe(12) + expect(circularBuffer.sum()).toBe( + circularBuffer.toArray().reduce((accumulator, n) => accumulator + n, 0) + ) + }) + it('Verify that circular buffer clear() works as intended', () => { const circularBuffer = new CircularBuffer(4) circularBuffer.put(1) diff --git a/tests/pools/utils.test.mjs b/tests/pools/utils.test.mjs index 35250b0fe..49fb6e073 100644 --- a/tests/pools/utils.test.mjs +++ b/tests/pools/utils.test.mjs @@ -667,6 +667,94 @@ parentPort.postMessage({ }) }) + it('Verify updateMeasurementStatistics() is bit-for-bit equivalent to a naive reference implementation', () => { + const referenceAverage = values => { + if (values.length === 0) return 0 + if (values.length === 1) return values[0] + let sum = 0 + for (const value of values) sum += value + return sum / values.length + } + const referenceMedian = values => { + if (values.length === 0) return 0 + if (values.length === 1) return values[0] + const sorted = [...values].sort((a, b) => a - b) + return (sorted[(values.length - 1) >> 1] + sorted[values.length >> 1]) / 2 + } + let seed = 0x2f6e2b1 + const random = () => { + seed ^= seed << 13 + seed >>>= 0 + seed ^= seed >>> 17 + seed ^= seed << 5 + seed >>>= 0 + return seed / 0x100000000 + } + const sizes = [2, 3, 5, MeasurementHistorySize, MeasurementHistorySize + 7] + for (const size of sizes) { + for (const flags of [ + { average: true, median: false }, + { average: false, median: true }, + { average: true, median: true }, + ]) { + const requirements = { aggregate: true, ...flags } + const measurementStatistics = { + history: new CircularBuffer(size), + } + const reference = [] + const iterations = size + 50 + for (let i = 0; i < iterations; i++) { + // Mixed distribution: duplicated values to exercise median ties, + // plain noise, and large-dynamics values that make the float64 + // summation order observable. + const value = Math.fround( + i % 7 === 0 + ? 1 + (i % 4) + : i % 7 === 1 + ? 10 ** (random() * 16 - 8) + : random() * 100 + ) + updateMeasurementStatistics( + measurementStatistics, + requirements, + value + ) + reference.push(value) + if (reference.length > size) reference.shift() + if (flags.average) { + expect( + Object.is( + measurementStatistics.average, + referenceAverage(reference) + ) + ).toBe(true) + } + if (flags.median) { + expect( + Object.is( + measurementStatistics.median, + referenceMedian(reference) + ) + ).toBe(true) + } + } + } + } + }) + + it('Verify updateMeasurementStatistics() preserves negative zero as the reference implementations do', () => { + const measurementStatistics = { + history: new CircularBuffer(MeasurementHistorySize), + } + updateMeasurementStatistics( + measurementStatistics, + { aggregate: true, average: true, median: true }, + -0 + ) + expect(Object.is(measurementStatistics.average, -0)).toBe(true) + expect(Object.is(measurementStatistics.median, -0)).toBe(true) + }) + it('Verify createWorker() behavior', () => { expect( createWorker( -- 2.53.0