From 06d6703e4b94df6d4b31e69e2a8f33abd29a91b9 Mon Sep 17 00:00:00 2001 From: alexvictoor Date: Sun, 15 Nov 2026 08:29:01 +0100 Subject: [PATCH 1/4] perf: 16 byte leaves for set 0 of the packed array Set 0 (the dense low byte) gets 16 byte leaves, so its set tree is one level shallower for some virtual lengths. Sets 1..7 keep 8 byte leaves. Each set has its own leaf shift and top level shift; the leaf cache stores long indexes as before. Encoded bytes do not change. The leaf cache keeps set 0's entry across the two 8 index groups of a 16 index block, so sequential scans walk set 0 once per block. Measured with src/bench/packed-leaves.bench.ts, master vs branch, three alternating runs each (hz = iterations per second, 200k records each): - record centre band: ~49.7 -> ~64.3 (about +29%) - record sparse tails: ~42.9 -> ~58.3 (about +36%) - sequential get, sparse (N=4096): ~12.8k -> ~18.6k (about +45%) - sequential get, centre (N=16384): ~6.4k -> ~8.0k (about +26%) Memory cost: isolated values reach the unpacked fallback later at virtual lengths 2^13..2^15 and sooner at 2^16 and 2^17 (about 16-18% fewer distinct values before fallback). Co-Authored-By: Claude Fable 5.1 --- .../__tests__/PackedArrayWideLeaves.test.ts | 122 ++++++++++++ assembly/packedarray/PackedArray.ts | 46 ++--- assembly/packedarray/PackedArrayContext.ts | 169 ++++++++++++----- src/PackedHistogram.encoding.spec.ts | 55 ++++++ src/bench/packed-leaves.bench.ts | 61 ++++++ src/packedarray/PackedArray.ts | 55 +++--- .../PackedArray.wideLeaves.spec.ts | 173 ++++++++++++++++++ src/packedarray/PackedArrayContext.ts | 165 ++++++++++++----- 8 files changed, 710 insertions(+), 136 deletions(-) create mode 100644 assembly/__tests__/PackedArrayWideLeaves.test.ts create mode 100644 src/PackedHistogram.encoding.spec.ts create mode 100644 src/bench/packed-leaves.bench.ts create mode 100644 src/packedarray/PackedArray.wideLeaves.spec.ts diff --git a/assembly/__tests__/PackedArrayWideLeaves.test.ts b/assembly/__tests__/PackedArrayWideLeaves.test.ts new file mode 100644 index 0000000..e7f0838 --- /dev/null +++ b/assembly/__tests__/PackedArrayWideLeaves.test.ts @@ -0,0 +1,122 @@ +/* + * 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"; + +// 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]); + } + } + }); +}); diff --git a/assembly/packedarray/PackedArray.ts b/assembly/packedarray/PackedArray.ts index a80f0f6..b1d7ae7 100644 --- a/assembly/packedarray/PackedArray.ts +++ b/assembly/packedarray/PackedArray.ts @@ -9,6 +9,7 @@ import { PackedArrayContext, MINIMUM_INITIAL_PACKED_ARRAY_CAPACITY, + LEAF_BYTE_MASK_BY_SET, } from "./PackedArrayContext"; const NUMBER_OF_SETS: i32 = 8; @@ -34,7 +35,8 @@ 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 and 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 @@ -87,9 +89,7 @@ export class PackedArray { return; } if ( - currentArrayContext.determineTopLevelShiftForVirtualLength( - newVirtualArrayLength - ) == currentArrayContext.getTopLevelShift() + currentArrayContext.hasTopLevelShiftsFor(newVirtualArrayLength) ) { // No changes to the array context contents is needed. Just change the virtual length. currentArrayContext.setVirtualLength(newVirtualArrayLength); @@ -123,9 +123,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 & LEAF_BYTE_MASK_BY_SET[byteNum]; let leafIndex = byteNum < this.knownSets ? unchecked(leafIndexBySet[byteNum]) @@ -142,7 +142,7 @@ export class PackedArray { unchecked((leafIndexBySet[byteNum] = NO_LEAF)); break; } - leafIndex = packedIndex >> 3; + leafIndex = (packedIndex - byteInLeaf) >> 3; unchecked((leafIndexBySet[byteNum] = leafIndex)); } value |= @@ -158,18 +158,20 @@ 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) { + // 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 ? min(this.knownSets, 1) : 0; + this.cachedGroup = group; + } } /** @@ -195,9 +197,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 & LEAF_BYTE_MASK_BY_SET[byteNum]; let leafIndex = byteNum < this.knownSets ? unchecked(leafIndexBySet[byteNum]) @@ -214,7 +216,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 +254,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 & LEAF_BYTE_MASK_BY_SET[byteNum]; let leafIndex = byteNum < this.knownSets ? unchecked(leafIndexBySet[byteNum]) @@ -282,7 +284,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 +302,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 +324,8 @@ 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 | LEAF_BYTE_MASK_BY_SET[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..8755971 100644 --- a/assembly/packedarray/PackedArrayContext.ts +++ b/assembly/packedarray/PackedArrayContext.ts @@ -30,7 +30,26 @@ 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 are 16 bytes wide: + // the set tree is one level shallower for some virtual lengths. The other sets keep 8 bytes, + // as a populated leaf costs its whole width. + const LEAF_LEVEL_SHIFT: i32 = 3; + const SET_0_LEAF_LEVEL_SHIFT: i32 = 4; + export const LEAF_LEVEL_SHIFT_BY_SET: StaticArray = [ + SET_0_LEAF_LEVEL_SHIFT, + LEAF_LEVEL_SHIFT, + LEAF_LEVEL_SHIFT, + LEAF_LEVEL_SHIFT, + LEAF_LEVEL_SHIFT, + LEAF_LEVEL_SHIFT, + LEAF_LEVEL_SHIFT, + LEAF_LEVEL_SHIFT + ]; + // Mask of the virtual index bits selecting the byte within a leaf, per set + export const LEAF_BYTE_MASK_BY_SET: StaticArray = [15, 7, 7, 7, 7, 7, 7, 7]; + // Length of a leaf in longs (8 bytes each), per set + const LEAF_LENGTH_IN_LONGS_BY_SET: StaticArray = [2, 1, 1, 1, 1, 1, 1, 1]; const NON_LEAF_ENTRY_SLOT_INDICATORS_OFFSET = 0; const NON_LEAF_ENTRY_HEADER_SIZE_IN_SHORTS = 1; const PACKED_ARRAY_GROWTH_INCREMENT = 16; @@ -52,7 +71,10 @@ 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); constructor(virtualLength: i32, initialPhysicalLength: i32) { this.physicalLength = ( @@ -245,18 +267,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 +335,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 +343,8 @@ entryPointerIndex: i32, insertedSlotIndex: i32, insertedSlotMask: i32, - nextLevelIsLeaf: boolean + nextLevelIsLeaf: boolean, + leafLengthInLongs: i32 ): i32 { let packedSlotIndicators = (this.getAtShortIndex(existingEntryIndex)) & 0xffff; @@ -334,7 +363,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 +464,14 @@ } // Work down the levels of non-leaf entries: + const leafLevelShift = LEAF_LEVEL_SHIFT_BY_SET[setNumber]; + const leafLengthInLongs = LEAF_LENGTH_IN_LONGS_BY_SET[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 +491,8 @@ entryPointerIndex, slotNumber, slotMask, - nextLevelIsLeaf + nextLevelIsLeaf, + leafLengthInLongs ); if (entryIndex < 0) { return -1; // The array is full, the index cannot be added @@ -476,13 +508,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 & LEAF_BYTE_MASK_BY_SET[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 +540,7 @@ } return this.nextIndexWithLeafBelow( rootEntryIndex, - this.topLevelShift, + this.topLevelShiftBySet[0], fromIndex ); } @@ -524,7 +558,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 == LEAF_LEVEL_SHIFT_BY_SET[0]; for ( let slotBitNumber = (fromIndex >>> indexShift) & 0xf; slotBitNumber < 16; @@ -558,14 +592,35 @@ 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 = LEAF_LEVEL_SHIFT_BY_SET[setNumber]; 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 */ + hasTopLevelShiftsFor(virtualLength: i32): boolean { + for (let setNumber = 0; setNumber < NUMBER_OF_SETS; setNumber++) { + if ( + this.determineTopLevelShiftForVirtualLength(virtualLength, setNumber) !== + this.topLevelShiftBySet[setNumber] + ) { + return false; + } + } + return true; } setVirtualLength(virtualLength: i32): void { @@ -574,15 +629,15 @@ "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++) { + this.topLevelShiftBySet[setNumber] = this.determineTopLevelShiftForVirtualLength( + virtualLength, + setNumber + ); + } this.virtualLength = virtualLength; } - getTopLevelShift(): i32 { - return this.topLevelShift; - } // // ## ## ######## ####### ######## ## ## ## ### ######## ######## @@ -609,11 +664,18 @@ 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++) { + 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,7 +692,8 @@ other, otherEntryIndex, entryIndexPointer, - other.topLevelShift + otherTopLevelShift, + setNumber ); } } @@ -639,9 +702,12 @@ other: PackedArrayContext, otherLevelEntryIndex: i32, levelEntryIndexPointer: i32, - otherIndexShift: i32 + otherIndexShift: i32, + setNumber: i32 ): void { - const nextLevelIsLeaf = otherIndexShift == LEAF_LEVEL_SHIFT; + const leafLevelShift = LEAF_LEVEL_SHIFT_BY_SET[setNumber]; + const leafLengthInLongs = LEAF_LENGTH_IN_LONGS_BY_SET[setNumber]; + const nextLevelIsLeaf = otherIndexShift == leafLevelShift; const packedSlotIndicators = other.getPackedSlotIndicators( otherLevelEntryIndex ); @@ -658,7 +724,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 +734,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 +747,8 @@ other, otherNextLevelEntryIndex, entryIndex + NON_LEAF_ENTRY_HEADER_SIZE_IN_SHORTS + i, - otherIndexShift - 4 + otherIndexShift - 4, + setNumber ); } } @@ -742,7 +811,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 +820,8 @@ output += this.nonLeafEntryToString( nextLevelEntryIndex, indexShift - 4, - indentLevel + 4 + indentLevel + 4, + leafLevelShift ); } } @@ -789,7 +859,12 @@ entryIndex.toString() + " \n"; if (entryIndex == 0) continue; - output += this.nonLeafEntryToString(entryIndex, this.topLevelShift, 4); + output += this.nonLeafEntryToString( + entryIndex, + this.topLevelShiftBySet[setNumber], + 4, + LEAF_LEVEL_SHIFT_BY_SET[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..cb79435 100644 --- a/src/packedarray/PackedArray.ts +++ b/src/packedarray/PackedArray.ts @@ -8,13 +8,16 @@ import { PackedArrayContext, MINIMUM_INITIAL_PACKED_ARRAY_CAPACITY, + LEAF_BYTE_MASK_BY_SET, } from "./PackedArrayContext"; const NUMBER_OF_SETS = 8; +// Read once: the hot loops below index a module-local array, not an import binding +const BYTE_IN_LEAF_MASK_BY_SET = LEAF_BYTE_MASK_BY_SET; // 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 +37,8 @@ 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 and 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,11 +83,7 @@ export class PackedArray { this.unpack(newVirtualArrayLength); return; } - if ( - currentArrayContext.determineTopLevelShiftForVirtualLength( - newVirtualArrayLength - ) == currentArrayContext.getTopLevelShift() - ) { + if (currentArrayContext.hasTopLevelShiftsFor(newVirtualArrayLength)) { // No changes to the array context contents is needed. Just change the virtual length. currentArrayContext.setVirtualLength(newVirtualArrayLength); return; @@ -108,9 +108,9 @@ export class PackedArray { // Context is packed: this.cacheGroupOf(index); const leafIndexBySet = this.leafIndexBySet; - const byteInLeaf = index & 0x7; let value = 0; for (let byteNum = 0; byteNum < NUMBER_OF_SETS; byteNum++) { + const byteInLeaf = index & BYTE_IN_LEAF_MASK_BY_SET[byteNum]; let leafIndex = byteNum < this.knownSets ? leafIndexBySet[byteNum] : UNKNOWN_LEAF; if (leafIndex < 0) { @@ -125,7 +125,7 @@ export class PackedArray { leafIndexBySet[byteNum] = NO_LEAF; break; } - leafIndex = packedIndex >> 3; + leafIndex = (packedIndex - byteInLeaf) >> 3; leafIndexBySet[byteNum] = leafIndex; } value += @@ -140,18 +140,20 @@ 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) { + // 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 ? min(this.knownSets, 1) : 0; + this.cachedGroup = group; + } } /** @@ -177,9 +179,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 & BYTE_IN_LEAF_MASK_BY_SET[byteNum]; let leafIndex = byteNum < this.knownSets ? leafIndexBySet[byteNum] : UNKNOWN_LEAF; if (leafIndex < 0) { @@ -194,7 +196,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 +235,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 & BYTE_IN_LEAF_MASK_BY_SET[byteNum]; let leafIndex = byteNum < this.knownSets ? leafIndexBySet[byteNum] : UNKNOWN_LEAF; if (leafIndex < 0) { @@ -261,7 +263,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 +281,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 +303,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 | BYTE_IN_LEAF_MASK_BY_SET[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..d533ae1 --- /dev/null +++ b/src/packedarray/PackedArray.wideLeaves.spec.ts @@ -0,0 +1,173 @@ +import { PackedArray } from "./PackedArray"; + +// 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]}` + ); + } + } + } + }); +}); diff --git a/src/packedarray/PackedArrayContext.ts b/src/packedarray/PackedArrayContext.ts index 6330b23..4ac16b9 100644 --- a/src/packedarray/PackedArrayContext.ts +++ b/src/packedarray/PackedArrayContext.ts @@ -30,7 +30,30 @@ 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 are 16 bytes wide: +// the set tree is one level shallower for some virtual lengths. The other sets keep 8 bytes, +// as a populated leaf costs its whole width. const LEAF_LEVEL_SHIFT = 3; +const SET_0_LEAF_LEVEL_SHIFT = 4; +export const LEAF_LEVEL_SHIFT_BY_SET = [ + SET_0_LEAF_LEVEL_SHIFT, + LEAF_LEVEL_SHIFT, + LEAF_LEVEL_SHIFT, + LEAF_LEVEL_SHIFT, + LEAF_LEVEL_SHIFT, + LEAF_LEVEL_SHIFT, + LEAF_LEVEL_SHIFT, + LEAF_LEVEL_SHIFT, +]; +// Mask of the virtual index bits selecting the byte within a leaf, per set +export const LEAF_BYTE_MASK_BY_SET = LEAF_LEVEL_SHIFT_BY_SET.map( + (leafLevelShift) => (1 << leafLevelShift) - 1 +); +// Length of a leaf in longs (8 bytes each), per set +const LEAF_LENGTH_IN_LONGS_BY_SET = LEAF_LEVEL_SHIFT_BY_SET.map( + (leafLevelShift) => 1 << (leafLevelShift - 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 +86,10 @@ 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 + ); constructor(virtualLength: number, initialPhysicalLength: number) { this.physicalLength = Math.max( @@ -247,17 +273,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 +336,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 +344,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 +364,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 +465,14 @@ export class PackedArrayContext { } // Work down the levels of non-leaf entries: + const leafLevelShift = LEAF_LEVEL_SHIFT_BY_SET[setNumber]; + const leafLengthInLongs = LEAF_LENGTH_IN_LONGS_BY_SET[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 +492,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 +509,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 & LEAF_BYTE_MASK_BY_SET[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 +541,7 @@ export class PackedArrayContext { } return this.nextIndexWithLeafBelow( rootEntryIndex, - this.topLevelShift, + this.topLevelShiftBySet[0], fromIndex ); } @@ -521,7 +559,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 === LEAF_LEVEL_SHIFT_BY_SET[0]; for ( let slotBitNumber = (fromIndex >>> indexShift) & 0xf; slotBitNumber < 16; @@ -553,13 +591,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 = LEAF_LEVEL_SHIFT_BY_SET[setNumber]; 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 +615,26 @@ 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++) { + 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 */ + hasTopLevelShiftsFor(virtualLength: number) { + for (let setNumber = 0; setNumber < NUMBER_OF_SETS; setNumber++) { + if ( + this.determineTopLevelShiftForVirtualLength( + virtualLength, + setNumber + ) !== this.topLevelShiftBySet[setNumber] + ) { + return false; + } + } + return true; } // @@ -602,11 +662,18 @@ export class PackedArrayContext { 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++) { + 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,7 +690,8 @@ export class PackedArrayContext { other, otherEntryIndex, entryIndexPointer, - other.topLevelShift + otherTopLevelShift, + setNumber ); } } @@ -632,9 +700,12 @@ export class PackedArrayContext { other: PackedArrayContext, otherLevelEntryIndex: number, levelEntryIndexPointer: number, - otherIndexShift: number + otherIndexShift: number, + setNumber: number ) { - const nextLevelIsLeaf = otherIndexShift == LEAF_LEVEL_SHIFT; + const leafLevelShift = LEAF_LEVEL_SHIFT_BY_SET[setNumber]; + const leafLengthInLongs = LEAF_LENGTH_IN_LONGS_BY_SET[setNumber]; + const nextLevelIsLeaf = otherIndexShift == leafLevelShift; const packedSlotIndicators = other.getPackedSlotIndicators(otherLevelEntryIndex); const numberOfSlots = bitCount(packedSlotIndicators); @@ -650,7 +721,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 +731,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 +744,8 @@ export class PackedArrayContext { other, otherNextLevelEntryIndex, entryIndex + NON_LEAF_ENTRY_HEADER_SIZE_IN_SHORTS + i, - otherIndexShift - 4 + otherIndexShift - 4, + setNumber ); } } @@ -712,7 +786,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 +807,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 +819,8 @@ export class PackedArrayContext { output += this.nonLeafEntryToString( nextLevelEntryIndex, indexShift - 4, - indentLevel + 4 + indentLevel + 4, + leafLevelShift ); } } @@ -782,7 +858,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, + LEAF_LEVEL_SHIFT_BY_SET[setNumber] + ); } catch (ex) { output += `Exception thrown in set ${setNumber}%d\n`; } From 6cb0ec2e0d3b705c4f5df808b63e038f121bae67 Mon Sep 17 00:00:00 2001 From: alexvictoor Date: Sun, 15 Nov 2026 09:30:05 +0100 Subject: [PATCH 2/4] perf: 16 byte set 0 leaves only up to 2^15 virtual length The wide set 0 leaves of 4cbe522 cost 16 bytes per lone value instead of 8, so large sparse arrays reached the 16 bit packed addresses sooner and fell back to unpacked storage earlier (2^16: 2573 vs 3072 distinct values, 2^17: 2192 vs 2688). Below 2^15 they fell back later or never. Set 0 leaves are now 16 bytes while the virtual length is at most 2^15 (WIDE_SET_0_LEAVES_MAX_VIRTUAL_LENGTH), 8 bytes above. The leaf shift, byte mask and leaf length are per context, chosen from the virtual length. A resize that changes the set 0 layout copies set 0 value by value, creating a leaf wherever the source has one, since get() relies on a higher byte only existing where set 0 does. Sets 1..7 keep the tree copy. The leaf cache keeps set 0 across the two groups of a 16 index block only while set 0 leaves are wide. Encoded bytes do not change. Memory probe (distinct isolated values before unpacked fallback, mean of 5 seeds): 2^15 3534 (master 3484), 40000 3356 (3356), 2^16 3112 (3112), 2^17 2692 (2692): equal to master from 2^16 up, better below. Co-Authored-By: Claude Fable 5.1 --- .../__tests__/PackedArrayWideLeaves.test.ts | 81 ++++++++++ assembly/packedarray/PackedArray.ts | 29 ++-- assembly/packedarray/PackedArrayContext.ts | 120 ++++++++++---- src/packedarray/PackedArray.ts | 32 ++-- .../PackedArray.wideLeaves.spec.ts | 153 ++++++++++++++++++ src/packedarray/PackedArrayContext.ts | 115 +++++++++---- 6 files changed, 440 insertions(+), 90 deletions(-) diff --git a/assembly/__tests__/PackedArrayWideLeaves.test.ts b/assembly/__tests__/PackedArrayWideLeaves.test.ts index e7f0838..ca3a5ae 100644 --- a/assembly/__tests__/PackedArrayWideLeaves.test.ts +++ b/assembly/__tests__/PackedArrayWideLeaves.test.ts @@ -8,6 +8,7 @@ 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. @@ -120,3 +121,83 @@ describe("Packed Array with 16 byte leaves for set 0", () => { } }); }); + +// 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 b1d7ae7..fb1973b 100644 --- a/assembly/packedarray/PackedArray.ts +++ b/assembly/packedarray/PackedArray.ts @@ -9,7 +9,6 @@ import { PackedArrayContext, MINIMUM_INITIAL_PACKED_ARRAY_CAPACITY, - LEAF_BYTE_MASK_BY_SET, } from "./PackedArrayContext"; const NUMBER_OF_SETS: i32 = 8; @@ -36,7 +35,8 @@ 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 - // (set 0 leaves are 16 bytes and cover two groups, the cache still holds one group), + // (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 @@ -88,17 +88,21 @@ export class PackedArray { this.unpack(newVirtualArrayLength); return; } - if ( - currentArrayContext.hasTopLevelShiftsFor(newVirtualArrayLength) - ) { + 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 { @@ -125,7 +129,7 @@ export class PackedArray { const leafIndexBySet = this.leafIndexBySet; let value: u64 = 0; for (let byteNum = 0; byteNum < NUMBER_OF_SETS; byteNum++) { - const byteInLeaf = index & LEAF_BYTE_MASK_BY_SET[byteNum]; + const byteInLeaf = index & arrayContext.leafByteMaskBySet[byteNum]; let leafIndex = byteNum < this.knownSets ? unchecked(leafIndexBySet[byteNum]) @@ -166,10 +170,13 @@ export class PackedArray { } const group = index >> 3; if (group != this.cachedGroup) { - // Set 0 leaves cover 16 indexes, two groups: its entry stays valid when the + // 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 ? min(this.knownSets, 1) : 0; + group >> 1 == this.cachedGroup >> 1 && + this.arrayContext.hasWideSet0Leaves() + ? min(this.knownSets, 1) + : 0; this.cachedGroup = group; } } @@ -199,7 +206,7 @@ export class PackedArray { const leafIndexBySet = this.leafIndexBySet; let remainingValueToAdd = value; for (let byteNum = 0; byteNum < NUMBER_OF_SETS; byteNum++) { - const byteInLeaf = index & LEAF_BYTE_MASK_BY_SET[byteNum]; + const byteInLeaf = index & arrayContext.leafByteMaskBySet[byteNum]; let leafIndex = byteNum < this.knownSets ? unchecked(leafIndexBySet[byteNum]) @@ -256,7 +263,7 @@ export class PackedArray { const leafIndexBySet = this.leafIndexBySet; let valueForNextLevels = value; for (let byteNum = 0; byteNum < NUMBER_OF_SETS; byteNum++) { - const byteInLeaf = index & LEAF_BYTE_MASK_BY_SET[byteNum]; + const byteInLeaf = index & arrayContext.leafByteMaskBySet[byteNum]; let leafIndex = byteNum < this.knownSets ? unchecked(leafIndexBySet[byteNum]) diff --git a/assembly/packedarray/PackedArrayContext.ts b/assembly/packedarray/PackedArrayContext.ts index 8755971..2b57ab9 100644 --- a/assembly/packedarray/PackedArrayContext.ts +++ b/assembly/packedarray/PackedArrayContext.ts @@ -31,25 +31,21 @@ 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 are 16 bytes wide: - // the set tree is one level shallower for some virtual lengths. The other sets keep 8 bytes, - // as a populated leaf costs its whole width. + // 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 SET_0_LEAF_LEVEL_SHIFT: i32 = 4; - export const LEAF_LEVEL_SHIFT_BY_SET: StaticArray = [ - SET_0_LEAF_LEVEL_SHIFT, - LEAF_LEVEL_SHIFT, - LEAF_LEVEL_SHIFT, - LEAF_LEVEL_SHIFT, - LEAF_LEVEL_SHIFT, - LEAF_LEVEL_SHIFT, - LEAF_LEVEL_SHIFT, - LEAF_LEVEL_SHIFT - ]; - // Mask of the virtual index bits selecting the byte within a leaf, per set - export const LEAF_BYTE_MASK_BY_SET: StaticArray = [15, 7, 7, 7, 7, 7, 7, 7]; - // Length of a leaf in longs (8 bytes each), per set - const LEAF_LENGTH_IN_LONGS_BY_SET: StaticArray = [2, 1, 1, 1, 1, 1, 1, 1]; + 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; @@ -75,7 +71,18 @@ 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) @@ -127,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 { @@ -464,8 +479,8 @@ } // Work down the levels of non-leaf entries: - const leafLevelShift = LEAF_LEVEL_SHIFT_BY_SET[setNumber]; - const leafLengthInLongs = LEAF_LENGTH_IN_LONGS_BY_SET[setNumber]; + const leafLevelShift = this.leafLevelShiftBySet[setNumber]; + const leafLengthInLongs = this.leafLengthInLongsBySet[setNumber]; for ( let indexShift = this.topLevelShiftBySet[setNumber]; indexShift >= leafLevelShift; @@ -510,7 +525,7 @@ // Byte index offset within leaf entry, the leaf entry being the long index const byteIndex = - (entryIndex << 3) + (virtualIndex & LEAF_BYTE_MASK_BY_SET[setNumber]); + (entryIndex << 3) + (virtualIndex & this.leafByteMaskBySet[setNumber]); return byteIndex; } @@ -601,7 +616,7 @@ virtualLength: i32, setNumber: i32 = 1 ): i32 { - const leafLevelShift = LEAF_LEVEL_SHIFT_BY_SET[setNumber]; + const leafLevelShift = leafLevelShiftFor(setNumber, virtualLength); const sizeMagnitude = ceil(Math.log2(virtualLength)); const levelsAboveTheFirst = max( ceil((sizeMagnitude - leafLevelShift - 4) / 4.0), @@ -611,18 +626,20 @@ } /** @return whether the set trees of this context are laid out for the given virtual length */ - hasTopLevelShiftsFor(virtualLength: i32): boolean { + 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] + this.topLevelShiftBySet[setNumber] ) { return false; } } return true; } - + setVirtualLength(virtualLength: i32): void { if (!this.isPacked) { throw new Error( @@ -630,6 +647,11 @@ ); } 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 @@ -657,14 +679,25 @@ 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 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 ); @@ -696,6 +729,25 @@ 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( @@ -705,8 +757,8 @@ otherIndexShift: i32, setNumber: i32 ): void { - const leafLevelShift = LEAF_LEVEL_SHIFT_BY_SET[setNumber]; - const leafLengthInLongs = LEAF_LENGTH_IN_LONGS_BY_SET[setNumber]; + const leafLevelShift = this.leafLevelShiftBySet[setNumber]; + const leafLengthInLongs = this.leafLengthInLongsBySet[setNumber]; const nextLevelIsLeaf = otherIndexShift == leafLevelShift; const packedSlotIndicators = other.getPackedSlotIndicators( otherLevelEntryIndex @@ -863,7 +915,7 @@ entryIndex, this.topLevelShiftBySet[setNumber], 4, - LEAF_LEVEL_SHIFT_BY_SET[setNumber] + this.leafLevelShiftBySet[setNumber] ); } //output += recordedValuesToString(); diff --git a/src/packedarray/PackedArray.ts b/src/packedarray/PackedArray.ts index cb79435..55d0431 100644 --- a/src/packedarray/PackedArray.ts +++ b/src/packedarray/PackedArray.ts @@ -8,12 +8,9 @@ import { PackedArrayContext, MINIMUM_INITIAL_PACKED_ARRAY_CAPACITY, - LEAF_BYTE_MASK_BY_SET, } from "./PackedArrayContext"; const NUMBER_OF_SETS = 8; -// Read once: the hot loops below index a module-local array, not an import binding -const BYTE_IN_LEAF_MASK_BY_SET = LEAF_BYTE_MASK_BY_SET; // 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) @@ -38,7 +35,8 @@ 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 - // (set 0 leaves are 16 bytes and cover two groups, the cache still holds one group), + // (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 @@ -83,15 +81,21 @@ export class PackedArray { this.unpack(newVirtualArrayLength); return; } - if (currentArrayContext.hasTopLevelShiftsFor(newVirtualArrayLength)) { + 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 byteMaskBySet = arrayContext.leafByteMaskBySet; let value = 0; for (let byteNum = 0; byteNum < NUMBER_OF_SETS; byteNum++) { - const byteInLeaf = index & BYTE_IN_LEAF_MASK_BY_SET[byteNum]; + const byteInLeaf = index & byteMaskBySet[byteNum]; let leafIndex = byteNum < this.knownSets ? leafIndexBySet[byteNum] : UNKNOWN_LEAF; if (leafIndex < 0) { @@ -148,10 +153,13 @@ export class PackedArray { } const group = floor(index / 8); if (group !== this.cachedGroup) { - // Set 0 leaves cover 16 indexes, two groups: its entry stays valid when the + // 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 ? min(this.knownSets, 1) : 0; + group >> 1 === this.cachedGroup >> 1 && + this.arrayContext.hasWideSet0Leaves() + ? min(this.knownSets, 1) + : 0; this.cachedGroup = group; } } @@ -179,9 +187,10 @@ export class PackedArray { // Context is packed: this.cacheGroupOf(index); const leafIndexBySet = this.leafIndexBySet; + const byteMaskBySet = arrayContext.leafByteMaskBySet; let remainingValueToAdd = value; for (let byteNum = 0; byteNum < NUMBER_OF_SETS; byteNum++) { - const byteInLeaf = index & BYTE_IN_LEAF_MASK_BY_SET[byteNum]; + const byteInLeaf = index & byteMaskBySet[byteNum]; let leafIndex = byteNum < this.knownSets ? leafIndexBySet[byteNum] : UNKNOWN_LEAF; if (leafIndex < 0) { @@ -235,9 +244,10 @@ export class PackedArray { // Context is packed: this.cacheGroupOf(index); const leafIndexBySet = this.leafIndexBySet; + const byteMaskBySet = arrayContext.leafByteMaskBySet; let valueForNextLevels = value; for (let byteNum = 0; byteNum < NUMBER_OF_SETS; byteNum++) { - const byteInLeaf = index & BYTE_IN_LEAF_MASK_BY_SET[byteNum]; + const byteInLeaf = index & byteMaskBySet[byteNum]; let leafIndex = byteNum < this.knownSets ? leafIndexBySet[byteNum] : UNKNOWN_LEAF; if (leafIndex < 0) { diff --git a/src/packedarray/PackedArray.wideLeaves.spec.ts b/src/packedarray/PackedArray.wideLeaves.spec.ts index d533ae1..7c0ea53 100644 --- a/src/packedarray/PackedArray.wideLeaves.spec.ts +++ b/src/packedarray/PackedArray.wideLeaves.spec.ts @@ -1,4 +1,6 @@ +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. @@ -171,3 +173,154 @@ describe("Packed array with 16 byte leaves for set 0", () => { } }); }); + +// 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 4ac16b9..d54950e 100644 --- a/src/packedarray/PackedArrayContext.ts +++ b/src/packedarray/PackedArrayContext.ts @@ -31,29 +31,20 @@ 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 are 16 bytes wide: -// the set tree is one level shallower for some virtual lengths. The other sets keep 8 bytes, -// as a populated leaf costs its whole width. +// 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 SET_0_LEAF_LEVEL_SHIFT = 4; -export const LEAF_LEVEL_SHIFT_BY_SET = [ - SET_0_LEAF_LEVEL_SHIFT, - LEAF_LEVEL_SHIFT, - LEAF_LEVEL_SHIFT, - LEAF_LEVEL_SHIFT, - LEAF_LEVEL_SHIFT, - LEAF_LEVEL_SHIFT, - LEAF_LEVEL_SHIFT, - LEAF_LEVEL_SHIFT, -]; -// Mask of the virtual index bits selecting the byte within a leaf, per set -export const LEAF_BYTE_MASK_BY_SET = LEAF_LEVEL_SHIFT_BY_SET.map( - (leafLevelShift) => (1 << leafLevelShift) - 1 -); -// Length of a leaf in longs (8 bytes each), per set -const LEAF_LENGTH_IN_LONGS_BY_SET = LEAF_LEVEL_SHIFT_BY_SET.map( - (leafLevelShift) => 1 << (leafLevelShift - LEAF_LEVEL_SHIFT) -); +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; @@ -90,6 +81,13 @@ export class PackedArrayContext { 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( @@ -142,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() { @@ -465,8 +471,8 @@ export class PackedArrayContext { } // Work down the levels of non-leaf entries: - const leafLevelShift = LEAF_LEVEL_SHIFT_BY_SET[setNumber]; - const leafLengthInLongs = LEAF_LENGTH_IN_LONGS_BY_SET[setNumber]; + const leafLevelShift = this.leafLevelShiftBySet[setNumber]; + const leafLengthInLongs = this.leafLengthInLongsBySet[setNumber]; for ( let indexShift = this.topLevelShiftBySet[setNumber]; indexShift >= leafLevelShift; @@ -511,7 +517,7 @@ export class PackedArrayContext { // Byte index offset within leaf entry. The leaf entry is the long index const byteIndex = - (entryIndex << 3) + (virtualIndex & LEAF_BYTE_MASK_BY_SET[setNumber]); + (entryIndex << 3) + (virtualIndex & this.leafByteMaskBySet[setNumber]); return byteIndex; } @@ -600,7 +606,7 @@ export class PackedArrayContext { virtualLength: number, setNumber: number = 1 ) { - const leafLevelShift = LEAF_LEVEL_SHIFT_BY_SET[setNumber]; + const leafLevelShift = leafLevelShiftFor(setNumber, virtualLength); const sizeMagnitude = ceil(log2(virtualLength)); const levelsAboveTheFirst = max( ceil((sizeMagnitude - leafLevelShift - 4) / 4), @@ -616,6 +622,11 @@ export class PackedArrayContext { ); } 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); } @@ -623,9 +634,11 @@ export class PackedArrayContext { } /** @return whether the set trees of this context are laid out for the given virtual length */ - hasTopLevelShiftsFor(virtualLength: number) { + hasLayoutFor(virtualLength: number) { for (let setNumber = 0; setNumber < NUMBER_OF_SETS; setNumber++) { if ( + leafLevelShiftFor(setNumber, virtualLength) !== + this.leafLevelShiftBySet[setNumber] || this.determineTopLevelShiftForVirtualLength( virtualLength, setNumber @@ -655,14 +668,25 @@ 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 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 ); @@ -694,6 +718,29 @@ export class PackedArrayContext { 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( @@ -703,8 +750,8 @@ export class PackedArrayContext { otherIndexShift: number, setNumber: number ) { - const leafLevelShift = LEAF_LEVEL_SHIFT_BY_SET[setNumber]; - const leafLengthInLongs = LEAF_LENGTH_IN_LONGS_BY_SET[setNumber]; + const leafLevelShift = this.leafLevelShiftBySet[setNumber]; + const leafLengthInLongs = this.leafLengthInLongsBySet[setNumber]; const nextLevelIsLeaf = otherIndexShift == leafLevelShift; const packedSlotIndicators = other.getPackedSlotIndicators(otherLevelEntryIndex); @@ -862,7 +909,7 @@ export class PackedArrayContext { entryIndex, this.topLevelShiftBySet[setNumber], 4, - LEAF_LEVEL_SHIFT_BY_SET[setNumber] + this.leafLevelShiftBySet[setNumber] ); } catch (ex) { output += `Exception thrown in set ${setNumber}%d\n`; From c5eec8eb29648e22dbfaffd152587a41c7563683 Mon Sep 17 00:00:00 2001 From: alexvictoor Date: Sun, 15 Nov 2026 19:53:34 +0100 Subject: [PATCH 3/4] style: brace the single-line ifs of the adaptive leaf copy Co-Authored-By: Claude Fable 5.1 --- assembly/packedarray/PackedArrayContext.ts | 8 ++++++-- src/packedarray/PackedArrayContext.ts | 8 ++++++-- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/assembly/packedarray/PackedArrayContext.ts b/assembly/packedarray/PackedArrayContext.ts index 2b57ab9..25b0168 100644 --- a/assembly/packedarray/PackedArrayContext.ts +++ b/assembly/packedarray/PackedArrayContext.ts @@ -742,9 +742,13 @@ private copySet0ValuesFromOther(other: PackedArrayContext): boolean { for (let virtualIndex = 0; virtualIndex < other.virtualLength; virtualIndex++) { const otherByteIndex = other.getPackedIndex(0, virtualIndex, false); - if (otherByteIndex < 0) continue; + if (otherByteIndex < 0) { + continue; + } const byteIndex = this.getPackedIndex(0, virtualIndex, true); - if (byteIndex < 0) return false; + if (byteIndex < 0) { + return false; + } this.setAtByteIndex(byteIndex, other.getAtByteIndex(otherByteIndex)); } return true; diff --git a/src/packedarray/PackedArrayContext.ts b/src/packedarray/PackedArrayContext.ts index d54950e..f1dcea8 100644 --- a/src/packedarray/PackedArrayContext.ts +++ b/src/packedarray/PackedArrayContext.ts @@ -735,9 +735,13 @@ export class PackedArrayContext { virtualIndex++ ) { const otherByteIndex = other.getPackedIndex(0, virtualIndex, false); - if (otherByteIndex < 0) continue; + if (otherByteIndex < 0) { + continue; + } const byteIndex = this.getPackedIndex(0, virtualIndex, true); - if (byteIndex < 0) return false; + if (byteIndex < 0) { + return false; + } this.setAtByteIndex(byteIndex, other.getAtByteIndex(otherByteIndex)); } return true; From 1d483a7e0b07feea0acd0b34cbbdd6ba343fb5ec Mon Sep 17 00:00:00 2001 From: alexvictoor Date: Sun, 15 Nov 2026 22:17:06 +0100 Subject: [PATCH 4/4] fix: walk set 0 with the adaptive leaf shift in nextNonZeroIndex The set-0 tree walk that master added for skipping empty subtrees took set 0's leaf shift and byte mask from the constant tables, which this branch replaces with per-context values that depend on the virtual length. The walk and its caller now read those from the context. Co-Authored-By: Claude Fable 5.1 --- assembly/packedarray/PackedArray.ts | 5 ++++- assembly/packedarray/PackedArrayContext.ts | 2 +- src/packedarray/PackedArray.ts | 2 +- src/packedarray/PackedArrayContext.ts | 2 +- 4 files changed, 7 insertions(+), 4 deletions(-) diff --git a/assembly/packedarray/PackedArray.ts b/assembly/packedarray/PackedArray.ts index fb1973b..2c25652 100644 --- a/assembly/packedarray/PackedArray.ts +++ b/assembly/packedarray/PackedArray.ts @@ -332,7 +332,10 @@ export class PackedArray { return -1; } // The leaf found only vouches for the group of indexes sharing its set-0 leaf - const groupEnd = min((index | LEAF_BYTE_MASK_BY_SET[0]) + 1, length); + 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 25b0168..afc14a6 100644 --- a/assembly/packedarray/PackedArrayContext.ts +++ b/assembly/packedarray/PackedArrayContext.ts @@ -573,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_BY_SET[0]; + const nextLevelIsLeaf = indexShift == this.leafLevelShiftBySet[0]; for ( let slotBitNumber = (fromIndex >>> indexShift) & 0xf; slotBitNumber < 16; diff --git a/src/packedarray/PackedArray.ts b/src/packedarray/PackedArray.ts index 55d0431..23cc6cd 100644 --- a/src/packedarray/PackedArray.ts +++ b/src/packedarray/PackedArray.ts @@ -315,7 +315,7 @@ export class PackedArray { } // The leaf found only vouches for the group of indexes sharing its set-0 leaf const groupEnd = Math.min( - (index | BYTE_IN_LEAF_MASK_BY_SET[0]) + 1, + (index | arrayContext.leafByteMaskBySet[0]) + 1, length ); for (; index < groupEnd; index++) { diff --git a/src/packedarray/PackedArrayContext.ts b/src/packedarray/PackedArrayContext.ts index f1dcea8..d5470be 100644 --- a/src/packedarray/PackedArrayContext.ts +++ b/src/packedarray/PackedArrayContext.ts @@ -565,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_BY_SET[0]; + const nextLevelIsLeaf = indexShift === this.leafLevelShiftBySet[0]; for ( let slotBitNumber = (fromIndex >>> indexShift) & 0xf; slotBitNumber < 16;