@typeberry/lib 0.9.0-959889e → 0.9.0-a723180

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/package.json +1 -1
  2. package/packages/core/collections/sorted-array.d.ts +1 -1
  3. package/packages/core/collections/sorted-array.d.ts.map +1 -1
  4. package/packages/core/collections/sorted-array.js +4 -2
  5. package/packages/core/collections/sorted-array.test.js +10 -0
  6. package/packages/core/collections/sorted-set.d.ts +1 -1
  7. package/packages/core/collections/sorted-set.d.ts.map +1 -1
  8. package/packages/core/collections/sorted-set.js +6 -2
  9. package/packages/core/collections/sorted-set.test.js +24 -0
  10. package/packages/core/utils/shutdown.d.ts +3 -3
  11. package/packages/core/utils/shutdown.d.ts.map +1 -1
  12. package/packages/core/utils/shutdown.js +2 -79
  13. package/packages/core/utils/shutdown.node.d.ts +5 -0
  14. package/packages/core/utils/shutdown.node.d.ts.map +1 -0
  15. package/packages/core/utils/shutdown.node.js +76 -0
  16. package/packages/core/utils/shutdown.test.js +32 -23
  17. package/packages/jam/config-node/node-config.d.ts +20 -2
  18. package/packages/jam/config-node/node-config.d.ts.map +1 -1
  19. package/packages/jam/config-node/node-config.js +25 -3
  20. package/packages/jam/config-node/node-config.test.js +8 -1
  21. package/packages/jam/database/index.d.ts +1 -0
  22. package/packages/jam/database/index.d.ts.map +1 -1
  23. package/packages/jam/database/index.js +1 -0
  24. package/packages/jam/database/leaf-db-update.d.ts +1 -0
  25. package/packages/jam/database/leaf-db-update.d.ts.map +1 -1
  26. package/packages/jam/database/leaf-db-update.js +22 -5
  27. package/packages/jam/database/leaf-db-update.test.d.ts +2 -0
  28. package/packages/jam/database/leaf-db-update.test.d.ts.map +1 -0
  29. package/packages/jam/database/leaf-db-update.test.js +81 -0
  30. package/packages/jam/database/serialized-states-db.d.ts +4 -0
  31. package/packages/jam/database/serialized-states-db.d.ts.map +1 -1
  32. package/packages/jam/database/serialized-states-db.js +18 -2
  33. package/packages/jam/database/serialized-states-db.test.d.ts +2 -0
  34. package/packages/jam/database/serialized-states-db.test.d.ts.map +1 -0
  35. package/packages/jam/database/serialized-states-db.test.js +109 -0
  36. package/packages/jam/database/states.d.ts +11 -0
  37. package/packages/jam/database/states.d.ts.map +1 -1
  38. package/packages/jam/database/states.js +3 -0
  39. package/packages/jam/database/value-refs.d.ts +117 -0
  40. package/packages/jam/database/value-refs.d.ts.map +1 -0
  41. package/packages/jam/database/value-refs.js +206 -0
  42. package/packages/jam/database/value-refs.test.d.ts +2 -0
  43. package/packages/jam/database/value-refs.test.d.ts.map +1 -0
  44. package/packages/jam/database/value-refs.test.js +165 -0
  45. package/packages/jam/database-fjall/blocks.d.ts +25 -0
  46. package/packages/jam/database-fjall/blocks.d.ts.map +1 -0
  47. package/packages/jam/database-fjall/blocks.js +86 -0
  48. package/packages/jam/database-fjall/blocks.test.d.ts +2 -0
  49. package/packages/jam/database-fjall/blocks.test.d.ts.map +1 -0
  50. package/packages/jam/database-fjall/blocks.test.js +62 -0
  51. package/packages/jam/database-fjall/hybrid-states.d.ts +14 -0
  52. package/packages/jam/database-fjall/hybrid-states.d.ts.map +1 -1
  53. package/packages/jam/database-fjall/hybrid-states.js +55 -6
  54. package/packages/jam/database-fjall/hybrid-states.test.js +94 -2
  55. package/packages/jam/database-fjall/index.d.ts +2 -0
  56. package/packages/jam/database-fjall/index.d.ts.map +1 -1
  57. package/packages/jam/database-fjall/index.js +2 -0
  58. package/packages/jam/database-fjall/root.d.ts +14 -8
  59. package/packages/jam/database-fjall/root.d.ts.map +1 -1
  60. package/packages/jam/database-fjall/root.js +25 -9
  61. package/packages/jam/database-fjall/states.d.ts +31 -0
  62. package/packages/jam/database-fjall/states.d.ts.map +1 -0
  63. package/packages/jam/database-fjall/states.js +99 -0
  64. package/packages/jam/database-fjall/states.test.d.ts +2 -0
  65. package/packages/jam/database-fjall/states.test.d.ts.map +1 -0
  66. package/packages/jam/database-fjall/states.test.js +150 -0
  67. package/packages/jam/database-lmdb/hybrid-states.d.ts +12 -0
  68. package/packages/jam/database-lmdb/hybrid-states.d.ts.map +1 -1
  69. package/packages/jam/database-lmdb/hybrid-states.js +45 -4
  70. package/packages/jam/database-lmdb/hybrid-states.test.js +94 -2
  71. package/packages/jam/database-lmdb/states.d.ts +1 -0
  72. package/packages/jam/database-lmdb/states.d.ts.map +1 -1
  73. package/packages/jam/database-lmdb/states.js +5 -0
  74. package/packages/jam/node/export.d.ts.map +1 -1
  75. package/packages/jam/node/export.js +18 -9
  76. package/packages/jam/node/main-fuzz.d.ts.map +1 -1
  77. package/packages/jam/node/main-fuzz.js +85 -71
  78. package/packages/jam/node/main-importer.d.ts +4 -2
  79. package/packages/jam/node/main-importer.d.ts.map +1 -1
  80. package/packages/jam/node/main-importer.js +26 -12
  81. package/packages/jam/node/main.d.ts.map +1 -1
  82. package/packages/jam/node/main.js +42 -15
  83. package/packages/jam/node/workers.d.ts +4 -4
  84. package/packages/jam/node/workers.d.ts.map +1 -1
  85. package/packages/workers/api/config.d.ts +2 -2
  86. package/packages/workers/api/config.d.ts.map +1 -1
  87. package/packages/workers/api/config.js +1 -1
  88. package/packages/workers/api/port.d.ts +5 -1
  89. package/packages/workers/api/port.d.ts.map +1 -1
  90. package/packages/workers/api/port.js +56 -13
  91. package/packages/workers/api/port.test.js +35 -0
  92. package/packages/workers/api-node/config.d.ts +45 -4
  93. package/packages/workers/api-node/config.d.ts.map +1 -1
  94. package/packages/workers/api-node/config.js +127 -9
  95. package/packages/workers/api-node/config.test.js +52 -3
  96. package/packages/workers/api-node/port.d.ts +3 -0
  97. package/packages/workers/api-node/port.d.ts.map +1 -1
  98. package/packages/workers/api-node/port.js +31 -2
  99. package/packages/workers/api-node/port.test.js +17 -0
  100. package/packages/workers/api-node/protocol.d.ts +3 -3
  101. package/packages/workers/api-node/protocol.d.ts.map +1 -1
  102. package/packages/workers/api-node/protocol.js +18 -12
  103. package/packages/workers/block-authorship/main.js +1 -1
  104. package/packages/workers/importer/finality.d.ts +4 -0
  105. package/packages/workers/importer/finality.d.ts.map +1 -1
  106. package/packages/workers/importer/finality.js +10 -1
  107. package/packages/workers/importer/finality.test.js +6 -0
  108. package/packages/workers/importer/importer.d.ts.map +1 -1
  109. package/packages/workers/importer/importer.js +3 -0
  110. package/packages/workers/importer/main.d.ts +1 -1
  111. package/packages/workers/importer/main.d.ts.map +1 -1
  112. package/packages/workers/importer/main.js +1 -1
  113. package/packages/workers/jam-network/main.js +1 -1
