From 6e9e424aafcbcb4286cfdda9215d902ec15f3d41 Mon Sep 17 00:00:00 2001 From: alexvictoor Date: Sat, 14 Nov 2026 21:41:08 +0100 Subject: [PATCH 1/5] perf: compute several percentiles in one counts scan Add getValuesAtPercentiles(percentiles) to every histogram implementation (JS, packed, Float64, WASM). One bounded scan of the counts fills all requested percentiles, in input order, instead of one scan per percentile. The summary getter uses it, so the eight summary percentiles take one pass. Co-Authored-By: Claude Haiku 5.5 --- assembly/Histogram.ts | 112 +++++++++++-- assembly/index.ts | 11 ++ src/Histogram.ts | 30 +++- src/Histogram.valuesAtPercentiles.spec.ts | 186 ++++++++++++++++++++++ src/JsHistogram.ts | 80 ++++++++-- src/wasm/index.ts | 38 +++++ 6 files changed, 420 insertions(+), 37 deletions(-) create mode 100644 src/Histogram.valuesAtPercentiles.spec.ts diff --git a/assembly/Histogram.ts b/assembly/Histogram.ts index 3ace11b..6f4cee4 100644 --- a/assembly/Histogram.ts +++ b/assembly/Histogram.ts @@ -661,21 +661,7 @@ export default class Histogram extends AbstractHistogramBase { * value that all value entries in the histogram are either larger than or equivalent to. */ getValueAtPercentile(percentile: f64): u64 { - const requestedPercentile = min(percentile, 100); // Truncate down to 100% - - // round count up to nearest integer, to ensure that the largest value that the requested percentile - // of overall recorded values is actually included. However, this must be done with care: - // - // First, Compute fp value for count at the requested percentile. Note that fp result end up - // being 1 ulp larger than the correct integer count for this percentile: - const fpCountAtPercentile = - (requestedPercentile / 100.0) * this.totalCount; - // Next, round up, but make sure to prevent <= 1 ulp inaccurancies in the above fp math from - // making us skip a count: - const countAtPercentile = max( - ceil(fpCountAtPercentile - ulp(fpCountAtPercentile)), // round up - 1 // Make sure we at least reach the first recorded entry - ); + const countAtPercentile = this.countAtPercentile(percentile); // Index 0 holds the zero values and is the only index below the one of // minNonZeroValue that may hold a count; nothing is recorded past the @@ -724,6 +710,102 @@ export default class Histogram extends AbstractHistogramBase { : this.highestEquivalentValue(valueAtIndex); } + /** + * Get the values at several percentiles with a single scan of the counts. + * Each entry is what getValueAtPercentile returns for the same percentile; + * results are in the input order. The percentiles may be unsorted or repeated. + */ + getValuesAtPercentiles(percentiles: Float64Array): Float64Array { + const count = percentiles.length; + const results = new Float64Array(count); + // Positions sorted by the count each one has to reach (`thresholds`). + // NaN percentiles are left out and stay at 0, as getValueAtPercentile. + const thresholds = new Float64Array(count); + const order = new Array(0); + for (let position = 0; position < count; position++) { + const percentile = percentiles[position]; + if (isNaN(percentile)) continue; + const threshold = this.countAtPercentile(percentile); + thresholds[position] = threshold; + // Insertion sort: a summary asks for 8 percentiles, lists stay short. + let j = order.length; + order.push(position); + while (j > 0 && thresholds[order[j - 1]] > threshold) { + order[j] = order[j - 1]; + j--; + } + order[j] = position; + } + const valid = order.length; + if (valid == 0) return results; + + const step = lanes() << 2; // indexes per 64-byte block + const end = this.highestNonZeroCountsIndex() + 1; + const lowest = this.lowestNonZeroCountsIndex(); + let next = 0; // First entry of `order` not yet resolved + let total: f64 = 0; // Sum of the counts below index i + let i: i32 = 0; + while (next < valid && i < end) { + // Index 0 is a chunk of its own; the other chunks are one index or, on + // flat storage, one 64-byte block that the next threshold does not reach. + let chunkEnd: i32 = i + 1; + if (isFlatStorage()) { + if (i > 0 && i + step <= end) { + const p = this.countsDataStart + (i << alignof()); + let acc = widenSum(v128.load(p)); + acc = i64x2.add(acc, widenSum(v128.load(p, 16))); + acc = i64x2.add(acc, widenSum(v128.load(p, 32))); + acc = i64x2.add(acc, widenSum(v128.load(p, 48))); + const totalToBlockEnd = total + horizontalSum(acc); + if (totalToBlockEnd < thresholds[order[next]]) { + total = totalToBlockEnd; + i += step; + continue; + } + chunkEnd = i + step; + } + } + for (; i < chunkEnd; i++) { + total += this.getCountAtIndex(i); + while (next < valid && total >= thresholds[order[next]]) { + const position = order[next]; + const valueAtIndex: u64 = this.valueFromIndex(i); + results[position] = ( + percentiles[position] === 0.0 + ? this.lowestEquivalentValue(valueAtIndex) + : this.highestEquivalentValue(valueAtIndex) + ); + next++; + } + if (next == valid) break; + } + if (chunkEnd == 1) i = lowest; // index 0 is followed by the lowest non-zero index + } + return results; + } + + /** + * Number of recorded values a percentile must reach, rounded as + * getValueAtPercentile has always rounded it. + */ + countAtPercentile(percentile: f64): f64 { + const requestedPercentile = min(percentile, 100); // Truncate down to 100% + + // round count up to nearest integer, to ensure that the largest value that the requested percentile + // of overall recorded values is actually included. However, this must be done with care: + // + // First, Compute fp value for count at the requested percentile. Note that fp result end up + // being 1 ulp larger than the correct integer count for this percentile: + const fpCountAtPercentile = + (requestedPercentile / 100.0) * this.totalCount; + // Next, round up, but make sure to prevent <= 1 ulp inaccurancies in the above fp math from + // making us skip a count: + return max( + ceil(fpCountAtPercentile - ulp(fpCountAtPercentile)), // round up + 1 // Make sure we at least reach the first recorded entry + ); + } + valueFromIndexes(bucketIndex: i32, subBucketIndex: i32): u64 { return (subBucketIndex) << (bucketIndex + this.unitMagnitude); } diff --git a/assembly/index.ts b/assembly/index.ts index bb8f252..7fa7047 100644 --- a/assembly/index.ts +++ b/assembly/index.ts @@ -18,6 +18,7 @@ import ByteBuffer from "./ByteBuffer"; import { PackedArray } from "./packedarray/PackedArray"; export const UINT8ARRAY_ID = idof(); +export const FLOAT64ARRAY_ID = idof(); class HistogramAdapter { private _histogram!: Histogram; @@ -156,6 +157,10 @@ class HistogramAdapter { return this._histogram.getValueAtPercentile(percentile); } + getValuesAtPercentiles(percentiles: Float64Array): Float64Array { + return this._histogram.getValuesAtPercentiles(percentiles); + } + outputPercentileDistribution( percentileTicksPerHalfDistance: f64, outputValueUnitScalingRatio: f64 @@ -447,6 +452,12 @@ export function getValueAtPercentile32(h: Histogram32, percentile: f64): f64 { r export function getValueAtPercentile64(h: Histogram64, percentile: f64): f64 { return h.getValueAtPercentile(percentile); } export function getValueAtPercentilePacked(h: PackedHistogram, percentile: f64): f64 { return h.getValueAtPercentile(percentile); } +export function getValuesAtPercentiles8(h: Histogram8, percentiles: Float64Array): Float64Array { return h.getValuesAtPercentiles(percentiles); } +export function getValuesAtPercentiles16(h: Histogram16, percentiles: Float64Array): Float64Array { return h.getValuesAtPercentiles(percentiles); } +export function getValuesAtPercentiles32(h: Histogram32, percentiles: Float64Array): Float64Array { return h.getValuesAtPercentiles(percentiles); } +export function getValuesAtPercentiles64(h: Histogram64, percentiles: Float64Array): Float64Array { return h.getValuesAtPercentiles(percentiles); } +export function getValuesAtPercentilesPacked(h: PackedHistogram, percentiles: Float64Array): Float64Array { return h.getValuesAtPercentiles(percentiles); } + export function outputPercentileDistribution8(h: Histogram8, percentileTicksPerHalfDistance: f64, outputValueUnitScalingRatio: f64): string { return h.outputPercentileDistribution(percentileTicksPerHalfDistance, outputValueUnitScalingRatio); } export function outputPercentileDistribution16(h: Histogram16, percentileTicksPerHalfDistance: f64, outputValueUnitScalingRatio: f64): string { return h.outputPercentileDistribution(percentileTicksPerHalfDistance, outputValueUnitScalingRatio); } export function outputPercentileDistribution32(h: Histogram32, percentileTicksPerHalfDistance: f64, outputValueUnitScalingRatio: f64): string { return h.outputPercentileDistribution(percentileTicksPerHalfDistance, outputValueUnitScalingRatio); } diff --git a/src/Histogram.ts b/src/Histogram.ts index b448861..7d4b9d9 100644 --- a/src/Histogram.ts +++ b/src/Histogram.ts @@ -97,6 +97,17 @@ export default interface Histogram { */ getValueAtPercentile(percentile: number): number; + /** + * Get the values at several percentiles with a single scan of the counts. + * Each entry is what {@link getValueAtPercentile} returns for the same + * percentile. Results are in the input order; the percentiles may be + * unsorted or repeated, and an empty list returns an empty array. + * + * @param percentiles The percentiles for which to return the associated values + * @return The values, one per requested percentile + */ + getValuesAtPercentiles(percentiles: number[]): number[]; + /** * Produce textual representation of the value distribution of histogram data by percentile. The distribution is * output with exponentially increasing resolution, with each exponentially decreasing half-distance containing @@ -240,15 +251,18 @@ export interface HistogramConstructor { export const toSummary = (histogram: Histogram): HistogramSummary => { const { totalCount, maxValue, numberOfSignificantValueDigits } = histogram; const round = keepSignificantDigits(numberOfSignificantValueDigits); + const [p50, p75, p90, p97_5, p99, p99_9, p99_99, p99_999] = histogram + .getValuesAtPercentiles([50, 75, 90, 97.5, 99, 99.9, 99.99, 99.999]) + .map((value) => round(value)); return { - p50: round(histogram.getValueAtPercentile(50)), - p75: round(histogram.getValueAtPercentile(75)), - p90: round(histogram.getValueAtPercentile(90)), - p97_5: round(histogram.getValueAtPercentile(97.5)), - p99: round(histogram.getValueAtPercentile(99)), - p99_9: round(histogram.getValueAtPercentile(99.9)), - p99_99: round(histogram.getValueAtPercentile(99.99)), - p99_999: round(histogram.getValueAtPercentile(99.999)), + p50, + p75, + p90, + p97_5, + p99, + p99_9, + p99_99, + p99_999, max: maxValue, totalCount, }; diff --git a/src/Histogram.valuesAtPercentiles.spec.ts b/src/Histogram.valuesAtPercentiles.spec.ts new file mode 100644 index 0000000..8638a51 --- /dev/null +++ b/src/Histogram.valuesAtPercentiles.spec.ts @@ -0,0 +1,186 @@ +/* + * This is a TypeScript port of the original Java version, which was written by + * Gil Tene as described in + * https://github.com/HdrHistogram/HdrHistogram + * and released to the public domain, as explained at + * http://creativecommons.org/publicdomain/zero/1.0/ + */ +import * as fc from "fast-check"; +import * as hdr from "./index"; +import { initWebAssembly } from "./wasm"; +import Histogram from "./Histogram"; +import { keepSignificantDigits } from "./formatters"; + +const runFromStryker = __dirname.includes("stryker"); +const runnerOptions = { + numRuns: runFromStryker ? 10 : 300, + verbose: true, +}; + +const numberOfSignificantValueDigits = 3; + +const implementations: { name: string; build: () => Histogram }[] = [ + { + name: "JS 32-bit", + build: () => + hdr.build({ bitBucketSize: 32, numberOfSignificantValueDigits }), + }, + { + name: "JS packed", + build: () => + hdr.build({ bitBucketSize: "packed", numberOfSignificantValueDigits }), + }, + { + name: "Float64", + build: () => + new hdr.Float64Histogram( + 1, + 1_000_000_000, + numberOfSignificantValueDigits + ), + }, + { + name: "WASM 32-bit", + build: () => + hdr.build({ + bitBucketSize: 32, + numberOfSignificantValueDigits, + useWebAssembly: true, + }), + }, + { + name: "WASM packed", + build: () => + hdr.build({ + bitBucketSize: "packed", + numberOfSignificantValueDigits, + useWebAssembly: true, + }), + }, +]; + +// Values spread over a wide range, so the counts have long empty stretches +// (the bounded scan and the block skipping both get exercised). +const recordsArb = fc.array( + fc.record({ + value: fc.integer({ min: 0, max: 5_000_000 }), + count: fc.integer({ min: 1, max: 50 }), + }), + { maxLength: 300 } +); + +// Unsorted, possibly repeated, including the edges (0, 100, above 100). +const percentilesArb = fc.array( + fc.oneof( + fc.constantFrom(0, 50, 75, 97.5, 99, 99.9, 99.99, 99.999, 100, 150), + fc.double({ min: 0, max: 100, noNaN: true }) + ), + { maxLength: 20 } +); + +type Record = { value: number; count: number }; + +const fill = (histogram: Histogram, records: Record[]) => { + records.forEach(({ value, count }) => + histogram.recordValueWithCount(value, count) + ); + return histogram; +}; + +describe.each(implementations)( + "getValuesAtPercentiles on $name", + ({ build }) => { + beforeAll(initWebAssembly); + + it("matches getValueAtPercentile for each requested percentile", () => { + fc.assert( + fc.property(recordsArb, percentilesArb, (records, percentiles) => { + const histogram = fill(build(), records); + try { + const expected = percentiles.map((p) => + histogram.getValueAtPercentile(p) + ); + expect(histogram.getValuesAtPercentiles(percentiles)).toEqual( + expected + ); + } finally { + histogram.destroy(); + } + }), + runnerOptions + ); + }); + + it("returns an empty array for an empty list", () => { + const histogram = fill(build(), [{ value: 42, count: 3 }]); + expect(histogram.getValuesAtPercentiles([])).toEqual([]); + histogram.destroy(); + }); + + it("returns 0 for every percentile of an empty histogram", () => { + const histogram = build(); + expect(histogram.getValuesAtPercentiles([0, 50, 99.9, 100])).toEqual([ + 0, 0, 0, 0, + ]); + histogram.destroy(); + }); + + it("keeps the input order for unsorted and repeated percentiles", () => { + const histogram = fill( + build(), + Array.from({ length: 100 }, (_, i) => ({ value: i + 1, count: 1 })) + ); + expect(histogram.getValuesAtPercentiles([99, 50, 99, 0, 100])).toEqual([ + 99, 50, 99, 1, 100, + ]); + histogram.destroy(); + }); + + it("truncates percentiles above 100 to 100", () => { + const histogram = fill(build(), [ + { value: 10, count: 1 }, + { value: 1000, count: 1 }, + ]); + const [above, top] = histogram.getValuesAtPercentiles([150, 100]); + expect(above).toBe(top); + expect(top).toBe(histogram.getValueAtPercentile(100)); + histogram.destroy(); + }); + + it("returns 0 for a NaN percentile and still answers the others", () => { + const histogram = fill(build(), [{ value: 50, count: 10 }]); + expect(histogram.getValuesAtPercentiles([NaN, 50])).toEqual([ + 0, + histogram.getValueAtPercentile(50), + ]); + histogram.destroy(); + }); + + it("summary values are the per-percentile values, rounded", () => { + fc.assert( + fc.property(recordsArb, (records) => { + const histogram = fill(build(), records); + try { + const round = keepSignificantDigits(numberOfSignificantValueDigits); + const at = (p: number) => round(histogram.getValueAtPercentile(p)); + expect(histogram.summary).toEqual({ + p50: at(50), + p75: at(75), + p90: at(90), + p97_5: at(97.5), + p99: at(99), + p99_9: at(99.9), + p99_99: at(99.99), + p99_999: at(99.999), + max: histogram.maxValue, + totalCount: histogram.totalCount, + }); + } finally { + histogram.destroy(); + } + }), + runnerOptions + ); + }); + } +); diff --git a/src/JsHistogram.ts b/src/JsHistogram.ts index ab3148e..400a899 100644 --- a/src/JsHistogram.ts +++ b/src/JsHistogram.ts @@ -496,20 +496,7 @@ export abstract class JsHistogram implements Histogram { * value that all value entries in the histogram are either larger than or equivalent to. */ getValueAtPercentile(percentile: number) { - const requestedPercentile = min(percentile, 100); // Truncate down to 100% - - // round count up to nearest integer, to ensure that the largest value that the requested percentile - // of overall recorded values is actually included. However, this must be done with care: - // - // First, Compute fp value for count at the requested percentile. Note that fp result end up - // being 1 ulp larger than the correct integer count for this percentile: - const fpCountAtPercentile = (requestedPercentile / 100.0) * this.totalCount; - // Next, round up, but make sure to prevent <= 1 ulp inaccurancies in the above fp math from - // making us skip a count: - const countAtPercentile = max( - ceil(fpCountAtPercentile - ulp(fpCountAtPercentile)), // round up - 1 // Make sure we at least reach the first recorded entry - ); + const countAtPercentile = this.countAtPercentile(percentile); // Index 0 holds the zero values and is the only index below the one of // minNonZeroValue that may hold a count; nothing is recorded past the @@ -530,6 +517,71 @@ export abstract class JsHistogram implements Histogram { return 0; } + /** + * Get the values at several percentiles with a single scan of the counts. + * Each entry is what {@link getValueAtPercentile} returns for the same + * percentile; results are in the input order. The percentiles may be + * unsorted or repeated. + * + * @param percentiles The percentiles for which to return the associated values + * @return The values, one per requested percentile + */ + getValuesAtPercentiles(percentiles: number[]): number[] { + const results = new Array(percentiles.length).fill(0); + const thresholds = percentiles.map((p) => this.countAtPercentile(p)); + // Requested positions sorted by the count each one has to reach. NaN + // percentiles stay at 0, as getValueAtPercentile returns for them. + const order = thresholds + .map((_, position) => position) + .filter((position) => !Number.isNaN(thresholds[position])) + .sort((a, b) => thresholds[a] - thresholds[b]); + + const lastIndex = this.highestNonZeroCountsIndex(); + let next = 0; // First entry of `order` not yet resolved + let totalToCurrentIndex = 0; + for ( + let i = 0; + next < order.length && i <= lastIndex; + i = this.nextCountsIndexToScan(i) + ) { + totalToCurrentIndex += this.getCountAtIndex(i); + while ( + next < order.length && + totalToCurrentIndex >= thresholds[order[next]] + ) { + const position = order[next]; + const valueAtIndex = this.valueFromIndex(i); + results[position] = + percentiles[position] === 0.0 + ? this.lowestEquivalentValue(valueAtIndex) + : this.highestEquivalentValue(valueAtIndex); + next++; + } + } + return results; + } + + /** + * Number of recorded values a percentile must reach, rounded as + * getValueAtPercentile has always rounded it. + */ + private countAtPercentile(percentile: number): number { + const requestedPercentile = min(percentile, 100); // Truncate down to 100% + + // round count up to nearest integer, to ensure that the largest value that the requested percentile + // of overall recorded values is actually included. However, this must be done with care: + // + // First, Compute fp value for count at the requested percentile. Note that fp result end up + // being 1 ulp larger than the correct integer count for this percentile: + const fpCountAtPercentile = (requestedPercentile / 100.0) * this.totalCount; + // Next, round up, but make sure to prevent <= 1 ulp inaccurancies in the above fp math from + // making us skip a count: + return max( + ceil(fpCountAtPercentile - ulp(fpCountAtPercentile)), // round up + 1 // Make sure we at least reach the first recorded entry + ); + } + valueFromIndexes(bucketIndex: number, subBucketIndex: number) { return subBucketIndex * pow(2, bucketIndex + this.unitMagnitude); } diff --git a/src/wasm/index.ts b/src/wasm/index.ts index b32a01f..9f9568a 100644 --- a/src/wasm/index.ts +++ b/src/wasm/index.ts @@ -29,6 +29,7 @@ let wasm: any = undefined; // Cached at first decode call to avoid re-reading a getter on every array creation let cachedUint8ArrayId: number = 0; +let cachedFloat64ArrayId: number = 0; // Per-suffix function tables — built once per histogram type, shared by all instances. // Avoids the 25+ property lookups that would otherwise happen in every constructor. @@ -59,6 +60,7 @@ interface WasmFns { expectedInterval: number ) => void; getValueAtPercentile: (ptr: number, percentile: number) => number; + getValuesAtPercentiles: (ptr: number, percentiles: number) => number; outputPercentileDistribution: ( ptr: number, ticksPerHalfDistance: number, @@ -107,6 +109,7 @@ function buildWasmFns(s: string): WasmFns { recordValueWithCount: wasm[`recordValueWithCount${s}`], recordValueWithExpectedInterval: wasm[`recordValueWithExpectedInterval${s}`], getValueAtPercentile: wasm[`getValueAtPercentile${s}`], + getValuesAtPercentiles: wasm[`getValuesAtPercentiles${s}`], outputPercentileDistribution: wasm[`outputPercentileDistribution${s}`], encode: wasm[`encode${s}`], reset: wasm[`reset${s}`], @@ -214,6 +217,29 @@ function newUint8Array(data: Uint8Array): number { return viewPtr; } +/** + * Copies a JS number array into WASM memory as a Float64Array, the same way + * newUint8Array does. The returned view is pinned: the caller unpins it. + */ +function newFloat64Array(values: number[]): number { + if (!cachedFloat64ArrayId) { + cachedFloat64ArrayId = + typeof wasm.FLOAT64ARRAY_ID === "number" + ? wasm.FLOAT64ARRAY_ID + : (wasm.FLOAT64ARRAY_ID as any).value; + } + const byteLength = values.length * 8; + const bufPtr = wasm.__pin(wasm.__new(byteLength, 1)); + new Float64Array(wasm.memory.buffer, bufPtr, values.length).set(values); + const viewPtr = wasm.__pin(wasm.__new(12, cachedFloat64ArrayId)); + const U32 = new Uint32Array(wasm.memory.buffer); + U32[viewPtr >>> 2] = bufPtr; // buffer ref + U32[(viewPtr + 4) >>> 2] = bufPtr; // dataStart + U32[(viewPtr + 8) >>> 2] = byteLength; // byteLength + wasm.__unpin(bufPtr); + return viewPtr; +} + const defaultRequest: BuildRequest = { bitBucketSize: 32, autoResize: true, @@ -390,6 +416,18 @@ export class WasmHistogram implements Histogram { return this._fns.getValueAtPercentile(this._ptr, percentile); } + getValuesAtPercentiles(percentiles: number[]): number[] { + if (percentiles.length === 0) return []; + const inputPtr = newFloat64Array(percentiles); + const arrPtr: number = wasm.__pin( + this._fns.getValuesAtPercentiles(this._ptr, inputPtr) + ); + const result = Array.from(getFloat64Array(arrPtr)); + wasm.__unpin(arrPtr); + wasm.__unpin(inputPtr); + return result; + } + outputPercentileDistribution( percentileTicksPerHalfDistance = 5, outputValueUnitScalingRatio = 1, From a86b07568d22bde6c9a537a7fbf19a2cf8359d81 Mon Sep 17 00:00:00 2001 From: alexvictoor Date: Sun, 15 Nov 2026 08:57:36 +0100 Subject: [PATCH 2/5] fix: review follow-ups for getValuesAtPercentiles - Percentiles are clamped to [0, 100] in countAtPercentile on both sides, so negative and -Infinity percentiles give the lowest value in JS and WASM alike (JS used to return 0 because ulp(x <= 0) is NaN, and in the AS batch path a -Infinity entry produced a NaN threshold that blocked every later entry). - The AS getValueAtPercentile returns 0 for a NaN percentile, as the JS one does, instead of reporting the value at index 0. - The AS batch path allocates nothing per call: thresholds and the sorted positions live in module-level scratch state, the results overwrite the input array, and the positions are sorted with Array#sort rather than an insertion sort. - The wasm wrapper reuses a pinned scratch Float64Array instead of allocating an input array and a result array per call (the minimal runtime only collects on destroy), and throws on a destroyed histogram. - newUint8Array and the scratch array share newArrayBufferView; the 64-byte block sum and the percentile-to-value rule are shared between the single and batch methods. - Tests cover negative, infinite and NaN percentiles (also with a unit magnitude above 0) and the destroyed-histogram guard. Co-Authored-By: Claude Fable 5.1 --- assembly/Histogram.ts | 119 ++++++++++++++-------- src/Histogram.valuesAtPercentiles.spec.ts | 61 ++++++++++- src/JsHistogram.ts | 25 +++-- src/wasm/index.ts | 117 +++++++++++++-------- 4 files changed, 224 insertions(+), 98 deletions(-) diff --git a/assembly/Histogram.ts b/assembly/Histogram.ts index 6f4cee4..a59f4bb 100644 --- a/assembly/Histogram.ts +++ b/assembly/Histogram.ts @@ -65,6 +65,30 @@ function horizontalSum(v: v128): u64 { return i64x2.extract_lane(v, 0) + i64x2.extract_lane(v, 1); } +/** Sum of the 64 bytes of U-wide counts starting at p (may be unaligned). */ +// @ts-ignore: decorator +@inline +function sumBlock(p: usize): u64 { + let acc = widenSum(v128.load(p)); + acc = i64x2.add(acc, widenSum(v128.load(p, 16))); + acc = i64x2.add(acc, widenSum(v128.load(p, 32))); + acc = i64x2.add(acc, widenSum(v128.load(p, 48))); + return horizontalSum(acc); +} + +// Scratch state of getValuesAtPercentiles, kept across calls: the minimal +// runtime only reclaims memory on __collect, so per-call allocations would +// grow the heap of a long-lived module. +let percentileThresholds = new Float64Array(0); +const percentileOrder = new Array(0); + +/** Orders two positions of percentileOrder by their threshold. */ +function byThreshold(a: i32, b: i32): i32 { + const ta = unchecked(percentileThresholds[a]); + const tb = unchecked(percentileThresholds[b]); + return ta < tb ? -1 : ta > tb ? 1 : 0; +} + /** Lane-wise wrapping add of U-wide integers (same wrap semantics as the scalar `` cast). */ // @ts-ignore: decorator @inline @@ -661,7 +685,9 @@ export default class Histogram extends AbstractHistogramBase { * value that all value entries in the histogram are either larger than or equivalent to. */ getValueAtPercentile(percentile: f64): u64 { - const countAtPercentile = this.countAtPercentile(percentile); + const fpCountAtPercentile = this.countAtPercentile(percentile); + if (isNaN(fpCountAtPercentile)) return 0; // NaN percentile + const countAtPercentile = fpCountAtPercentile; // Index 0 holds the zero values and is the only index below the one of // minNonZeroValue that may hold a count; nothing is recorded past the @@ -679,12 +705,8 @@ export default class Histogram extends AbstractHistogramBase { const base = this.countsDataStart; const step = lanes() << 2; while (i + step <= end) { - const p = base + (i << alignof()); - let acc = widenSum(v128.load(p)); - acc = i64x2.add(acc, widenSum(v128.load(p, 16))); - acc = i64x2.add(acc, widenSum(v128.load(p, 32))); - acc = i64x2.add(acc, widenSum(v128.load(p, 48))); - const totalToBlockEnd = totalToCurrentIndex + horizontalSum(acc); + const totalToBlockEnd = + totalToCurrentIndex + sumBlock(base + (i << alignof())); if (totalToBlockEnd >= countAtPercentile) break; totalToCurrentIndex = totalToBlockEnd; i += step; @@ -704,6 +726,13 @@ export default class Histogram extends AbstractHistogramBase { } if (i >= end) return 0; } + return this.valueAtPercentileIndex(i, percentile); + } + + /** The value reported for a percentile whose count is reached at index i. */ + // @ts-ignore: decorator + @inline + private valueAtPercentileIndex(i: i32, percentile: f64): u64 { const valueAtIndex: u64 = this.valueFromIndex(i); return percentile === 0.0 ? this.lowestEquivalentValue(valueAtIndex) @@ -712,32 +741,34 @@ export default class Histogram extends AbstractHistogramBase { /** * Get the values at several percentiles with a single scan of the counts. - * Each entry is what getValueAtPercentile returns for the same percentile; - * results are in the input order. The percentiles may be unsorted or repeated. + * Each entry of `percentiles` is replaced by what getValueAtPercentile + * returns for it, so the results are in the input order; the array is + * returned. The percentiles may be unsorted or repeated. The caller keeps + * ownership of the array: nothing is allocated per call. */ getValuesAtPercentiles(percentiles: Float64Array): Float64Array { const count = percentiles.length; - const results = new Float64Array(count); - // Positions sorted by the count each one has to reach (`thresholds`). - // NaN percentiles are left out and stay at 0, as getValueAtPercentile. - const thresholds = new Float64Array(count); - const order = new Array(0); + if (percentileThresholds.length < count) { + percentileThresholds = new Float64Array(count); + } + const thresholds = percentileThresholds; + // Positions sorted by the count each one has to reach. A NaN threshold + // (NaN percentile) is left out and its entry becomes 0, as in + // getValueAtPercentile. + const order = percentileOrder; + order.length = 0; for (let position = 0; position < count; position++) { - const percentile = percentiles[position]; - if (isNaN(percentile)) continue; - const threshold = this.countAtPercentile(percentile); - thresholds[position] = threshold; - // Insertion sort: a summary asks for 8 percentiles, lists stay short. - let j = order.length; - order.push(position); - while (j > 0 && thresholds[order[j - 1]] > threshold) { - order[j] = order[j - 1]; - j--; + const threshold = this.countAtPercentile(unchecked(percentiles[position])); + if (isNaN(threshold)) { + unchecked((percentiles[position] = 0)); + continue; } - order[j] = position; + unchecked((thresholds[position] = threshold)); + order.push(position); } const valid = order.length; - if (valid == 0) return results; + if (valid == 0) return percentiles; + order.sort(byThreshold); const step = lanes() << 2; // indexes per 64-byte block const end = this.highestNonZeroCountsIndex() + 1; @@ -751,13 +782,10 @@ export default class Histogram extends AbstractHistogramBase { let chunkEnd: i32 = i + 1; if (isFlatStorage()) { if (i > 0 && i + step <= end) { - const p = this.countsDataStart + (i << alignof()); - let acc = widenSum(v128.load(p)); - acc = i64x2.add(acc, widenSum(v128.load(p, 16))); - acc = i64x2.add(acc, widenSum(v128.load(p, 32))); - acc = i64x2.add(acc, widenSum(v128.load(p, 48))); - const totalToBlockEnd = total + horizontalSum(acc); - if (totalToBlockEnd < thresholds[order[next]]) { + const totalToBlockEnd = + total + + sumBlock(this.countsDataStart + (i << alignof())); + if (totalToBlockEnd < unchecked(thresholds[unchecked(order[next])])) { total = totalToBlockEnd; i += step; continue; @@ -767,13 +795,14 @@ export default class Histogram extends AbstractHistogramBase { } for (; i < chunkEnd; i++) { total += this.getCountAtIndex(i); - while (next < valid && total >= thresholds[order[next]]) { - const position = order[next]; - const valueAtIndex: u64 = this.valueFromIndex(i); - results[position] = ( - percentiles[position] === 0.0 - ? this.lowestEquivalentValue(valueAtIndex) - : this.highestEquivalentValue(valueAtIndex) + while (next < valid && total >= unchecked(thresholds[unchecked(order[next])])) { + // Each position is resolved once, so its percentile is read before + // the result overwrites it. + const position = unchecked(order[next]); + unchecked( + (percentiles[position] = ( + this.valueAtPercentileIndex(i, unchecked(percentiles[position])) + )) ); next++; } @@ -781,7 +810,12 @@ export default class Histogram extends AbstractHistogramBase { } if (chunkEnd == 1) i = lowest; // index 0 is followed by the lowest non-zero index } - return results; + // Thresholds never reached (an empty histogram, or a count above the + // recorded total that cannot happen) leave their entry at 0. + for (; next < valid; next++) { + unchecked((percentiles[unchecked(order[next])] = 0)); + } + return percentiles; } /** @@ -789,7 +823,8 @@ export default class Histogram extends AbstractHistogramBase { * getValueAtPercentile has always rounded it. */ countAtPercentile(percentile: f64): f64 { - const requestedPercentile = min(percentile, 100); // Truncate down to 100% + // Clamp to [0, 100]; a NaN percentile stays NaN + const requestedPercentile = max(min(percentile, 100), 0); // round count up to nearest integer, to ensure that the largest value that the requested percentile // of overall recorded values is actually included. However, this must be done with care: diff --git a/src/Histogram.valuesAtPercentiles.spec.ts b/src/Histogram.valuesAtPercentiles.spec.ts index 8638a51..cb2b471 100644 --- a/src/Histogram.valuesAtPercentiles.spec.ts +++ b/src/Histogram.valuesAtPercentiles.spec.ts @@ -69,11 +69,26 @@ const recordsArb = fc.array( { maxLength: 300 } ); -// Unsorted, possibly repeated, including the edges (0, 100, above 100). +// Unsorted, possibly repeated, including the edges (0, 100, above 100, +// negative, infinite). const percentilesArb = fc.array( fc.oneof( - fc.constantFrom(0, 50, 75, 97.5, 99, 99.9, 99.99, 99.999, 100, 150), - fc.double({ min: 0, max: 100, noNaN: true }) + fc.constantFrom( + 0, + 50, + 75, + 97.5, + 99, + 99.9, + 99.99, + 99.999, + 100, + 150, + -1, + -Infinity, + Infinity + ), + fc.double({ min: -10, max: 110, noNaN: true }) ), { maxLength: 20 } ); @@ -89,9 +104,34 @@ const fill = (histogram: Histogram, records: Record[]) => { describe.each(implementations)( "getValuesAtPercentiles on $name", - ({ build }) => { + ({ build, name }) => { beforeAll(initWebAssembly); + it("returns 0 for NaN when the unit magnitude is not 0", () => { + const useWebAssembly = name.startsWith("WASM"); + const bitBucketSize = name.endsWith("packed") ? "packed" : 32; + const histogram = hdr.build({ + bitBucketSize, + useWebAssembly, + lowestDiscernibleValue: 1000, + highestTrackableValue: 1_000_000, + numberOfSignificantValueDigits, + }); + histogram.recordValue(5000); + expect(histogram.getValueAtPercentile(NaN)).toBe(0); + expect(histogram.getValuesAtPercentiles([NaN, 50])).toEqual([ + 0, + histogram.getValueAtPercentile(50), + ]); + histogram.destroy(); + }); + + it.runIf(name.startsWith("WASM"))("throws after destroy", () => { + const histogram = fill(build(), [{ value: 42, count: 3 }]); + histogram.destroy(); + expect(() => histogram.getValuesAtPercentiles([50])).toThrow(); + }); + it("matches getValueAtPercentile for each requested percentile", () => { fc.assert( fc.property(recordsArb, percentilesArb, (records, percentiles) => { @@ -156,6 +196,19 @@ describe.each(implementations)( histogram.destroy(); }); + it("treats negative and -Infinity percentiles as 0", () => { + const histogram = fill( + build(), + Array.from({ length: 100 }, (_, i) => ({ value: i + 1, count: 1 })) + ); + expect(histogram.getValueAtPercentile(-1)).toBe(1); + expect(histogram.getValueAtPercentile(-Infinity)).toBe(1); + expect( + histogram.getValuesAtPercentiles([-Infinity, 50, -1, Infinity]) + ).toEqual([1, 50, 1, 100]); + histogram.destroy(); + }); + it("summary values are the per-percentile values, rounded", () => { fc.assert( fc.property(recordsArb, (records) => { diff --git a/src/JsHistogram.ts b/src/JsHistogram.ts index 400a899..c2c6325 100644 --- a/src/JsHistogram.ts +++ b/src/JsHistogram.ts @@ -508,15 +508,20 @@ export abstract class JsHistogram implements Histogram { for (let i = 0; i <= lastIndex; i = i === 0 ? firstNonZeroIndex : i + 1) { totalToCurrentIndex += this.getCountAtIndex(i); if (totalToCurrentIndex >= countAtPercentile) { - const valueAtIndex = this.valueFromIndex(i); - return percentile === 0.0 - ? this.lowestEquivalentValue(valueAtIndex) - : this.highestEquivalentValue(valueAtIndex); + return this.valueAtPercentileIndex(i, percentile); } } return 0; } + /** The value reported for a percentile whose count is reached at index i. */ + private valueAtPercentileIndex(i: number, percentile: number): number { + const valueAtIndex = this.valueFromIndex(i); + return percentile === 0.0 + ? this.lowestEquivalentValue(valueAtIndex) + : this.highestEquivalentValue(valueAtIndex); + } + /** * Get the values at several percentiles with a single scan of the counts. * Each entry is what {@link getValueAtPercentile} returns for the same @@ -550,11 +555,10 @@ export abstract class JsHistogram implements Histogram { totalToCurrentIndex >= thresholds[order[next]] ) { const position = order[next]; - const valueAtIndex = this.valueFromIndex(i); - results[position] = - percentiles[position] === 0.0 - ? this.lowestEquivalentValue(valueAtIndex) - : this.highestEquivalentValue(valueAtIndex); + results[position] = this.valueAtPercentileIndex( + i, + percentiles[position] + ); next++; } } @@ -566,7 +570,8 @@ export abstract class JsHistogram implements Histogram { * getValueAtPercentile has always rounded it. */ private countAtPercentile(percentile: number): number { - const requestedPercentile = min(percentile, 100); // Truncate down to 100% + // Clamp to [0, 100]; a NaN percentile stays NaN + const requestedPercentile = max(min(percentile, 100), 0); // round count up to nearest integer, to ensure that the largest value that the requested percentile // of overall recorded values is actually included. However, this must be done with care: diff --git a/src/wasm/index.ts b/src/wasm/index.ts index 9f9568a..3000188 100644 --- a/src/wasm/index.ts +++ b/src/wasm/index.ts @@ -3,7 +3,7 @@ import Histogram, { NO_TAG, BitBucketSize, toSummary, - HistogramSummary + HistogramSummary, } from "../Histogram"; import * as base64 from "../base64"; import { inflate } from "../JsHistogram.encoding"; @@ -87,7 +87,8 @@ const COLLECT_INTERVAL = 1; function buildWasmFns(s: string): WasmFns { return { - getNumberOfSignificantValueDigits: wasm[`getNumberOfSignificantValueDigits${s}`], + getNumberOfSignificantValueDigits: + wasm[`getNumberOfSignificantValueDigits${s}`], getAutoResize: wasm[`getAutoResize${s}`], setAutoResize: wasm[`setAutoResize${s}`], getHighestTrackableValue: wasm[`getHighestTrackableValue${s}`], @@ -107,14 +108,17 @@ function buildWasmFns(s: string): WasmFns { getNonZeroCounts: wasm[`getNonZeroCounts${s}`], recordValue: wasm[`recordValue${s}`], recordValueWithCount: wasm[`recordValueWithCount${s}`], - recordValueWithExpectedInterval: wasm[`recordValueWithExpectedInterval${s}`], + recordValueWithExpectedInterval: + wasm[`recordValueWithExpectedInterval${s}`], getValueAtPercentile: wasm[`getValueAtPercentile${s}`], getValuesAtPercentiles: wasm[`getValuesAtPercentiles${s}`], outputPercentileDistribution: wasm[`outputPercentileDistribution${s}`], encode: wasm[`encode${s}`], reset: wasm[`reset${s}`], - addWhileCorrectingForCoordinatedOmission: wasm[`addWhileCorrectingForCoordinatedOmission${s}`], - copyCorrectedForCoordinatedOmission: wasm[`copyCorrectedForCoordinatedOmission${s}`], + addWhileCorrectingForCoordinatedOmission: + wasm[`addWhileCorrectingForCoordinatedOmission${s}`], + copyCorrectedForCoordinatedOmission: + wasm[`copyCorrectedForCoordinatedOmission${s}`], }; } @@ -135,11 +139,9 @@ const wasmImports = { lineNumber: number, columnNumber: number ) { - throw new Error( - `Abort in WebAssembly at ${lineNumber}:${columnNumber}` - ); - } - } + throw new Error(`Abort in WebAssembly at ${lineNumber}:${columnNumber}`); + }, + }, }; // @ts-ignore @@ -187,7 +189,11 @@ function getFloat64Array(ptr: number): Float64Array { const U32 = new Uint32Array(wasm.memory.buffer); const dataStart = U32[(ptr + 4) >>> 2]; const byteLength = U32[(ptr + 8) >>> 2]; - return new Float64Array(wasm.memory.buffer, dataStart, byteLength / 8).slice(); + return new Float64Array( + wasm.memory.buffer, + dataStart, + byteLength / 8 + ).slice(); } /** @@ -206,38 +212,67 @@ function newUint8Array(data: Uint8Array): number { // Allocate underlying ArrayBuffer (id=1) and pin it during construction const bufPtr = wasm.__pin(wasm.__new(length, 1)); new Uint8Array(wasm.memory.buffer).set(data, bufPtr); - // Allocate the Uint8Array view (12-byte ArrayBufferView struct) and pin it - // so it stays alive through the GC cycles triggered by the decode allocation storm. - const viewPtr = wasm.__pin(wasm.__new(12, cachedUint8ArrayId)); + return newArrayBufferView(cachedUint8ArrayId, bufPtr, length); +} + +/** + * Allocates a pinned 12-byte ArrayBufferView of class `id` over the buffer + * at bufPtr, and releases the construction pin of that buffer. The view + * stays alive through the GC cycles triggered by later allocations until + * the caller unpins it. + */ +function newArrayBufferView( + id: number, + bufPtr: number, + byteLength: number +): number { + const viewPtr = wasm.__pin(wasm.__new(12, id)); const U32 = new Uint32Array(wasm.memory.buffer); U32[viewPtr >>> 2] = bufPtr; // buffer ref U32[(viewPtr + 4) >>> 2] = bufPtr; // dataStart - U32[(viewPtr + 8) >>> 2] = length; // byteLength + U32[(viewPtr + 8) >>> 2] = byteLength; // byteLength wasm.__unpin(bufPtr); return viewPtr; } -/** - * Copies a JS number array into WASM memory as a Float64Array, the same way - * newUint8Array does. The returned view is pinned: the caller unpins it. - */ -function newFloat64Array(values: number[]): number { +function float64ArrayId(): number { if (!cachedFloat64ArrayId) { cachedFloat64ArrayId = typeof wasm.FLOAT64ARRAY_ID === "number" ? wasm.FLOAT64ARRAY_ID : (wasm.FLOAT64ARRAY_ID as any).value; } - const byteLength = values.length * 8; - const bufPtr = wasm.__pin(wasm.__new(byteLength, 1)); - new Float64Array(wasm.memory.buffer, bufPtr, values.length).set(values); - const viewPtr = wasm.__pin(wasm.__new(12, cachedFloat64ArrayId)); + return cachedFloat64ArrayId; +} + +// Scratch Float64Array shared by the calls that pass a batch of numbers to +// WASM. A fresh array per call would never be freed: the minimal (tcms) +// runtime only reclaims memory on __collect, so per-call allocations would +// grow the wasm heap of a long-lived module. The view is pinned once and +// grown only when a larger batch arrives; its byteLength is set on each call. +let scratchFloat64View = 0; +let scratchFloat64Capacity = 0; // in elements + +/** + * Copies `values` into the scratch Float64Array and returns its (pinned, + * reused) view pointer. Memory views are taken after any allocation, as the + * wasm memory may have grown. + */ +function fillScratchFloat64Array(values: ArrayLike): number { + const length = values.length; + if (!scratchFloat64View || length > scratchFloat64Capacity) { + const capacity = Math.max(length, scratchFloat64Capacity * 2, 256); + const bufPtr = wasm.__pin(wasm.__new(capacity * 8, 1)); + const viewPtr = newArrayBufferView(float64ArrayId(), bufPtr, capacity * 8); + if (scratchFloat64View) wasm.__unpin(scratchFloat64View); + scratchFloat64View = viewPtr; + scratchFloat64Capacity = capacity; + } const U32 = new Uint32Array(wasm.memory.buffer); - U32[viewPtr >>> 2] = bufPtr; // buffer ref - U32[(viewPtr + 4) >>> 2] = bufPtr; // dataStart - U32[(viewPtr + 8) >>> 2] = byteLength; // byteLength - wasm.__unpin(bufPtr); - return viewPtr; + const dataStart = U32[(scratchFloat64View + 4) >>> 2]; + new Float64Array(wasm.memory.buffer, dataStart, length).set(values); + U32[(scratchFloat64View + 8) >>> 2] = length * 8; // byteLength + return scratchFloat64View; } const defaultRequest: BuildRequest = { @@ -245,7 +280,7 @@ const defaultRequest: BuildRequest = { autoResize: true, lowestDiscernibleValue: 1, highestTrackableValue: 2, - numberOfSignificantValueDigits: 3 + numberOfSignificantValueDigits: 3, }; const remoteHistogramClassFor = (size?: BitBucketSize) => @@ -264,7 +299,10 @@ export class WasmHistogram implements Histogram { private _suffix: string; private _fns: WasmFns; - constructor(wasmPtr: number, private _remoteHistogramClass: string) { + constructor( + wasmPtr: number, + private _remoteHistogramClass: string + ) { this.tag = NO_TAG; this._suffix = suffixFor(_remoteHistogramClass); this._fns = getWasmFns(this._suffix); @@ -417,15 +455,12 @@ export class WasmHistogram implements Histogram { } getValuesAtPercentiles(percentiles: number[]): number[] { + if (this._ptr === 0) throw new Error("Cannot use a destroyed histogram"); if (percentiles.length === 0) return []; - const inputPtr = newFloat64Array(percentiles); - const arrPtr: number = wasm.__pin( - this._fns.getValuesAtPercentiles(this._ptr, inputPtr) - ); - const result = Array.from(getFloat64Array(arrPtr)); - wasm.__unpin(arrPtr); - wasm.__unpin(inputPtr); - return result; + // The WASM side overwrites the scratch array with the values, in place + const viewPtr = fillScratchFloat64Array(percentiles); + this._fns.getValuesAtPercentiles(this._ptr, viewPtr); + return Array.from(getFloat64Array(viewPtr)); } outputPercentileDistribution( @@ -498,9 +533,7 @@ export class WasmHistogram implements Histogram { add(otherHistogram: WasmHistogram): void { if (!(otherHistogram instanceof WasmHistogram)) { - throw new Error( - "Cannot add a regular JS histogram to a WASM histogram" - ); + throw new Error("Cannot add a regular JS histogram to a WASM histogram"); } wasm[`addHistogram${otherHistogram._suffix}to${this._suffix}`]( this._ptr, From cd83ac632792954b26ba85aac959bfee6294b602 Mon Sep 17 00:00:00 2001 From: alexvictoor Date: Sun, 15 Nov 2026 19:53:41 +0100 Subject: [PATCH 3/5] style: align getValuesAtPercentiles tests and ifs with the codebase conventions Co-Authored-By: Claude Fable 5.1 --- assembly/Histogram.ts | 12 +++- src/Histogram.valuesAtPercentiles.spec.ts | 85 +++++++++++++++-------- src/wasm/index.ts | 8 ++- 3 files changed, 70 insertions(+), 35 deletions(-) diff --git a/assembly/Histogram.ts b/assembly/Histogram.ts index a59f4bb..e96d3aa 100644 --- a/assembly/Histogram.ts +++ b/assembly/Histogram.ts @@ -686,7 +686,9 @@ export default class Histogram extends AbstractHistogramBase { */ getValueAtPercentile(percentile: f64): u64 { const fpCountAtPercentile = this.countAtPercentile(percentile); - if (isNaN(fpCountAtPercentile)) return 0; // NaN percentile + if (isNaN(fpCountAtPercentile)) { + return 0; // NaN percentile + } const countAtPercentile = fpCountAtPercentile; // Index 0 holds the zero values and is the only index below the one of @@ -767,7 +769,9 @@ export default class Histogram extends AbstractHistogramBase { order.push(position); } const valid = order.length; - if (valid == 0) return percentiles; + if (valid == 0) { + return percentiles; + } order.sort(byThreshold); const step = lanes() << 2; // indexes per 64-byte block @@ -806,7 +810,9 @@ export default class Histogram extends AbstractHistogramBase { ); next++; } - if (next == valid) break; + if (next == valid) { + break; + } } if (chunkEnd == 1) i = lowest; // index 0 is followed by the lowest non-zero index } diff --git a/src/Histogram.valuesAtPercentiles.spec.ts b/src/Histogram.valuesAtPercentiles.spec.ts index cb2b471..3911267 100644 --- a/src/Histogram.valuesAtPercentiles.spec.ts +++ b/src/Histogram.valuesAtPercentiles.spec.ts @@ -107,7 +107,8 @@ describe.each(implementations)( ({ build, name }) => { beforeAll(initWebAssembly); - it("returns 0 for NaN when the unit magnitude is not 0", () => { + it("should return 0 for NaN when the unit magnitude is not 0", () => { + // given const useWebAssembly = name.startsWith("WASM"); const bitBucketSize = name.endsWith("packed") ? "packed" : 32; const histogram = hdr.build({ @@ -118,21 +119,26 @@ describe.each(implementations)( numberOfSignificantValueDigits, }); histogram.recordValue(5000); - expect(histogram.getValueAtPercentile(NaN)).toBe(0); - expect(histogram.getValuesAtPercentiles([NaN, 50])).toEqual([ - 0, - histogram.getValueAtPercentile(50), - ]); + // when + const single = histogram.getValueAtPercentile(NaN); + const values = histogram.getValuesAtPercentiles([NaN, 50]); + // then + expect(single).toBe(0); + expect(values).toEqual([0, histogram.getValueAtPercentile(50)]); histogram.destroy(); }); - it.runIf(name.startsWith("WASM"))("throws after destroy", () => { + it.runIf(name.startsWith("WASM"))("should throw after destroy", () => { + // given const histogram = fill(build(), [{ value: 42, count: 3 }]); histogram.destroy(); - expect(() => histogram.getValuesAtPercentiles([50])).toThrow(); + // when + const call = () => histogram.getValuesAtPercentiles([50]); + // then + expect(call).toThrow(); }); - it("matches getValueAtPercentile for each requested percentile", () => { + it("should match getValueAtPercentile for each requested percentile", () => { fc.assert( fc.property(recordsArb, percentilesArb, (records, percentiles) => { const histogram = fill(build(), records); @@ -151,65 +157,84 @@ describe.each(implementations)( ); }); - it("returns an empty array for an empty list", () => { + it("should return an empty array for an empty list", () => { + // given const histogram = fill(build(), [{ value: 42, count: 3 }]); - expect(histogram.getValuesAtPercentiles([])).toEqual([]); + // when + const values = histogram.getValuesAtPercentiles([]); + // then + expect(values).toEqual([]); histogram.destroy(); }); - it("returns 0 for every percentile of an empty histogram", () => { + it("should return 0 for every percentile of an empty histogram", () => { + // given const histogram = build(); - expect(histogram.getValuesAtPercentiles([0, 50, 99.9, 100])).toEqual([ - 0, 0, 0, 0, - ]); + // when + const values = histogram.getValuesAtPercentiles([0, 50, 99.9, 100]); + // then + expect(values).toEqual([0, 0, 0, 0]); histogram.destroy(); }); - it("keeps the input order for unsorted and repeated percentiles", () => { + it("should keep the input order for unsorted and repeated percentiles", () => { + // given const histogram = fill( build(), Array.from({ length: 100 }, (_, i) => ({ value: i + 1, count: 1 })) ); - expect(histogram.getValuesAtPercentiles([99, 50, 99, 0, 100])).toEqual([ - 99, 50, 99, 1, 100, - ]); + // when + const values = histogram.getValuesAtPercentiles([99, 50, 99, 0, 100]); + // then + expect(values).toEqual([99, 50, 99, 1, 100]); histogram.destroy(); }); - it("truncates percentiles above 100 to 100", () => { + it("should truncate percentiles above 100 to 100", () => { + // given const histogram = fill(build(), [ { value: 10, count: 1 }, { value: 1000, count: 1 }, ]); + // when const [above, top] = histogram.getValuesAtPercentiles([150, 100]); + // then expect(above).toBe(top); expect(top).toBe(histogram.getValueAtPercentile(100)); histogram.destroy(); }); - it("returns 0 for a NaN percentile and still answers the others", () => { + it("should return 0 for a NaN percentile and still answer the others", () => { + // given const histogram = fill(build(), [{ value: 50, count: 10 }]); - expect(histogram.getValuesAtPercentiles([NaN, 50])).toEqual([ - 0, - histogram.getValueAtPercentile(50), - ]); + // when + const values = histogram.getValuesAtPercentiles([NaN, 50]); + // then + expect(values).toEqual([0, histogram.getValueAtPercentile(50)]); histogram.destroy(); }); - it("treats negative and -Infinity percentiles as 0", () => { + it("should treat negative and -Infinity percentiles as 0", () => { + // given const histogram = fill( build(), Array.from({ length: 100 }, (_, i) => ({ value: i + 1, count: 1 })) ); + // when + const values = histogram.getValuesAtPercentiles([ + -Infinity, + 50, + -1, + Infinity, + ]); + // then expect(histogram.getValueAtPercentile(-1)).toBe(1); expect(histogram.getValueAtPercentile(-Infinity)).toBe(1); - expect( - histogram.getValuesAtPercentiles([-Infinity, 50, -1, Infinity]) - ).toEqual([1, 50, 1, 100]); + expect(values).toEqual([1, 50, 1, 100]); histogram.destroy(); }); - it("summary values are the per-percentile values, rounded", () => { + it("should compute summary values equal to the per-percentile values, rounded", () => { fc.assert( fc.property(recordsArb, (records) => { const histogram = fill(build(), records); diff --git a/src/wasm/index.ts b/src/wasm/index.ts index 3000188..e5ce8de 100644 --- a/src/wasm/index.ts +++ b/src/wasm/index.ts @@ -455,8 +455,12 @@ export class WasmHistogram implements Histogram { } getValuesAtPercentiles(percentiles: number[]): number[] { - if (this._ptr === 0) throw new Error("Cannot use a destroyed histogram"); - if (percentiles.length === 0) return []; + if (this._ptr === 0) { + throw new Error("Cannot use a destroyed histogram"); + } + if (percentiles.length === 0) { + return []; + } // The WASM side overwrites the scratch array with the values, in place const viewPtr = fillScratchFloat64Array(percentiles); this._fns.getValuesAtPercentiles(this._ptr, viewPtr); From 21d935e0d6b483a5cff61803a83017dbd58a34b6 Mon Sep 17 00:00:00 2001 From: alexvictoor Date: Sun, 15 Nov 2026 20:15:50 +0100 Subject: [PATCH 4/5] refactor: getValuesAtPercentiles takes the percentiles as varargs `histogram.getValuesAtPercentiles(50, 99, 99.9)` reads like the single percentile call; a list is passed with the spread operator. The wasm boundary still receives one Float64Array, so the AS side is unchanged. Co-Authored-By: Claude Fable 5.1 --- src/Histogram.ts | 8 +++---- src/Histogram.valuesAtPercentiles.spec.ts | 26 +++++++++++------------ src/JsHistogram.ts | 4 ++-- src/wasm/index.ts | 2 +- 4 files changed, 20 insertions(+), 20 deletions(-) diff --git a/src/Histogram.ts b/src/Histogram.ts index 7d4b9d9..f8c4a3c 100644 --- a/src/Histogram.ts +++ b/src/Histogram.ts @@ -100,13 +100,13 @@ export default interface Histogram { /** * Get the values at several percentiles with a single scan of the counts. * Each entry is what {@link getValueAtPercentile} returns for the same - * percentile. Results are in the input order; the percentiles may be - * unsorted or repeated, and an empty list returns an empty array. + * percentile. Results are in the argument order; the percentiles may be + * unsorted or repeated, and no argument returns an empty array. * * @param percentiles The percentiles for which to return the associated values * @return The values, one per requested percentile */ - getValuesAtPercentiles(percentiles: number[]): number[]; + getValuesAtPercentiles(...percentiles: number[]): number[]; /** * Produce textual representation of the value distribution of histogram data by percentile. The distribution is @@ -252,7 +252,7 @@ export const toSummary = (histogram: Histogram): HistogramSummary => { const { totalCount, maxValue, numberOfSignificantValueDigits } = histogram; const round = keepSignificantDigits(numberOfSignificantValueDigits); const [p50, p75, p90, p97_5, p99, p99_9, p99_99, p99_999] = histogram - .getValuesAtPercentiles([50, 75, 90, 97.5, 99, 99.9, 99.99, 99.999]) + .getValuesAtPercentiles(50, 75, 90, 97.5, 99, 99.9, 99.99, 99.999) .map((value) => round(value)); return { p50, diff --git a/src/Histogram.valuesAtPercentiles.spec.ts b/src/Histogram.valuesAtPercentiles.spec.ts index 3911267..673e229 100644 --- a/src/Histogram.valuesAtPercentiles.spec.ts +++ b/src/Histogram.valuesAtPercentiles.spec.ts @@ -121,7 +121,7 @@ describe.each(implementations)( histogram.recordValue(5000); // when const single = histogram.getValueAtPercentile(NaN); - const values = histogram.getValuesAtPercentiles([NaN, 50]); + const values = histogram.getValuesAtPercentiles(NaN, 50); // then expect(single).toBe(0); expect(values).toEqual([0, histogram.getValueAtPercentile(50)]); @@ -133,7 +133,7 @@ describe.each(implementations)( const histogram = fill(build(), [{ value: 42, count: 3 }]); histogram.destroy(); // when - const call = () => histogram.getValuesAtPercentiles([50]); + const call = () => histogram.getValuesAtPercentiles(50); // then expect(call).toThrow(); }); @@ -146,7 +146,7 @@ describe.each(implementations)( const expected = percentiles.map((p) => histogram.getValueAtPercentile(p) ); - expect(histogram.getValuesAtPercentiles(percentiles)).toEqual( + expect(histogram.getValuesAtPercentiles(...percentiles)).toEqual( expected ); } finally { @@ -157,11 +157,11 @@ describe.each(implementations)( ); }); - it("should return an empty array for an empty list", () => { + it("should return an empty array when called without percentiles", () => { // given const histogram = fill(build(), [{ value: 42, count: 3 }]); // when - const values = histogram.getValuesAtPercentiles([]); + const values = histogram.getValuesAtPercentiles(); // then expect(values).toEqual([]); histogram.destroy(); @@ -171,20 +171,20 @@ describe.each(implementations)( // given const histogram = build(); // when - const values = histogram.getValuesAtPercentiles([0, 50, 99.9, 100]); + const values = histogram.getValuesAtPercentiles(0, 50, 99.9, 100); // then expect(values).toEqual([0, 0, 0, 0]); histogram.destroy(); }); - it("should keep the input order for unsorted and repeated percentiles", () => { + it("should keep the argument order for unsorted and repeated percentiles", () => { // given const histogram = fill( build(), Array.from({ length: 100 }, (_, i) => ({ value: i + 1, count: 1 })) ); // when - const values = histogram.getValuesAtPercentiles([99, 50, 99, 0, 100]); + const values = histogram.getValuesAtPercentiles(99, 50, 99, 0, 100); // then expect(values).toEqual([99, 50, 99, 1, 100]); histogram.destroy(); @@ -197,7 +197,7 @@ describe.each(implementations)( { value: 1000, count: 1 }, ]); // when - const [above, top] = histogram.getValuesAtPercentiles([150, 100]); + const [above, top] = histogram.getValuesAtPercentiles(150, 100); // then expect(above).toBe(top); expect(top).toBe(histogram.getValueAtPercentile(100)); @@ -208,7 +208,7 @@ describe.each(implementations)( // given const histogram = fill(build(), [{ value: 50, count: 10 }]); // when - const values = histogram.getValuesAtPercentiles([NaN, 50]); + const values = histogram.getValuesAtPercentiles(NaN, 50); // then expect(values).toEqual([0, histogram.getValueAtPercentile(50)]); histogram.destroy(); @@ -221,12 +221,12 @@ describe.each(implementations)( Array.from({ length: 100 }, (_, i) => ({ value: i + 1, count: 1 })) ); // when - const values = histogram.getValuesAtPercentiles([ + const values = histogram.getValuesAtPercentiles( -Infinity, 50, -1, - Infinity, - ]); + Infinity + ); // then expect(histogram.getValueAtPercentile(-1)).toBe(1); expect(histogram.getValueAtPercentile(-Infinity)).toBe(1); diff --git a/src/JsHistogram.ts b/src/JsHistogram.ts index c2c6325..f569a3d 100644 --- a/src/JsHistogram.ts +++ b/src/JsHistogram.ts @@ -525,13 +525,13 @@ export abstract class JsHistogram implements Histogram { /** * Get the values at several percentiles with a single scan of the counts. * Each entry is what {@link getValueAtPercentile} returns for the same - * percentile; results are in the input order. The percentiles may be + * percentile; results are in the argument order. The percentiles may be * unsorted or repeated. * * @param percentiles The percentiles for which to return the associated values * @return The values, one per requested percentile */ - getValuesAtPercentiles(percentiles: number[]): number[] { + getValuesAtPercentiles(...percentiles: number[]): number[] { const results = new Array(percentiles.length).fill(0); const thresholds = percentiles.map((p) => this.countAtPercentile(p)); // Requested positions sorted by the count each one has to reach. NaN diff --git a/src/wasm/index.ts b/src/wasm/index.ts index e5ce8de..08d6bba 100644 --- a/src/wasm/index.ts +++ b/src/wasm/index.ts @@ -454,7 +454,7 @@ export class WasmHistogram implements Histogram { return this._fns.getValueAtPercentile(this._ptr, percentile); } - getValuesAtPercentiles(percentiles: number[]): number[] { + getValuesAtPercentiles(...percentiles: number[]): number[] { if (this._ptr === 0) { throw new Error("Cannot use a destroyed histogram"); } From 8e139f39280bcb7d3f5c8ee0176254564a9a84c2 Mon Sep 17 00:00:00 2001 From: alexvictoor Date: Sun, 15 Nov 2026 22:09:28 +0100 Subject: [PATCH 5/5] fix: packed getValueAtPercentile shares the clamped percentile threshold Master now overrides getValueAtPercentile in PackedHistogram to walk only the populated indexes. That override computed its own threshold without clamping negative percentiles to 0, and ulp() of a negative number is NaN, so a negative percentile returned 0 on a packed histogram while getValuesAtPercentiles returned the lowest recorded value. Both now share countAtPercentile and valueAtPercentileIndex, and getValuesAtPercentiles walks the counts through nextNonZeroIndexInRange so packed histograms skip their empty subtrees there too. Co-Authored-By: Claude Fable 5.1 --- src/JsHistogram.ts | 10 +++++----- src/PackedHistogram.ts | 23 ++--------------------- 2 files changed, 7 insertions(+), 26 deletions(-) diff --git a/src/JsHistogram.ts b/src/JsHistogram.ts index f569a3d..f6c55a3 100644 --- a/src/JsHistogram.ts +++ b/src/JsHistogram.ts @@ -515,7 +515,7 @@ export abstract class JsHistogram implements Histogram { } /** The value reported for a percentile whose count is reached at index i. */ - private valueAtPercentileIndex(i: number, percentile: number): number { + protected valueAtPercentileIndex(i: number, percentile: number): number { const valueAtIndex = this.valueFromIndex(i); return percentile === 0.0 ? this.lowestEquivalentValue(valueAtIndex) @@ -545,9 +545,9 @@ export abstract class JsHistogram implements Histogram { let next = 0; // First entry of `order` not yet resolved let totalToCurrentIndex = 0; for ( - let i = 0; - next < order.length && i <= lastIndex; - i = this.nextCountsIndexToScan(i) + let i = this.nextNonZeroIndexInRange(0, lastIndex); + next < order.length && i >= 0; + i = this.nextNonZeroIndexInRange(i + 1, lastIndex) ) { totalToCurrentIndex += this.getCountAtIndex(i); while ( @@ -569,7 +569,7 @@ export abstract class JsHistogram implements Histogram { * Number of recorded values a percentile must reach, rounded as * getValueAtPercentile has always rounded it. */ - private countAtPercentile(percentile: number): number { + protected countAtPercentile(percentile: number): number { // Clamp to [0, 100]; a NaN percentile stays NaN const requestedPercentile = max(min(percentile, 100), 0); diff --git a/src/PackedHistogram.ts b/src/PackedHistogram.ts index 6dea40a..c19ecff 100644 --- a/src/PackedHistogram.ts +++ b/src/PackedHistogram.ts @@ -7,9 +7,6 @@ */ import JsHistogram from "./JsHistogram"; import { PackedArray } from "./packedarray/PackedArray"; -import ulp from "./ulp"; - -const { ceil, max, min } = Math; /** *

A High Dynamic Range (HDR) Histogram that uses a packed internal representation

*

@@ -91,20 +88,7 @@ class PackedHistogram extends JsHistogram { * whole counts array. */ getValueAtPercentile(percentile: number) { - const requestedPercentile = min(percentile, 100); // Truncate down to 100% - - // round count up to nearest integer, to ensure that the largest value that the requested percentile - // of overall recorded values is actually included. However, this must be done with care: - // - // First, Compute fp value for count at the requested percentile. Note that fp result end up - // being 1 ulp larger than the correct integer count for this percentile: - const fpCountAtPercentile = (requestedPercentile / 100.0) * this.totalCount; - // Next, round up, but make sure to prevent <= 1 ulp inaccurancies in the above fp math from - // making us skip a count: - const countAtPercentile = max( - ceil(fpCountAtPercentile - ulp(fpCountAtPercentile)), // round up - 1 // Make sure we at least reach the first recorded entry - ); + const countAtPercentile = this.countAtPercentile(percentile); let totalToCurrentIndex = 0; for ( @@ -114,10 +98,7 @@ class PackedHistogram extends JsHistogram { ) { totalToCurrentIndex += this.getCountAtIndex(i); if (totalToCurrentIndex >= countAtPercentile) { - const valueAtIndex = this.valueFromIndex(i); - return percentile === 0.0 - ? this.lowestEquivalentValue(valueAtIndex) - : this.highestEquivalentValue(valueAtIndex); + return this.valueAtPercentileIndex(i, percentile); } } return 0;