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'
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,
}
}
+/**
+ * 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.
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
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)
})
})
+ 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(