@@ -0,0 +1,81 @@
1
+ import assert from "node:assert";
2
+ import { before, describe, it } from "node:test";
3
+ import { Bytes, BytesBlob } from "#@typeberry/bytes";
4
+ import { SortedSet } from "#@typeberry/collections";
5
+ import { Blake2b, HASH_SIZE } from "#@typeberry/hash";
6
+ import { StateEntryUpdateAction } from "#@typeberry/state-merkleization";
7
+ import { leafComparator } from "#@typeberry/trie";
8
+ import { updateLeafs } from "./leaf-db-update.js";
9
+ let blake2b;
10
+ before(async () => {
11
+ blake2b = await Blake2b.createHasher();
12
+ });
13
+ function key(n) {
14
+ return Bytes.fill(HASH_SIZE, n).asOpaque();
15
+ }
16
+ /** A value larger than 32 bytes, so it does not fit into the leaf and is hash-referenced. */
17
+ function bigValue(b) {
18
+ return Bytes.fill(64, b);
19
+ }
20
+ /** A value that fits directly into the leaf node. */
21
+ function smallValue(b) {
22
+ return Bytes.fill(4, b);
23
+ }
24
+ function emptyLeafs() {
25
+ return SortedSet.fromArray(leafComparator, []);
26
+ }
27
+ function asStrings(hashes) {
28
+ return hashes.map((h) => h.toString());
29
+ }
30
+ describe("updateLeafs", () => {
31
+ it("collects a freshly inserted non-embedded value and removes nothing", () => {
32
+ const leafs = emptyLeafs();
33
+ const res = updateLeafs(leafs, blake2b, [[StateEntryUpdateAction.Insert, key(1), bigValue(0xaa)]]);
34
+ assert.strictEqual(res.values.length, 1);
35
+ assert.deepStrictEqual(res.removed, []);
36
+ });
37
+ it("collects nothing for an embedded value", () => {
38
+ const leafs = emptyLeafs();
39
+ const res = updateLeafs(leafs, blake2b, [[StateEntryUpdateAction.Insert, key(1), smallValue(0xaa)]]);
40
+ assert.deepStrictEqual(res.values, []);
41
+ assert.deepStrictEqual(res.removed, []);
42
+ });
43
+ it("emits the displaced value hash in `removed` when a leaf is replaced", () => {
44
+ const leafs = emptyLeafs();
45
+ const first = updateLeafs(leafs, blake2b, [[StateEntryUpdateAction.Insert, key(1), bigValue(0xaa)]]);
46
+ const oldHash = first.values[0][0];
47
+ const res = updateLeafs(leafs, blake2b, [[StateEntryUpdateAction.Insert, key(1), bigValue(0xbb)]]);
48
+ assert.strictEqual(res.values.length, 1);
49
+ assert.deepStrictEqual(asStrings(res.removed), asStrings([oldHash]));
50
+ });
51
+ it("cancels out when the same value is re-inserted at the same key", () => {
52
+ const leafs = emptyLeafs();
53
+ updateLeafs(leafs, blake2b, [[StateEntryUpdateAction.Insert, key(1), bigValue(0xaa)]]);
54
+ const res = updateLeafs(leafs, blake2b, [[StateEntryUpdateAction.Insert, key(1), bigValue(0xaa)]]);
55
+ assert.deepStrictEqual(res.values, []);
56
+ assert.deepStrictEqual(res.removed, []);
57
+ });
58
+ it("emits the old hash when a non-embedded value becomes embedded", () => {
59
+ const leafs = emptyLeafs();
60
+ const first = updateLeafs(leafs, blake2b, [[StateEntryUpdateAction.Insert, key(1), bigValue(0xaa)]]);
61
+ const oldHash = first.values[0][0];
62
+ const res = updateLeafs(leafs, blake2b, [[StateEntryUpdateAction.Insert, key(1), smallValue(0xbb)]]);
63
+ assert.deepStrictEqual(res.values, []);
64
+ assert.deepStrictEqual(asStrings(res.removed), asStrings([oldHash]));
65
+ });
66
+ it("emits the removed value hash when a non-embedded leaf is removed", () => {
67
+ const leafs = emptyLeafs();
68
+ const first = updateLeafs(leafs, blake2b, [[StateEntryUpdateAction.Insert, key(1), bigValue(0xaa)]]);
69
+ const oldHash = first.values[0][0];
70
+ const res = updateLeafs(leafs, blake2b, [[StateEntryUpdateAction.Remove, key(1), BytesBlob.empty()]]);
71
+ assert.deepStrictEqual(res.values, []);
72
+ assert.deepStrictEqual(asStrings(res.removed), asStrings([oldHash]));
73
+ });
74
+ it("removes nothing when an embedded leaf is removed", () => {
75
+ const leafs = emptyLeafs();
76
+ updateLeafs(leafs, blake2b, [[StateEntryUpdateAction.Insert, key(1), smallValue(0xaa)]]);
77
+ const res = updateLeafs(leafs, blake2b, [[StateEntryUpdateAction.Remove, key(1), BytesBlob.empty()]]);
78
+ assert.deepStrictEqual(res.values, []);
79
+ assert.deepStrictEqual(res.removed, []);
80
+ });
81
+ });
@@ -15,6 +15,8 @@ export declare class InMemorySerializedStates implements StatesDb<SerializedStat
15
15
  private readonly blake2b;
