@typeberry/lib 0.9.0-3f2c45b → 0.9.0-4a9f363

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 (110) 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/index.d.ts +1 -0
  11. package/packages/core/utils/index.d.ts.map +1 -1
  12. package/packages/core/utils/index.js +1 -0
  13. package/packages/core/utils/shutdown.d.ts +18 -0
  14. package/packages/core/utils/shutdown.d.ts.map +1 -0
  15. package/packages/core/utils/shutdown.js +3 -0
  16. package/packages/core/utils/shutdown.node.d.ts +5 -0
  17. package/packages/core/utils/shutdown.node.d.ts.map +1 -0
  18. package/packages/core/utils/shutdown.node.js +76 -0
  19. package/packages/core/utils/shutdown.test.d.ts +2 -0
  20. package/packages/core/utils/shutdown.test.d.ts.map +1 -0
  21. package/packages/core/utils/shutdown.test.js +164 -0
  22. package/packages/extensions/ipc/server.d.ts.map +1 -1
  23. package/packages/extensions/ipc/server.js +7 -0
  24. package/packages/jam/config-node/node-config.d.ts +20 -2
  25. package/packages/jam/config-node/node-config.d.ts.map +1 -1
  26. package/packages/jam/config-node/node-config.js +25 -3
  27. package/packages/jam/config-node/node-config.test.js +8 -1
  28. package/packages/jam/database/index.d.ts +1 -0
  29. package/packages/jam/database/index.d.ts.map +1 -1
  30. package/packages/jam/database/index.js +1 -0
  31. package/packages/jam/database/leaf-db-update.d.ts +1 -0
  32. package/packages/jam/database/leaf-db-update.d.ts.map +1 -1
  33. package/packages/jam/database/leaf-db-update.js +22 -5
  34. package/packages/jam/database/leaf-db-update.test.d.ts +2 -0
  35. package/packages/jam/database/leaf-db-update.test.d.ts.map +1 -0
  36. package/packages/jam/database/leaf-db-update.test.js +81 -0
  37. package/packages/jam/database/serialized-states-db.d.ts +1 -0
  38. package/packages/jam/database/serialized-states-db.d.ts.map +1 -1
  39. package/packages/jam/database/serialized-states-db.js +4 -0
  40. package/packages/jam/database/states.d.ts +11 -0
  41. package/packages/jam/database/states.d.ts.map +1 -1
  42. package/packages/jam/database/states.js +3 -0
  43. package/packages/jam/database/value-refs.d.ts +117 -0
  44. package/packages/jam/database/value-refs.d.ts.map +1 -0
  45. package/packages/jam/database/value-refs.js +206 -0
  46. package/packages/jam/database/value-refs.test.d.ts +2 -0
  47. package/packages/jam/database/value-refs.test.d.ts.map +1 -0
  48. package/packages/jam/database/value-refs.test.js +165 -0
  49. package/packages/jam/database-fjall/blocks.d.ts +25 -0
  50. package/packages/jam/database-fjall/blocks.d.ts.map +1 -0
  51. package/packages/jam/database-fjall/blocks.js +86 -0
  52. package/packages/jam/database-fjall/blocks.test.d.ts +2 -0
  53. package/packages/jam/database-fjall/blocks.test.d.ts.map +1 -0
  54. package/packages/jam/database-fjall/blocks.test.js +62 -0
  55. package/packages/jam/database-fjall/hybrid-states.d.ts +14 -0
  56. package/packages/jam/database-fjall/hybrid-states.d.ts.map +1 -1
  57. package/packages/jam/database-fjall/hybrid-states.js +55 -6
  58. package/packages/jam/database-fjall/index.d.ts +2 -0
  59. package/packages/jam/database-fjall/index.d.ts.map +1 -1
  60. package/packages/jam/database-fjall/index.js +2 -0
  61. package/packages/jam/database-fjall/root.d.ts +14 -8
  62. package/packages/jam/database-fjall/root.d.ts.map +1 -1
  63. package/packages/jam/database-fjall/root.js +25 -9
  64. package/packages/jam/database-fjall/states.d.ts +31 -0
  65. package/packages/jam/database-fjall/states.d.ts.map +1 -0
  66. package/packages/jam/database-fjall/states.js +99 -0
  67. package/packages/jam/database-fjall/states.test.d.ts +2 -0
  68. package/packages/jam/database-fjall/states.test.d.ts.map +1 -0
  69. package/packages/jam/database-fjall/states.test.js +150 -0
  70. package/packages/jam/database-lmdb/hybrid-states.d.ts +12 -0
  71. package/packages/jam/database-lmdb/hybrid-states.d.ts.map +1 -1
  72. package/packages/jam/database-lmdb/hybrid-states.js +45 -4
  73. package/packages/jam/database-lmdb/states.d.ts +1 -0
  74. package/packages/jam/database-lmdb/states.d.ts.map +1 -1
  75. package/packages/jam/database-lmdb/states.js +5 -0
  76. package/packages/jam/node/export.d.ts.map +1 -1
  77. package/packages/jam/node/export.js +18 -9
  78. package/packages/jam/node/main-fuzz.d.ts +4 -1
  79. package/packages/jam/node/main-fuzz.d.ts.map +1 -1
  80. package/packages/jam/node/main-fuzz.js +111 -82
  81. package/packages/jam/node/main-importer.d.ts +4 -2
  82. package/packages/jam/node/main-importer.d.ts.map +1 -1
  83. package/packages/jam/node/main-importer.js +26 -12
  84. package/packages/jam/node/main.d.ts.map +1 -1
  85. package/packages/jam/node/main.js +42 -15
  86. package/packages/jam/node/workers.d.ts +4 -4
  87. package/packages/jam/node/workers.d.ts.map +1 -1
  88. package/packages/workers/api/config.d.ts +2 -2
  89. package/packages/workers/api/config.d.ts.map +1 -1
  90. package/packages/workers/api/config.js +1 -1
  91. package/packages/workers/api/port.d.ts +5 -1
  92. package/packages/workers/api/port.d.ts.map +1 -1
  93. package/packages/workers/api/port.js +56 -13
  94. package/packages/workers/api/port.test.js +35 -0
  95. package/packages/workers/api-node/config.d.ts +45 -4
  96. package/packages/workers/api-node/config.d.ts.map +1 -1
  97. package/packages/workers/api-node/config.js +127 -9
  98. package/packages/workers/api-node/config.test.js +52 -3
  99. package/packages/workers/api-node/port.d.ts +3 -0
  100. package/packages/workers/api-node/port.d.ts.map +1 -1
  101. package/packages/workers/api-node/port.js +31 -2
  102. package/packages/workers/api-node/port.test.js +17 -0
  103. package/packages/workers/api-node/protocol.d.ts +3 -3
  104. package/packages/workers/api-node/protocol.d.ts.map +1 -1
  105. package/packages/workers/api-node/protocol.js +18 -12
  106. package/packages/workers/block-authorship/main.js +1 -1
  107. package/packages/workers/importer/main.d.ts +1 -1
  108. package/packages/workers/importer/main.d.ts.map +1 -1
  109. package/packages/workers/importer/main.js +1 -1
  110. package/packages/workers/jam-network/main.js +1 -1
