From c7897989d31f197ffe54cbd67bb7d5c7dda31769 Mon Sep 17 00:00:00 2001 From: alexvictoor Date: Sun, 15 Nov 2026 09:23:42 +0100 Subject: [PATCH 1/3] fix: throw on count overflow and underflow in fixed-width histograms 8/16/32-bit count storage is unsigned, so a count past the cell width wrapped silently (255 + 1 -> 0 in an 8-bit JS array, 2^32 -> 0 in the 32-bit WASM build), and a negative count was stored as a huge value or dropped. The JS `newCount < 0` check could never fire for unsigned arrays. Writes now range-check against the cell width, as Java's ShortCountsHistogram and IntCountsHistogram do, and throw " would overflow -bit integer count" or " would underflow -bit integer count". The check runs before the write, so the offending cell is never modified. 64-bit, Float64 and packed storage keep their previous behaviour. WASM aborts now carry the AssemblyScript message instead of only the source location, which optimized builds do not have. Known limitation: add/subtract of same-shaped histograms are not atomic. An overflow part-way through leaves the cells before the failing one applied and totalCount unchanged, as Java's add does. Pre-validating the whole range was measured at 5-7x slower on add and was not kept. Co-Authored-By: Claude Fable 5.1 --- assembly/Histogram.ts | 110 ++++++++++++++--- assembly/__tests__/Histogram.test.ts | 25 ++++ assembly/index.ts | 2 +- src/Histogram.spec.ts | 172 +++++++++++++++++++++++++++ src/TypedArrayHistogram.spec.ts | 110 +++++++++++++++++ src/TypedArrayHistogram.ts | 53 +++++++-- src/wasm/index.ts | 8 ++ 7 files changed, 451 insertions(+), 29 deletions(-) diff --git a/assembly/Histogram.ts b/assembly/Histogram.ts index e96d3aa..e9d3880 100644 --- a/assembly/Histogram.ts +++ b/assembly/Histogram.ts @@ -119,6 +119,42 @@ function laneSub(a: v128, b: v128): v128 { } } +/** + * Largest count a U-wide cell can hold. u64 cells never overflow in practice, so + * their checks are compiled out (guarded by sizeof() < 8 at each call site). + */ +// @ts-ignore: decorator +@inline +function countMax(): u64 { + return (1 << (sizeof() << 3)) - 1; +} + +// Aborts with the message (AssemblyScript's throw of an Error carries no message in the +// minimal runtime, so the JS wrapper would only see the location). + +/** Aborts for a count that would overflow a narrow U cell, naming the width. */ +function overflowAbort(count: u64): void { + abort(count.toString() + " would overflow " + (sizeof() << 3).toString() + "-bit integer count"); +} + +/** Aborts for a count that would underflow a narrow U cell, naming the width. */ +function underflowAbort(count: i64): void { + abort(count.toString() + " would underflow " + (sizeof() << 3).toString() + "-bit integer count"); +} + +/** Lane-wise unsigned a < b for narrow U (u64 lanes are never compared this way). */ +// @ts-ignore: decorator +@inline +function laneLtU(a: v128, b: v128): v128 { + if (sizeof() == 1) { + return i8x16.lt_u(a, b); + } else if (sizeof() == 2) { + return i16x8.lt_u(a, b); + } else { + return i32x4.lt_u(a, b); + } +} + export default class Histogram extends AbstractHistogramBase { // "Hot" accessed fields (used in the the value recording code path) are bunched here, such // that they will have a good chance of ending up in the same cache line as the totalCounts and @@ -583,6 +619,17 @@ export default class Histogram extends AbstractHistogramBase { } @inline + /** + * Entry point for count arguments that arrive as f64 (the JS boundary). A negative + * count would otherwise saturate to 0 in the u64 cast and be dropped silently. + */ + recordCountAtValueFromF64(count: f64, value: f64): void { + if (sizeof() < 8 && count < 0) { + underflowAbort(count); + } + this.recordCountAtValue(count, value); + } + recordCountAtValue(count: u64, value: u64): void { const countsIndex = this.countsArrayIndex(value); if (countsIndex >= this.countsArrayLength) { @@ -870,18 +917,24 @@ export default class Histogram extends AbstractHistogramBase { return; } // @ts-ignore - const currentCount = unchecked(this.counts[index]); - const newCount = currentCount + 1; - if (newCount < 0) { - throw new Error( - newCount.toString() + " would overflow short integer count" - ); + // @ts-ignore + const newCount = unchecked(this.counts[index]) + 1; + if (sizeof() < 8 && newCount > countMax()) { + overflowAbort(newCount); } // @ts-ignore - unchecked((this.counts[index] = newCount)); + unchecked((this.counts[index] = newCount)); } setCountAtIndex(index: i32, value: u64): void { + if (sizeof() < 8) { + if (value < 0) { + underflowAbort(value); + } + if (value > countMax()) { + overflowAbort(value); + } + } // @ts-ignore unchecked((this.counts[index] = value)); } @@ -895,13 +948,28 @@ export default class Histogram extends AbstractHistogramBase { return; } // @ts-ignore - const currentCount = unchecked(this.counts[index]); - const newCount = currentCount + value; - if (newCount < 0) { - throw newCount + " would overflow short integer count"; + const currentCount = unchecked(this.counts[index]); + if (sizeof() == 8) { + // @ts-ignore + unchecked((this.counts[index] = (currentCount + value))); + return; + } + if (value >= 0) { + const newCount = currentCount + value; + if (newCount > countMax()) { + overflowAbort(newCount); + } + // @ts-ignore + unchecked((this.counts[index] = newCount)); + } else { + // Negative values arrive as two's complement (subtract); the magnitude is their negation. + const decrement = (0) - value; + if (decrement > currentCount) { + underflowAbort(currentCount - decrement); + } + // @ts-ignore + unchecked((this.counts[index] = (currentCount - decrement))); } - // @ts-ignore - unchecked((this.counts[index] = newCount)); } incrementTotalCount(): void { @@ -988,8 +1056,15 @@ export default class Histogram extends AbstractHistogramBase { for (; i + step <= end; i += step) { const offset = i << alignof(); const other = v128.load(src + offset); + const current = v128.load(dst + offset); + const sum = laneAdd(current, other); + if (sizeof() < 8 && v128.any_true(laneLtU(sum, current))) { + // A lane would wrap: leave this block to the checked scalar loop below, + // which reports the exact cell and width. + break; + } acc = i64x2.add(acc, widenSum(other)); - v128.store(dst + offset, laneAdd(v128.load(dst + offset), other)); + v128.store(dst + offset, sum); } observedOtherTotalCount += horizontalSum(acc); } @@ -1176,8 +1251,13 @@ export default class Histogram extends AbstractHistogramBase { for (; i + step <= end; i += step) { const offset = i << alignof(); const other = v128.load(src + offset); + const current = v128.load(dst + offset); + if (sizeof() < 8 && v128.any_true(laneLtU(current, other))) { + // A lane would go negative: leave this block to the checked scalar loop below. + break; + } acc = i64x2.add(acc, widenSum(other)); - v128.store(dst + offset, laneSub(v128.load(dst + offset), other)); + v128.store(dst + offset, laneSub(current, other)); } observedOtherTotalCount += horizontalSum(acc); } diff --git a/assembly/__tests__/Histogram.test.ts b/assembly/__tests__/Histogram.test.ts index 0fa5d0d..328fb5a 100644 --- a/assembly/__tests__/Histogram.test.ts +++ b/assembly/__tests__/Histogram.test.ts @@ -526,3 +526,28 @@ describe("Histogram scans bounded by recorded min and max", () => { ); }); }); + +describe("Histogram count range", () => { + // Overflow and underflow abort the module (AssemblyScript has no throw assertion here), + // so these cover the in-range boundaries; the throwing paths are covered by the + // WASM tests in src/Histogram.spec.ts. + test("should accept a count equal to the 8-bit maximum", () => { + const histogram = new Histogram8(1, 9007199254740991, 3); + histogram.setCountAtIndex(5, 255); + expect(histogram.getCountAtIndex(5)).equal(255); + }); + + test("should add up to exactly the 16-bit maximum", () => { + const histogram = new Histogram16(1, 1000000, 3); + histogram.setCountAtIndex(7, 65000); + histogram.addToCountAtIndex(7, 535); + expect(histogram.getCountAtIndex(7)).equal(65535); + }); + + test("should subtract down to exactly zero without wrapping", () => { + const histogram = new Histogram32(1, 1000000, 3); + histogram.setCountAtIndex(9, 4294967295); + histogram.addToCountAtIndex(9, 0 - 4294967295); + expect(histogram.getCountAtIndex(9)).equal(0); + }); +}); diff --git a/assembly/index.ts b/assembly/index.ts index 7fa7047..2a58d00 100644 --- a/assembly/index.ts +++ b/assembly/index.ts @@ -140,7 +140,7 @@ class HistogramAdapter { } recordValueWithCount(value: f64, count: f64): void { - this._histogram.recordCountAtValue(count, value); + this._histogram.recordCountAtValueFromF64(count, value); } recordValueWithExpectedInterval( diff --git a/src/Histogram.spec.ts b/src/Histogram.spec.ts index 951f3a0..97483c0 100644 --- a/src/Histogram.spec.ts +++ b/src/Histogram.spec.ts @@ -835,3 +835,175 @@ describe("Histogram bucket boundaries near 2^53", () => { histogram.destroy(); }); }); + +describe("WASM histogram count range", () => { + beforeAll(initWebAssembly); + + [8, 16, 32].forEach((bits) => { + const max = Math.pow(2, bits) - 1; + const label = `${bits}-bit`; + + it(`should throw on recordValueWithCount past the ${label} maximum, leaving the histogram unchanged (WASM)`, () => { + const histogram = build({ + bitBucketSize: bits, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + histogram.recordValueWithCount(42, max); + const before = histogram.summary; + expect(() => histogram.recordValueWithCount(42, 1)).toThrow( + `would overflow ${bits}-bit integer count` + ); + expect(histogram.summary).toEqual(before); + expect(histogram.totalCount).toBe(max); + histogram.destroy(); + }); + + it(`should throw on add when the summed ${label} count would overflow, leaving the histogram unchanged (WASM)`, () => { + const histogram = build({ + bitBucketSize: bits, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + const other = build({ + bitBucketSize: bits, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + histogram.recordValueWithCount(42, max - 10); + other.recordValueWithCount(42, 11); + const before = histogram.summary; + expect(() => histogram.add(other)).toThrow( + `would overflow ${bits}-bit integer count` + ); + expect(histogram.summary).toEqual(before); + histogram.destroy(); + other.destroy(); + }); + + it(`should add up to exactly the ${label} maximum (WASM)`, () => { + const histogram = build({ + bitBucketSize: bits, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + const other = build({ + bitBucketSize: bits, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + histogram.recordValueWithCount(42, max - 10); + other.recordValueWithCount(42, 10); + histogram.add(other); + expect(histogram.totalCount).toBe(max); + histogram.destroy(); + other.destroy(); + }); + + it(`should throw on subtract when the ${label} result would underflow, leaving the histogram unchanged (WASM)`, () => { + const histogram = build({ + bitBucketSize: bits, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + const other = build({ + bitBucketSize: bits, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + histogram.recordValueWithCount(42, 5); + other.recordValueWithCount(42, 6); + const before = histogram.summary; + expect(() => histogram.subtract(other)).toThrow( + `would underflow ${bits}-bit integer count` + ); + expect(histogram.summary).toEqual(before); + histogram.destroy(); + other.destroy(); + }); + }); + + [8, 16, 32].forEach((bits) => { + it(`should throw on a negative recordValueWithCount on a ${bits}-bit WASM histogram instead of dropping it`, () => { + const histogram = build({ + bitBucketSize: bits, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + expect(() => histogram.recordValueWithCount(42, -1)).toThrow( + `would underflow ${bits}-bit integer count` + ); + expect(histogram.totalCount).toBe(0); + histogram.destroy(); + }); + }); + + it("should keep 64-bit WASM histograms unbounded by the 32-bit maximum", () => { + const histogram = build({ + bitBucketSize: 64, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + histogram.recordValueWithCount(42, 4294967295); + histogram.recordValueWithCount(42, 4294967295); + expect(histogram.totalCount).toBe(8589934590); + histogram.destroy(); + }); +}); + +describe("WASM histogram add across a wide counts range", () => { + beforeAll(initWebAssembly); + + [8, 16, 32].forEach((bits) => { + const max = Math.pow(2, bits) - 1; + + it(`should throw on add when a cell in the middle of a vectorised block range would overflow ${bits}-bit (WASM)`, () => { + const histogram = build({ + bitBucketSize: bits, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + const other = build({ + bitBucketSize: bits, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + for (let v = 1000; v < 200000; v += 997) { + other.recordValueWithCount(v, 1); + } + other.recordValueWithCount(100000, 1); + histogram.recordValueWithCount(100000, max); + expect(() => histogram.add(other)).toThrow( + `would overflow ${bits}-bit integer count` + ); + expect(histogram.totalCount).toBe(max); + histogram.destroy(); + other.destroy(); + }); + + it(`should add a wide range without overflow up to the ${bits}-bit maximum (WASM)`, () => { + const histogram = build({ + bitBucketSize: bits, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + const other = build({ + bitBucketSize: bits, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + let expected = 0; + for (let v = 1000; v < 200000; v += 997) { + other.recordValueWithCount(v, 1); + expected++; + } + other.recordValueWithCount(100000, 1); + expected++; + histogram.recordValueWithCount(100000, max - 1); + histogram.add(other); + expect(histogram.totalCount).toBe(expected + max - 1); + histogram.destroy(); + other.destroy(); + }); + }); +}); diff --git a/src/TypedArrayHistogram.spec.ts b/src/TypedArrayHistogram.spec.ts index 99493df..4139852 100644 --- a/src/TypedArrayHistogram.spec.ts +++ b/src/TypedArrayHistogram.spec.ts @@ -67,3 +67,113 @@ import Float64Histogram from "./Float64Histogram"; }); } ); + +describe("Typed array histogram count range", () => { + const cases = [ + { name: "8-bit", Histogram: Int8Histogram, max: 255, bits: 8 }, + { name: "16-bit", Histogram: Int16Histogram, max: 65535, bits: 16 }, + { name: "32-bit", Histogram: Int32Histogram, max: 4294967295, bits: 32 }, + ]; + + cases.forEach(({ name, Histogram, max, bits }) => { + describe(`${name} histogram`, () => { + it("should accept a count up to the storage maximum", () => { + const histogram = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); + histogram.recordValueWithCount(42, max); + expect(histogram.getCountAtIndex(histogram.countsArrayIndex(42))).toBe( + max + ); + expect(histogram.totalCount).toBe(max); + }); + + it("should throw on recordValueWithCount past the storage maximum, leaving the histogram unchanged", () => { + const histogram = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); + histogram.recordValueWithCount(42, max); + expect(() => histogram.recordValueWithCount(42, 1)).toThrow( + `would overflow ${bits}-bit integer count` + ); + expect(histogram.getCountAtIndex(histogram.countsArrayIndex(42))).toBe( + max + ); + expect(histogram.totalCount).toBe(max); + }); + + it("should throw on recordValue when the counter is already at the maximum", () => { + const histogram = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); + histogram.setCountAtIndex(histogram.countsArrayIndex(42), max); + expect(() => histogram.recordValue(42)).toThrow( + `would overflow ${bits}-bit integer count` + ); + expect(histogram.totalCount).toBe(0); + }); + + it("should throw on addToCountAtIndex and setCountAtIndex past the maximum", () => { + const histogram = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); + expect(() => histogram.setCountAtIndex(5, max + 1)).toThrow( + "would overflow" + ); + histogram.setCountAtIndex(5, max - 1); + expect(() => histogram.addToCountAtIndex(5, 2)).toThrow( + `would overflow ${bits}-bit integer count` + ); + expect(histogram.getCountAtIndex(5)).toBe(max - 1); + }); + + it("should throw on a negative count instead of wrapping", () => { + const histogram = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); + histogram.recordValueWithCount(42, 3); + expect(() => histogram.recordValueWithCount(42, -4)).toThrow( + `would underflow ${bits}-bit integer count` + ); + expect(histogram.getCountAtIndex(histogram.countsArrayIndex(42))).toBe( + 3 + ); + expect(histogram.totalCount).toBe(3); + }); + + it("should throw on add when the summed count would overflow, leaving the histogram unchanged", () => { + const histogram = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); + const other = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); + histogram.recordValueWithCount(42, max - 10); + other.recordValueWithCount(42, 11); + const before = histogram.summary; + expect(() => histogram.add(other)).toThrow( + `would overflow ${bits}-bit integer count` + ); + expect(histogram.summary).toEqual(before); + expect(other.totalCount).toBe(11); + }); + + it("should add up to exactly the storage maximum", () => { + const histogram = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); + const other = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); + histogram.recordValueWithCount(42, max - 10); + other.recordValueWithCount(42, 10); + histogram.add(other); + expect(histogram.getCountAtIndex(histogram.countsArrayIndex(42))).toBe( + max + ); + expect(histogram.totalCount).toBe(max); + }); + + it("should throw on subtract when the result would underflow, leaving the histogram unchanged", () => { + const histogram = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); + const other = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); + histogram.recordValueWithCount(42, 5); + other.recordValueWithCount(42, 6); + const before = histogram.summary; + expect(() => histogram.subtract(other)).toThrow( + `would underflow ${bits}-bit integer count` + ); + expect(histogram.summary).toEqual(before); + }); + }); + }); + + it("should keep Float64 histograms unbounded by the 32-bit maximum", () => { + const histogram = new Float64Histogram(1, Number.MAX_SAFE_INTEGER, 3); + histogram.recordValueWithCount(42, 4294967295); + histogram.recordValueWithCount(42, 4294967295); + expect(histogram.totalCount).toBe(8589934590); + }); +}); diff --git a/src/TypedArrayHistogram.ts b/src/TypedArrayHistogram.ts index 64bbfae..5768407 100644 --- a/src/TypedArrayHistogram.ts +++ b/src/TypedArrayHistogram.ts @@ -17,6 +17,12 @@ type TypedArray = ArrayLike & { class TypedArrayHistogram extends JsHistogram { _counts: TypedArray; _totalCount: number; + // Counts are range-checked against the storage width: unsigned typed arrays + // would otherwise wrap silently (255 + 1 -> 0 in an 8-bit array). + // Float64 storage keeps the safe-integer range it always had. + private readonly countBits: number; + private readonly countMin: number; + private readonly countMax: number; constructor( private arrayCtr: new (size: number) => TypedArray, @@ -31,6 +37,14 @@ class TypedArrayHistogram extends JsHistogram { ); this._totalCount = 0; this._counts = new arrayCtr(this.countsArrayLength); + this.countBits = this._counts.BYTES_PER_ELEMENT * 8; + if (this.countBits < 64) { + this.countMin = 0; + this.countMax = Math.pow(2, this.countBits) - 1; + } else { + this.countMin = Number.MIN_SAFE_INTEGER; + this.countMax = Number.MAX_SAFE_INTEGER; + } } clearCounts() { @@ -50,33 +64,46 @@ class TypedArrayHistogram extends JsHistogram { } incrementCountAtIndex(index: number) { - const currentCount = this._counts[index]; - const newCount = currentCount + 1; - if (newCount < 0) { - throw newCount + " would overflow short integer count"; + const newCount = this._counts[index] + 1; + if (newCount > this.countMax) { + this.throwCountOverflow(newCount); } this._counts[index] = newCount; } addToCountAtIndex(index: number, value: number) { - const currentCount = this._counts[index]; - const newCount = currentCount + value; - if ( - newCount < Number.MIN_SAFE_INTEGER || - newCount > Number.MAX_SAFE_INTEGER - ) { - throw newCount + " would overflow integer count"; + const newCount = this._counts[index] + value; + if (newCount > this.countMax) { + this.throwCountOverflow(newCount); + } + if (newCount < this.countMin) { + this.throwCountUnderflow(newCount); } this._counts[index] = newCount; } setCountAtIndex(index: number, value: number) { - if (value < Number.MIN_SAFE_INTEGER || value > Number.MAX_SAFE_INTEGER) { - throw value + " would overflow integer count"; + if (value > this.countMax) { + this.throwCountOverflow(value); + } + if (value < this.countMin) { + this.throwCountUnderflow(value); } this._counts[index] = value; } + private throwCountOverflow(count: number): never { + throw new Error(`${count} would overflow ${this.countWidthLabel()} count`); + } + + private throwCountUnderflow(count: number): never { + throw new Error(`${count} would underflow ${this.countWidthLabel()} count`); + } + + private countWidthLabel() { + return this.countBits < 64 ? `${this.countBits}-bit integer` : "integer"; + } + resize(newHighestTrackableValue: number) { this.establishSize(newHighestTrackableValue); const newCounts = new this.arrayCtr(this.countsArrayLength); diff --git a/src/wasm/index.ts b/src/wasm/index.ts index 08d6bba..9410047 100644 --- a/src/wasm/index.ts +++ b/src/wasm/index.ts @@ -139,6 +139,14 @@ const wasmImports = { lineNumber: number, columnNumber: number ) { + // AssemblyScript aborts carry the message (e.g. "... would overflow 8-bit integer count"); + // optimized builds have no source positions, so the location is added only when present. + if (messagePtr) { + const location = lineNumber + ? ` (WebAssembly at ${lineNumber}:${columnNumber})` + : ""; + throw new Error(`${getString(messagePtr)}${location}`); + } throw new Error(`Abort in WebAssembly at ${lineNumber}:${columnNumber}`); }, }, From fc027e4bfb8ffb7d1dc68bd6449ea18c8b734b00 Mon Sep 17 00:00:00 2001 From: alexvictoor Date: Sun, 15 Nov 2026 19:54:16 +0100 Subject: [PATCH 2/3] style: add given/when/then to the count overflow tests Co-Authored-By: Claude Fable 5.1 --- assembly/__tests__/Histogram.test.ts | 9 ++++ src/Histogram.spec.ts | 49 ++++++++++++++------- src/TypedArrayHistogram.spec.ts | 65 +++++++++++++++++++--------- 3 files changed, 87 insertions(+), 36 deletions(-) diff --git a/assembly/__tests__/Histogram.test.ts b/assembly/__tests__/Histogram.test.ts index 328fb5a..472d671 100644 --- a/assembly/__tests__/Histogram.test.ts +++ b/assembly/__tests__/Histogram.test.ts @@ -532,22 +532,31 @@ describe("Histogram count range", () => { // so these cover the in-range boundaries; the throwing paths are covered by the // WASM tests in src/Histogram.spec.ts. test("should accept a count equal to the 8-bit maximum", () => { + // given const histogram = new Histogram8(1, 9007199254740991, 3); + // when histogram.setCountAtIndex(5, 255); + // then expect(histogram.getCountAtIndex(5)).equal(255); }); test("should add up to exactly the 16-bit maximum", () => { + // given const histogram = new Histogram16(1, 1000000, 3); histogram.setCountAtIndex(7, 65000); + // when histogram.addToCountAtIndex(7, 535); + // then expect(histogram.getCountAtIndex(7)).equal(65535); }); test("should subtract down to exactly zero without wrapping", () => { + // given const histogram = new Histogram32(1, 1000000, 3); histogram.setCountAtIndex(9, 4294967295); + // when histogram.addToCountAtIndex(9, 0 - 4294967295); + // then expect(histogram.getCountAtIndex(9)).equal(0); }); }); diff --git a/src/Histogram.spec.ts b/src/Histogram.spec.ts index 97483c0..0ebb015 100644 --- a/src/Histogram.spec.ts +++ b/src/Histogram.spec.ts @@ -844,6 +844,7 @@ describe("WASM histogram count range", () => { const label = `${bits}-bit`; it(`should throw on recordValueWithCount past the ${label} maximum, leaving the histogram unchanged (WASM)`, () => { + // given const histogram = build({ bitBucketSize: bits, useWebAssembly: true, @@ -851,15 +852,17 @@ describe("WASM histogram count range", () => { }); histogram.recordValueWithCount(42, max); const before = histogram.summary; - expect(() => histogram.recordValueWithCount(42, 1)).toThrow( - `would overflow ${bits}-bit integer count` - ); + // when + const act = () => histogram.recordValueWithCount(42, 1); + // then + expect(act).toThrow(`would overflow ${bits}-bit integer count`); expect(histogram.summary).toEqual(before); expect(histogram.totalCount).toBe(max); histogram.destroy(); }); it(`should throw on add when the summed ${label} count would overflow, leaving the histogram unchanged (WASM)`, () => { + // given const histogram = build({ bitBucketSize: bits, useWebAssembly: true, @@ -873,15 +876,17 @@ describe("WASM histogram count range", () => { histogram.recordValueWithCount(42, max - 10); other.recordValueWithCount(42, 11); const before = histogram.summary; - expect(() => histogram.add(other)).toThrow( - `would overflow ${bits}-bit integer count` - ); + // when + const act = () => histogram.add(other); + // then + expect(act).toThrow(`would overflow ${bits}-bit integer count`); expect(histogram.summary).toEqual(before); histogram.destroy(); other.destroy(); }); it(`should add up to exactly the ${label} maximum (WASM)`, () => { + // given const histogram = build({ bitBucketSize: bits, useWebAssembly: true, @@ -894,13 +899,16 @@ describe("WASM histogram count range", () => { }); histogram.recordValueWithCount(42, max - 10); other.recordValueWithCount(42, 10); + // when histogram.add(other); + // then expect(histogram.totalCount).toBe(max); histogram.destroy(); other.destroy(); }); it(`should throw on subtract when the ${label} result would underflow, leaving the histogram unchanged (WASM)`, () => { + // given const histogram = build({ bitBucketSize: bits, useWebAssembly: true, @@ -914,9 +922,10 @@ describe("WASM histogram count range", () => { histogram.recordValueWithCount(42, 5); other.recordValueWithCount(42, 6); const before = histogram.summary; - expect(() => histogram.subtract(other)).toThrow( - `would underflow ${bits}-bit integer count` - ); + // when + const act = () => histogram.subtract(other); + // then + expect(act).toThrow(`would underflow ${bits}-bit integer count`); expect(histogram.summary).toEqual(before); histogram.destroy(); other.destroy(); @@ -925,27 +934,32 @@ describe("WASM histogram count range", () => { [8, 16, 32].forEach((bits) => { it(`should throw on a negative recordValueWithCount on a ${bits}-bit WASM histogram instead of dropping it`, () => { + // given const histogram = build({ bitBucketSize: bits, useWebAssembly: true, numberOfSignificantValueDigits: 3, }); - expect(() => histogram.recordValueWithCount(42, -1)).toThrow( - `would underflow ${bits}-bit integer count` - ); + // when + const act = () => histogram.recordValueWithCount(42, -1); + // then + expect(act).toThrow(`would underflow ${bits}-bit integer count`); expect(histogram.totalCount).toBe(0); histogram.destroy(); }); }); it("should keep 64-bit WASM histograms unbounded by the 32-bit maximum", () => { + // given const histogram = build({ bitBucketSize: 64, useWebAssembly: true, numberOfSignificantValueDigits: 3, }); + // when histogram.recordValueWithCount(42, 4294967295); histogram.recordValueWithCount(42, 4294967295); + // then expect(histogram.totalCount).toBe(8589934590); histogram.destroy(); }); @@ -958,6 +972,7 @@ describe("WASM histogram add across a wide counts range", () => { const max = Math.pow(2, bits) - 1; it(`should throw on add when a cell in the middle of a vectorised block range would overflow ${bits}-bit (WASM)`, () => { + // given const histogram = build({ bitBucketSize: bits, useWebAssembly: true, @@ -973,15 +988,17 @@ describe("WASM histogram add across a wide counts range", () => { } other.recordValueWithCount(100000, 1); histogram.recordValueWithCount(100000, max); - expect(() => histogram.add(other)).toThrow( - `would overflow ${bits}-bit integer count` - ); + // when + const act = () => histogram.add(other); + // then + expect(act).toThrow(`would overflow ${bits}-bit integer count`); expect(histogram.totalCount).toBe(max); histogram.destroy(); other.destroy(); }); it(`should add a wide range without overflow up to the ${bits}-bit maximum (WASM)`, () => { + // given const histogram = build({ bitBucketSize: bits, useWebAssembly: true, @@ -1000,7 +1017,9 @@ describe("WASM histogram add across a wide counts range", () => { other.recordValueWithCount(100000, 1); expected++; histogram.recordValueWithCount(100000, max - 1); + // when histogram.add(other); + // then expect(histogram.totalCount).toBe(expected + max - 1); histogram.destroy(); other.destroy(); diff --git a/src/TypedArrayHistogram.spec.ts b/src/TypedArrayHistogram.spec.ts index 4139852..bffe9f9 100644 --- a/src/TypedArrayHistogram.spec.ts +++ b/src/TypedArrayHistogram.spec.ts @@ -78,8 +78,11 @@ describe("Typed array histogram count range", () => { cases.forEach(({ name, Histogram, max, bits }) => { describe(`${name} histogram`, () => { it("should accept a count up to the storage maximum", () => { + // given const histogram = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); + // when histogram.recordValueWithCount(42, max); + // then expect(histogram.getCountAtIndex(histogram.countsArrayIndex(42))).toBe( max ); @@ -87,11 +90,13 @@ describe("Typed array histogram count range", () => { }); it("should throw on recordValueWithCount past the storage maximum, leaving the histogram unchanged", () => { + // given const histogram = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); histogram.recordValueWithCount(42, max); - expect(() => histogram.recordValueWithCount(42, 1)).toThrow( - `would overflow ${bits}-bit integer count` - ); + // when + const act = () => histogram.recordValueWithCount(42, 1); + // then + expect(act).toThrow(`would overflow ${bits}-bit integer count`); expect(histogram.getCountAtIndex(histogram.countsArrayIndex(42))).toBe( max ); @@ -99,32 +104,40 @@ describe("Typed array histogram count range", () => { }); it("should throw on recordValue when the counter is already at the maximum", () => { + // given const histogram = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); histogram.setCountAtIndex(histogram.countsArrayIndex(42), max); - expect(() => histogram.recordValue(42)).toThrow( - `would overflow ${bits}-bit integer count` - ); + // when + const act = () => histogram.recordValue(42); + // then + expect(act).toThrow(`would overflow ${bits}-bit integer count`); expect(histogram.totalCount).toBe(0); }); it("should throw on addToCountAtIndex and setCountAtIndex past the maximum", () => { + // given const histogram = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); - expect(() => histogram.setCountAtIndex(5, max + 1)).toThrow( - "would overflow" - ); + // when + const setAct = () => histogram.setCountAtIndex(5, max + 1); + // then + expect(setAct).toThrow("would overflow"); + // given histogram.setCountAtIndex(5, max - 1); - expect(() => histogram.addToCountAtIndex(5, 2)).toThrow( - `would overflow ${bits}-bit integer count` - ); + // when + const addAct = () => histogram.addToCountAtIndex(5, 2); + // then + expect(addAct).toThrow(`would overflow ${bits}-bit integer count`); expect(histogram.getCountAtIndex(5)).toBe(max - 1); }); it("should throw on a negative count instead of wrapping", () => { + // given const histogram = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); histogram.recordValueWithCount(42, 3); - expect(() => histogram.recordValueWithCount(42, -4)).toThrow( - `would underflow ${bits}-bit integer count` - ); + // when + const act = () => histogram.recordValueWithCount(42, -4); + // then + expect(act).toThrow(`would underflow ${bits}-bit integer count`); expect(histogram.getCountAtIndex(histogram.countsArrayIndex(42))).toBe( 3 ); @@ -132,24 +145,29 @@ describe("Typed array histogram count range", () => { }); it("should throw on add when the summed count would overflow, leaving the histogram unchanged", () => { + // given const histogram = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); const other = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); histogram.recordValueWithCount(42, max - 10); other.recordValueWithCount(42, 11); const before = histogram.summary; - expect(() => histogram.add(other)).toThrow( - `would overflow ${bits}-bit integer count` - ); + // when + const act = () => histogram.add(other); + // then + expect(act).toThrow(`would overflow ${bits}-bit integer count`); expect(histogram.summary).toEqual(before); expect(other.totalCount).toBe(11); }); it("should add up to exactly the storage maximum", () => { + // given const histogram = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); const other = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); histogram.recordValueWithCount(42, max - 10); other.recordValueWithCount(42, 10); + // when histogram.add(other); + // then expect(histogram.getCountAtIndex(histogram.countsArrayIndex(42))).toBe( max ); @@ -157,23 +175,28 @@ describe("Typed array histogram count range", () => { }); it("should throw on subtract when the result would underflow, leaving the histogram unchanged", () => { + // given const histogram = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); const other = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); histogram.recordValueWithCount(42, 5); other.recordValueWithCount(42, 6); const before = histogram.summary; - expect(() => histogram.subtract(other)).toThrow( - `would underflow ${bits}-bit integer count` - ); + // when + const act = () => histogram.subtract(other); + // then + expect(act).toThrow(`would underflow ${bits}-bit integer count`); expect(histogram.summary).toEqual(before); }); }); }); it("should keep Float64 histograms unbounded by the 32-bit maximum", () => { + // given const histogram = new Float64Histogram(1, Number.MAX_SAFE_INTEGER, 3); + // when histogram.recordValueWithCount(42, 4294967295); histogram.recordValueWithCount(42, 4294967295); + // then expect(histogram.totalCount).toBe(8589934590); }); }); From 1f2a816f8c34599068a6fb82198c674423b60a94 Mon Sep 17 00:00:00 2001 From: alexvictoor Date: Sun, 15 Nov 2026 20:28:52 +0100 Subject: [PATCH 3/3] fix: review follow-ups for the count overflow checks - Restore @inline on recordCountAtValue; recordCountAtValueFromF64 is undecorated - Remove the duplicated @ts-ignore in incrementCountAtIndex - WASM 64-bit: subtract underflow throws (scalar and vector paths, u64 lanes compared unsigned via a sign bias) - WASM: a negative count throws for every width, instead of saturating to 0 for u64 - Typed array histograms check the count before an auto-resize, so a rejected count leaves highestTrackableValue unchanged - Tests: rename the single-cell add/subtract tests, add Java-semantics tests (earlier cells stay applied when a later cell throws), add 64-bit WASM tests Co-Authored-By: Claude Fable 5.1 --- assembly/Histogram.ts | 26 +++++----- assembly/__tests__/Histogram.test.ts | 10 ++++ src/Histogram.spec.ts | 72 +++++++++++++++++++++++++++- src/TypedArrayHistogram.spec.ts | 53 +++++++++++++++++++- src/TypedArrayHistogram.ts | 12 +++++ 5 files changed, 156 insertions(+), 17 deletions(-) diff --git a/assembly/Histogram.ts b/assembly/Histogram.ts index e9d3880..dd3e3d2 100644 --- a/assembly/Histogram.ts +++ b/assembly/Histogram.ts @@ -142,7 +142,7 @@ function underflowAbort(count: i64): void { abort(count.toString() + " would underflow " + (sizeof() << 3).toString() + "-bit integer count"); } -/** Lane-wise unsigned a < b for narrow U (u64 lanes are never compared this way). */ +/** Lane-wise unsigned a < b. u64 lanes flip the sign bit so the signed compare orders them unsigned. */ // @ts-ignore: decorator @inline function laneLtU(a: v128, b: v128): v128 { @@ -150,8 +150,11 @@ function laneLtU(a: v128, b: v128): v128 { return i8x16.lt_u(a, b); } else if (sizeof() == 2) { return i16x8.lt_u(a, b); - } else { + } else if (sizeof() == 4) { return i32x4.lt_u(a, b); + } else { + const bias = i64x2.splat(i64.MIN_VALUE); + return i64x2.lt_s(v128.xor(a, bias), v128.xor(b, bias)); } } @@ -618,18 +621,20 @@ export default class Histogram extends AbstractHistogramBase { return index == 0 ? this.lowestNonZeroCountsIndex() : index + 1; } - @inline /** * Entry point for count arguments that arrive as f64 (the JS boundary). A negative - * count would otherwise saturate to 0 in the u64 cast and be dropped silently. + * count is not representable in any U cell (and would saturate to 0 in the u64 cast, + * dropping the record silently), so it aborts for every width. */ recordCountAtValueFromF64(count: f64, value: f64): void { - if (sizeof() < 8 && count < 0) { + if (count < 0) { underflowAbort(count); } this.recordCountAtValue(count, value); } + // @ts-ignore: decorator + @inline recordCountAtValue(count: u64, value: u64): void { const countsIndex = this.countsArrayIndex(value); if (countsIndex >= this.countsArrayLength) { @@ -917,7 +922,6 @@ export default class Histogram extends AbstractHistogramBase { return; } // @ts-ignore - // @ts-ignore const newCount = unchecked(this.counts[index]) + 1; if (sizeof() < 8 && newCount > countMax()) { overflowAbort(newCount); @@ -949,20 +953,16 @@ export default class Histogram extends AbstractHistogramBase { } // @ts-ignore const currentCount = unchecked(this.counts[index]); - if (sizeof() == 8) { - // @ts-ignore - unchecked((this.counts[index] = (currentCount + value))); - return; - } if (value >= 0) { const newCount = currentCount + value; - if (newCount > countMax()) { + if (sizeof() < 8 && newCount > countMax()) { overflowAbort(newCount); } // @ts-ignore unchecked((this.counts[index] = newCount)); } else { // Negative values arrive as two's complement (subtract); the magnitude is their negation. + // A cell of U (u64 included) cannot go below zero, so the check applies to every width. const decrement = (0) - value; if (decrement > currentCount) { underflowAbort(currentCount - decrement); @@ -1252,7 +1252,7 @@ export default class Histogram extends AbstractHistogramBase { const offset = i << alignof(); const other = v128.load(src + offset); const current = v128.load(dst + offset); - if (sizeof() < 8 && v128.any_true(laneLtU(current, other))) { + if (v128.any_true(laneLtU(current, other))) { // A lane would go negative: leave this block to the checked scalar loop below. break; } diff --git a/assembly/__tests__/Histogram.test.ts b/assembly/__tests__/Histogram.test.ts index 472d671..a7eedb9 100644 --- a/assembly/__tests__/Histogram.test.ts +++ b/assembly/__tests__/Histogram.test.ts @@ -559,4 +559,14 @@ describe("Histogram count range", () => { // then expect(histogram.getCountAtIndex(9)).equal(0); }); + + test("should subtract a 64-bit cell down to exactly zero", () => { + // given + const histogram = new Histogram64(1, 1000000, 3); + histogram.setCountAtIndex(9, 5); + // when + histogram.addToCountAtIndex(9, 0 - 5); + // then + expect(histogram.getCountAtIndex(9)).equal(0); + }); }); diff --git a/src/Histogram.spec.ts b/src/Histogram.spec.ts index 0ebb015..cb04cd6 100644 --- a/src/Histogram.spec.ts +++ b/src/Histogram.spec.ts @@ -861,7 +861,7 @@ describe("WASM histogram count range", () => { histogram.destroy(); }); - it(`should throw on add when the summed ${label} count would overflow, leaving the histogram unchanged (WASM)`, () => { + it(`should throw on add when the only cell to change would overflow ${label}, leaving the histogram unchanged (WASM)`, () => { // given const histogram = build({ bitBucketSize: bits, @@ -907,7 +907,7 @@ describe("WASM histogram count range", () => { other.destroy(); }); - it(`should throw on subtract when the ${label} result would underflow, leaving the histogram unchanged (WASM)`, () => { + it(`should throw on subtract when the only cell to change would underflow ${label}, leaving the histogram unchanged (WASM)`, () => { // given const histogram = build({ bitBucketSize: bits, @@ -949,6 +949,74 @@ describe("WASM histogram count range", () => { }); }); + it("should throw on add at a later cell, leaving earlier cells applied and totalCount unchanged (8-bit WASM)", () => { + // given + const histogram = build({ + bitBucketSize: 8, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + const other = build({ + bitBucketSize: 8, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + histogram.recordValueWithCount(42, 255); + other.recordValueWithCount(1, 5); + other.recordValueWithCount(42, 1); + // when + const act = () => histogram.add(other); + // then + expect(act).toThrow("would overflow 8-bit integer count"); + // non-zero counts are [index, count, ...] pairs in index order: value 1 (5) then value 42 (255) + const counts = Array.from(histogram.getNonZeroCounts()).filter( + (_, i) => i % 2 === 1 + ); + expect(counts).toEqual([5, 255]); + expect(histogram.totalCount).toBe(255); + histogram.destroy(); + other.destroy(); + }); + + it("should throw on subtract when the 64-bit result would underflow, leaving the histogram unchanged (WASM)", () => { + // given + const histogram = build({ + bitBucketSize: 64, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + const other = build({ + bitBucketSize: 64, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + histogram.recordValueWithCount(42, 5); + other.recordValueWithCount(42, 6); + const before = histogram.summary; + // when + const act = () => histogram.subtract(other); + // then + expect(act).toThrow("would underflow 64-bit integer count"); + expect(histogram.summary).toEqual(before); + histogram.destroy(); + other.destroy(); + }); + + it("should throw on a negative recordValueWithCount on a 64-bit WASM histogram instead of dropping it", () => { + // given + const histogram = build({ + bitBucketSize: 64, + useWebAssembly: true, + numberOfSignificantValueDigits: 3, + }); + // when + const act = () => histogram.recordValueWithCount(42, -3); + // then + expect(act).toThrow("would underflow 64-bit integer count"); + expect(histogram.totalCount).toBe(0); + histogram.destroy(); + }); + it("should keep 64-bit WASM histograms unbounded by the 32-bit maximum", () => { // given const histogram = build({ diff --git a/src/TypedArrayHistogram.spec.ts b/src/TypedArrayHistogram.spec.ts index bffe9f9..e9bba8f 100644 --- a/src/TypedArrayHistogram.spec.ts +++ b/src/TypedArrayHistogram.spec.ts @@ -144,7 +144,7 @@ describe("Typed array histogram count range", () => { expect(histogram.totalCount).toBe(3); }); - it("should throw on add when the summed count would overflow, leaving the histogram unchanged", () => { + it("should throw on add when the only cell to change would overflow, leaving the histogram unchanged", () => { // given const histogram = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); const other = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); @@ -174,7 +174,7 @@ describe("Typed array histogram count range", () => { expect(histogram.totalCount).toBe(max); }); - it("should throw on subtract when the result would underflow, leaving the histogram unchanged", () => { + it("should throw on subtract when the only cell to change would underflow, leaving the histogram unchanged", () => { // given const histogram = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); const other = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); @@ -190,6 +190,55 @@ describe("Typed array histogram count range", () => { }); }); + describe("8-bit histogram with several cells changing", () => { + it("should throw on add at a later cell, leaving earlier cells applied and totalCount unchanged", () => { + // given + const histogram = new Int8Histogram(1, Number.MAX_SAFE_INTEGER, 3); + const other = new Int8Histogram(1, Number.MAX_SAFE_INTEGER, 3); + histogram.recordValueWithCount(42, 255); + other.recordValueWithCount(1, 5); + other.recordValueWithCount(42, 1); + // when + const act = () => histogram.add(other); + // then + expect(act).toThrow("would overflow 8-bit integer count"); + expect(histogram.getCountAtIndex(histogram.countsArrayIndex(1))).toBe(5); + expect(histogram.getCountAtIndex(histogram.countsArrayIndex(42))).toBe( + 255 + ); + expect(histogram.totalCount).toBe(255); + }); + + it("should throw on subtract at a later cell, leaving earlier cells applied and totalCount unchanged", () => { + // given + const histogram = new Int8Histogram(1, Number.MAX_SAFE_INTEGER, 3); + const other = new Int8Histogram(1, Number.MAX_SAFE_INTEGER, 3); + histogram.recordValueWithCount(1, 10); + other.recordValueWithCount(1, 5); + other.recordValueWithCount(42, 1); + // when + const act = () => histogram.subtract(other); + // then + expect(act).toThrow("would underflow 8-bit integer count"); + expect(histogram.getCountAtIndex(histogram.countsArrayIndex(1))).toBe(5); + expect(histogram.getCountAtIndex(histogram.countsArrayIndex(42))).toBe(0); + expect(histogram.totalCount).toBe(10); + }); + + it("should leave highestTrackableValue unchanged when an auto-resizing histogram rejects the count", () => { + // given + const histogram = new Int8Histogram(1, 1000, 3); + histogram.autoResize = true; + const highestBefore = histogram.highestTrackableValue; + // when + const act = () => histogram.recordValueWithCount(1000000, 300); + // then + expect(act).toThrow("would overflow 8-bit integer count"); + expect(histogram.highestTrackableValue).toBe(highestBefore); + expect(histogram.totalCount).toBe(0); + }); + }); + it("should keep Float64 histograms unbounded by the 32-bit maximum", () => { // given const histogram = new Float64Histogram(1, Number.MAX_SAFE_INTEGER, 3); diff --git a/src/TypedArrayHistogram.ts b/src/TypedArrayHistogram.ts index 5768407..c1c1974 100644 --- a/src/TypedArrayHistogram.ts +++ b/src/TypedArrayHistogram.ts @@ -63,6 +63,18 @@ class TypedArrayHistogram extends JsHistogram { return -1; } + // Checked before the base class resizes an auto-resizing histogram, so a rejected + // count leaves the histogram's range untouched. Only reached on the out-of-range path. + handleRecordException(count: number, value: number) { + if (count > this.countMax) { + this.throwCountOverflow(count); + } + if (count < this.countMin) { + this.throwCountUnderflow(count); + } + super.handleRecordException(count, value); + } + incrementCountAtIndex(index: number) { const newCount = this._counts[index] + 1; if (newCount > this.countMax) {