16
16
  private readonly db;
17
17
  private readonly valuesDb;
18
+ private readonly refsStore;
19
+ private readonly refs;
18
20
  static new({ chainSpec }: {
19
21
  chainSpec: ChainSpec;
20
22
  }): Promise<InMemorySerializedStates>;
@@ -27,7 +29,9 @@ export declare class InMemorySerializedStates implements StatesDb<SerializedStat
27
29
  getStateRoot(state: SerializedState<LeafDb>): Promise<StateRootHash>;
28
30
  updateAndSetState(header: HeaderHash, state: SerializedState<LeafDb>, update: Partial<State & ServicesUpdate>): Promise<Result<OK, StateUpdateError>>;
29
31
  getState(header: HeaderHash): SerializedState<LeafDb> | null;
32
+ commitFinalized(headers: HeaderHash[]): void;
30
33
  markUnused(header: HeaderHash): void;
34
+ private applyRefs;
31
35
  close(): Promise<void>;
32
36
  }
33
37
  //# sourceMappingURL=serialized-states-db.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"serialized-states-db.d.ts","sourceRoot":"","sources":["../../../../../packages/jam/database/serialized-states-db.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAGlE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC1C,OAAO,KAAK,EAAE,KAAK,EA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af-db-update.js";
8
+ import { InMemoryValueRefsStore, ValueRefs } from "./value-refs.js";
8
9
  /** In-memory serialized-states db. */