@@ -7,18 +7,34 @@ export function updateLeafs(leafs, blake2b, data) {
7
7
  const blake2bTrieHasher = getBlake2bTrieHasher(blake2b);
8
8
  // We will collect all values that don't fit directly into leaf nodes.
9
9
  const values = [];
10
+ // Value hashes that are no longer referenced by the leaf they were stored under.
11
+ // NOTE this does not yet mean they can be removed from the DB - the same value
12
+ // may still be referenced by another leaf or another state. It's up to value
13
+ // ref-counting to decide that.
14
+ const removed = [];
10
15
  for (const [action, key, value] of data) {
11
16
  if (action === StateEntryUpdateAction.Insert) {
12
17
  const leafNode = InMemoryTrie.constructLeaf(blake2bTrieHasher, key.asOpaque(), value);
13
- leafs.replace(leafNode);
14
- if (!leafNode.hasEmbeddedValue()) {
15
- values.push([leafNode.getValueHash(), value]);
18
+ const displaced = leafs.replace(leafNode);
19
+ const newHash = leafNode.hasEmbeddedValue() ? null : leafNode.getValueHash();
20
+ const oldHash = displaced !== undefined && !displaced.hasEmbeddedValue() ? displaced.getValueHash() : null;
21
+ // Re-inserting the exact same value under the same key is a no-op for the DB.
22
+ if (newHash !== null && oldHash !== null && newHash.isEqualTo(oldHash)) {
23
+ continue;
24
+ }
25
+ if (newHash !== null) {
26
+ values.push([newHash, value]);
27
+ }
28
+ if (oldHash !== null) {
29
+ removed.push(oldHash);
16
30
  }
17
31
  }
18
32
  else if (action === StateEntryUpdateAction.Remove) {
19
33
  const leafNode = InMemoryTrie.constructLeaf(blake2bTrieHasher, key.asOpaque(), BytesBlob.empty());
20
- leafs.removeOne(leafNode);
21
- // TODO [ToDr] Handle ref-counting values or updating some header-hash-based references.
34
+ const removedLeaf = leafs.removeOne(leafNode);
35
+ if (removedLeaf !== undefined && !removedLeaf.hasEmbeddedValue()) {
36
+ removed.push(removedLeaf.getValueHash());
37
+ }
22
38
  }
23
39
  else {
24
40
  assertNever(action);
@@ -26,6 +42,7 @@ export function updateLeafs(leafs, blake2b, data) {
26
42
  }
27
43
  return {
28
44
  values,
45
+ removed,
29
46
  leafs,
30
47
  };
31
48
  }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=leaf-db-update.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"leaf-db-update.test.d.ts","sourceRoot":"","sources":["../../../../../packages/jam/database/leaf-db-update.test.ts"],"names":[],"mappings":""}
@@ -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
+ });
@@ -27,6 +27,7 @@ export declare class InMemorySerializedStates implements StatesDb<SerializedStat
27
27
  getStateRoot(state: SerializedState<LeafDb>): Promise<StateRootHash>;
