Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions assembly/__tests__/PackedArrayAccess.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,68 @@ describe("Packed Array leaf cache", () => {
expect<i32>(mismatches(packed, model)).equal(0);
});

test("writes within a group see each other without reads in between", () => {
// Writes alone cache their group, so the leaves looked up by one write
// serve the next writes of the group, including sets never looked up yet.
const packed = new PackedArray(64);
packed.add(24, 1); // caches group 3, set 0 only
packed.add(25, 0x200); // inserts set 1 while group 3 is cached
packed.increment(25);
packed.set(26, 0x030201); // inserts set 2
packed.set(24, 0x7f); // set 0 known, higher sets looked up: no leaf yet for set 3
expect<u64>(packed.get(24)).equal(0x7f);
expect<u64>(packed.get(25)).equal(0x201);
expect<u64>(packed.get(26)).equal(0x030201);
expect<u64>(packed.get(27)).equal(0);
});

test("carries propagate through cached and uncached sets", () => {
const packed = new PackedArray(64);
packed.set(40, 0xffff); // sets 0 and 1
expect<u64>(packed.get(40)).equal(0xffff);
packed.add(41, 1); // cached group 5, set 0 known
packed.increment(40); // carries into set 1 (cached) then inserts set 2
expect<u64>(packed.get(40)).equal(0x10000);
packed.add(40, 0xffffffffffff0000); // carries up to the top set
expect<u64>(packed.get(40)).equal(0);
expect<u64>(packed.get(41)).equal(1);
});

test("set to a smaller value through the cache clears the higher bytes", () => {
const packed = new PackedArray(64);
packed.set(50, 0x01020304);
packed.set(51, 0x05); // group 6 cached by the write above
packed.set(50, 0x0102); // sets 2 and 3 are cached leaves, zeroed
expect<u64>(packed.get(50)).equal(0x0102);
packed.set(50, 0);
expect<u64>(packed.get(50)).equal(0);
packed.set(52, 0); // no leaf created for a zero at an unknown set
expect<u64>(packed.get(52)).equal(0);
expect<u64>(packed.get(51)).equal(5);
});

test("cached writes keep their values when the packed storage fills up", () => {
const length = 5000;
const packed = new PackedArray(length);
const model = new StaticArray<u64>(length);
for (let i = 0; i < length; i++) {
// the cached group gets extra writes before the unpacking one
const v = u64.MAX_VALUE - i;
packed.add(i, v);
model[i] += v;
const neighbour = i & ~7;
packed.add(neighbour, 1);
model[neighbour] += 1;
}
expect<i32>(mismatches(packed, model)).equal(0);
// and the array keeps working once unpacked
packed.set(10, 42);
model[10] = 42;
packed.increment(11);
model[11] += 1;
expect<i32>(mismatches(packed, model)).equal(0);
});