9
10
  export class InMemorySerializedStates {
10
11
  spec;
11
12
  blake2b;
12
13
  db = HashDictionary.new();
13
14
  valuesDb = HashDictionary.new();
15
+ refsStore = new InMemoryValueRefsStore();
16
+ refs = new ValueRefs(this.refsStore);
14
17
  static async new({ chainSpec }) {
15
18
  const blake2b = await Blake2b.createHasher();
16
19
  return new InMemorySerializedStates(chainSpec, blake2b);
@@ -30,6 +33,7 @@ export class InMemorySerializedStates {
30
33
  this.valuesDb.set(val[0], val[1]);
31
34
  }
32
35
  this.db.set(headerHash, leafs);
36
+ this.applyRefs(this.refs.onInitial(values.map((v) => v[0])));
33
37
  return Result.ok(OK);
34
38
  }
35
39
  async getStateRoot(state) {
@@ -40,17 +44,19 @@ export class InMemorySerializedStates {
40
44
  const updatedValues = serializeStateUpdate(this.spec, blake2b, update);
41
45
  // make sure to clone the leafs before writing, since the collection is re-used.
42
46
  const newLeafs = SortedSet.fromSortedArray(leafComparator, state.backend.leafs.array);
43
- const { values, leafs } = updateLeafs(newLeafs, blake2b, updatedValues);
47
+ const { values, removed, leafs } = updateLeafs(newLeafs, blake2b, updatedValues);
44
48
  // make sure to reset the cache and re-create leafsdb lookup
45
49
  state.updateBackend(LeafDb.fromLeaves(leafs, state.backend.db));
46
50
  // insert values to the db
47
51
  // valuesdb can be shared between all states because it's just
48
- // <valuehash> -> <value> mapping and existence is managed by trie leafs.
52
+ // <valuehash> -> <value> mapping and existence is managed by value
53
+ // refcounting, driven by the per-block deltas recorded below.
49
54
  for (const val of values) {
50
55
  this.valuesDb.set(val[0], val[1]);
51
56
  }
52
57
  // store new set of leaves
53
58
  this.db.set(header, leafs);
59
+ this.applyRefs(this.refs.onImport(header, { inserted: values.map((v) => v[0]), removed }));
54
60
  return Result.ok(OK);
55
61
  }
56
62
  getState(header) {
@@ -70,8 +76,18 @@ export class InMemorySerializedStates {
70
76
  });
71
77
  return SerializedState.new(this.spec, this.blake2b, leafDb);
72
78
  }
79
+ commitFinalized(headers) {
80
+ this.applyRefs(this.refs.commitFinalized(headers));
81
+ }
73
82
  markUnused(header) {
83
+ this.applyRefs(this.refs.releaseUnfinalized(header));
74
84
  this.db.delete(header);
75
85
  }
86
+ applyRefs(update) {
87
+ this.refsStore.apply(update);
88
+ for (const v of update.removeValues) {
89
+ this.valuesDb.delete(v);
90
+ }
91
+ }
76
92
  async close() { }
77
93
  }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=serialized-states-db.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serialized-states-db.test.d.ts","sourceRoot":"","sources":["../../../../../packages/jam/database/serialized-states-db.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,109 @@