28
28
  updateAndSetState(header: HeaderHash, state: SerializedState<LeafDb>, update: Partial<State & ServicesUpdate>): Promise<Result<OK, StateUpdateError>>;
29
29
  getState(header: HeaderHash): SerializedState<LeafDb> | null;
30
+ commitFinalized(_headers: HeaderHash[]): void;
30
31
  markUnused(header: HeaderHash): void;
31
32
  close(): Promise<void>;
32
33
  }
@@ -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,EAAE,MAAM,2BAA2B,CAAC;AACvD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kCAAkC,CAAC;AACvE,OAAO,EACL,eAAe,EACf,KAAK,YAAY,EAGlB,MAAM,gCAAgC,CAAC;AAExC,OAAO,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,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EAAE,SAAS,CAAA;KAAE;IAKxD,MAAM,CAAC,UAAU,CAAC,EAAE,SAAS,EAAE,OAAO,EAAE,EAAE;QAAE,SAAS,EAAE,SAAS,CAAC;QAAC,OAAO,EAAE,OAAO,CAAA;KAAE;IAIpF,OAAO;IAKD,kBAAkB,CAAC,UAAU,EAAE,UAAU,EAAE,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,MAAM,CAAC,EAAE,EAAE,gBAAgB,CAAC,CAAC;IAiBxG,YAAY,CAAC,KAAK,EAAE,eAAe,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC,aAAa,CAAC;IAIpE,iBAAiB,CACrB,MAAM,EAAE,UAAU,EAClB,KAAK,EAAE,eAAe,CAAC,MAAM,CAAC,EAC9B,MAAM,EAAE,OAAO,CAAC,KAAK,GAAG,cAAc,CAAC,GACtC,OAAO,CAAC,MAAM,CAAC,EAAE,EAAE,gBAAgB,CAAC,CAAC;IAsBxC,QAAQ,CAAC,MAAM,EAAE,UAAU,GAAG,eAAe,CAAC,MAAM,CAAC,GAAG,IAAI;IAkB5D,eAAe,CAAC,QAAQ,EAAE,UAAU,EAAE,GAAG,IAAI;IAK7C,UAAU,CAAC,MAAM,EAAE,UAAU,GAAG,IAAI;IAI9B,KAAK;CACZ"}
@@ -70,6 +70,10 @@ export class InMemorySerializedStates {
70
70
  });
71
71
  return SerializedState.new(this.spec, this.blake2b, leafDb);
72
72
  }
73
+ commitFinalized(_headers) {
74
+ // No value pruning here: this in-memory db keeps every value in a plain map
75
+ // and is not the long-running fuzz target the refcounting is meant for.
76
+ }
73
77
  markUnused(header) {
74
78
  this.db.delete(header);
75
79
  }
@@ -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,C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54
  return InMemoryState.copyFrom(this.spec, state, state.intoServicesData());
55
55
  }
56
+ commitFinalized(_headers) {
57
+ // 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;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,GAAG,MAAM;IAIxC,QAAQ,CAAC,MAAM,EAAE,UAAU,GAAG,UAAU,GAAG,SAAS;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
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=value-refs.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"value-refs.test.d.ts","sourceRoot":"","sources":["../../../../../packages/jam/database/value-refs.test.ts"],"names":[],"mappings":""}