test("physical array growth during a cached group keeps the cache valid", () => {
// Small initial capacity so inserts trigger resizeArray() repeatedly.
const packed = new PackedArray(8192, 16);
Expand Down
187 changes: 115 additions & 72 deletions assembly/packedarray/PackedArray.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ import {
} from "./PackedArrayContext";

const NUMBER_OF_SETS: i32 = 8;
const NO_LEAF: i32 = -1;
// Leaf cache entry states, besides a leaf long index (>= 0)
const NO_LEAF: i32 = -1; // the set has no leaf for the cached group
const UNKNOWN_LEAF: i32 = -2; // the set is beyond knownSets (not looked up yet)

/**
* A Packed array of signed 64 bit values, and supports {@link #get get()}, {@link #set set()},
Expand All @@ -30,18 +32,28 @@ export class PackedArray {

private arrayContext: PackedArrayContext;

// Leaf cache for sequential reads.
// Leaf cache for sequential reads and writes.
//
// The 8 virtual indexes of a group (index >> 3) share one leaf per byte set,
// so a scan over consecutive indexes would otherwise repeat the same set-tree
// walks 8 times. leafIndexBySet remembers, for the group last read, the long
// index of each set's leaf (NO_LEAF when the set has no entry for that
// group). set() and add() record the leaves they insert for the cached group,
// and anything that rebuilds the context invalidates the cache.
// 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
// entry for that group; sets from knownSets upwards have not been looked up
// yet (writes only walk the sets they touch), whatever leafIndexBySet holds
// there. The known sets always form a prefix because get(), add() and set()
// resolve sets from byte 0 upwards and never skip one, so evicting a group
// is a single knownSets = 0 rather than a reset of every entry, which keeps
// the miss path (random recordValue) as cheap as before the cache. A leaf
// never moves once created, so a cached leaf index stays valid for the
// lifetime of the context, and every write that creates a leaf records it,
// so a known NO_LEAF entry is always current. Any access to another group
// evicts the cached one, writes included. Anything that rebuilds the context
// invalidates the cache.
private cachedGroup: i32 = -1;
private knownSets: i32 = 0;
private leafIndexBySet: StaticArray<i32> = new StaticArray<i32>(
NUMBER_OF_SETS
);
).fill(NO_LEAF);

constructor(
virtualLength: i32,
Expand All @@ -60,6 +72,7 @@ export class PackedArray {

public setVirtualLength(newVirtualArrayLength: i32): void {
this.cachedGroup = -1;
this.knownSets = 0;
if (newVirtualArrayLength < this.length()) {
throw new Error(
"Cannot set virtual length, as requested length " +
Expand Down Expand Up @@ -108,16 +121,29 @@ export class PackedArray {
return arrayContext.getAtUnpackedIndex(index);
}
// Context is packed:
if (index >> 3 != this.cachedGroup) {
this.fillLeafCache(index);
}
const byteInLeaf = index & 0x7;
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 leafIndex = unchecked(leafIndexBySet[byteNum]);
if (leafIndex == NO_LEAF) {
break;
let leafIndex =
byteNum < this.knownSets
? unchecked(leafIndexBySet[byteNum])
: UNKNOWN_LEAF;
if (leafIndex < 0) {
// Sets are populated from byte 0 upwards (see set() and add()), so once
// a set has no leaf for this group the higher sets have none either.
if (leafIndex == NO_LEAF) {
break;
}
const packedIndex = arrayContext.getPackedIndex(byteNum, index, false);
this.knownSets = byteNum + 1;
if (packedIndex < 0) {
unchecked((leafIndexBySet[byteNum] = NO_LEAF));
break;
}
leafIndex = packedIndex >> 3;
unchecked((leafIndexBySet[byteNum] = leafIndex));
}
value |=
(<u64>arrayContext.getAtByteIndex((leafIndex << 3) + byteInLeaf)) <<
Expand All @@ -127,33 +153,22 @@ export class PackedArray {
}

/**
* Walk the set trees once for the group of 8 indexes containing `index`, and
* remember the leaf of every set that has one.
* Make the group of 8 indexes containing `index` the cached one, its leaves
* to be looked up on demand.
*/
private fillLeafCache(index: i32): void {
const arrayContext = this.arrayContext;
const leafIndexBySet = this.leafIndexBySet;
let byteNum = 0;
for (; byteNum < NUMBER_OF_SETS; byteNum++) {
const packedIndex = arrayContext.getPackedIndex(byteNum, index, false);
if (packedIndex < 0) {
break;
}
unchecked((leafIndexBySet[byteNum] = packedIndex >> 3));
}
// Sets are populated from byte 0 upwards (see set() and add()), so once a
// set has no leaf for this group the higher sets have none either.
for (; byteNum < NUMBER_OF_SETS; byteNum++) {
unchecked((leafIndexBySet[byteNum] = NO_LEAF));
}
this.cachedGroup = index >> 3;
}

/** Keep the leaf cache coherent with a leaf just looked up with insertAsNeeded. */
@inline
private noteLeaf(index: i32, byteNum: i32, packedIndex: i32): void {
if (index >> 3 == this.cachedGroup) {
unchecked((this.leafIndexBySet[byteNum] = packedIndex >> 3));
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
throw new Error(
`Attempting access at index ${index}, beyond virtualLength ${this.arrayContext.getVirtualLength()}`
);
}
}

Expand All @@ -165,13 +180,6 @@ export class PackedArray {
this.add(index, 1);
}

private safeGetPackedIndexgetPackedIndex(
setNumber: i32,
virtualIndex: i32
): i32 {
return this.arrayContext.getPackedIndex(setNumber, virtualIndex, true);
}

/**
* Add to a value at a virtual index in the array
* @param index the virtual index of the value to be added to
Expand All @@ -185,23 +193,37 @@ export class PackedArray {
return;
}
// 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 packedIndex = this.safeGetPackedIndexgetPackedIndex(byteNum, index);
if (packedIndex < 0) {
// The packed storage is full, the lower bytes have already been added
this.unpack();
this.arrayContext.addAndGetAtUnpackedIndex(
index,
remainingValueToAdd << (byteNum << 3)
);
return;
let leafIndex =
byteNum < this.knownSets
? unchecked(leafIndexBySet[byteNum])
: UNKNOWN_LEAF;
if (leafIndex < 0) {
// Make sure byte is populated:
const packedIndex = arrayContext.getPackedIndex(byteNum, index, true);
if (packedIndex < 0) {
// The packed storage is full, the lower bytes have already been added
this.unpack();
this.arrayContext.addAndGetAtUnpackedIndex(
index,
remainingValueToAdd << (byteNum << 3)
);
return;
}
leafIndex = packedIndex >> 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.
this.knownSets = byteNum + 1;
}
this.noteLeaf(index, byteNum, packedIndex);

const byteToAdd = <u8>(remainingValueToAdd & 0xff);
const afterAddByteValue = arrayContext.addAtByteIndex(
packedIndex,
(leafIndex << 3) + byteInLeaf,
byteToAdd
);

Expand All @@ -228,30 +250,50 @@ export class PackedArray {
return;
}
// 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++) {
if (valueForNextLevels == 0) {
// Special-case zeros to avoid inflating packed array for no reason
const packedIndex = arrayContext.getPackedIndex(byteNum, index, false);
if (packedIndex < 0) {
return; // no need to create entries for zero values if they don't already exist
let leafIndex =
byteNum < this.knownSets
? unchecked(leafIndexBySet[byteNum])
: UNKNOWN_LEAF;
if (leafIndex < 0) {
let packedIndex: i32;
if (valueForNextLevels == 0) {
// Special-case zeros to avoid inflating packed array for no reason
if (leafIndex == NO_LEAF) {
return; // no need to create entries for zero values if they don't already exist
}
packedIndex = arrayContext.getPackedIndex(byteNum, index, false);
if (packedIndex < 0) {
unchecked((leafIndexBySet[byteNum] = NO_LEAF));
this.knownSets = byteNum + 1;
return;
}
} else {
// Make sure byte is populated:
packedIndex = arrayContext.getPackedIndex(byteNum, index, true);
if (packedIndex < 0) {
// The packed storage is full
this.unpack();
this.arrayContext.setAtUnpackedIndex(index, value);
return;
}
}
leafIndex = packedIndex >> 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.
this.knownSets = byteNum + 1;
}
// Make sure byte is populated:
const packedIndex = arrayContext.getPackedIndex(byteNum, index, true);
if (packedIndex < 0) {
// The packed storage is full
this.unpack();
this.arrayContext.setAtUnpackedIndex(index, value);
return;
}
this.noteLeaf(index, byteNum, packedIndex);

// Determine value to write, and prepare for next levels
const byteToWrite: u8 = <u8>(valueForNextLevels & 0xff);
valueForNextLevels = valueForNextLevels >> 8;

arrayContext.setAtByteIndex(packedIndex, byteToWrite);
arrayContext.setAtByteIndex((leafIndex << 3) + byteInLeaf, byteToWrite);
}
}

Expand Down Expand Up @@ -293,6 +335,7 @@ export class PackedArray {
*/
public clear(): void {
this.cachedGroup = -1;
this.knownSets = 0;
this.arrayContext.clear();
}

Expand Down
Loading
Loading