1
+ import assert from "node:assert";
2
+ import { before, describe, it } from "node:test";
3
+ import { tryAsServiceId } from "#@typeberry/block";
4
+ import { Bytes, BytesBlob } from "#@typeberry/bytes";
5
+ import { tinyChainSpec } from "#@typeberry/config";
6
+ import { Blake2b, HASH_SIZE } from "#@typeberry/hash";
7
+ import { StorageItem, UpdateStorage } from "#@typeberry/state";
8
+ import { testState } from "#@typeberry/state/test.utils.js";
9
+ import { StateEntries } from "#@typeberry/state-merkleization";
10
+ import { asOpaqueType, deepEqual, OK, Result } from "#@typeberry/utils";
11
+ import { InMemorySerializedStates } from "./serialized-states-db.js";
12
+ let blake2b;
13
+ before(async () => {
14
+ blake2b = await Blake2b.createHasher();
15
+ });
16
+ const spec = tinyChainSpec;
17
+ function hh(n) {
18
+ return Bytes.fill(HASH_SIZE, n).asOpaque();
19
+ }
20
+ const storageKey = asOpaqueType(BytesBlob.blobFromString("test-key"));
21
+ /** A state update writing a single large (non-embedded) value under `storageKey`. */
22
+ function storageUpdate(value) {
23
+ const item = StorageItem.create({ key: storageKey, value: BytesBlob.blobFromString(value) });
24
+ return {
25
+ storage: new Map([[tryAsServiceId(0), [UpdateStorage.set({ storage: item })]]]),
26
+ };
27
+ }
28
+ // > 32 bytes => stored in the values db (not embedded in the leaf).
29
+ const BIG_1 = "a".repeat(100);
30
+ const BIG_2 = "b".repeat(100);
31
+ async function newStates() {
32
+ const states = InMemorySerializedStates.withHasher({ chainSpec: spec, blake2b });
33
+ const res = await states.insertInitialState(hh(0), StateEntries.serializeInMemory(spec, blake2b, testState()));
34
+ deepEqual(res, Result.ok(OK));
35
+ return states;
36
+ }
37
+ /** `true` if every value referenced by the state can still be resolved. */
38
+ function canReadFully(state) {
39
+ if (state === null) {
40
+ return false;
41
+ }
42
+ try {
43
+ state.backend.intoStateEntries();
44
+ return true;
45
+ }
46
+ catch {
47
+ return false;
48
+ }
49
+ }
50
+ describe("InMemorySerializedStates value refcounting", () => {
51
+ it("keeps a replaced value until the block replacing it finalizes", async () => {
52
+ const states = await newStates();
53
+ const s0 = states.getState(hh(0));
54
+ assert.ok(s0 !== null);
55
+ await states.updateAndSetState(hh(1), s0, storageUpdate(BIG_1));
56
+ // a handle to the post-1 state, surviving the pruning below
57
+ const stale1 = states.getState(hh(1));
58
+ const s1 = states.getState(hh(1));
59
+ assert.ok(s1 !== null);
60
+ await states.updateAndSetState(hh(2), s1, storageUpdate(BIG_2));
61
+ states.commitFinalized([hh(1)]);
62
+ assert.ok(canReadFully(stale1), "still referenced by the finalized tip");
63
+ states.commitFinalized([hh(2)]);
64
+ assert.ok(!canReadFully(stale1), "replaced value is dropped once the replacement finalizes");
65
+ assert.ok(canReadFully(states.getState(hh(2))), "the new finalized tip stays fully readable");
66
+ });
67
+ it("collects values of a pruned dead fork and keeps the surviving chain intact", async () => {
68
+ const states = await newStates();
69
+ const s0 = states.getState(hh(0));
70
+ assert.ok(s0 !== null);
71
+ await states.updateAndSetState(hh(1), s0, storageUpdate(BIG_1));
72
+ // a dead fork on top of genesis, inserting a different value
73
+ const fork = states.getState(hh(0));
74
+ assert.ok(fork !== null);
75
+ await states.updateAndSetState(hh(0xaa), fork, storageUpdate(BIG_2));
76
+ const staleFork = states.getState(hh(0xaa));
77
+ states.markUnused(hh(0xaa));
78
+ assert.strictEqual(states.getState(hh(0xaa)), null);
79
+ assert.ok(!canReadFully(staleFork), "fork-only value is collected");
80
+ assert.ok(canReadFully(states.getState(hh(1))), "surviving chain is unaffected");
81
+ });
82
+ it("does not collect a value shared with a pruned fork", async () => {
83
+ const states = await newStates();
84
+ const s0 = states.getState(hh(0));
85
+ assert.ok(s0 !== null);
86
+ await states.updateAndSetState(hh(1), s0, storageUpdate(BIG_1));
87
+ // the fork writes the very same value
88
+ const fork = states.getState(hh(0));
89
+ assert.ok(fork !== null);
90
+ await states.updateAndSetState(hh(0xaa), fork, storageUpdate(BIG_1));
91
+ states.markUnused(hh(0xaa));
92
+ assert.ok(canReadFully(states.getState(hh(1))), "value still referenced by the surviving chain");
93
+ });
94
+ it("follows the importer lifecycle: commit finalized, then prune", async () => {
95
+ const states = await newStates();
96
+ const s0 = states.getState(hh(0));
97
+ assert.ok(s0 !== null);
98
+ await states.updateAndSetState(hh(1), s0, storageUpdate(BIG_1));
99
+ const s1 = states.getState(hh(1));
100
+ assert.ok(s1 !== null);
101
+ await states.updateAndSetState(hh(2), s1, storageUpdate(BIG_2));
102
+ // finality round: 1 and 2 finalized, genesis and 1 pruned
103
+ states.commitFinalized([hh(1), hh(2)]);
104
+ states.markUnused(hh(0));
105
+ states.markUnused(hh(1));
106
+ assert.strictEqual(states.getState(hh(1)), null);
107
+ assert.ok(canReadFully(states.getState(hh(2))), "finalized tip fully readable after pruning");
108
+ });
109
+ });
@@ -33,6 +33,16 @@ export interface StatesDb<T extends State = State> {
33
33
  updateAndSetState(header: HeaderHash, state: T, update: Partial<State & ServicesUpdate>): Promise<Result<OK, StateUpdateError>>;
34
34
  /** Retrieve posterior state of given header. */
35
35
  getState(header: HeaderHash): T | null;
36
+ /**
37
+ * Notify the backend about newly finalized blocks, in ancestor-first order.
38
+ *
39
+ * Backends that share data between states (e.g. a content-addressed values DB)
40
+ * use this to move the blocks' references from speculative to finalized.
41
+ * MUST be called before `markUnused` of the same finality round, otherwise
42
+ * the newly finalized blocks would be treated as dead forks and values still
43
+ * referenced by the finalized state could be dropped.
44
+ */
45
+ commitFinalized(headers: HeaderHash[]): void;
36
46
  /** Mark state as no longer needed. Backend may remove it asynchronously. */
37
47
  markUnused(header: HeaderHash): void;
38
48
  /**
@@ -56,6 +66,7 @@ export declare class InMemoryStates implements StatesDb<InMemoryState> {
56
66
  /** Insert a full state into the database. */
57
67
  insertInitialState(headerHash: HeaderHash, state: InMemoryState): Promise<Result<OK, StateUpdateError>>;
58
68
  getState(headerHash: HeaderHash): InMemoryState | null;
69
+ commitFinalized(_headers: HeaderHash[]): void;
59
70
  markUnused(header: HeaderHash): void;
60
71
  close(): Promise<void>;
61
72
  }
