diff --git a/assembly/Histogram.ts b/assembly/Histogram.ts index 807be56..3ace11b 100644 --- a/assembly/Histogram.ts +++ b/assembly/Histogram.ts @@ -705,6 +705,14 @@ export default class Histogram extends AbstractHistogramBase { } } for (; i < end; i++) { + if (!isFlatStorage()) { + // Jump over the empty subtrees of the packed counts + i = this.nextNonZeroIndex(i); + if (i < 0 || i >= end) { + i = end; + break; + } + } totalToCurrentIndex += this.getCountAtIndex(i); if (totalToCurrentIndex >= countAtPercentile) break; } @@ -783,6 +791,25 @@ export default class Histogram extends AbstractHistogramBase { return unchecked(this.counts[index]); } + /** + * Lowest index >= fromIndex with a non-zero count, or -1 when there is none. + * A packed histogram skips the empty subtrees of its counts array, so the + * scans built on this cost time proportional to the populated indexes + * rather than to the counts array length. + */ + nextNonZeroIndex(fromIndex: i32): i32 { + if (idof() == idof()) { + return changetype(this.counts).nextNonZeroIndex(fromIndex); + } + const length = this.countsArrayLength; + for (let i = fromIndex; i < length; i++) { + if (this.getCountAtIndex(i) != 0) { + return i; + } + } + return -1; + } + /** Address of counts[0] in linear memory. Only valid when isFlatStorage(). */ @inline get countsDataStart(): usize { @@ -844,6 +871,13 @@ export default class Histogram extends AbstractHistogramBase { observedOtherTotalCount += horizontalSum(acc); } for (; i < end; i++) { + if (!isFlatStorage()) { + // Jump over the empty subtrees of the other packed counts + i = otherHistogram.nextNonZeroIndex(i); + if (i < 0 || i >= end) { + break; + } + } const otherCount = otherHistogram.getCountAtIndex(i); if (otherCount > 0) { this.addToCountAtIndex(i, otherCount); @@ -876,6 +910,13 @@ export default class Histogram extends AbstractHistogramBase { i < otherMaxIndex; i = otherHistogram.nextCountsIndexToScan(i) ) { + if (!isFlatStorage()) { + // Jump over the empty subtrees of the other packed counts + i = otherHistogram.nextNonZeroIndex(i); + if (i < 0 || i >= otherMaxIndex) { + break; + } + } otherCount = otherHistogram.getCountAtIndex(i); if (otherCount > 0) { this.recordCountAtValue(otherCount, otherHistogram.valueFromIndex(i)); @@ -945,6 +986,13 @@ export default class Histogram extends AbstractHistogramBase { } } for (; index < lengthToCover; index++) { + if (!isFlatStorage()) { + // Jump over the empty subtrees of the packed counts + index = this.nextNonZeroIndex(index); + if (index < 0 || index >= lengthToCover) { + break; + } + } const countAtIndex: u64 = this.getCountAtIndex(index); if (countAtIndex > 0) { observedTotalCount += countAtIndex; @@ -1011,6 +1059,13 @@ export default class Histogram extends AbstractHistogramBase { observedOtherTotalCount += horizontalSum(acc); } for (; i < end; i++) { + if (!isFlatStorage()) { + // Jump over the empty subtrees of the other packed counts + i = otherHistogram.nextNonZeroIndex(i); + if (i < 0 || i >= end) { + break; + } + } const otherCount = otherHistogram.getCountAtIndex(i); if (otherCount > 0) { this.addToCountAtIndex(i, -otherCount); @@ -1025,6 +1080,13 @@ export default class Histogram extends AbstractHistogramBase { i <= otherLastIndex; i = otherHistogram.nextCountsIndexToScan(i) ) { + if (!isFlatStorage()) { + // Jump over the empty subtrees of the other packed counts + i = otherHistogram.nextNonZeroIndex(i); + if (i < 0 || i > otherLastIndex) { + break; + } + } const otherCount = otherHistogram.getCountAtIndex(i); if (otherCount > 0) { const otherValue = otherHistogram.valueFromIndex(i); diff --git a/assembly/__tests__/PackedArrayIteration.test.ts b/assembly/__tests__/PackedArrayIteration.test.ts new file mode 100644 index 0000000..b4b71bf --- /dev/null +++ b/assembly/__tests__/PackedArrayIteration.test.ts @@ -0,0 +1,191 @@ +/* + * Cross-checks PackedArray.nextNonZeroIndex (set-0 tree walk) against a brute + * force scan of a plain array model: sparse and dense contents, values whose + * low byte is zero, values set back to zero, resizes and the unpacked fallback. + */ + +import { describe, test, expect } from "assemblyscript-unittest-framework/assembly"; +import { PackedArray } from "../packedarray/PackedArray"; + +let seed: u32 = 4242; +function nextRandom(): u32 { + seed = seed * 1664525 + 1013904223; + return seed; +} + +function bruteForceNext(model: StaticArray, fromIndex: i32): i32 { + for (let i = fromIndex; i < model.length; i++) { + if (model[i] != 0) return i; + } + return -1; +} + +/** + * Number of disagreements between the walk and the model: first a full walk + * from index 0, then lookups from random start indexes (including past the end). + */ +function mismatches(packed: PackedArray, model: StaticArray): i32 { + let count = 0; + let index = packed.nextNonZeroIndex(0); + let expected = bruteForceNext(model, 0); + while (expected >= 0) { + if (index != expected) count++; + if (index < 0) break; + index = packed.nextNonZeroIndex(index + 1); + expected = bruteForceNext(model, expected + 1); + } + if (index != -1) count++; + for (let n = 0; n < 200; n++) { + const from = (nextRandom() % (model.length + 16)); + if (packed.nextNonZeroIndex(from) != bruteForceNext(model, from)) count++; + } + return count; +} + +describe("Packed Array non-zero iteration", () => { + test("should find no non-zero index in an empty array", () => { + // given + const packed = new PackedArray(100000); + // when + const fromStart = packed.nextNonZeroIndex(0); + const fromLastIndex = packed.nextNonZeroIndex(99999); + const fromEnd = packed.nextNonZeroIndex(100000); + // then + expect(fromStart).equal(-1); + expect(fromLastIndex).equal(-1); + expect(fromEnd).equal(-1); + }); + + test("should walk a sparse array", () => { + // given + const length = 100000; + const packed = new PackedArray(length); + const model = new StaticArray(length); + for (let n = 0; n < 300; n++) { + const i = (nextRandom() % length); + const v = (1 + (nextRandom() % 1000)); + packed.add(i, v); + model[i] += v; + } + // when + const count = mismatches(packed, model); + // then + expect(count).equal(0); + }); + + test("should find values whose low byte is zero", () => { + // given + const packed = new PackedArray(4096); + const model = new StaticArray(4096); + packed.set(300, 256); + model[300] = 256; + packed.set(2000, 0x10000); + model[2000] = 0x10000; + packed.set(4095, 0x0100000000000000); + model[4095] = 0x0100000000000000; + // when + const first = packed.nextNonZeroIndex(0); + const second = packed.nextNonZeroIndex(301); + const third = packed.nextNonZeroIndex(2001); + const count = mismatches(packed, model); + // then + expect(first).equal(300); + expect(second).equal(2000); + expect(third).equal(4095); + expect(count).equal(0); + }); + + test("should walk a dense array", () => { + // given + const length = 4096; + const packed = new PackedArray(length); + const model = new StaticArray(length); + for (let i = 0; i < length; i++) { + const v = (nextRandom() % 100000); + packed.set(i, v); + model[i] = v; + } + // when + const count = mismatches(packed, model); + // then + expect(count).equal(0); + }); + + test("should skip values set back to zero, leaving their leaf in place", () => { + // given + const length = 20000; + const packed = new PackedArray(length); + const model = new StaticArray(length); + for (let n = 0; n < 500; n++) { + const i = (nextRandom() % length); + const v = (1 + (nextRandom() % 100000)); + packed.set(i, v); + model[i] = v; + } + // when + for (let i = 0; i < length; i++) { + if (model[i] != 0 && nextRandom() % 2 == 0) { + packed.set(i, 0); + model[i] = 0; + } + } + const count = mismatches(packed, model); + // then + expect(count).equal(0); + }); + + test("should walk the whole array after a resize", () => { + // given + const packed = new PackedArray(256, 16); + const model = new StaticArray(100000); + for (let i = 0; i < 256; i += 5) { + const v = (1 + (nextRandom() % 1000000)); + packed.set(i, v); + model[i] = v; + } + packed.resize(100000); + // when + for (let n = 0; n < 200; n++) { + const i = (nextRandom() % 100000); + const v = (1 + (nextRandom() % 1000000)); + packed.add(i, v); + model[i] += v; + } + const count = mismatches(packed, model); + // then + expect(count).equal(0); + }); + + test("should scan linearly once the array is unpacked", () => { + // 64 bit values at every index outgrow the packed representation + // given + const length = 5000; + const packed = new PackedArray(length); + const model = new StaticArray(length); + for (let i = 0; i < length; i++) { + packed.set(i, u64.MAX_VALUE - i); + model[i] = u64.MAX_VALUE - i; + } + for (let i = 0; i < length; i++) { + if (nextRandom() % 4 != 0) { + packed.set(i, 0); + model[i] = 0; + } + } + // when + const countBeforeResize = mismatches(packed, model); + // then + expect(countBeforeResize).equal(0); + + // given + packed.resize(6000); + const grown = new StaticArray(6000); + for (let i = 0; i < length; i++) grown[i] = model[i]; + packed.set(5999, 7); + grown[5999] = 7; + // when + const countAfterResize = mismatches(packed, grown); + // then + expect(countAfterResize).equal(0); + }); +}); diff --git a/assembly/encoding.ts b/assembly/encoding.ts index a364516..aff77bc 100644 --- a/assembly/encoding.ts +++ b/assembly/encoding.ts @@ -45,11 +45,13 @@ function fillBufferFromCountsArray( // Count trailing 0s (which follow this count): let zerosCount = 0; if (count == 0) { - zerosCount = 1; - while (srcIndex < countsLimit && self.getCountAtIndex(srcIndex) == 0) { - zerosCount++; - srcIndex++; - } + // The run of zeros extends to the next non-zero count (or to the limit); + // a packed histogram finds it without visiting every empty index. + const nextNonZeroIndex = self.nextNonZeroIndex(srcIndex); + const zerosEnd = + nextNonZeroIndex < 0 ? countsLimit : min(nextNonZeroIndex, countsLimit); + zerosCount = 1 + zerosEnd - srcIndex; + srcIndex = zerosEnd; } if (zerosCount > 1) { ZigZagEncoding.encode(buffer, -zerosCount); diff --git a/assembly/packedarray/PackedArray.ts b/assembly/packedarray/PackedArray.ts index 0afb704..a80f0f6 100644 --- a/assembly/packedarray/PackedArray.ts +++ b/assembly/packedarray/PackedArray.ts @@ -297,6 +297,42 @@ export class PackedArray { } } + /** + * Lowest index >= fromIndex holding a non-zero value, or -1 when there is none. + * + * On a packed context the set-0 tree is walked to skip the groups of 8 + * indexes that were never populated, so a scan over the whole array costs + * time proportional to the populated groups rather than to the virtual + * length. An unpacked context is scanned linearly. + */ + nextNonZeroIndex(fromIndex: i32): i32 { + const arrayContext = this.arrayContext; + const length = arrayContext.getVirtualLength(); + let index = fromIndex; + if (!arrayContext.isPacked) { + for (; index < length; index++) { + if (arrayContext.getAtUnpackedIndex(index) != 0) { + return index; + } + } + return -1; + } + while (index < length) { + index = arrayContext.nextIndexWithLeaf(index); + if (index < 0) { + return -1; + } + // The leaf found only vouches for the group of 8 indexes holding index + const groupEnd = min((index | 0x7) + 1, length); + for (; index < groupEnd; index++) { + if (this.get(index) != 0) { + return index; + } + } + } + return -1; + } + /** * Move the contents to a new unpacked context of the given virtual length, * once the packed representation cannot grow any further diff --git a/assembly/packedarray/PackedArrayContext.ts b/assembly/packedarray/PackedArrayContext.ts index 795eda9..8e32fd8 100644 --- a/assembly/packedarray/PackedArrayContext.ts +++ b/assembly/packedarray/PackedArrayContext.ts @@ -480,6 +480,84 @@ return byteIndex; } + /** + * Lowest virtual index >= fromIndex whose group of 8 indexes has a leaf in + * set 0, i.e. whose values may be non-zero. Groups without a leaf are all + * zeros and are skipped by descending only into the populated slots of + * the set-0 tree, so the walk costs time proportional to the populated + * groups rather than to the virtual length. + * + * Sets are populated in order 0..7 (see PackedArray set/add), so a group + * with a leaf in any set has one in set 0: the set-0 tree covers every + * group that may hold a non-zero value. The converse does not hold (a leaf + * may be all zeros, or hold a byte 0 of 0 under a non-zero byte 1), so the + * caller still has to read the values of the group returned. + * + * @return the index, which may exceed the virtual length when the last + * group is partial, or -1 when no group at or after fromIndex has a leaf + */ + nextIndexWithLeaf(fromIndex: i32): i32 { + if (fromIndex >= this.virtualLength) { + return -1; + } + const rootEntryIndex = this.getIndexAtShortIndex(SET_0_START_INDEX); + if (rootEntryIndex == 0) { + return -1; // Set 0 has no tree at all: nothing was ever stored + } + return this.nextIndexWithLeafBelow( + rootEntryIndex, + this.topLevelShift, + fromIndex + ); + } + + /** + * Walk the entry at entryIndex, which decodes the 4 index bits above + * indexShift, for the lowest index >= fromIndex with a leaf below it. + * fromIndex lies in the index range covered by the entry. + */ + private nextIndexWithLeafBelow( + entryIndex: i32, + indexShift: i32, + fromIndex: i32 + ): i32 { + const packedSlotIndicators = this.getPackedSlotIndicators(entryIndex); + // The indexes covered by this entry share the bits above the ones its slots decode + const entryBase = fromIndex & ~((1 << (indexShift + 4)) - 1); + const nextLevelIsLeaf = indexShift == LEAF_LEVEL_SHIFT; + for ( + let slotBitNumber = (fromIndex >>> indexShift) & 0xf; + slotBitNumber < 16; + slotBitNumber++ + ) { + const slotMask = 1 << slotBitNumber; + if ((packedSlotIndicators & slotMask) == 0) { + continue; // nothing was ever stored under this slot + } + const slotStart = entryBase | (slotBitNumber << indexShift); + // Past the slot holding fromIndex, resume from the start of each slot + const from = slotStart > fromIndex ? slotStart : fromIndex; + if (nextLevelIsLeaf) { + return from; + } + const slotNumber = popcnt(packedSlotIndicators & (slotMask - 1)); + const nextLevelEntryIndex = ( + this.getIndexAtShortIndex( + entryIndex + NON_LEAF_ENTRY_HEADER_SIZE_IN_SHORTS + slotNumber + ) + ); + const found = this.nextIndexWithLeafBelow( + nextLevelEntryIndex, + indexShift - 4, + from + ); + if (found >= 0) { + return found; + } + } + return -1; + } + determineTopLevelShiftForVirtualLength(virtualLength: i32): i32 { const sizeMagnitude = ceil(Math.log2(virtualLength)); const eightsSizeMagnitude = sizeMagnitude - 3; diff --git a/src/JsHistogram.encoding.ts b/src/JsHistogram.encoding.ts index 5479fed..4f0467f 100644 --- a/src/JsHistogram.encoding.ts +++ b/src/JsHistogram.encoding.ts @@ -12,7 +12,7 @@ import { BitBucketSize } from "./Histogram"; import { constructorFromBucketSize } from "./JsHistogramFactory"; import ZigZagEncoding from "./ZigZagEncoding"; -const { max } = Math; +const { max, min } = Math; const V2EncodingCookieBase = 0x1c849303; const V2CompressedEncodingCookieBase = 0x1c849304; @@ -44,11 +44,13 @@ function fillBufferFromCountsArray(self: JsHistogram, buffer: ByteBuffer) { // Count trailing 0s (which follow this count): let zerosCount = 0; if (count == 0) { - zerosCount = 1; - while (srcIndex < countsLimit && self.getCountAtIndex(srcIndex) == 0) { - zerosCount++; - srcIndex++; - } + // The run of zeros extends to the next non-zero count (or to the limit); + // a packed histogram finds it without visiting every empty index. + const nextNonZeroIndex = self.nextNonZeroIndex(srcIndex); + const zerosEnd = + nextNonZeroIndex < 0 ? countsLimit : min(nextNonZeroIndex, countsLimit); + zerosCount = 1 + zerosEnd - srcIndex; + srcIndex = zerosEnd; } if (zerosCount > 1) { ZigZagEncoding.encode(buffer, -zerosCount); diff --git a/src/JsHistogram.ts b/src/JsHistogram.ts index 51aa332..ab3148e 100644 --- a/src/JsHistogram.ts +++ b/src/JsHistogram.ts @@ -116,6 +116,23 @@ export abstract class JsHistogram implements Histogram { abstract getCountAtIndex(index: number): number; + /** + * Lowest index >= fromIndex with a non-zero count, or -1 when there is none. + * Storage that can skip empty regions of the counts array (PackedHistogram) + * overrides this so that whole-array scans cost time proportional to the + * populated indexes rather than to the counts array length. + * @internal + */ + nextNonZeroIndex(fromIndex: number): number { + const length = this.countsArrayLength; + for (let i = fromIndex; i < length; i++) { + if (this.getCountAtIndex(i) !== 0) { + return i; + } + } + return -1; + } + abstract incrementCountAtIndex(index: number): void; abstract addToCountAtIndex(index: number, value: number): void; @@ -444,6 +461,25 @@ export abstract class JsHistogram implements Histogram { return index === 0 ? this.lowestNonZeroCountsIndex() : index + 1; } + /** + * Smallest index in [fromIndex, lastIndex] whose count may be non-zero, or + * -1. Index 0 aside, no count lives below the index of minNonZeroValue, and + * the storage then skips its empty counts (whole subtrees when packed). + */ + nextNonZeroIndexInRange(fromIndex: number, lastIndex: number): number { + if (fromIndex > lastIndex) { + return -1; + } + if (fromIndex === 0) { + if (this.getCountAtIndex(0) !== 0) { + return 0; + } + fromIndex = this.lowestNonZeroCountsIndex(); + } + const index = this.nextNonZeroIndex(fromIndex); + return index > lastIndex ? -1 : index; + } + /** * Get the value at a given percentile. * When the given percentile is > 0.0, the value returned is the value that the given @@ -1007,9 +1043,9 @@ export abstract class JsHistogram implements Histogram { let observedOtherTotalCount = 0; const otherLastIndex = otherHistogram.highestNonZeroCountsIndex(); for ( - let i = 0; - i <= otherLastIndex; - i = otherHistogram.nextCountsIndexToScan(i) + let i = otherHistogram.nextNonZeroIndexInRange(0, otherLastIndex); + i >= 0; + i = otherHistogram.nextNonZeroIndexInRange(i + 1, otherLastIndex) ) { const otherCount = otherHistogram.getCountAtIndex(i); if (otherCount > 0) { @@ -1039,9 +1075,9 @@ export abstract class JsHistogram implements Histogram { // Record the remaining values, up to but not including the max value: for ( - let i = 0; - i < otherMaxIndex; - i = otherHistogram.nextCountsIndexToScan(i) + let i = otherHistogram.nextNonZeroIndexInRange(0, otherMaxIndex - 1); + i >= 0; + i = otherHistogram.nextNonZeroIndexInRange(i + 1, otherMaxIndex - 1) ) { otherCount = otherHistogram.getCountAtIndex(i); if (otherCount > 0) { @@ -1114,9 +1150,9 @@ export abstract class JsHistogram implements Histogram { // visiting only the indexes of the other histogram that may hold a count: let observedOtherTotalCount = 0; for ( - let i = 0; - i <= otherLastIndex; - i = otherHistogram.nextCountsIndexToScan(i) + let i = otherHistogram.nextNonZeroIndexInRange(0, otherLastIndex); + i >= 0; + i = otherHistogram.nextNonZeroIndexInRange(i + 1, otherLastIndex) ) { const otherCount = otherHistogram.getCountAtIndex(i); if (otherCount > 0) { @@ -1127,9 +1163,9 @@ export abstract class JsHistogram implements Histogram { this.setTotalCount(this.totalCount - observedOtherTotalCount); } else { for ( - let i = 0; - i <= otherLastIndex; - i = otherHistogram.nextCountsIndexToScan(i) + let i = otherHistogram.nextNonZeroIndexInRange(0, otherLastIndex); + i >= 0; + i = otherHistogram.nextNonZeroIndexInRange(i + 1, otherLastIndex) ) { const otherCount = otherHistogram.getCountAtIndex(i); if (otherCount > 0) { @@ -1165,7 +1201,11 @@ export abstract class JsHistogram implements Histogram { let maxIndex = -1; let minNonZeroIndex = -1; let observedTotalCount = 0; - for (let index = 0; index < lengthToCover; index++) { + for ( + let index = this.nextNonZeroIndex(0); + index >= 0 && index < lengthToCover; + index = this.nextNonZeroIndex(index + 1) + ) { const countAtIndex = this.getCountAtIndex(index); if (countAtIndex > 0) { observedTotalCount += countAtIndex; diff --git a/src/PackedHistogram.spec.ts b/src/PackedHistogram.spec.ts index 7400f63..1f5fedc 100644 --- a/src/PackedHistogram.spec.ts +++ b/src/PackedHistogram.spec.ts @@ -1,5 +1,200 @@ import Histogram from "./PackedHistogram"; import Float64Histogram from "./Float64Histogram"; +import Int32Histogram from "./Int32Histogram"; +import { build } from "./index"; +import { initWebAssembly } from "./wasm"; + +// A few hundred values spread over the whole range: most of the counts array +// is empty, which is what the packed representation is made for. +const sparseValues = (count: number, seed: number) => { + const values: number[] = []; + let state = seed; + for (let i = 0; i < count; i++) { + state = (state * 1664525 + 1013904223) % 4294967296; + values.push(1 + Math.floor((state / 4294967296) * 2 ** 52)); + } + return values; +}; + +const PERCENTILES = [0, 1, 25, 50, 75, 90, 99, 99.9, 99.99, 100]; + +describe("Sparse packed histogram vs its flat counterpart", () => { + const buildPair = (values: number[]) => { + const packed = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); + const flat = new Int32Histogram(1, Number.MAX_SAFE_INTEGER, 3); + values.forEach((value) => { + packed.recordValue(value); + flat.recordValue(value); + }); + return { packed, flat }; + }; + + const expectSameStatistics = (packed: Histogram, flat: Int32Histogram) => { + expect(packed.totalCount).toBe(flat.totalCount); + expect(packed.maxValue).toBe(flat.maxValue); + expect(packed.minNonZeroValue).toBe(flat.minNonZeroValue); + PERCENTILES.forEach((percentile) => { + expect(packed.getValueAtPercentile(percentile)).toBe( + flat.getValueAtPercentile(percentile) + ); + }); + }; + + it("should compute the same percentiles", () => { + // given + const values = sparseValues(300, 1); + // when + const { packed, flat } = buildPair(values); + // then + expectSameStatistics(packed, flat); + }); + + it("should compute the same percentiles with counts spanning several bytes", () => { + // given + const packed = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); + const flat = new Float64Histogram(1, Number.MAX_SAFE_INTEGER, 3); + sparseValues(50, 2).forEach((value) => { + packed.recordValue(value); + flat.recordValue(value); + }); + // when + [256, 65536, 2 ** 24, 2 ** 32].forEach((count, i) => { + packed.recordValueWithCount(1000 * (i + 1), count); + flat.recordValueWithCount(1000 * (i + 1), count); + }); + // then + expect(packed.totalCount).toBe(flat.totalCount); + PERCENTILES.forEach((percentile) => { + expect(packed.getValueAtPercentile(percentile)).toBe( + flat.getValueAtPercentile(percentile) + ); + }); + }); + + it("should encode to the same bytes", async () => { + // given + const { packed, flat } = buildPair(sparseValues(300, 3)); + // when + const packedEncoded = await packed.encodeIntoCompressedBase64(); + const flatEncoded = await flat.encodeIntoCompressedBase64(); + // then + expect(packedEncoded).toBe(flatEncoded); + }); + + it("should encode to the same bytes once counts were set back to zero", async () => { + // given + const { packed, flat } = buildPair(sparseValues(300, 4)); + const removed = sparseValues(300, 4).filter((_, i) => i % 3 === 0); + const other = buildPair(removed); + // when + packed.subtract(other.packed); + flat.subtract(other.flat); + // then + expectSameStatistics(packed, flat); + expect(await packed.encodeIntoCompressedBase64()).toBe( + await flat.encodeIntoCompressedBase64() + ); + }); + + it("should add and subtract like its flat counterpart", () => { + // given + const { packed, flat } = buildPair(sparseValues(300, 5)); + const other = buildPair(sparseValues(200, 6)); + // the other max above this one's max: it becomes the max, then gets removed + other.packed.recordValue(2 ** 52 + 12345); + other.flat.recordValue(2 ** 52 + 12345); + // when + packed.add(other.packed); + flat.add(other.flat); + // then + expectSameStatistics(packed, flat); + // when + packed.subtract(other.packed); + flat.subtract(other.flat); + // then + expectSameStatistics(packed, flat); + }); + + it("should add histograms of different layouts like its flat counterpart", () => { + // given + const { packed, flat } = buildPair(sparseValues(300, 7)); + const otherPacked = new Histogram(1, Number.MAX_SAFE_INTEGER, 2); + const otherFlat = new Int32Histogram(1, Number.MAX_SAFE_INTEGER, 2); + sparseValues(200, 8).forEach((value) => { + otherPacked.recordValue(value); + otherFlat.recordValue(value); + }); + // when + packed.add(otherPacked); + flat.add(otherFlat); + // then + expectSameStatistics(packed, flat); + // when + flat.add(otherPacked); // a packed source into a flat destination + packed.add(otherFlat); + // then + expectSameStatistics(packed, flat); + }); + + it("should re-establish tracking values after a reset and a resize", () => { + // given + const packed = new Histogram(1, 2, 3); + const flat = new Int32Histogram(1, 2, 3); + packed.autoResize = true; + flat.autoResize = true; + // when + sparseValues(100, 9).forEach((value) => { + packed.recordValue(value); + flat.recordValue(value); + }); + // then + expectSameStatistics(packed, flat); + // given + packed.reset(); + flat.reset(); + // when + sparseValues(100, 10).forEach((value) => { + packed.recordValue(value); + flat.recordValue(value); + }); + // then + expectSameStatistics(packed, flat); + }); +}); + +describe("Sparse WASM packed histogram vs the JS one", () => { + beforeAll(() => initWebAssembly()); + + it("should compute the same percentiles and encode to the same bytes", async () => { + // given + const values = sparseValues(300, 11); + const wasmPacked = build({ + useWebAssembly: true, + bitBucketSize: "packed", + highestTrackableValue: Number.MAX_SAFE_INTEGER, + autoResize: false, + }); + const packed = new Histogram(1, Number.MAX_SAFE_INTEGER, 3); + // when + values.forEach((value) => { + wasmPacked.recordValue(value); + packed.recordValue(value); + }); + // then + try { + PERCENTILES.forEach((percentile) => { + expect(wasmPacked.getValueAtPercentile(percentile)).toBe( + packed.getValueAtPercentile(percentile) + ); + }); + expect(await wasmPacked.encodeIntoCompressedBase64()).toBe( + await packed.encodeIntoCompressedBase64() + ); + } finally { + wasmPacked.destroy(); + } + }); +}); describe("Packed histogram", () => { it("should compute median value in first bucket", () => { diff --git a/src/PackedHistogram.ts b/src/PackedHistogram.ts index b48ff87..6dea40a 100644 --- a/src/PackedHistogram.ts +++ b/src/PackedHistogram.ts @@ -7,6 +7,9 @@ */ 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

*

@@ -77,6 +80,49 @@ class PackedHistogram extends JsHistogram { return this.packedCounts.get(index); } + /** @internal */ + nextNonZeroIndex(fromIndex: number) { + return this.packedCounts.nextNonZeroIndex(fromIndex); + } + + /** + * Same contract as {@link JsHistogram#getValueAtPercentile}, accumulating + * only the populated indexes of the packed counts instead of scanning the + * 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 + ); + + let totalToCurrentIndex = 0; + for ( + let i = this.nextNonZeroIndex(0); + i >= 0; + i = this.nextNonZeroIndex(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 0; + } + protected _getEstimatedFootprintInBytes() { return 192 + 8 * this.packedCounts.getPhysicalLength(); } diff --git a/src/TypedArrayHistogram.ts b/src/TypedArrayHistogram.ts index abf6f34..64bbfae 100644 --- a/src/TypedArrayHistogram.ts +++ b/src/TypedArrayHistogram.ts @@ -37,6 +37,18 @@ class TypedArrayHistogram extends JsHistogram { this._counts.fill(0); } + /** @internal */ + nextNonZeroIndex(fromIndex: number) { + const counts = this._counts; + const length = this.countsArrayLength; + for (let i = fromIndex; i < length; i++) { + if (counts[i] !== 0) { + return i; + } + } + return -1; + } + incrementCountAtIndex(index: number) { const currentCount = this._counts[index]; const newCount = currentCount + 1; diff --git a/src/bench/histogram-sparse-packed.bench.ts b/src/bench/histogram-sparse-packed.bench.ts new file mode 100644 index 0000000..710c575 --- /dev/null +++ b/src/bench/histogram-sparse-packed.bench.ts @@ -0,0 +1,84 @@ +import { build, Histogram } from "../index"; +import { encodeIntoCompressedBase64 } from "../encoding"; +import { initWebAssembly } from "../wasm"; + +// A sparse histogram: a few hundred distinct values spread over a wide range, +// so that most of the counts array is empty. Scans over the counts array +// (percentiles, add, encoding) then cost far more than the recorded values +// warrant unless the packed representation skips its empty subtrees. +const RECORDED_VALUES = 300; +const values: number[] = []; +for (let i = 0; i < RECORDED_VALUES; i++) { + values.push(1 + Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)); +} + +const buildSparseHistogram = ( + bitBucketSize: 32 | "packed", + useWebAssembly: boolean +): Histogram => { + const histogram = build({ + bitBucketSize, + useWebAssembly, + autoResize: false, + highestTrackableValue: Number.MAX_SAFE_INTEGER, + numberOfSignificantValueDigits: 3, + }); + values.forEach((value) => histogram.recordValue(value)); + return histogram; +}; + +beforeAll(() => initWebAssembly()); + +test("Sparse histogram get value at percentile", async ({ bench }) => { + const int32 = buildSparseHistogram(32, false); + const packed = buildSparseHistogram("packed", false); + const wasmPacked = buildSparseHistogram("packed", true); + + await bench.compare( + bench("Int32Histogram", () => { + int32.getValueAtPercentile(99); + }), + bench("Packed Histogram", () => { + packed.getValueAtPercentile(99); + }), + bench("WASM Packed Histogram", () => { + wasmPacked.getValueAtPercentile(99); + }) + ); +}); + +// No WASM variant: the wasm module exports no addHistogramPackedto* entry +// point, so a WASM packed histogram cannot be added to another one yet. +test("Sparse histogram add", async ({ bench }) => { + const int32 = buildSparseHistogram(32, false); + const int32Other = buildSparseHistogram(32, false); + const packed = buildSparseHistogram("packed", false); + const packedOther = buildSparseHistogram("packed", false); + + await bench.compare( + bench("Int32Histogram", () => { + int32.add(int32Other); + }), + bench("Packed Histogram", () => { + packed.add(packedOther); + }) + ); +}); + +test("Sparse histogram encoding", async ({ bench }) => { + const int32 = buildSparseHistogram(32, false); + const packed = buildSparseHistogram("packed", false); + const wasmPacked = buildSparseHistogram("packed", true); + + await bench.compare( + bench("Int32Histogram", async () => { + await encodeIntoCompressedBase64(int32); + }), + bench("Packed Histogram", async () => { + await encodeIntoCompressedBase64(packed); + }), + bench("WASM Packed Histogram", async () => { + await encodeIntoCompressedBase64(wasmPacked); + }) + ); +}); diff --git a/src/packedarray/PackedArray.fc.spec.ts b/src/packedarray/PackedArray.fc.spec.ts index 2328e90..352f252 100644 --- a/src/packedarray/PackedArray.fc.spec.ts +++ b/src/packedarray/PackedArray.fc.spec.ts @@ -12,14 +12,14 @@ const runFromStryker = __dirname.includes("stryker"); const runnerOptions = { numRuns: runFromStryker ? 10 : 1000, - verbose: true + verbose: true, }; describe("Packed array", () => { it("should store data as a regular sparse array", () => { const SIZE = 1000; fc.assert( - fc.property(arbData(SIZE), entries => { + fc.property(arbData(SIZE), (entries) => { const packedArray = new PackedArray(SIZE + 1); const sparseArray = new Array(); entries.forEach(([index, value]) => packedArray.add(index, value)); @@ -39,6 +39,169 @@ describe("Packed array", () => { }); }); +describe("Packed array non-zero iteration", () => { + const bruteForceNext = (model: number[], fromIndex: number) => { + for (let i = fromIndex; i < model.length; i++) { + if (model[i] !== 0) return i; + } + return -1; + }; + + /** The walk from 0 visits exactly the non-zero indexes of the model, in order */ + const walkMatches = (packedArray: PackedArray, model: number[]) => { + const walked: number[] = []; + for ( + let i = packedArray.nextNonZeroIndex(0); + i >= 0; + i = packedArray.nextNonZeroIndex(i + 1) + ) { + walked.push(i); + } + const expected: number[] = []; + model.forEach((value, index) => { + if (value !== 0) expected.push(index); + }); + expect(walked).toEqual(expected); + }; + + /** nextNonZeroIndex agrees with a brute force scan from arbitrary start indexes */ + const lookupsMatch = ( + packedArray: PackedArray, + model: number[], + fromIndexes: number[] + ) => { + fromIndexes.forEach((fromIndex) => { + expect(packedArray.nextNonZeroIndex(fromIndex)).toBe( + bruteForceNext(model, fromIndex) + ); + }); + }; + + const arbFromIndexes = (size: number) => + fc.array(fc.integer({ min: 0, max: size + 10 }), { maxLength: 20 }); + + it("should visit the non-zero indexes of a sparse array", () => { + const SIZE = 100000; + fc.assert( + fc.property( + arbSparseData(SIZE, 300), + arbFromIndexes(SIZE), + (entries, fromIndexes) => { + const packedArray = new PackedArray(SIZE); + const model = new Array(SIZE).fill(0); + entries.forEach(([index, value]) => { + packedArray.add(index, value); + model[index] += value; + }); + walkMatches(packedArray, model); + lookupsMatch(packedArray, model, fromIndexes); + } + ), + runnerOptions + ); + }); + + it("should visit the non-zero indexes of a dense array", () => { + const SIZE = 2048; + fc.assert( + fc.property( + fc.array(fc.integer({ min: 0, max: 0x1ffff }), { + minLength: SIZE, + maxLength: SIZE, + }), + arbFromIndexes(SIZE), + (values, fromIndexes) => { + const packedArray = new PackedArray(SIZE); + values.forEach((value, index) => packedArray.set(index, value)); + walkMatches(packedArray, values); + lookupsMatch(packedArray, values, fromIndexes); + } + ), + { ...runnerOptions, numRuns: runFromStryker ? 5 : 100 } + ); + }); + + it("should skip values set back to zero", () => { + const SIZE = 50000; + fc.assert( + fc.property( + arbSparseData(SIZE, 200), + fc.array(fc.nat(199), { maxLength: 100 }), + (entries, zeroedPositions) => { + const packedArray = new PackedArray(SIZE); + const model = new Array(SIZE).fill(0); + entries.forEach(([index, value]) => { + packedArray.set(index, value); + model[index] = value; + }); + zeroedPositions.forEach((position) => { + if (position < entries.length) { + const [index] = entries[position]; + packedArray.set(index, 0); + model[index] = 0; + } + }); + walkMatches(packedArray, model); + } + ), + runnerOptions + ); + }); + + it("should keep walking after the virtual length grows", () => { + fc.assert( + fc.property( + arbSparseData(500, 50), + arbSparseData(100000, 100), + (entriesBefore, entriesAfter) => { + const packedArray = new PackedArray(501); + const model = new Array(100001).fill(0); + entriesBefore.forEach(([index, value]) => { + packedArray.add(index, value); + model[index] += value; + }); + packedArray.setVirtualLength(100001); + entriesAfter.forEach(([index, value]) => { + packedArray.add(index, value); + model[index] += value; + }); + walkMatches(packedArray, model); + } + ), + runnerOptions + ); + }); + + it("should scan linearly once the packed storage is full", () => { + // 64 bit values at every index outgrow the packed representation + const SIZE = 5000; + fc.assert( + fc.property( + fc.array(fc.boolean(), { minLength: SIZE, maxLength: SIZE }), + arbFromIndexes(SIZE), + (keep, fromIndexes) => { + const packedArray = new PackedArray(SIZE); + const model = new Array(SIZE).fill(0); + for (let index = 0; index < SIZE; index++) { + packedArray.set(index, Number.MAX_SAFE_INTEGER - index); + } + expect(packedArray.getPhysicalLength()).toBe(SIZE); // unpacked + keep.forEach((isKept, index) => { + if (isKept) { + model[index] = Number.MAX_SAFE_INTEGER - index; + } else { + packedArray.set(index, 0); + } + }); + walkMatches(packedArray, model); + lookupsMatch(packedArray, model, fromIndexes); + } + ), + { ...runnerOptions, numRuns: runFromStryker ? 3 : 20 } + ); + }); +}); + describe("Packed array leaf cache", () => { it("should match a plain array under interleaved operations within a few groups", () => { // 4 groups of 8 indexes: most operations hit the cached group, with @@ -149,3 +312,18 @@ const arbOperations = (size: number) => { { minLength: 1, maxLength: 200 } ); }; + +/** Up to maxEntries (index, value) pairs over [0, size), values spanning several bytes */ +const arbSparseData = (size: number, maxEntries: number) => + fc.array( + fc.tuple( + fc.integer({ min: 0, max: size - 1 }), + fc.oneof( + fc.integer({ min: 1, max: 255 }), + fc.integer({ min: 256, max: 0xffffff }), + fc.constant(256), + fc.constant(0x10000) + ) + ), + { maxLength: maxEntries } + ); diff --git a/src/packedarray/PackedArray.ts b/src/packedarray/PackedArray.ts index 631edcb..8d2b63d 100644 --- a/src/packedarray/PackedArray.ts +++ b/src/packedarray/PackedArray.ts @@ -7,7 +7,7 @@ */ import { PackedArrayContext, - MINIMUM_INITIAL_PACKED_ARRAY_CAPACITY + MINIMUM_INITIAL_PACKED_ARRAY_CAPACITY, } from "./PackedArrayContext"; const NUMBER_OF_SETS = 8; @@ -276,6 +276,42 @@ export class PackedArray { } } + /** + * Lowest index >= fromIndex holding a non-zero value, or -1 when there is none. + * + * On a packed context the set-0 tree is walked to skip the groups of 8 + * indexes that were never populated, so a scan over the whole array costs + * time proportional to the populated groups rather than to the virtual + * length. An unpacked context is scanned linearly. + */ + nextNonZeroIndex(fromIndex: number): number { + const arrayContext = this.arrayContext; + const length = arrayContext.getVirtualLength(); + let index = fromIndex; + if (!arrayContext.isPacked) { + for (; index < length; index++) { + if (arrayContext.getAtUnpackedIndex(index) !== 0) { + return index; + } + } + return -1; + } + while (index < length) { + index = arrayContext.nextIndexWithLeaf(index); + if (index < 0) { + return -1; + } + // The leaf found only vouches for the group of 8 indexes holding index + const groupEnd = Math.min((index | 0x7) + 1, length); + for (; index < groupEnd; index++) { + if (this.get(index) !== 0) { + return index; + } + } + } + return -1; + } + /** * Move the contents to a new unpacked context of the given virtual length, * once the packed representation cannot grow any further diff --git a/src/packedarray/PackedArrayContext.ts b/src/packedarray/PackedArrayContext.ts index 7c3535f..6330b23 100644 --- a/src/packedarray/PackedArrayContext.ts +++ b/src/packedarray/PackedArrayContext.ts @@ -269,9 +269,8 @@ export class PackedArrayContext { * @param previousVersionIndex the index of the previous version of the entry */ private consolidateEntry(entryIndex: number, previousVersionIndex: number) { - const previousVersionPackedSlotsIndicators = this.getPackedSlotIndicators( - previousVersionIndex - ); + const previousVersionPackedSlotsIndicators = + this.getPackedSlotIndicators(previousVersionIndex); // Previous version exists, needs consolidation const packedSlotsIndicators = this.getPackedSlotIndicators(entryIndex); @@ -478,6 +477,82 @@ export class PackedArrayContext { return byteIndex; } + /** + * Lowest virtual index >= fromIndex whose group of 8 indexes has a leaf in + * set 0, i.e. whose values may be non-zero. Groups without a leaf are all + * zeros and are skipped by descending only into the populated slots of + * the set-0 tree, so the walk costs time proportional to the populated + * groups rather than to the virtual length. + * + * Sets are populated in order 0..7 (see PackedArray set/add), so a group + * with a leaf in any set has one in set 0: the set-0 tree covers every + * group that may hold a non-zero value. The converse does not hold (a leaf + * may be all zeros, or hold a byte 0 of 0 under a non-zero byte 1), so the + * caller still has to read the values of the group returned. + * + * @return the index, which may exceed the virtual length when the last + * group is partial, or -1 when no group at or after fromIndex has a leaf + */ + nextIndexWithLeaf(fromIndex: number): number { + if (fromIndex >= this.virtualLength) { + return -1; + } + const rootEntryIndex = this.getIndexAtShortIndex(SET_0_START_INDEX); + if (rootEntryIndex === 0) { + return -1; // Set 0 has no tree at all: nothing was ever stored + } + return this.nextIndexWithLeafBelow( + rootEntryIndex, + this.topLevelShift, + fromIndex + ); + } + + /** + * Walk the entry at entryIndex, which decodes the 4 index bits above + * indexShift, for the lowest index >= fromIndex with a leaf below it. + * fromIndex lies in the index range covered by the entry. + */ + private nextIndexWithLeafBelow( + entryIndex: number, + indexShift: number, + fromIndex: number + ): number { + const packedSlotIndicators = this.getPackedSlotIndicators(entryIndex); + // The indexes covered by this entry share the bits above the ones its slots decode + const entryBase = fromIndex & ~((1 << (indexShift + 4)) - 1); + const nextLevelIsLeaf = indexShift === LEAF_LEVEL_SHIFT; + for ( + let slotBitNumber = (fromIndex >>> indexShift) & 0xf; + slotBitNumber < 16; + slotBitNumber++ + ) { + const slotMask = 1 << slotBitNumber; + if ((packedSlotIndicators & slotMask) === 0) { + continue; // nothing was ever stored under this slot + } + const slotStart = entryBase | (slotBitNumber << indexShift); + // Past the slot holding fromIndex, resume from the start of each slot + const from = slotStart > fromIndex ? slotStart : fromIndex; + if (nextLevelIsLeaf) { + return from; + } + const slotNumber = bitCount32(packedSlotIndicators & (slotMask - 1)); + const nextLevelEntryIndex = this.getIndexAtShortIndex( + entryIndex + NON_LEAF_ENTRY_HEADER_SIZE_IN_SHORTS + slotNumber + ); + const found = this.nextIndexWithLeafBelow( + nextLevelEntryIndex, + indexShift - 4, + from + ); + if (found >= 0) { + return found; + } + } + return -1; + } + determineTopLevelShiftForVirtualLength(virtualLength: number) { const sizeMagnitude = ceil(log2(virtualLength)); const eightsSizeMagnitude = sizeMagnitude - 3; @@ -493,9 +568,8 @@ export class PackedArrayContext { "Should never be adjusting the virtual size of a non-packed context" ); } - this.topLevelShift = this.determineTopLevelShiftForVirtualLength( - virtualLength - ); + this.topLevelShift = + this.determineTopLevelShiftForVirtualLength(virtualLength); this.virtualLength = virtualLength; } @@ -561,9 +635,8 @@ export class PackedArrayContext { otherIndexShift: number ) { const nextLevelIsLeaf = otherIndexShift == LEAF_LEVEL_SHIFT; - const packedSlotIndicators = other.getPackedSlotIndicators( - otherLevelEntryIndex - ); + const packedSlotIndicators = + other.getPackedSlotIndicators(otherLevelEntryIndex); const numberOfSlots = bitCount(packedSlotIndicators); const sizeOfEntry = NON_LEAF_ENTRY_HEADER_SIZE_IN_SHORTS + numberOfSlots; const entryIndex = this.newEntry(sizeOfEntry); @@ -720,7 +793,5 @@ export class PackedArrayContext { } const toHex = (n: number) => { - return Number(n) - .toString(16) - .padStart(2, "0"); + return Number(n).toString(16).padStart(2, "0"); };