diff --git a/assembly/__tests__/PackedArrayWideLeaves.test.ts b/assembly/__tests__/PackedArrayWideLeaves.test.ts new file mode 100644 index 0000000..ca3a5ae --- /dev/null +++ b/assembly/__tests__/PackedArrayWideLeaves.test.ts @@ -0,0 +1,203 @@ +/* + * This is a AssemblyScript 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 { describe, test, expect } from "assemblyscript-unittest-framework/assembly"; +import { PackedArray } from "../packedarray/PackedArray"; +import { WIDE_SET_0_LEAVES_MAX_VIRTUAL_LENGTH } from "../packedarray/PackedArrayContext"; + +// Set 0 of a packed array uses 16 byte leaves: these tests cover the resize, sharing, +// fallback and random paths that the wider leaves change. +describe("Packed Array with 16 byte leaves for set 0", () => { + test("should keep values when a resize changes the depth of the set trees", () => { + // given: the set 0 tree gets one more level past 2^12, the others past 2^10 + const array = new PackedArray(1000, 16); + array.set(0, 1); + array.set(17, 300); + array.set(255, 70000); + array.set(700, 1099511627781); + array.set(999, 42); + + // when + array.setVirtualLength(8192); + array.set(8000, 5); + + // then + expect(array.get(0)).equal(1); + expect(array.get(17)).equal(300); + expect(array.get(255)).equal(70000); + expect(array.get(700)).equal(1099511627781); + expect(array.get(999)).equal(42); + expect(array.get(8000)).equal(5); + expect(array.get(4096)).equal(0); + }); + + test("should share one leaf between the indexes of a 16 index block", () => { + // given + const array = new PackedArray(1024, 16); + array.set(16, 1); + const physicalLength = array.getPhysicalLength(); + + // when: the other 15 indexes of the block are written, in both 8 index groups + for (let index = 17; index < 32; index++) { + array.set(index, index); + } + + // then + expect(array.getPhysicalLength()).equal(physicalLength); + expect(array.get(16)).equal(1); + for (let index = 17; index < 32; index++) { + expect(array.get(index)).equal(index); + } + }); + + test("should keep set 0 coherent when alternating between the two groups of a 16 index block", () => { + // given: group 0 is cached with no leaf, then group 1 of the same block gets one + const array = new PackedArray(1024, 16); + expect(array.get(3)).equal(0); + array.set(9, 5); + + // when / then: back to group 0 of the block, which now shares the leaf + expect(array.get(3)).equal(0); + expect(array.get(9)).equal(5); + array.add(2, 7); + expect(array.get(2)).equal(7); + expect(array.get(9)).equal(5); + array.set(1, 0); + expect(array.get(1)).equal(0); + }); + + test("should keep values once the packed storage falls back to unpacked", () => { + // given: isolated values, one leaf each, until the 16 bit addresses run out + const length: i32 = 1 << 16; + const array = new PackedArray(length, 16); + const plain = new Array(length); + for (let i = 0; i < length; i++) plain[i] = 0; + for (let i = 0; i < 20000 && array.getPhysicalLength() <= 8191; i++) { + const index = (i * 7919) % length; + array.add(index, (i + 1)); + plain[index] += (i + 1); + } + + // then + expect(array.getPhysicalLength() > 8191).equal(true); + for (let index = 0; index < length; index++) { + expect(array.get(index)).equal(plain[index]); + } + }); + + test("should match a plain array across the depth thresholds of the set trees", () => { + const lengths: i32[] = [1000, 4096, 4097, 8192, 8193, 40000]; + let seed: u32 = 2024; + for (let l = 0; l < lengths.length; l++) { + const length = lengths[l]; + // given + const array = new PackedArray(length, 16); + const plain = new Array(length); + for (let i = 0; i < length; i++) plain[i] = 0; + + // when: a hot band, isolated values, carries into the next sets + for (let k = 0; k < 20000; k++) { + seed = seed * 1664525 + 1013904223; + const hot = (seed >>> 8) % 2 == 0; + seed = seed * 1664525 + 1013904223; + const index = hot + ? min(length - 1, 100 + ((seed >>> 8) % 40)) + : ((seed >>> 8) % length); + seed = seed * 1664525 + 1013904223; + const value: u64 = (seed >>> 8) % 5 == 0 ? 250 + ((seed >>> 8) % 10) : 1; + array.add(index, value); + plain[index] += value; + } + + // then + for (let index = 0; index < length; index++) { + expect(array.get(index)).equal(plain[index]); + } + } + }); +}); + +// Set 0 leaves are 16 bytes up to WIDE_SET_0_LEAVES_MAX_VIRTUAL_LENGTH, and 8 bytes above it: +// a resize across that threshold changes the layout of set 0. +describe("Packed Array across the wide set 0 threshold", () => { + const WIDE_MAX: i32 = WIDE_SET_0_LEAVES_MAX_VIRTUAL_LENGTH; + + test("should keep counts when a resize moves set 0 to 8 byte leaves", () => { + // given: values in both groups of a block, and at the last index of a wide length + const array = new PackedArray(WIDE_MAX, 16); + array.set(0, 1); + array.set(9, 300); + array.set(16, 7); + array.set(1000, 1099511627781); + array.set(WIDE_MAX - 1, 70000); + + // when + array.setVirtualLength(WIDE_MAX + 1); + + // then + expect(array.get(0)).equal(1); + expect(array.get(9)).equal(300); + expect(array.get(16)).equal(7); + expect(array.get(1000)).equal(1099511627781); + expect(array.get(WIDE_MAX - 1)).equal(70000); + expect(array.get(WIDE_MAX)).equal(0); + array.set(WIDE_MAX, 9); + expect(array.get(WIDE_MAX)).equal(9); + }); + + test("should keep a value whose low byte is zero across a resize over the threshold", () => { + // given: 256 only sets byte 1, the set 0 leaf exists with a zero byte + const array = new PackedArray(WIDE_MAX, 16); + array.set(0, 256); + + // when + array.setVirtualLength(WIDE_MAX + 1); + + // then + expect(array.get(0)).equal(256); + }); + + test("should keep the cached group coherent across a resize over the threshold", () => { + // given: group 2 is cached, with its set 0 leaf in the wide layout + const array = new PackedArray(WIDE_MAX, 16); + array.set(16, 5); + expect(array.get(17)).equal(0); + + // when + array.setVirtualLength(WIDE_MAX + 1); + + // then + expect(array.get(17)).equal(0); + array.set(17, 3); + expect(array.get(16)).equal(5); + expect(array.get(17)).equal(3); + expect(array.get(18)).equal(0); + expect(array.get(24)).equal(0); + }); + + test("should keep values when a resize follows a nearly full packed storage", () => { + // given: isolated values until the packed storage nearly runs out, at a wide length + const array = new PackedArray(WIDE_MAX, 16); + const indexes = new Array(); + const values = new Array(); + for (let i = 0; i < 20000 && array.getPhysicalLength() < 8000; i++) { + const index = (i * 7919) % WIDE_MAX; + array.add(index, (i + 1)); + indexes.push(index); + values.push((i + 1)); + } + + // when + array.setVirtualLength(WIDE_MAX + 1); + + // then: packed or unpacked, the values are kept + for (let i = 0; i < indexes.length; i++) { + expect(array.get(indexes[i])).equal(values[i]); + } + }); +}); diff --git a/assembly/packedarray/PackedArray.ts b/assembly/packedarray/PackedArray.ts index a80f0f6..2c25652 100644 --- a/assembly/packedarray/PackedArray.ts +++ b/assembly/packedarray/PackedArray.ts @@ -34,7 +34,9 @@ export class PackedArray { // Leaf cache for sequential reads and writes. // - // The 8 virtual indexes of a group (index >> 3) share one leaf per byte set, + // The 8 virtual indexes of a group (index >> 3) share one leaf per byte set + // (set 0 leaves are 16 bytes when the virtual length allows it and then cover two groups; + // the cache still holds one group), // so a scan over consecutive indexes would otherwise repeat the same set-tree // walks 8 times. For the group last accessed, leafIndexBySet[0 .. knownSets) // holds the long index of each set's leaf, or NO_LEAF when the set has no @@ -86,19 +88,21 @@ export class PackedArray { this.unpack(newVirtualArrayLength); return; } - if ( - currentArrayContext.determineTopLevelShiftForVirtualLength( - newVirtualArrayLength - ) == currentArrayContext.getTopLevelShift() - ) { + if (currentArrayContext.hasLayoutFor(newVirtualArrayLength)) { // No changes to the array context contents is needed. Just change the virtual length. currentArrayContext.setVirtualLength(newVirtualArrayLength); return; } - this.arrayContext = currentArrayContext.copyAndIncreaseSize( + const resizedArrayContext = currentArrayContext.copyAndIncreaseSize( this.getPhysicalLength(), newVirtualArrayLength ); + if (resizedArrayContext === null) { + // The packed storage cannot hold the layout of the new virtual length + this.unpack(newVirtualArrayLength); + return; + } + this.arrayContext = resizedArrayContext; } @operator("[]") private __get(index: i32): u64 { @@ -123,9 +127,9 @@ export class PackedArray { // Context is packed: this.cacheGroupOf(index); const leafIndexBySet = this.leafIndexBySet; - const byteInLeaf = index & 0x7; let value: u64 = 0; for (let byteNum = 0; byteNum < NUMBER_OF_SETS; byteNum++) { + const byteInLeaf = index & arrayContext.leafByteMaskBySet[byteNum]; let leafIndex = byteNum < this.knownSets ? unchecked(leafIndexBySet[byteNum]) @@ -142,7 +146,7 @@ export class PackedArray { unchecked((leafIndexBySet[byteNum] = NO_LEAF)); break; } - leafIndex = packedIndex >> 3; + leafIndex = (packedIndex - byteInLeaf) >> 3; unchecked((leafIndexBySet[byteNum] = leafIndex)); } value |= @@ -158,18 +162,23 @@ export class PackedArray { */ @inline private cacheGroupOf(index: i32): void { - const group = index >> 3; - if (group != this.cachedGroup) { - // No set is known after a miss, so every access walks set 0 first, and - // getPackedIndex() checks the virtualLength bound there. - this.cachedGroup = group; - this.knownSets = 0; - } else if (index >= this.arrayContext.getVirtualLength()) { - // A hit skips the walk, and the last group may be partly beyond the bound + // The last group may be partly beyond the bound, and a hit skips the walk + if (index >= this.arrayContext.getVirtualLength()) { throw new Error( `Attempting access at index ${index}, beyond virtualLength ${this.arrayContext.getVirtualLength()}` ); } + const group = index >> 3; + if (group != this.cachedGroup) { + // Wide set 0 leaves cover 16 indexes, two groups: its entry stays valid when the + // new group is in the same block. Any other set walks again. + this.knownSets = + group >> 1 == this.cachedGroup >> 1 && + this.arrayContext.hasWideSet0Leaves() + ? min(this.knownSets, 1) + : 0; + this.cachedGroup = group; + } } /** @@ -195,9 +204,9 @@ export class PackedArray { // Context is packed: this.cacheGroupOf(index); const leafIndexBySet = this.leafIndexBySet; - const byteInLeaf = index & 0x7; let remainingValueToAdd = value; for (let byteNum = 0; byteNum < NUMBER_OF_SETS; byteNum++) { + const byteInLeaf = index & arrayContext.leafByteMaskBySet[byteNum]; let leafIndex = byteNum < this.knownSets ? unchecked(leafIndexBySet[byteNum]) @@ -214,7 +223,7 @@ export class PackedArray { ); return; } - leafIndex = packedIndex >> 3; + leafIndex = (packedIndex - byteInLeaf) >> 3; unchecked((leafIndexBySet[byteNum] = leafIndex)); // A known NO_LEAF is always the last known set (get() and a zero set() // stop there), so this never shrinks the prefix. @@ -252,9 +261,9 @@ export class PackedArray { // Context is packed: this.cacheGroupOf(index); const leafIndexBySet = this.leafIndexBySet; - const byteInLeaf = index & 0x7; let valueForNextLevels = value; for (let byteNum = 0; byteNum < NUMBER_OF_SETS; byteNum++) { + const byteInLeaf = index & arrayContext.leafByteMaskBySet[byteNum]; let leafIndex = byteNum < this.knownSets ? unchecked(leafIndexBySet[byteNum]) @@ -282,7 +291,7 @@ export class PackedArray { return; } } - leafIndex = packedIndex >> 3; + leafIndex = (packedIndex - byteInLeaf) >> 3; unchecked((leafIndexBySet[byteNum] = leafIndex)); // A known NO_LEAF is always the last known set (get() and a zero set() // stop there), so this never shrinks the prefix. @@ -300,8 +309,8 @@ 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 + * On a packed context the set-0 tree is walked to skip the groups of + * indexes (one set-0 leaf each) 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. */ @@ -322,8 +331,11 @@ export class PackedArray { 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); + // The leaf found only vouches for the group of indexes sharing its set-0 leaf + const groupEnd = min( + (index | arrayContext.leafByteMaskBySet[0]) + 1, + length + ); for (; index < groupEnd; index++) { if (this.get(index) != 0) { return index; diff --git a/assembly/packedarray/PackedArrayContext.ts b/assembly/packedarray/PackedArrayContext.ts index 8e32fd8..afc14a6 100644 --- a/assembly/packedarray/PackedArrayContext.ts +++ b/assembly/packedarray/PackedArrayContext.ts @@ -30,7 +30,22 @@ export const MAX_SUPPORTED_PACKED_COUNTS_ARRAY_LENGTH: i32 = 8191; const SET_0_START_INDEX = 0; const NUMBER_OF_SETS = 8; - const LEAF_LEVEL_SHIFT = 3; + // A leaf of a set covers the 2^leafLevelShift virtual indexes sharing their high bits. + // Set 0 is the dense byte (most recorded values only use it), so its leaves can be 16 bytes wide: + // the set tree is one level shallower for some virtual lengths, and a 16 index block shares one + // leaf. A populated leaf costs its whole width, though: a lone value costs 16 bytes instead of 8, + // which fills the 16 bit packed addresses sooner for large sparse arrays. So the wide leaves are + // only used up to WIDE_SET_0_LEAVES_MAX_VIRTUAL_LENGTH, and the other sets keep 8 bytes. + const LEAF_LEVEL_SHIFT: i32 = 3; + const WIDE_SET_0_LEAF_LEVEL_SHIFT: i32 = 4; + export const WIDE_SET_0_LEAVES_MAX_VIRTUAL_LENGTH: i32 = 1 << 15; + + /** @return the leaf level shift of a set, for a virtual length */ + function leafLevelShiftFor(setNumber: i32, virtualLength: i32): i32 { + return setNumber == 0 && virtualLength <= WIDE_SET_0_LEAVES_MAX_VIRTUAL_LENGTH + ? WIDE_SET_0_LEAF_LEVEL_SHIFT + : LEAF_LEVEL_SHIFT; + } const NON_LEAF_ENTRY_SLOT_INDICATORS_OFFSET = 0; const NON_LEAF_ENTRY_HEADER_SIZE_IN_SHORTS = 1; const PACKED_ARRAY_GROWTH_INCREMENT = 16; @@ -52,8 +67,22 @@ private dataStart: usize = 0; private populatedShortLength: i32 = 0; private virtualLength: i32; - private topLevelShift: i32 = i32.MAX_VALUE; // Make it non-sensical until properly initialized. - + // Per set, make it non-sensical until properly initialized. + private topLevelShiftBySet: StaticArray = new StaticArray( + NUMBER_OF_SETS + ).fill(i32.MAX_VALUE); + // Per set layout of the leaves, for the virtual length of this context + private leafLevelShiftBySet: StaticArray = new StaticArray( + NUMBER_OF_SETS + ).fill(LEAF_LEVEL_SHIFT); + /** Mask of the virtual index bits selecting the byte within a leaf, per set */ + public leafByteMaskBySet: StaticArray = new StaticArray( + NUMBER_OF_SETS + ).fill((1 << LEAF_LEVEL_SHIFT) - 1); + private leafLengthInLongsBySet: StaticArray = new StaticArray( + NUMBER_OF_SETS + ).fill(1); + constructor(virtualLength: i32, initialPhysicalLength: i32) { this.physicalLength = ( Math.max(initialPhysicalLength, MINIMUM_INITIAL_PACKED_ARRAY_CAPACITY) @@ -105,16 +134,24 @@ ); } + /** + * @return a context of the new virtual length holding the same values, or null if the packed + * storage cannot hold them (the caller then moves to an unpacked context) + */ public copyAndIncreaseSize( newPhysicalArrayLength: i32, newVirtualArrayLength: i32 - ): PackedArrayContext { + ): PackedArrayContext | null { const ctx = new PackedArrayContext( newVirtualArrayLength, newPhysicalArrayLength ); - ctx.populateEquivalentEntriesWithEntriesFromOther(this); - return ctx; + return ctx.populateEquivalentEntriesWithEntriesFromOther(this) ? ctx : null; + } + + /** @return whether set 0 leaves cover two 8 index groups (16 bytes), so a group shares them */ + public hasWideSet0Leaves(): boolean { + return this.leafLevelShiftBySet[0] == WIDE_SET_0_LEAF_LEVEL_SHIFT; } public getPopulatedShortLength(): i32 { @@ -245,18 +282,23 @@ return newEntryIndex; } - /** @return the long index of the new leaf, or -1 if the array is full */ - private newLeafEntry(): i32 { + /** + * @param lengthInLongs the length of the leaf, 1 for an 8 byte leaf + * @return the long index of the new leaf, or -1 if the array is full + */ + private newLeafEntry(lengthInLongs: i32): i32 { // Add entry at the end of the array: let newEntryIndex = this.getPopulatedLongLength(); - if (!this.expandArrayIfNeeded(1)) { + if (!this.expandArrayIfNeeded(lengthInLongs)) { return -1; } - this.setPopulatedLongLength(newEntryIndex + 1); - - this.setAtLongIndex(newEntryIndex, 0); - + this.setPopulatedLongLength(newEntryIndex + lengthInLongs); + + for (let i = 0; i < lengthInLongs; i++) { + this.setAtLongIndex(newEntryIndex + i, 0); + } + return newEntryIndex; } @@ -308,6 +350,7 @@ * @param insertedSlotIndex realtive [packed] index of slot being inserted into entry * @param insertedSlotMask mask value fo slot being inserted * @param nextLevelIsLeaf the level below this one is a leaf level + * @param leafLengthInLongs the length of the leaves, when the level below is a leaf level * @return the updated index of the entry, or -1 if the array is full (the entry is then left untouched) */ expandEntry( @@ -315,7 +358,8 @@ entryPointerIndex: i32, insertedSlotIndex: i32, insertedSlotMask: i32, - nextLevelIsLeaf: boolean + nextLevelIsLeaf: boolean, + leafLengthInLongs: i32 ): i32 { let packedSlotIndicators = (this.getAtShortIndex(existingEntryIndex)) & 0xffff; @@ -334,7 +378,7 @@ // Create new next-level entry to refer to from slot at this level: let indexOfNewNextLevelEntry = 0; if (nextLevelIsLeaf) { - indexOfNewNextLevelEntry = this.newLeafEntry(); // Establish long-index to new leaf entry + indexOfNewNextLevelEntry = this.newLeafEntry(leafLengthInLongs); // Establish long-index to new leaf entry if (indexOfNewNextLevelEntry < 0) { return -1; } @@ -435,12 +479,14 @@ } // Work down the levels of non-leaf entries: + const leafLevelShift = this.leafLevelShiftBySet[setNumber]; + const leafLengthInLongs = this.leafLengthInLongsBySet[setNumber]; for ( - let indexShift = this.topLevelShift; - indexShift >= LEAF_LEVEL_SHIFT; + let indexShift = this.topLevelShiftBySet[setNumber]; + indexShift >= leafLevelShift; indexShift -= 4 ) { - const nextLevelIsLeaf = indexShift === LEAF_LEVEL_SHIFT; + const nextLevelIsLeaf = indexShift === leafLevelShift; // Target is a packedSlotIndicators entry const packedSlotIndicators = this.getPackedSlotIndicators(entryIndex); const slotBitNumber = (virtualIndex >>> indexShift) & 0xf; @@ -460,7 +506,8 @@ entryPointerIndex, slotNumber, slotMask, - nextLevelIsLeaf + nextLevelIsLeaf, + leafLengthInLongs ); if (entryIndex < 0) { return -1; // The array is full, the index cannot be added @@ -476,13 +523,15 @@ // entryIndex is the long-index of a leaf entry that contains the value byte for the given set - const byteIndex = (entryIndex << 3) + (virtualIndex & 0x7); // Determine byte index offset within leaf entry + // Byte index offset within leaf entry, the leaf entry being the long index + const byteIndex = + (entryIndex << 3) + (virtualIndex & this.leafByteMaskBySet[setNumber]); 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 + * Lowest virtual index >= fromIndex whose group of indexes (the ones sharing + * a set-0 leaf) 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. @@ -506,7 +555,7 @@ } return this.nextIndexWithLeafBelow( rootEntryIndex, - this.topLevelShift, + this.topLevelShiftBySet[0], fromIndex ); } @@ -524,7 +573,7 @@ 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; + const nextLevelIsLeaf = indexShift == this.leafLevelShiftBySet[0]; for ( let slotBitNumber = (fromIndex >>> indexShift) & 0xf; slotBitNumber < 16; @@ -558,31 +607,59 @@ return -1; } - determineTopLevelShiftForVirtualLength(virtualLength: i32): i32 { + /** + * The top level shift of the set tree of the given set, for a virtual length: the levels of + * non-leaf entries are at shifts leafLevelShift, leafLevelShift + 4, ..., top, and the top + * level must cover the most significant bit of the virtual length, with at least two levels. + */ + determineTopLevelShiftForVirtualLength( + virtualLength: i32, + setNumber: i32 = 1 + ): i32 { + const leafLevelShift = leafLevelShiftFor(setNumber, virtualLength); const sizeMagnitude = ceil(Math.log2(virtualLength)); - const eightsSizeMagnitude = sizeMagnitude - 3; - let multipleOfFourSizeMagnitude = - ceil(eightsSizeMagnitude / 4.0) * 4; - multipleOfFourSizeMagnitude = max(multipleOfFourSizeMagnitude, 8); - const topLevelShiftNeeded = multipleOfFourSizeMagnitude - 4 + 3; - return topLevelShiftNeeded; + const levelsAboveTheFirst = max( + ceil((sizeMagnitude - leafLevelShift - 4) / 4.0), + 1 + ); + return leafLevelShift + 4 * levelsAboveTheFirst; } - + + /** @return whether the set trees of this context are laid out for the given virtual length */ + hasLayoutFor(virtualLength: i32): boolean { + for (let setNumber = 0; setNumber < NUMBER_OF_SETS; setNumber++) { + if ( + leafLevelShiftFor(setNumber, virtualLength) !== + this.leafLevelShiftBySet[setNumber] || + this.determineTopLevelShiftForVirtualLength(virtualLength, setNumber) !== + this.topLevelShiftBySet[setNumber] + ) { + return false; + } + } + return true; + } + setVirtualLength(virtualLength: i32): void { if (!this.isPacked) { throw new Error( "Should never be adjusting the virtual size of a non-packed context" ); } - this.topLevelShift = this.determineTopLevelShiftForVirtualLength( - virtualLength - ); + for (let setNumber = 0; setNumber < NUMBER_OF_SETS; setNumber++) { + const leafLevelShift = leafLevelShiftFor(setNumber, virtualLength); + this.leafLevelShiftBySet[setNumber] = leafLevelShift; + this.leafByteMaskBySet[setNumber] = (1 << leafLevelShift) - 1; + this.leafLengthInLongsBySet[setNumber] = + 1 << (leafLevelShift - LEAF_LEVEL_SHIFT); + this.topLevelShiftBySet[setNumber] = this.determineTopLevelShiftForVirtualLength( + virtualLength, + setNumber + ); + } this.virtualLength = virtualLength; } - getTopLevelShift(): i32 { - return this.topLevelShift; - } // // ## ## ######## ####### ######## ## ## ## ### ######## ######## @@ -602,18 +679,36 @@ this.physicalLength = newLength; } + /** @return false if the packed storage runs out while copying */ private populateEquivalentEntriesWithEntriesFromOther( other: PackedArrayContext - ): void { + ): boolean { if (this.virtualLength < other.getVirtualLength()) { throw new Error("Cannot populate array of smaller virtual length"); } - - for (let i = 0; i < NUMBER_OF_SETS; i++) { - const otherEntryIndex = other.getAtShortIndex(SET_0_START_INDEX + i); + + for (let setNumber = 0; setNumber < NUMBER_OF_SETS; setNumber++) { + if ( + setNumber == 0 && + this.leafLevelShiftBySet[0] != other.leafLevelShiftBySet[0] + ) { + // The leaves of set 0 have another width: their layout cannot be copied as is + if (!this.copySet0ValuesFromOther(other)) { + return false; + } + continue; + } + const otherEntryIndex = other.getAtShortIndex( + SET_0_START_INDEX + setNumber + ); if (otherEntryIndex == 0) continue; // No tree to duplicate - let entryIndexPointer = SET_0_START_INDEX + i; - for (let i = this.topLevelShift; i > other.topLevelShift; i -= 4) { + let entryIndexPointer = SET_0_START_INDEX + setNumber; + const otherTopLevelShift = other.topLevelShiftBySet[setNumber]; + for ( + let i = this.topLevelShiftBySet[setNumber]; + i > otherTopLevelShift; + i -= 4 + ) { // for each inserted level: // Allocate entry in other: const sizeOfEntry = NON_LEAF_ENTRY_HEADER_SIZE_IN_SHORTS + 1; @@ -630,18 +725,45 @@ other, otherEntryIndex, entryIndexPointer, - other.topLevelShift + otherTopLevelShift, + setNumber ); } + return true; + } + + /** + * Copies set 0 of other, one virtual index at a time: for a set 0 whose leaves have another + * width the trees are not aligned, so the layout cannot be copied. A leaf is created wherever + * other has one, zero byte or not: get() stops at the first set without a leaf, so the higher + * sets must only be present where set 0 is. + * @return false if the packed storage runs out + */ + private copySet0ValuesFromOther(other: PackedArrayContext): boolean { + for (let virtualIndex = 0; virtualIndex < other.virtualLength; virtualIndex++) { + const otherByteIndex = other.getPackedIndex(0, virtualIndex, false); + if (otherByteIndex < 0) { + continue; + } + const byteIndex = this.getPackedIndex(0, virtualIndex, true); + if (byteIndex < 0) { + return false; + } + this.setAtByteIndex(byteIndex, other.getAtByteIndex(otherByteIndex)); + } + return true; } private copyEntriesAtLevelFromOther( other: PackedArrayContext, otherLevelEntryIndex: i32, levelEntryIndexPointer: i32, - otherIndexShift: i32 + otherIndexShift: i32, + setNumber: i32 ): void { - const nextLevelIsLeaf = otherIndexShift == LEAF_LEVEL_SHIFT; + const leafLevelShift = this.leafLevelShiftBySet[setNumber]; + const leafLengthInLongs = this.leafLengthInLongsBySet[setNumber]; + const nextLevelIsLeaf = otherIndexShift == leafLevelShift; const packedSlotIndicators = other.getPackedSlotIndicators( otherLevelEntryIndex ); @@ -658,7 +780,7 @@ for (let i: u8 = 0; i < numberOfSlots; i++) { if (nextLevelIsLeaf) { // Make leaf in other: - const leafEntryIndex = this.newLeafEntry(); + const leafEntryIndex = this.newLeafEntry(leafLengthInLongs); this.setIndexAtEntrySlot(entryIndex, i, leafEntryIndex); @@ -668,8 +790,10 @@ otherLevelEntryIndex, i ); - this.longArray[leafEntryIndex] = - other.longArray[otherNextLevelEntryIndex]; + for (let longNum = 0; longNum < leafLengthInLongs; longNum++) { + this.longArray[leafEntryIndex + longNum] = + other.longArray[otherNextLevelEntryIndex + longNum]; + } } else { const otherNextLevelEntryIndex = other.getIndexAtEntrySlot( otherLevelEntryIndex, @@ -679,7 +803,8 @@ other, otherNextLevelEntryIndex, entryIndex + NON_LEAF_ENTRY_HEADER_SIZE_IN_SHORTS + i, - otherIndexShift - 4 + otherIndexShift - 4, + setNumber ); } } @@ -742,7 +867,7 @@ } } output += " ] (indexShift = " + indexShift.toString() + ")\n"; - const nextLevelIsLeaf = indexShift == LEAF_LEVEL_SHIFT; + const nextLevelIsLeaf = indexShift == leafLevelShift; for (let i: u8 = 0; i < numberOfslotsInEntry; i++) { const nextLevelEntryIndex = this.getIndexAtEntrySlot(entryIndex, i); if (nextLevelIsLeaf) { @@ -751,7 +876,8 @@ output += this.nonLeafEntryToString( nextLevelEntryIndex, indexShift - 4, - indentLevel + 4 + indentLevel + 4, + leafLevelShift ); } } @@ -789,7 +915,12 @@ entryIndex.toString() + " \n"; if (entryIndex == 0) continue; - output += this.nonLeafEntryToString(entryIndex, this.topLevelShift, 4); + output += this.nonLeafEntryToString( + entryIndex, + this.topLevelShiftBySet[setNumber], + 4, + this.leafLevelShiftBySet[setNumber] + ); } //output += recordedValuesToString(); return output; diff --git a/src/PackedHistogram.encoding.spec.ts b/src/PackedHistogram.encoding.spec.ts new file mode 100644 index 0000000..59c5012 --- /dev/null +++ b/src/PackedHistogram.encoding.spec.ts @@ -0,0 +1,55 @@ +import Histogram from "./PackedHistogram"; +import { Int32Histogram } from "./index"; +import { encodeIntoCompressedBase64 } from "./encoding"; +import { initWebAssembly } from "./wasm"; + +beforeAll(() => initWebAssembly()); + +// Records the same counts in a packed histogram and in its Int32 twin: a contiguous band of +// latencies in the centre, and isolated values across the tails. +const recordBoth = () => { + const packed = new Histogram(1, 3_600_000_000, 3); + const int32 = new Int32Histogram(1, 3_600_000_000, 3); + let seed = 99; + const rand = () => { + seed = (seed * 1664525 + 1013904223) >>> 0; + return seed / 0x100000000; + }; + for (let k = 0; k < 20000; k++) { + const value = + rand() < 0.7 + ? 1_000_000 + Math.floor(rand() * 5000) + : Math.floor(rand() * 3_600_000_000); + const count = 1 + Math.floor(rand() * 300); + packed.recordValueWithCount(value, count); + int32.recordValueWithCount(value, count); + } + return { packed, int32 }; +}; + +describe("Packed histogram cross-check against Int32 histogram", () => { + it("should encode the same bytes as the Int32 histogram with the same counts", async () => { + // given + const { packed, int32 } = recordBoth(); + + // when + const packedEncoded = await encodeIntoCompressedBase64(packed); + const int32Encoded = await encodeIntoCompressedBase64(int32); + + // then + expect(packed.totalCount).toBe(int32.totalCount); + expect(packedEncoded).toBe(int32Encoded); + }); + + it("should report the same percentiles as the Int32 histogram", () => { + // given + const { packed, int32 } = recordBoth(); + + // then + for (const percentile of [1, 50, 90, 99, 99.99]) { + expect(packed.getValueAtPercentile(percentile)).toBe( + int32.getValueAtPercentile(percentile) + ); + } + }); +}); diff --git a/src/bench/packed-leaves.bench.ts b/src/bench/packed-leaves.bench.ts new file mode 100644 index 0000000..48eea26 --- /dev/null +++ b/src/bench/packed-leaves.bench.ts @@ -0,0 +1,61 @@ +import { test } from "vitest"; +import { PackedArray } from "../packedarray/PackedArray"; + +// Packed array recording and scanning, on the same seeded inputs on every branch. +// Run it on master and on the branch to compare: only the packedarray sources differ. + +// Seeded PRNG so every run and every branch sees the same indexes +const seeded = (seed: number) => () => { + seed = (seed * 1664525 + 1013904223) >>> 0; + return seed / 0x100000000; +}; + +// Sizes chosen so that neither workload falls back to unpacked storage +const N_CENTRE = 1 << 14; +const N_SPARSE = 1 << 12; +const OPS = 200_000; +const rand = seeded(42); +// contiguous latencies in the centre: a band of 512 indexes +const centre = Array.from( + { length: OPS }, + () => N_CENTRE / 2 - 256 + Math.floor(rand() * 512) +); +// isolated values across the whole range (tails and sparse) +const sparse = Array.from({ length: OPS }, () => Math.floor(rand() * N_SPARSE)); +const counts = Array.from({ length: OPS }, () => 1 + Math.floor(rand() * 3)); + +const filled = (n: number, indexes: number[]) => { + const array = new PackedArray(n, 16); + for (let i = 0; i < indexes.length; i++) array.add(indexes[i], counts[i]); + return array; +}; +const centreFilled = filled(N_CENTRE, centre); +const sparseFilled = filled(N_SPARSE, sparse); + +test("Packed array recording", async ({ bench }) => { + await bench.compare( + bench("record centre band", () => { + const array = new PackedArray(N_CENTRE, 16); + for (let i = 0; i < OPS; i++) array.add(centre[i], counts[i]); + }), + bench("record sparse tails", () => { + const array = new PackedArray(N_SPARSE, 16); + for (let i = 0; i < OPS; i++) array.add(sparse[i], counts[i]); + }) + ); +}); + +test("Packed array scans", async ({ bench }) => { + await bench.compare( + bench("sequential get, centre-filled", () => { + let sum = 0; + for (let i = 0; i < N_CENTRE; i++) sum += centreFilled.get(i); + return sum; + }), + bench("sequential get, sparse-filled", () => { + let sum = 0; + for (let i = 0; i < N_SPARSE; i++) sum += sparseFilled.get(i); + return sum; + }) + ); +}); diff --git a/src/packedarray/PackedArray.ts b/src/packedarray/PackedArray.ts index 8d2b63d..23cc6cd 100644 --- a/src/packedarray/PackedArray.ts +++ b/src/packedarray/PackedArray.ts @@ -14,7 +14,7 @@ const NUMBER_OF_SETS = 8; // Leaf cache entry states, besides a leaf long index (>= 0) const NO_LEAF = -1; // the set has no leaf for the cached group const UNKNOWN_LEAF = -2; // the set is beyond knownSets (not looked up yet) -const { floor } = Math; +const { floor, min } = Math; // 256^byteNum, the weight of each set's byte in a 64 bit value const BYTE_WEIGHTS = [0, 1, 2, 3, 4, 5, 6, 7].map((n) => 256 ** n); @@ -34,7 +34,9 @@ export class PackedArray { // Leaf cache for sequential reads and writes. // - // The 8 virtual indexes of a group (index >> 3) share one leaf per byte set, + // The 8 virtual indexes of a group (index >> 3) share one leaf per byte set + // (set 0 leaves are 16 bytes when the virtual length allows it and then cover two groups; + // the cache still holds one group), // so a scan over consecutive indexes would otherwise repeat the same set-tree // walks 8 times. For the group last accessed, leafIndexBySet[0 .. knownSets) // holds the long index of each set's leaf, or NO_LEAF when the set has no @@ -79,19 +81,21 @@ export class PackedArray { this.unpack(newVirtualArrayLength); return; } - if ( - currentArrayContext.determineTopLevelShiftForVirtualLength( - newVirtualArrayLength - ) == currentArrayContext.getTopLevelShift() - ) { + if (currentArrayContext.hasLayoutFor(newVirtualArrayLength)) { // No changes to the array context contents is needed. Just change the virtual length. currentArrayContext.setVirtualLength(newVirtualArrayLength); return; } - this.arrayContext = currentArrayContext.copyAndIncreaseSize( + const resizedArrayContext = currentArrayContext.copyAndIncreaseSize( this.getPhysicalLength(), newVirtualArrayLength ); + if (resizedArrayContext === null) { + // The packed storage cannot hold the layout of the new virtual length + this.unpack(newVirtualArrayLength); + return; + } + this.arrayContext = resizedArrayContext; } /** @@ -108,9 +112,10 @@ export class PackedArray { // Context is packed: this.cacheGroupOf(index); const leafIndexBySet = this.leafIndexBySet; - const byteInLeaf = index & 0x7; + const byteMaskBySet = arrayContext.leafByteMaskBySet; let value = 0; for (let byteNum = 0; byteNum < NUMBER_OF_SETS; byteNum++) { + const byteInLeaf = index & byteMaskBySet[byteNum]; let leafIndex = byteNum < this.knownSets ? leafIndexBySet[byteNum] : UNKNOWN_LEAF; if (leafIndex < 0) { @@ -125,7 +130,7 @@ export class PackedArray { leafIndexBySet[byteNum] = NO_LEAF; break; } - leafIndex = packedIndex >> 3; + leafIndex = (packedIndex - byteInLeaf) >> 3; leafIndexBySet[byteNum] = leafIndex; } value += @@ -140,18 +145,23 @@ export class PackedArray { * to be looked up on demand. */ private cacheGroupOf(index: number) { - const group = floor(index / 8); - if (group !== this.cachedGroup) { - // No set is known after a miss, so every access walks set 0 first, and - // getPackedIndex() checks the virtualLength bound there. - this.cachedGroup = group; - this.knownSets = 0; - } else if (index >= this.arrayContext.getVirtualLength()) { - // A hit skips the walk, and the last group may be partly beyond the bound + // The last group may be partly beyond the bound, and a hit skips the walk + if (index >= this.arrayContext.getVirtualLength()) { throw new Error( `Attempting access at index ${index}, beyond virtualLength ${this.arrayContext.getVirtualLength()}` ); } + const group = floor(index / 8); + if (group !== this.cachedGroup) { + // Wide set 0 leaves cover 16 indexes, two groups: its entry stays valid when the + // new group is in the same block. Any other set walks again. + this.knownSets = + group >> 1 === this.cachedGroup >> 1 && + this.arrayContext.hasWideSet0Leaves() + ? min(this.knownSets, 1) + : 0; + this.cachedGroup = group; + } } /** @@ -177,9 +187,10 @@ export class PackedArray { // Context is packed: this.cacheGroupOf(index); const leafIndexBySet = this.leafIndexBySet; - const byteInLeaf = index & 0x7; + const byteMaskBySet = arrayContext.leafByteMaskBySet; let remainingValueToAdd = value; for (let byteNum = 0; byteNum < NUMBER_OF_SETS; byteNum++) { + const byteInLeaf = index & byteMaskBySet[byteNum]; let leafIndex = byteNum < this.knownSets ? leafIndexBySet[byteNum] : UNKNOWN_LEAF; if (leafIndex < 0) { @@ -194,7 +205,7 @@ export class PackedArray { ); return; } - leafIndex = packedIndex >> 3; + leafIndex = (packedIndex - byteInLeaf) >> 3; leafIndexBySet[byteNum] = leafIndex; // A known NO_LEAF is always the last known set (get() and a zero set() // stop there), so this never shrinks the prefix. @@ -233,9 +244,10 @@ export class PackedArray { // Context is packed: this.cacheGroupOf(index); const leafIndexBySet = this.leafIndexBySet; - const byteInLeaf = index & 0x7; + const byteMaskBySet = arrayContext.leafByteMaskBySet; let valueForNextLevels = value; for (let byteNum = 0; byteNum < NUMBER_OF_SETS; byteNum++) { + const byteInLeaf = index & byteMaskBySet[byteNum]; let leafIndex = byteNum < this.knownSets ? leafIndexBySet[byteNum] : UNKNOWN_LEAF; if (leafIndex < 0) { @@ -261,7 +273,7 @@ export class PackedArray { return; } } - leafIndex = packedIndex >> 3; + leafIndex = (packedIndex - byteInLeaf) >> 3; leafIndexBySet[byteNum] = leafIndex; // A known NO_LEAF is always the last known set (get() and a zero set() // stop there), so this never shrinks the prefix. @@ -279,8 +291,8 @@ 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 + * On a packed context the set-0 tree is walked to skip the groups of + * indexes (one set-0 leaf each) 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. */ @@ -301,8 +313,11 @@ export class PackedArray { 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); + // The leaf found only vouches for the group of indexes sharing its set-0 leaf + const groupEnd = Math.min( + (index | arrayContext.leafByteMaskBySet[0]) + 1, + length + ); for (; index < groupEnd; index++) { if (this.get(index) !== 0) { return index; diff --git a/src/packedarray/PackedArray.wideLeaves.spec.ts b/src/packedarray/PackedArray.wideLeaves.spec.ts new file mode 100644 index 0000000..7c0ea53 --- /dev/null +++ b/src/packedarray/PackedArray.wideLeaves.spec.ts @@ -0,0 +1,326 @@ +import * as fc from "fast-check"; +import { PackedArray } from "./PackedArray"; +import { WIDE_SET_0_LEAVES_MAX_VIRTUAL_LENGTH } from "./PackedArrayContext"; + +// Set 0 of a packed array uses 16 byte leaves: these tests cover the resize, sharing, +// fallback and iteration paths that the wider leaves change. +describe("Packed array with 16 byte leaves for set 0", () => { + // Deterministic PRNG, so that failures reproduce + const seeded = (seed: number) => () => { + seed = (seed * 1664525 + 1013904223) >>> 0; + return seed / 0x100000000; + }; + + it("should keep values when a resize changes the depth of the set trees", () => { + // given: the set 0 tree gets one more level past 2^12, the others past 2^10 + const array = new PackedArray(1000, 16); + const values = new Map([ + [0, 1], + [17, 300], + [255, 70000], + [700, 2 ** 40 + 5], + [999, 42], + ]); + values.forEach((value, index) => array.set(index, value)); + + // when + array.setVirtualLength(8192); + array.set(8000, 5); + + // then + values.forEach((value, index) => expect(array.get(index)).toBe(value)); + expect(array.get(8000)).toBe(5); + expect(array.get(4096)).toBe(0); + }); + + it("should share one leaf between the indexes of a 16 index block", () => { + // given + const array = new PackedArray(1024, 16); + array.set(16, 1); + const physicalLength = array.getPhysicalLength(); + + // when: the other 15 indexes of the block are written, in both 8 index groups + for (let index = 17; index < 32; index++) { + array.set(index, index); + } + + // then + expect(array.getPhysicalLength()).toBe(physicalLength); + expect(array.get(16)).toBe(1); + for (let index = 17; index < 32; index++) { + expect(array.get(index)).toBe(index); + } + }); + + it("should not allocate leaves when setting zeros", () => { + // given + const array = new PackedArray(1 << 12, 16); + const physicalLength = array.getPhysicalLength(); + + // when + for (let index = 0; index < 1 << 12; index++) { + array.set(index, 0); + } + + // then + expect(array.getPhysicalLength()).toBe(physicalLength); + expect(array.get(1234)).toBe(0); + }); + + it("should iterate over the non zero values of a sparse array", () => { + // given + const array = new PackedArray(1 << 12, 16); + const expected = [3, 16, 31, 32, 1000, 1015, 4095]; + expected.forEach((index) => array.increment(index)); + + // when + const nonZero: number[] = []; + for (let index = 0; index < array.length(); index++) { + if (array.get(index) !== 0) { + nonZero.push(index); + } + } + + // then + expect(nonZero).toEqual(expected); + }); + + it("should keep values once the packed storage falls back to unpacked", () => { + // given: isolated values, one leaf each, until the 16 bit addresses run out + const length = 1 << 16; + const array = new PackedArray(length, 16); + const values = new Map(); + for (let i = 0; i < 20000 && array.getPhysicalLength() <= 8191; i++) { + const index = (i * 7919) % length; + array.add(index, i + 1); + values.set(index, (values.get(index) ?? 0) + i + 1); + } + + // then + expect(array.getPhysicalLength()).toBeGreaterThan(8191); + values.forEach((value, index) => expect(array.get(index)).toBe(value)); + }); + + it("should keep set 0 coherent when alternating between the two groups of a 16 index block", () => { + // given: group 0 is cached with no leaf, then group 1 of the same block gets one + const array = new PackedArray(1024, 16); + expect(array.get(3)).toBe(0); + array.set(9, 5); + + // when / then: back to group 0 of the block, which now shares the leaf + expect(array.get(3)).toBe(0); + expect(array.get(9)).toBe(5); + array.add(2, 7); + expect(array.get(2)).toBe(7); + expect(array.get(9)).toBe(5); + array.set(1, 0); + expect(array.get(1)).toBe(0); + }); + + it("should match a plain array on random operations within a 16 index block", () => { + const rand = seeded(77); + for (let round = 0; round < 50; round++) { + // given: a small range, where most accesses switch between the two groups + const length = 64; + const array = new PackedArray(length, 16); + const plain = new Float64Array(length); + for (let k = 0; k < 2000; k++) { + const index = Math.floor(rand() * length); + const op = rand(); + if (op < 0.4) { + const value = 1 + Math.floor(rand() * 300); + array.add(index, value); + plain[index] += value; + } else if (op < 0.5) { + array.set(index, 0); + plain[index] = 0; + } else { + expect(array.get(index)).toBe(plain[index]); + } + } + for (let index = 0; index < length; index++) { + expect(array.get(index)).toBe(plain[index]); + } + } + }); + + it("should match a plain array across the depth thresholds of the set trees", () => { + const rand = seeded(2024); + for (const length of [1000, 4096, 4097, 8192, 8193, 40000]) { + // given + const array = new PackedArray(length, 16); + const plain = new Float64Array(length); + + // when: a hot band, isolated values, carries into the next sets + for (let k = 0; k < 20000; k++) { + const index = + rand() < 0.5 + ? Math.min(length - 1, 100 + Math.floor(rand() * 40)) + : Math.floor(rand() * length); + const value = rand() < 0.2 ? 250 + Math.floor(rand() * 10) : 1; + array.add(index, value); + plain[index] += value; + } + + // then + for (let index = 0; index < length; index++) { + if (array.get(index) !== plain[index]) { + throw new Error( + `length ${length}: index ${index} is ${array.get(index)}, expected ${plain[index]}` + ); + } + } + } + }); +}); + +// Set 0 leaves are 16 bytes up to WIDE_SET_0_LEAVES_MAX_VIRTUAL_LENGTH, and 8 bytes above it: +// a resize across that threshold changes the layout of set 0. +describe("Packed array across the wide set 0 threshold", () => { + const WIDE_MAX = WIDE_SET_0_LEAVES_MAX_VIRTUAL_LENGTH; + const runFromStryker = __dirname.includes("stryker"); + const seeded = (seed: number) => () => { + seed = (seed * 1664525 + 1013904223) >>> 0; + return seed / 0x100000000; + }; + + it("should keep counts when a resize moves set 0 to 8 byte leaves", () => { + // given: values in both groups of a block, the last index of a wide length + const array = new PackedArray(WIDE_MAX, 16); + const values = new Map([ + [0, 1], + [9, 300], + [16, 7], + [1000, 2 ** 40 + 5], + [WIDE_MAX - 1, 70000], + ]); + values.forEach((value, index) => array.set(index, value)); + + // when + array.setVirtualLength(WIDE_MAX + 1); + + // then + values.forEach((value, index) => expect(array.get(index)).toBe(value)); + expect(array.get(WIDE_MAX)).toBe(0); + array.set(WIDE_MAX, 9); + expect(array.get(WIDE_MAX)).toBe(9); + }); + + it("should keep a value whose low byte is zero across a resize over the threshold", () => { + // given: 256 only sets byte 1, the set 0 leaf exists with a zero byte + const array = new PackedArray(WIDE_MAX, 16); + array.set(0, 256); + + // when + array.setVirtualLength(WIDE_MAX + 1); + + // then + expect(array.get(0)).toBe(256); + }); + + it("should keep the cached group coherent across a resize over the threshold", () => { + // given: group 2 is cached, with a leaf for its set 0 in the wide layout + const array = new PackedArray(WIDE_MAX, 16); + array.set(16, 5); + expect(array.get(17)).toBe(0); + + // when: the resize changes the set 0 layout while group 2 is cached + array.setVirtualLength(WIDE_MAX + 1); + + // then: the cached group is walked again in the new layout + expect(array.get(17)).toBe(0); + array.set(17, 3); + expect(array.get(16)).toBe(5); + expect(array.get(17)).toBe(3); + expect(array.get(18)).toBe(0); + expect(array.get(24)).toBe(0); + }); + + it("should keep values when a resize follows a nearly full packed storage", () => { + // given: isolated values until the packed storage nearly runs out, at a wide length + const array = new PackedArray(WIDE_MAX, 16); + const values = new Map(); + for (let i = 0; i < 20000 && array.getPhysicalLength() < 8000; i++) { + const index = (i * 7919) % WIDE_MAX; + array.add(index, i + 1); + values.set(index, (values.get(index) ?? 0) + i + 1); + } + + // when: the narrower leaves may not fit in the remaining storage + array.setVirtualLength(WIDE_MAX + 1); + + // then: packed or unpacked, the values are kept + values.forEach((value, index) => expect(array.get(index)).toBe(value)); + expect(array.get(WIDE_MAX)).toBe(0); + }); + + it("should match a plain array in both widths of set 0 leaves", () => { + const rand = seeded(5); + for (const length of [1000, WIDE_MAX, WIDE_MAX + 1, 40000]) { + // given + const array = new PackedArray(length, 16); + const plain = new Float64Array(length); + + // when: a hot band that shares blocks, isolated values, and carries + for (let k = 0; k < 5000; k++) { + const index = + rand() < 0.5 + ? Math.min(length - 1, 100 + Math.floor(rand() * 40)) + : Math.floor(rand() * length); + const value = rand() < 0.2 ? 250 + Math.floor(rand() * 10) : 1; + array.add(index, value); + plain[index] += value; + } + + // then + for (let index = 0; index < length; index++) { + expect(array.get(index)).toBe(plain[index]); + } + } + }); + + it("should match a plain array across resizes over the threshold", () => { + fc.assert( + fc.property( + fc.integer({ min: WIDE_MAX - 300, max: WIDE_MAX }), + fc.array( + fc.tuple( + fc.constantFrom("add", "set", "get", "resize"), + fc.nat(1 << 20), + fc.nat(1000) + ), + { maxLength: 300 } + ), + (startLength, ops) => { + let length = startLength; + const array = new PackedArray(length, 16); + const plain: number[] = new Array(length).fill(0); + for (const [kind, rawIndex, amount] of ops) { + if (kind === "resize") { + const grown = length + 1 + (amount % 64) * 8; + array.setVirtualLength(grown); + for (let i = length; i < grown; i++) plain.push(0); + length = grown; + continue; + } + const index = rawIndex % length; + if (kind === "add") { + array.add(index, amount + 1); + plain[index] += amount + 1; + } else if (kind === "set") { + const value = amount % 3 === 0 ? 0 : amount; + array.set(index, value); + plain[index] = value; + } else { + expect(array.get(index)).toBe(plain[index]); + } + } + for (let index = 0; index < length; index++) { + expect(array.get(index)).toBe(plain[index]); + } + } + ), + { numRuns: runFromStryker ? 10 : 300 } + ); + }); +}); diff --git a/src/packedarray/PackedArrayContext.ts b/src/packedarray/PackedArrayContext.ts index 6330b23..d5470be 100644 --- a/src/packedarray/PackedArrayContext.ts +++ b/src/packedarray/PackedArrayContext.ts @@ -30,7 +30,21 @@ export const MINIMUM_INITIAL_PACKED_ARRAY_CAPACITY = 16; export const MAX_SUPPORTED_PACKED_COUNTS_ARRAY_LENGTH = 8191; const SET_0_START_INDEX = 0; const NUMBER_OF_SETS = 8; +// A leaf of a set covers the 2^leafLevelShift virtual indexes sharing their high bits. +// Set 0 is the dense byte (most recorded values only use it), so its leaves can be 16 bytes wide: +// the set tree is one level shallower for some virtual lengths, and a 16 index block shares one +// leaf. A populated leaf costs its whole width, though: a lone value costs 16 bytes instead of 8, +// which fills the 16 bit packed addresses sooner for large sparse arrays. So the wide leaves are +// only used up to WIDE_SET_0_LEAVES_MAX_VIRTUAL_LENGTH, and the other sets keep 8 bytes. const LEAF_LEVEL_SHIFT = 3; +const WIDE_SET_0_LEAF_LEVEL_SHIFT = 4; +export const WIDE_SET_0_LEAVES_MAX_VIRTUAL_LENGTH = 1 << 15; + +/** @return the leaf level shift of a set, for a virtual length */ +const leafLevelShiftFor = (setNumber: number, virtualLength: number) => + setNumber === 0 && virtualLength <= WIDE_SET_0_LEAVES_MAX_VIRTUAL_LENGTH + ? WIDE_SET_0_LEAF_LEVEL_SHIFT + : LEAF_LEVEL_SHIFT; const NON_LEAF_ENTRY_SLOT_INDICATORS_OFFSET = 0; const NON_LEAF_ENTRY_HEADER_SIZE_IN_SHORTS = 1; const PACKED_ARRAY_GROWTH_INCREMENT = 16; @@ -63,7 +77,17 @@ export class PackedArrayContext { private longArray: Float64Array; private populatedShortLength: number = 0; private virtualLength: number; - private topLevelShift: number = Number.MAX_VALUE; // Make it non-sensical until properly initialized. + // Per set, make it non-sensical until properly initialized. + private topLevelShiftBySet: number[] = new Array(NUMBER_OF_SETS).fill( + Number.MAX_VALUE + ); + // Per set layout of the leaves, for the virtual length of this context + private leafLevelShiftBySet: number[] = new Array(NUMBER_OF_SETS).fill( + LEAF_LEVEL_SHIFT + ); + /** Mask of the virtual index bits selecting the byte within a leaf, per set (read by the hot loops) */ + public leafByteMaskBySet: number[] = [7, 7, 7, 7, 7, 7, 7, 7]; + private leafLengthInLongsBySet: number[] = new Array(NUMBER_OF_SETS).fill(1); constructor(virtualLength: number, initialPhysicalLength: number) { this.physicalLength = Math.max( @@ -116,16 +140,24 @@ export class PackedArrayContext { ); } + /** + * @return a context of the new virtual length holding the same values, or null if the packed + * storage cannot hold them (the caller then moves to an unpacked context) + */ public copyAndIncreaseSize( newPhysicalArrayLength: number, newVirtualArrayLength: number - ) { + ): PackedArrayContext | null { const ctx = new PackedArrayContext( newVirtualArrayLength, newPhysicalArrayLength ); - ctx.populateEquivalentEntriesWithEntriesFromOther(this); - return ctx; + return ctx.populateEquivalentEntriesWithEntriesFromOther(this) ? ctx : null; + } + + /** @return whether set 0 leaves cover two 8 index groups (16 bytes), so a group shares them */ + public hasWideSet0Leaves() { + return this.leafLevelShiftBySet[0] === WIDE_SET_0_LEAF_LEVEL_SHIFT; } public getPopulatedShortLength() { @@ -247,17 +279,22 @@ export class PackedArrayContext { return newEntryIndex; } - /** @return the long index of the new leaf, or -1 if the array is full */ - private newLeafEntry() { + /** + * @param lengthInLongs the length of the leaf, 1 for an 8 byte leaf + * @return the long index of the new leaf, or -1 if the array is full + */ + private newLeafEntry(lengthInLongs: number) { // Add entry at the end of the array: const newEntryIndex = this.getPopulatedLongLength(); - if (!this.expandArrayIfNeeded(1)) { + if (!this.expandArrayIfNeeded(lengthInLongs)) { return -1; } - this.setPopulatedLongLength(newEntryIndex + 1); + this.setPopulatedLongLength(newEntryIndex + lengthInLongs); - this.setAtLongIndex(newEntryIndex, 0); + for (let i = 0; i < lengthInLongs; i++) { + this.setAtLongIndex(newEntryIndex + i, 0); + } return newEntryIndex; } @@ -305,6 +342,7 @@ export class PackedArrayContext { * @param insertedSlotIndex realtive [packed] index of slot being inserted into entry * @param insertedSlotMask mask value fo slot being inserted * @param nextLevelIsLeaf the level below this one is a leaf level + * @param leafLengthInLongs the length of the leaves, when the level below is a leaf level * @return the updated index of the entry, or -1 if the array is full (the entry is then left untouched) */ expandEntry( @@ -312,7 +350,8 @@ export class PackedArrayContext { entryPointerIndex: number, insertedSlotIndex: number, insertedSlotMask: number, - nextLevelIsLeaf: boolean + nextLevelIsLeaf: boolean, + leafLengthInLongs: number ): number { let packedSlotIndicators = this.getAtShortIndex(existingEntryIndex) & 0xffff; @@ -331,7 +370,7 @@ export class PackedArrayContext { // Create new next-level entry to refer to from slot at this level: let indexOfNewNextLevelEntry = 0; if (nextLevelIsLeaf) { - indexOfNewNextLevelEntry = this.newLeafEntry(); // Establish long-index to new leaf entry + indexOfNewNextLevelEntry = this.newLeafEntry(leafLengthInLongs); // Establish long-index to new leaf entry if (indexOfNewNextLevelEntry < 0) { return -1; } @@ -432,12 +471,14 @@ export class PackedArrayContext { } // Work down the levels of non-leaf entries: + const leafLevelShift = this.leafLevelShiftBySet[setNumber]; + const leafLengthInLongs = this.leafLengthInLongsBySet[setNumber]; for ( - let indexShift = this.topLevelShift; - indexShift >= LEAF_LEVEL_SHIFT; + let indexShift = this.topLevelShiftBySet[setNumber]; + indexShift >= leafLevelShift; indexShift -= 4 ) { - const nextLevelIsLeaf = indexShift === LEAF_LEVEL_SHIFT; + const nextLevelIsLeaf = indexShift === leafLevelShift; // Target is a packedSlotIndicators entry const packedSlotIndicators = this.getPackedSlotIndicators(entryIndex); const slotBitNumber = (virtualIndex >>> indexShift) & 0xf; @@ -457,7 +498,8 @@ export class PackedArrayContext { entryPointerIndex, slotNumber, slotMask, - nextLevelIsLeaf + nextLevelIsLeaf, + leafLengthInLongs ); if (entryIndex < 0) { return -1; // The array is full, the index cannot be added @@ -473,13 +515,15 @@ export class PackedArrayContext { // entryIndex is the long-index of a leaf entry that contains the value byte for the given set - const byteIndex = (entryIndex << 3) + (virtualIndex & 0x7); // Determine byte index offset within leaf entry + // Byte index offset within leaf entry. The leaf entry is the long index + const byteIndex = + (entryIndex << 3) + (virtualIndex & this.leafByteMaskBySet[setNumber]); 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 + * Lowest virtual index >= fromIndex whose group of indexes (the ones sharing + * a set-0 leaf) 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. @@ -503,7 +547,7 @@ export class PackedArrayContext { } return this.nextIndexWithLeafBelow( rootEntryIndex, - this.topLevelShift, + this.topLevelShiftBySet[0], fromIndex ); } @@ -521,7 +565,7 @@ export class PackedArrayContext { 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; + const nextLevelIsLeaf = indexShift === this.leafLevelShiftBySet[0]; for ( let slotBitNumber = (fromIndex >>> indexShift) & 0xf; slotBitNumber < 16; @@ -553,13 +597,22 @@ export class PackedArrayContext { return -1; } - determineTopLevelShiftForVirtualLength(virtualLength: number) { + /** + * The top level shift of the set tree of the given set, for a virtual length: the levels of + * non-leaf entries are at shifts leafLevelShift, leafLevelShift + 4, ..., top, and the top + * level must cover the most significant bit of the virtual length, with at least two levels. + */ + determineTopLevelShiftForVirtualLength( + virtualLength: number, + setNumber: number = 1 + ) { + const leafLevelShift = leafLevelShiftFor(setNumber, virtualLength); const sizeMagnitude = ceil(log2(virtualLength)); - const eightsSizeMagnitude = sizeMagnitude - 3; - let multipleOfFourSizeMagnitude = ceil(eightsSizeMagnitude / 4) * 4; - multipleOfFourSizeMagnitude = max(multipleOfFourSizeMagnitude, 8); - const topLevelShiftNeeded = multipleOfFourSizeMagnitude - 4 + 3; - return topLevelShiftNeeded; + const levelsAboveTheFirst = max( + ceil((sizeMagnitude - leafLevelShift - 4) / 4), + 1 + ); + return leafLevelShift + 4 * levelsAboveTheFirst; } setVirtualLength(virtualLength: number) { @@ -568,13 +621,33 @@ export class PackedArrayContext { "Should never be adjusting the virtual size of a non-packed context" ); } - this.topLevelShift = - this.determineTopLevelShiftForVirtualLength(virtualLength); + for (let setNumber = 0; setNumber < NUMBER_OF_SETS; setNumber++) { + const leafLevelShift = leafLevelShiftFor(setNumber, virtualLength); + this.leafLevelShiftBySet[setNumber] = leafLevelShift; + this.leafByteMaskBySet[setNumber] = (1 << leafLevelShift) - 1; + this.leafLengthInLongsBySet[setNumber] = + 1 << (leafLevelShift - LEAF_LEVEL_SHIFT); + this.topLevelShiftBySet[setNumber] = + this.determineTopLevelShiftForVirtualLength(virtualLength, setNumber); + } this.virtualLength = virtualLength; } - getTopLevelShift() { - return this.topLevelShift; + /** @return whether the set trees of this context are laid out for the given virtual length */ + hasLayoutFor(virtualLength: number) { + for (let setNumber = 0; setNumber < NUMBER_OF_SETS; setNumber++) { + if ( + leafLevelShiftFor(setNumber, virtualLength) !== + this.leafLevelShiftBySet[setNumber] || + this.determineTopLevelShiftForVirtualLength( + virtualLength, + setNumber + ) !== this.topLevelShiftBySet[setNumber] + ) { + return false; + } + } + return true; } // @@ -595,18 +668,36 @@ export class PackedArrayContext { this.physicalLength = newLength; } + /** @return false if the packed storage runs out while copying */ private populateEquivalentEntriesWithEntriesFromOther( other: PackedArrayContext - ) { + ): boolean { if (this.virtualLength < other.getVirtualLength()) { throw new Error("Cannot populate array of smaller virtual length"); } - for (let i = 0; i < NUMBER_OF_SETS; i++) { - const otherEntryIndex = other.getAtShortIndex(SET_0_START_INDEX + i); + for (let setNumber = 0; setNumber < NUMBER_OF_SETS; setNumber++) { + if ( + setNumber === 0 && + this.leafLevelShiftBySet[0] !== other.leafLevelShiftBySet[0] + ) { + // The leaves of set 0 have another width: their layout cannot be copied as is + if (!this.copySet0ValuesFromOther(other)) { + return false; + } + continue; + } + const otherEntryIndex = other.getAtShortIndex( + SET_0_START_INDEX + setNumber + ); if (otherEntryIndex == 0) continue; // No tree to duplicate - let entryIndexPointer = SET_0_START_INDEX + i; - for (let i = this.topLevelShift; i > other.topLevelShift; i -= 4) { + let entryIndexPointer = SET_0_START_INDEX + setNumber; + const otherTopLevelShift = other.topLevelShiftBySet[setNumber]; + for ( + let i = this.topLevelShiftBySet[setNumber]; + i > otherTopLevelShift; + i -= 4 + ) { // for each inserted level: // Allocate entry in other: const sizeOfEntry = NON_LEAF_ENTRY_HEADER_SIZE_IN_SHORTS + 1; @@ -623,18 +714,49 @@ export class PackedArrayContext { other, otherEntryIndex, entryIndexPointer, - other.topLevelShift + otherTopLevelShift, + setNumber ); } + return true; + } + + /** + * Copies set 0 of other, one virtual index at a time: for a set 0 whose leaves have another + * width the trees are not aligned, so the layout cannot be copied. A leaf is created wherever + * other has one, zero byte or not: get() stops at the first set without a leaf, so the higher + * sets must only be present where set 0 is. + * @return false if the packed storage runs out + */ + private copySet0ValuesFromOther(other: PackedArrayContext): boolean { + for ( + let virtualIndex = 0; + virtualIndex < other.virtualLength; + virtualIndex++ + ) { + const otherByteIndex = other.getPackedIndex(0, virtualIndex, false); + if (otherByteIndex < 0) { + continue; + } + const byteIndex = this.getPackedIndex(0, virtualIndex, true); + if (byteIndex < 0) { + return false; + } + this.setAtByteIndex(byteIndex, other.getAtByteIndex(otherByteIndex)); + } + return true; } private copyEntriesAtLevelFromOther( other: PackedArrayContext, otherLevelEntryIndex: number, levelEntryIndexPointer: number, - otherIndexShift: number + otherIndexShift: number, + setNumber: number ) { - const nextLevelIsLeaf = otherIndexShift == LEAF_LEVEL_SHIFT; + const leafLevelShift = this.leafLevelShiftBySet[setNumber]; + const leafLengthInLongs = this.leafLengthInLongsBySet[setNumber]; + const nextLevelIsLeaf = otherIndexShift == leafLevelShift; const packedSlotIndicators = other.getPackedSlotIndicators(otherLevelEntryIndex); const numberOfSlots = bitCount(packedSlotIndicators); @@ -650,7 +772,7 @@ export class PackedArrayContext { for (let i = 0; i < numberOfSlots; i++) { if (nextLevelIsLeaf) { // Make leaf in other: - const leafEntryIndex = this.newLeafEntry(); + const leafEntryIndex = this.newLeafEntry(leafLengthInLongs); this.setIndexAtEntrySlot(entryIndex, i, leafEntryIndex); @@ -660,8 +782,10 @@ export class PackedArrayContext { otherLevelEntryIndex, i ); - this.longArray[leafEntryIndex] = - other.longArray[otherNextLevelEntryIndex]; + for (let longNum = 0; longNum < leafLengthInLongs; longNum++) { + this.longArray[leafEntryIndex + longNum] = + other.longArray[otherNextLevelEntryIndex + longNum]; + } } else { const otherNextLevelEntryIndex = other.getIndexAtEntrySlot( otherLevelEntryIndex, @@ -671,7 +795,8 @@ export class PackedArrayContext { other, otherNextLevelEntryIndex, entryIndex + NON_LEAF_ENTRY_HEADER_SIZE_IN_SHORTS + i, - otherIndexShift - 4 + otherIndexShift - 4, + setNumber ); } } @@ -712,7 +837,8 @@ export class PackedArrayContext { private nonLeafEntryToString( entryIndex: number, indexShift: number, - indentLevel: number + indentLevel: number, + leafLevelShift: number ) { let output = ""; for (let i = 0; i < indentLevel; i++) { @@ -732,7 +858,7 @@ export class PackedArrayContext { } } output += ` ] (indexShift = ${indexShift})\n`; - const nextLevelIsLeaf = indexShift == LEAF_LEVEL_SHIFT; + const nextLevelIsLeaf = indexShift == leafLevelShift; for (let i = 0; i < numberOfslotsInEntry; i++) { const nextLevelEntryIndex = this.getIndexAtEntrySlot(entryIndex, i); if (nextLevelIsLeaf) { @@ -744,7 +870,8 @@ export class PackedArrayContext { output += this.nonLeafEntryToString( nextLevelEntryIndex, indexShift - 4, - indentLevel + 4 + indentLevel + 4, + leafLevelShift ); } } @@ -782,7 +909,12 @@ export class PackedArrayContext { const entryIndex = this.getIndexAtShortIndex(entryPointerIndex); output += `Set ${setNumber}: root = ${entryIndex} \n`; if (entryIndex == 0) continue; - output += this.nonLeafEntryToString(entryIndex, this.topLevelShift, 4); + output += this.nonLeafEntryToString( + entryIndex, + this.topLevelShiftBySet[setNumber], + 4, + this.leafLevelShiftBySet[setNumber] + ); } catch (ex) { output += `Exception thrown in set ${setNumber}%d\n`; }