@@ -1 +1 @@
1
- {"version":3,"file":"states.d.ts","sourceRoot":"","sources":["../../../../../packages/jam/database/states.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAElE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAEnD,OAAO,EAAE,aAAa,EAAE,KAAK,cAAc,EAAE,KAAK,KAAK,EAAe,MAAM,kBAAkB,CAAC;AAE/F,OAAO,EAAe,EAAE,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAE3D,0DAA0D;AAC1D,oBAAY,gBAAgB;IAC1B,oDAAoD;IACpD,QAAQ,IAAI;IACZ,iDAAiD;IACjD,MAAM,IAAI;CACX;AAED,wFAAwF;AACxF,MAAM,WAAW,YAAY,CAAC,CAAC,GAAG,KAAK;IACrC,qEAAqE;IACrE,kBAAkB,CAAC,UAAU,EAAE,UAAU,EAAE,YAAY,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,EAAE,EAAE,gBAAgB,CAAC,CAAC,CAAC;CACpG;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,QAAQ,CAAC,CAAC,SAAS,KA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 // nothing to do: every state is a full, independent copy.
58
+ }
56
59
  markUnused(header) {
57
60
  this.db.delete(header);
58
61
  }
@@ -0,0 +1,117 @@
1
+ import type { HeaderHash } from "#@typeberry/block";
2
+ import type { ValueHash } from "#@typeberry/trie";
3
+ /** The value hashes a single block introduced and stopped referencing. */
4
+ export interface ValueDelta {
5
+ /** Value hashes (non-embedded) that the block started referencing. */
6
+ inserted: ValueHash[];
7
+ /** Value hashes (non-embedded) that the block stopped referencing. */
8
+ removed: ValueHash[];
9
+ }
10
+ /**
11
+ * Synchronous, read-only view of the persisted refcounting state.
12
+ *
13
+ * Both LMDB and fjall offer synchronous reads, so reads can go straight
14
+ * to the backing store. All writes go through `ValueRefsUpdate` batches
15
+ * instead, since persistent backends can only write asynchronously
16
+ * (LMDB transactions, fjall inserts + persist).
17
+ */
18
+ export interface ValueRefsReader {
19
+ /** How many leaves of the finalized-tip state reference the value. Missing keys read as `0`. */
20
+ getFinalizedCount(hash: ValueHash): number;
21
+ /** How many surviving, not-yet-finalized blocks inserted the value. Missing keys read as `0`. */
22
+ getPendingCount(hash: ValueHash): number;
23
+ /** The value delta of a not-yet-finalized block, if known. */
24
+ getDelta(header: HeaderHash): ValueDelta | undefined;
25
+ }
26
+ /**
27
+ * A batch of refcounting mutations produced by a single `ValueRefs` operation.
28
+ *
29
+ * The backend is responsible for applying the batch using its own write
30
+ * primitive - ideally atomically with the state write that triggered it
31
+ * (one LMDB transaction, one fjall persist).
32
+ *
33
+ * Counts are absolute values rather than increments, so applying the same
34
+ * update more than once (e.g. on crash-replay) is harmless.
35
+ *
36
+ * When atomicity is not available, apply in field order and `removeValues`
37
+ * strictly last: a crash after counts are persisted but before values are
38
+ * removed only leaks values, while the opposite order could drop a value
39
+ * the persisted counts still consider referencd.
40
+ */
41
+ export interface ValueRefsUpdate {
42
+ /** New absolute finalized counts. Count `0` means the entry should be removed. */
43
+ finalizedCounts: [ValueHash, number][];
44
+ /** New absolute pending counts. Count `0` means the entry should be removed. */
45
+ pendingCounts: [ValueHash, number][];
46
+ /** Deltas of freshly imported blocks to persist. */
47
+ setDeltas: [HeaderHash, ValueDelta][];
48
+ /** Deltas consumed by finalization or fork pruning. */
49
+ removeDeltas: HeaderHash[];
50
+ /** Values that are no longer referenced and can be removed from the values DB. */
51
+ removeValues: ValueHash[];
52
+ }
53
+ /** `true` if applying the update would not change anything. */
54
+ export declare function isEmptyUpdate(update: ValueRefsUpdate): boolean;
55
+ /**
56
+ * Decides when a content-addressed value can be removed from the values DB.
57
+ *
58
+ * A value is needed as long as some surviving state references it. Surviving
59
+ * states are the finalized tip plus its unfinalized descendants, so we track:
60
+ * - `finalized`: how many leaves in the current finalized-tip state reference V,
61
+ * advanced strictly by replaying finalized blocks' deltas (never on prune);
62
+ * - `pending`: how many surviving, not-yet-finalized blocks inserted V (an
63
+ * over-approximation of unfinalized references).
64
+ *
65
+ * A value is removable exactly when both counts reach zero.
66
+ *
67
+ * This class only makes decisions: every operation reads the current state
68
+ * through `ValueRefsReader` and returns a `ValueRefsUpdate` describing what
69
+ * should change. Nothing is written here - the owning backend applies the
70
+ * update with whatever consistency guarantees it can provide.
71
+ */
72
+ export declare class ValueRefs {
73
+ private readonly reader;
74
+ constructor(reader: ValueRefsReader);
75
+ /** Record values referenced by the genesis / initial finalized state. */
76
+ onInitial(inserted: ValueHash[]): ValueRefsUpdate;
77
+ /**
78
+ * Record a freshly imported, not-yet-finalized block.
79
+ *
80
+ * Importing the same header twice is a no-op, otherwise the second import
81
+ * would double-count `pending` references and pin the values forever.
82
+ */
83
+ onImport(header: HeaderHash, delta: ValueDelta): ValueRefsUpdate;
84
+ /**
85
+ * Apply the value deltas of newly finalized blocks, in finalized (ancestor-first) order.
86
+ *
87
+ * Moves each inserted value from `pending` to `finalized`, drops `finalized`
88
+ * references for removed values, and collects anything that becomes unreferenced.
89
+ */
90
+ commitFinalized(headers: HeaderHash[]): ValueRefsUpdate;
91
+ /**
92
+ * Release the speculative references of a state being discarded.
93
+ *
94
+ * For a header that was still unfinalized (a dead fork) the returned update
95
+ * releases its inserted values, which may become collectable. For an already
96
+ * finalized state the update is empty (check with `isEmptyUpdate`): its delta
97
+ * was consumed on finality and its values are accounted for in `finalized`.
98
+ */
99
+ releaseUnfinalized(header: HeaderHash): ValueRefsUpdate;
100
+ }
101
+ /**
102
+ * In-memory refcounting store, reusable by the in-memory and hybrid states DBs
103
+ * (the hybrids cannot resume from disk anyway, so persisting counts buys nothing).
104
+ *
105
+ * NOTE: `apply` does not touch the values DB - the caller owns it and must
106
+ * handle `update.removeValues` itself.
107
+ */
108
+ export declare class InMemoryValueRefsStore implements ValueRefsReader {
109
+ private readonly finalized;
110
+ private readonly pending;
111
+ private readonly deltas;
112
+ getFinalizedCount(hash: ValueHash): number;
113
+ getPendingCount(hash: ValueHash): number;
114
+ getDelta(header: HeaderHash): ValueDelta | undefined;
115
+ apply(update: ValueRefsUpdate): void;
116
+ }
117
+ //# sourceMappingURL=value-refs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"value-refs.d.ts","sourceRoot":"","sources":["../../../../../packages/jam/database/value-refs.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEnD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAEjD,0EAA0E;AAC1E,MAAM,WAAW,UAAU;IACzB,sEAAsE;IACtE,QAAQ,EAAE,SAAS,EAAE,CAAC;IACtB,sEAAsE;IACtE,OAAO,EAAE,SAAS,EAAE,CAAC;CACtB;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,eAAe;IAC9B,gGAAgG;IAChG,iBAAiB,CAAC,IAAI,EAAE,SAAS,GAAG,MAAM,CAAC;IAC3C,iGAAiG;IACjG,eAAe,CAAC,IAAI,EAAE,SAAS,GAAG,MAAM,CAAC;IACzC,8DAA8D;IAC9D,QAAQ,CAAC,MAAM,EAAE,UAAU,GAAG,UAAU,GAAG,SAAS,CAAC;CACtD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S;IAIpD,KAAK,CAAC,MAAM,EAAE,eAAe,GAAG,IAAI;CAUrC"}
@@ -0,0 +1,206 @@
1
+ import { HashDictionary } from "#@typeberry/collections";
2
+ /** `true` if applying the update would not change anything. */
3
+ export function isEmptyUpdate(update) {
4
+ return (update.finalizedCounts.length === 0 &&
5
+ update.pendingCounts.length === 0 &&
6
+ update.setDeltas.length === 0 &&
7
+ update.removeDeltas.length === 0 &&
8
+ update.removeValues.length === 0);
9
+ }
10
+ /**
11
+ * Decides when a content-addressed value can be removed from the values DB.
12
+ *
13
+ * A value is needed as long as some surviving state references it. Surviving
14
+ * states are the finalized tip plus its unfinalized descendants, so we track:
15
+ * - `finalized`: how many leaves in the current finalized-tip state reference V,
16
+ * advanced strictly by replaying finalized blocks' deltas (never on prune);
17
+ * - `pending`: how many surviving, not-yet-finalized blocks inserted V (an
18
+ * over-approximation of unfinalized references).
19
+ *
20
+ * A value is removable exactly when both counts reach zero.
21
+ *
22
+ * This class only makes decisions: every operation reads the current state
23
+ * through `ValueRefsReader` and returns a `ValueRefsUpdate` describing what
24
+ * should change. Nothing is written here - the owning backend applies the
25
+ * update with whatever consistency guarantees it can provide.
26
+ */
27
+ export class ValueRefs {
28
+ reader;
29
+ constructor(reader) {
30
+ this.reader = reader;
31
+ }
32
+ /** Record values referenced by the genesis / initial finalized state. */
33
+ onInitial(inserted) {
34
+ const update = new UpdateBuilder(this.reader);
35
+ for (const v of inserted) {
36
+ update.incFinalized(v);
37
+ }
38
+ return update.build();
39
+ }
40
+ /**
41
+ * Record a freshly imported, not-yet-finalized block.
42
+ *
43
+ * Importing the same header twice is a no-op, otherwise the second import
44
+ * would double-count `pending` references and pin the values forever.
45
+ */
46
+ onImport(header, delta) {
47
+ const update = new UpdateBuilder(this.reader);
48
+ if (update.getDelta(header) !== undefined) {
49
+ return update.build();
50
+ }
51
+ update.setDelta(header, delta);
52
+ for (const v of delta.inserted) {
53
+ update.incPending(v);
54
+ }
55
+ return update.build();
56
+ }
57
+ /**
58
+ * Apply the value deltas of newly finalized blocks, in finalized (ancestor-first) order.
59
+ *
60
+ * Moves each inserted value from `pending` to `finalized`, drops `finalized`
61
+ * references for removed values, and collects anything that becomes unreferenced.
62
+ */
63
+ commitFinalized(headers) {
64
+ const update = new UpdateBuilder(this.reader);
65
+ for (const header of headers) {
66
+ const delta = update.getDelta(header);
67
+ if (delta === undefined) {
68
+ // already committed, or not tracked (e.g. genesis)
69
+ continue;
70
+ }
71
+ for (const v of delta.inserted) {
72
+ update.incFinalized(v);
73
+ update.decPending(v);
74
+ }
75
+ for (const v of delta.removed) {
76
+ update.decFinalized(v);
77
+ }
78
+ update.removeDelta(header);
79
+ }
80
+ return update.build();
81
+ }
82
+ /**
83
+ * Release the speculative references of a state being discarded.
84
+ *
85
+ * For a header that was still unfinalized (a dead fork) the returned update
86
+ * releases its inserted values, which may become collectable. For an already
87
+ * finalized state the update is empty (check with `isEmptyUpdate`): its delta
88
+ * was consumed on finality and its values are accounted for in `finalized`.
89
+ */
90
+ releaseUnfinalized(header) {
91
+ const update = new UpdateBuilder(this.reader);
92
+ const delta = update.getDelta(header);
93
+ if (delta === undefined) {
94
+ return update.build();
95
+ }
96
+ for (const v of delta.inserted) {
97
+ update.decPending(v);
98
+ }
99
+ update.removeDelta(header);
100
+ return update.build();
101
+ }
102
+ }
103
+ /**
104
+ * Accumulates mutations of a single operation as an overlay over the reader,
105
+ * so that later steps observe earlier ones (e.g. several blocks finalized at once).
106
+ */
107
+ class UpdateBuilder {
108
+ reader;
109
+ finalized = HashDictionary.new();
110
+ pending = HashDictionary.new();
111
+ setDeltas = HashDictionary.new();
112
+ removedDeltas = HashDictionary.new();
113
+ /** Values that lost a reference and may need removal - verified against final counts in `build`. */
114
+ removalCandidates = HashDictionary.new();
115
+ constructor(reader) {
116
+ this.reader = reader;
117
+ }
118
+ getDelta(header) {
119
+ if (this.removedDeltas.has(header)) {
120
+ return undefined;
121
+ }
122
+ return this.setDeltas.get(header) ?? this.reader.getDelta(header);
123
+ }
124
+ setDelta(header, delta) {
125
+ this.setDeltas.set(header, delta);
126
+ }
127
+ removeDelta(header) {
128
+ this.removedDeltas.set(header, header);
129
+ }
130
+ incFinalized(v) {
131
+ this.finalized.set(v, this.getFinalized(v) + 1);
132
+ }
133
+ decFinalized(v) {
134
+ this.finalized.set(v, Math.max(0, this.getFinalized(v) - 1));
135
+ this.removalCandidates.set(v, v);
136
+ }
137
+ incPending(v) {
138
+ this.pending.set(v, this.getPending(v) + 1);
139
+ }
140
+ decPending(v) {
141
+ this.pending.set(v, Math.max(0, this.getPending(v) - 1));
142
+ this.removalCandidates.set(v, v);
143
+ }
144
+ build() {
145
+ const removeValues = [];
146
+ for (const v of this.removalCandidates.values()) {
147
+ if (this.getFinalized(v) === 0 && this.getPending(v) === 0) {
148
+ removeValues.push(v);
149
+ }
150
+ }
151
+ return {
152
+ finalizedCounts: Array.from(this.finalized),
153
+ pendingCounts: Array.from(this.pending),
154
+ setDeltas: Array.from(this.setDeltas),
155
+ removeDeltas: Array.from(this.removedDeltas.keys()),
156
+ removeValues,
157
+ };
158
+ }
159
+ getFinalized(v) {
160
+ return this.finalized.get(v) ?? this.reader.getFinalizedCount(v);
161
+ }
162
+ getPending(v) {
163
+ return this.pending.get(v) ?? this.reader.getPendingCount(v);
164
+ }
165
+ }
166
+ /**
167
+ * In-memory refcounting store, reusable by the in-memory and hybrid states DBs
168
+ * (the hybrids cannot resume from disk anyway, so persisting counts buys nothing).
169
+ *
170
+ * NOTE: `apply` does not touch the values DB - the caller owns it and must
171
+ * handle `update.removeValues` itself.
172
+ */
173
+ export class InMemoryValueRefsStore {
174
+ finalized = HashDictionary.new();
175
+ pending = HashDictionary.new();
176
+ deltas = HashDictionary.new();
177
+ getFinalizedCount(hash) {
178
+ return this.finalized.get(hash) ?? 0;
179
+ }
180
+ getPendingCount(hash) {
181
+ return this.pending.get(hash) ?? 0;
182
+ }
183
+ getDelta(header) {
184
+ return this.deltas.get(header);
185
+ }
186
+ apply(update) {
187
+ applyCounts(this.finalized, update.finalizedCounts);
188
+ applyCounts(this.pending, update.pendingCounts);
189
+ for (const [header, delta] of update.setDeltas) {
190
+ this.deltas.set(header, delta);
191
+ }
192
+ for (const header of update.removeDeltas) {
193
+ this.deltas.delete(header);
194
+ }
195
+ }
196
+ }
197
+ function applyCounts(store, counts) {
198
+ for (const [hash, count] of counts) {
199
+ if (count === 0) {
200
+ store.delete(hash);
201
+ }
202
+ else {
203
+ store.set(hash, count);
204
+ }
205
+ }
206
+ }