2023-05-11 14:25:29 +00:00
|
|
|
# nimbus-eth1
|
2024-02-20 03:07:38 +00:00
|
|
|
# Copyright (c) 2023-2024 Status Research & Development GmbH
|
2023-05-11 14:25:29 +00:00
|
|
|
# Licensed under either of
|
|
|
|
# * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0)
|
|
|
|
# * MIT license ([LICENSE-MIT](LICENSE-MIT) or
|
|
|
|
# http://opensource.org/licenses/MIT)
|
|
|
|
# at your option. This file may not be copied, modified, or distributed
|
|
|
|
# except according to those terms.
|
|
|
|
|
|
|
|
{.push raises: [].}
|
|
|
|
|
|
|
|
import
|
2023-09-15 15:23:53 +00:00
|
|
|
results,
|
2024-07-02 18:25:06 +00:00
|
|
|
stew/[arrayops, endians2],
|
2023-11-08 12:18:32 +00:00
|
|
|
./aristo_desc
|
2023-05-11 14:25:29 +00:00
|
|
|
|
2024-09-13 13:47:50 +00:00
|
|
|
export aristo_desc, results
|
No ext update (#2494)
* Imported/rebase from `no-ext`, PR #2485
Store extension nodes together with the branch
Extension nodes must be followed by a branch - as such, it makes sense
to store the two together both in the database and in memory:
* fewer reads, writes and updates to traverse the tree
* simpler logic for maintaining the node structure
* less space used, both memory and storage, because there are fewer
nodes overall
There is also a downside: hashes can no longer be cached for an
extension - instead, only the extension+branch hash can be cached - this
seems like a fine tradeoff since computing it should be fast.
TODO: fix commented code
* Fix merge functions and `toNode()`
* Update `merkleSignCommit()` prototype
why:
Result is always a 32bit hash
* Update short Merkle hash key generation
details:
Ethereum reference MPTs use Keccak hashes as node links if the size of
an RLP encoded node is at least 32 bytes. Otherwise, the RLP encoded
node value is used as a pseudo node link (rather than a hash.) This is
specified in the yellow paper, appendix D.
Different to the `Aristo` implementation, the reference MPT would not
store such a node on the key-value database. Rather the RLP encoded node value is stored instead of a node link in a parent node
is stored as a node link on the parent database.
Only for the root hash, the top level node is always referred to by the
hash.
* Fix/update `Extension` sections
why:
Were commented out after removal of a dedicated `Extension` type which
left the system disfunctional.
* Clean up unused error codes
* Update unit tests
* Update docu
---------
Co-authored-by: Jacek Sieka <jacek@status.im>
2024-07-16 19:47:59 +00:00
|
|
|
|
2024-07-04 23:48:45 +00:00
|
|
|
# Allocation-free version short big-endian encoding that skips the leading
|
|
|
|
# zeroes
|
2024-07-02 18:25:06 +00:00
|
|
|
type
|
2024-07-04 23:48:45 +00:00
|
|
|
SbeBuf*[I] = object
|
2024-07-02 18:25:06 +00:00
|
|
|
buf*: array[sizeof(I), byte]
|
|
|
|
len*: byte
|
|
|
|
|
2024-07-04 13:46:52 +00:00
|
|
|
RVidBuf* = object
|
2024-07-04 23:48:45 +00:00
|
|
|
buf*: array[sizeof(SbeBuf[VertexID]) * 2, byte]
|
2024-07-04 13:46:52 +00:00
|
|
|
len*: byte
|
|
|
|
|
2024-07-02 18:25:06 +00:00
|
|
|
func significantBytesBE(val: openArray[byte]): byte =
|
|
|
|
for i in 0 ..< val.len:
|
|
|
|
if val[i] != 0:
|
|
|
|
return byte(val.len - i)
|
|
|
|
return 1
|
|
|
|
|
2024-07-04 23:48:45 +00:00
|
|
|
func blobify*(v: VertexID|uint64): SbeBuf[typeof(v)] =
|
2024-07-02 18:25:06 +00:00
|
|
|
let b = v.uint64.toBytesBE()
|
2024-07-04 23:48:45 +00:00
|
|
|
SbeBuf[typeof(v)](buf: b, len: significantBytesBE(b))
|
2024-07-02 18:25:06 +00:00
|
|
|
|
2024-07-04 23:48:45 +00:00
|
|
|
func blobify*(v: StUint): SbeBuf[typeof(v)] =
|
2024-07-02 18:25:06 +00:00
|
|
|
let b = v.toBytesBE()
|
2024-07-04 23:48:45 +00:00
|
|
|
SbeBuf[typeof(v)](buf: b, len: significantBytesBE(b))
|
2024-07-02 18:25:06 +00:00
|
|
|
|
2024-07-04 23:48:45 +00:00
|
|
|
template data*(v: SbeBuf): openArray[byte] =
|
2024-07-02 18:25:06 +00:00
|
|
|
let vv = v
|
|
|
|
vv.buf.toOpenArray(vv.buf.len - int(vv.len), vv.buf.high)
|
|
|
|
|
|
|
|
|
2024-07-04 13:46:52 +00:00
|
|
|
func blobify*(rvid: RootedVertexID): RVidBuf =
|
|
|
|
# Length-prefixed root encoding creates a unique and common prefix for all
|
|
|
|
# verticies sharing the same root
|
|
|
|
# TODO evaluate an encoding that colocates short roots (like VertexID(1)) with
|
|
|
|
# the length
|
|
|
|
let root = rvid.root.blobify()
|
|
|
|
result.buf[0] = root.len
|
|
|
|
assign(result.buf.toOpenArray(1, root.len), root.data())
|
|
|
|
|
|
|
|
if rvid.root == rvid.vid:
|
|
|
|
result.len = root.len + 1
|
|
|
|
else:
|
|
|
|
# We can derive the length of the `vid` from the total length
|
|
|
|
let vid = rvid.vid.blobify()
|
|
|
|
assign(result.buf.toOpenArray(root.len + 1, root.len + vid.len), vid.data())
|
|
|
|
result.len = root.len + 1 + vid.len
|
|
|
|
|
2024-07-02 18:25:06 +00:00
|
|
|
proc deblobify*[T: uint64|VertexID](data: openArray[byte], _: type T): Result[T,AristoError] =
|
|
|
|
if data.len < 1 or data.len > 8:
|
2024-07-04 13:46:52 +00:00
|
|
|
return err(Deblob64LenUnsupported)
|
2024-07-02 18:25:06 +00:00
|
|
|
|
2024-11-20 15:04:32 +00:00
|
|
|
var tmp = 0'u64
|
|
|
|
let start = 8 - data.len
|
|
|
|
for i in 0..<data.len:
|
|
|
|
tmp += uint64(data[i]) shl (8*(7-(i + start)))
|
2024-07-02 18:25:06 +00:00
|
|
|
|
2024-11-20 15:04:32 +00:00
|
|
|
ok T(tmp)
|
2024-07-02 18:25:06 +00:00
|
|
|
|
|
|
|
proc deblobify*(data: openArray[byte], _: type UInt256): Result[UInt256,AristoError] =
|
|
|
|
if data.len < 1 or data.len > 32:
|
2024-07-04 13:46:52 +00:00
|
|
|
return err(Deblob256LenUnsupported)
|
2024-07-02 18:25:06 +00:00
|
|
|
|
|
|
|
ok UInt256.fromBytesBE(data)
|
|
|
|
|
2024-07-04 13:46:52 +00:00
|
|
|
func deblobify*(data: openArray[byte], T: type RootedVertexID): Result[T, AristoError] =
|
|
|
|
let rlen = int(data[0])
|
|
|
|
if data.len < 2:
|
|
|
|
return err(DeblobRVidLenUnsupported)
|
|
|
|
|
|
|
|
if data.len < rlen + 1:
|
|
|
|
return err(DeblobRVidLenUnsupported)
|
|
|
|
|
|
|
|
let
|
|
|
|
root = ?deblobify(data.toOpenArray(1, rlen), VertexID)
|
|
|
|
vid = if data.len > rlen + 1:
|
|
|
|
?deblobify(data.toOpenArray(rlen + 1, data.high()), VertexID)
|
|
|
|
else:
|
|
|
|
root
|
|
|
|
ok (root, vid)
|
|
|
|
|
|
|
|
template data*(v: RVidBuf): openArray[byte] =
|
|
|
|
let vv = v
|
|
|
|
vv.buf.toOpenArray(0, vv.len - 1)
|
|
|
|
|
2023-05-11 14:25:29 +00:00
|
|
|
# ------------------------------------------------------------------------------
|
2023-07-05 20:27:48 +00:00
|
|
|
# Private helper
|
2023-05-11 14:25:29 +00:00
|
|
|
# ------------------------------------------------------------------------------
|
|
|
|
|
2024-07-02 18:25:06 +00:00
|
|
|
proc load64(data: openArray[byte]; start: var int, len: int): Result[uint64,AristoError] =
|
|
|
|
if data.len < start + len:
|
2024-07-04 13:46:52 +00:00
|
|
|
return err(Deblob256LenUnsupported)
|
2024-07-02 18:25:06 +00:00
|
|
|
|
|
|
|
let val = ?deblobify(data.toOpenArray(start, start + len - 1), uint64)
|
|
|
|
start += len
|
2023-07-05 20:27:48 +00:00
|
|
|
ok val
|
|
|
|
|
2024-07-02 18:25:06 +00:00
|
|
|
proc load256(data: openArray[byte]; start: var int, len: int): Result[UInt256,AristoError] =
|
|
|
|
if data.len < start + len:
|
2024-07-04 13:46:52 +00:00
|
|
|
return err(Deblob256LenUnsupported)
|
2024-07-02 18:25:06 +00:00
|
|
|
let val = ?deblobify(data.toOpenArray(start, start + len - 1), UInt256)
|
|
|
|
start += len
|
2023-07-05 20:27:48 +00:00
|
|
|
ok val
|
|
|
|
|
2023-05-11 14:25:29 +00:00
|
|
|
# ------------------------------------------------------------------------------
|
2023-09-15 15:23:53 +00:00
|
|
|
# Public functions
|
2023-05-11 14:25:29 +00:00
|
|
|
# ------------------------------------------------------------------------------
|
|
|
|
|
2024-10-01 21:03:10 +00:00
|
|
|
proc blobifyTo*(pyl: LeafPayload, data: var seq[byte]) =
|
2023-07-05 20:27:48 +00:00
|
|
|
case pyl.pType
|
|
|
|
of AccountData:
|
2024-07-02 18:25:06 +00:00
|
|
|
# `lens` holds `len-1` since `mask` filters out the zero-length case (which
|
|
|
|
# allows saving 1 bit per length)
|
|
|
|
var lens: uint16
|
2023-07-05 20:27:48 +00:00
|
|
|
var mask: byte
|
|
|
|
if 0 < pyl.account.nonce:
|
|
|
|
mask = mask or 0x01
|
2024-07-02 18:25:06 +00:00
|
|
|
let tmp = pyl.account.nonce.blobify()
|
|
|
|
lens += tmp.len - 1 # 3 bits
|
|
|
|
data &= tmp.data()
|
2023-07-05 20:27:48 +00:00
|
|
|
|
2024-07-02 18:25:06 +00:00
|
|
|
if 0 < pyl.account.balance:
|
|
|
|
mask = mask or 0x02
|
|
|
|
let tmp = pyl.account.balance.blobify()
|
|
|
|
lens += uint16(tmp.len - 1) shl 3 # 5 bits
|
|
|
|
data &= tmp.data()
|
2023-07-05 20:27:48 +00:00
|
|
|
|
2024-08-07 13:28:01 +00:00
|
|
|
if pyl.stoID.isValid:
|
2024-07-02 18:25:06 +00:00
|
|
|
mask = mask or 0x04
|
2024-08-07 13:28:01 +00:00
|
|
|
let tmp = pyl.stoID.vid.blobify()
|
2024-07-02 18:25:06 +00:00
|
|
|
lens += uint16(tmp.len - 1) shl 8 # 3 bits
|
|
|
|
data &= tmp.data()
|
2023-07-05 20:27:48 +00:00
|
|
|
|
2024-07-02 18:25:06 +00:00
|
|
|
if pyl.account.codeHash != EMPTY_CODE_HASH:
|
|
|
|
mask = mask or 0x08
|
2024-06-01 15:13:24 +00:00
|
|
|
data &= pyl.account.codeHash.data
|
2023-07-05 20:27:48 +00:00
|
|
|
|
2024-07-02 18:25:06 +00:00
|
|
|
data &= lens.toBytesBE()
|
2024-06-01 15:13:24 +00:00
|
|
|
data &= [mask]
|
2024-07-04 23:48:45 +00:00
|
|
|
of StoData:
|
|
|
|
data &= pyl.stoData.blobify().data
|
|
|
|
data &= [0x20.byte]
|
2023-07-05 20:27:48 +00:00
|
|
|
|
Pre-allocate vids for branches (#2882)
Each branch node may have up to 16 sub-items - currently, these are
given VertexID based when they are first needed leading to a
mostly-random order of vertexid for each subitem.
Here, we pre-allocate all 16 vertex ids such that when a branch subitem
is filled, it already has a vertexid waiting for it. This brings several
important benefits:
* subitems are sorted and "close" in their id sequencing - this means
that when rocksdb stores them, they are likely to end up in the same
data block thus improving read efficiency
* because the ids are consequtive, we can store just the starting id and
a bitmap representing which subitems are in use - this reduces disk
space usage for branches allowing more of them fit into a single disk
read, further improving disk read and caching performance - disk usage
at block 18M is down from 84 to 78gb!
* the in-memory footprint of VertexRef reduced allowing more instances
to fit into caches and less memory to be used overall.
Because of the increased locality of reference, it turns out that we no
longer need to iterate over the entire database to efficiently generate
the hash key database because the normal computation is now faster -
this significantly benefits "live" chain processing as well where each
dirtied key must be accompanied by a read of all branch subitems next to
it - most of the performance benefit in this branch comes from this
locality-of-reference improvement.
On a sample resync, there's already ~20% improvement with later blocks
seeing increasing benefit (because the trie is deeper in later blocks
leading to more benefit from branch read perf improvements)
```
blocks: 18729664, baseline: 190h43m49s, contender: 153h59m0s
Time (total): -36h44m48s, -19.27%
```
Note: clients need to be resynced as the PR changes the on-disk format
R.I.P. little bloom filter - your life in the repo was short but
valuable
2024-12-04 10:42:04 +00:00
|
|
|
proc blobifyTo*(vtx: VertexRef, key: HashKey, data: var seq[byte]) =
|
2023-06-30 22:22:33 +00:00
|
|
|
## This function serialises the vertex argument to a database record.
|
|
|
|
## Contrary to RLP based serialisation, these records aim to align on
|
|
|
|
## fixed byte boundaries.
|
2023-05-11 14:25:29 +00:00
|
|
|
## ::
|
|
|
|
## Branch:
|
Store keys together with node data (#2849)
Currently, computed hash keys are stored in a separate column family
with respect to the MPT data they're generated from - this has several
disadvantages:
* A lot of space is wasted because the lookup key (`RootedVertexID`) is
repeated in both tables - this is 30% of the `AriKey` content!
* rocksdb must maintain in-memory bloom filters and LRU caches for said
keys, doubling its "minimal efficient cache size"
* An extra disk traversal must be made to check for existence of cached
hash key
* Doubles the amount of files on disk due to each column family being
its own set of files
Here, the two CFs are joined such that both key and data is stored in
`AriVtx`. This means:
* we save ~30% disk space on repeated lookup keys
* we save ~2gb of memory overhead that can be used to cache data instead
of indices
* we can skip storing hash keys for MPT leaf nodes - these are trivial
to compute and waste a lot of space - previously they had to present in
the `AriKey` CF to avoid having to look in two tables on the happy path.
* There is a small increase in write amplification because when a hash
value is updated for a branch node, we must write both key and branch
data - previously we would write only the key
* There's a small shift in CPU usage - instead of performing lookups in
the database, hashes for leaf nodes are (re)-computed on the fly
* We can return to slightly smaller on-disk SST files since there's
fewer of them, which should reduce disk traffic a bit
Internally, there are also other advantages:
* when clearing keys, we no longer have to store a zero hash in memory -
instead, we deduce staleness of the cached key from the presence of an
updated VertexRef - this saves ~1gb of mem overhead during import
* hash key cache becomes dedicated to branch keys since leaf keys are no
longer stored in memory, reducing churn
* key computation is a lot faster thanks to the skipped second disk
traversal - a key computation for mainnet can be completed in 11 hours
instead of ~2 days (!) thanks to better cache usage and less read
amplification - with additional improvements to the on-disk format, we
can probably get rid of the initial full traversal method of seeding the
key cache on first start after import
All in all, this PR reduces the size of a mainnet database from 160gb to
110gb and the peak memory footprint during import by ~1-2gb.
2024-11-20 08:56:27 +00:00
|
|
|
## <HashKey> -- optional hash key
|
2024-10-01 21:03:10 +00:00
|
|
|
## [VertexID, ..] -- list of up to 16 child vertices lookup keys
|
|
|
|
## seq[byte] -- hex encoded partial path (non-empty for extension nodes)
|
No ext update (#2494)
* Imported/rebase from `no-ext`, PR #2485
Store extension nodes together with the branch
Extension nodes must be followed by a branch - as such, it makes sense
to store the two together both in the database and in memory:
* fewer reads, writes and updates to traverse the tree
* simpler logic for maintaining the node structure
* less space used, both memory and storage, because there are fewer
nodes overall
There is also a downside: hashes can no longer be cached for an
extension - instead, only the extension+branch hash can be cached - this
seems like a fine tradeoff since computing it should be fast.
TODO: fix commented code
* Fix merge functions and `toNode()`
* Update `merkleSignCommit()` prototype
why:
Result is always a 32bit hash
* Update short Merkle hash key generation
details:
Ethereum reference MPTs use Keccak hashes as node links if the size of
an RLP encoded node is at least 32 bytes. Otherwise, the RLP encoded
node value is used as a pseudo node link (rather than a hash.) This is
specified in the yellow paper, appendix D.
Different to the `Aristo` implementation, the reference MPT would not
store such a node on the key-value database. Rather the RLP encoded node value is stored instead of a node link in a parent node
is stored as a node link on the parent database.
Only for the root hash, the top level node is always referred to by the
hash.
* Fix/update `Extension` sections
why:
Were commented out after removal of a dedicated `Extension` type which
left the system disfunctional.
* Clean up unused error codes
* Update unit tests
* Update docu
---------
Co-authored-by: Jacek Sieka <jacek@status.im>
2024-07-16 19:47:59 +00:00
|
|
|
## uint64 -- lengths of each child vertex, each taking 4 bits
|
Store keys together with node data (#2849)
Currently, computed hash keys are stored in a separate column family
with respect to the MPT data they're generated from - this has several
disadvantages:
* A lot of space is wasted because the lookup key (`RootedVertexID`) is
repeated in both tables - this is 30% of the `AriKey` content!
* rocksdb must maintain in-memory bloom filters and LRU caches for said
keys, doubling its "minimal efficient cache size"
* An extra disk traversal must be made to check for existence of cached
hash key
* Doubles the amount of files on disk due to each column family being
its own set of files
Here, the two CFs are joined such that both key and data is stored in
`AriVtx`. This means:
* we save ~30% disk space on repeated lookup keys
* we save ~2gb of memory overhead that can be used to cache data instead
of indices
* we can skip storing hash keys for MPT leaf nodes - these are trivial
to compute and waste a lot of space - previously they had to present in
the `AriKey` CF to avoid having to look in two tables on the happy path.
* There is a small increase in write amplification because when a hash
value is updated for a branch node, we must write both key and branch
data - previously we would write only the key
* There's a small shift in CPU usage - instead of performing lookups in
the database, hashes for leaf nodes are (re)-computed on the fly
* We can return to slightly smaller on-disk SST files since there's
fewer of them, which should reduce disk traffic a bit
Internally, there are also other advantages:
* when clearing keys, we no longer have to store a zero hash in memory -
instead, we deduce staleness of the cached key from the presence of an
updated VertexRef - this saves ~1gb of mem overhead during import
* hash key cache becomes dedicated to branch keys since leaf keys are no
longer stored in memory, reducing churn
* key computation is a lot faster thanks to the skipped second disk
traversal - a key computation for mainnet can be completed in 11 hours
instead of ~2 days (!) thanks to better cache usage and less read
amplification - with additional improvements to the on-disk format, we
can probably get rid of the initial full traversal method of seeding the
key cache on first start after import
All in all, this PR reduces the size of a mainnet database from 160gb to
110gb and the peak memory footprint during import by ~1-2gb.
2024-11-20 08:56:27 +00:00
|
|
|
## 0x80 + xx -- marker(0/2) + pathSegmentLen(6)
|
2023-05-11 14:25:29 +00:00
|
|
|
##
|
|
|
|
## Leaf:
|
2024-10-01 21:03:10 +00:00
|
|
|
## seq[byte] -- opaque leaf data payload (might be zero length)
|
|
|
|
## seq[byte] -- hex encoded partial path (at least one byte)
|
Store keys together with node data (#2849)
Currently, computed hash keys are stored in a separate column family
with respect to the MPT data they're generated from - this has several
disadvantages:
* A lot of space is wasted because the lookup key (`RootedVertexID`) is
repeated in both tables - this is 30% of the `AriKey` content!
* rocksdb must maintain in-memory bloom filters and LRU caches for said
keys, doubling its "minimal efficient cache size"
* An extra disk traversal must be made to check for existence of cached
hash key
* Doubles the amount of files on disk due to each column family being
its own set of files
Here, the two CFs are joined such that both key and data is stored in
`AriVtx`. This means:
* we save ~30% disk space on repeated lookup keys
* we save ~2gb of memory overhead that can be used to cache data instead
of indices
* we can skip storing hash keys for MPT leaf nodes - these are trivial
to compute and waste a lot of space - previously they had to present in
the `AriKey` CF to avoid having to look in two tables on the happy path.
* There is a small increase in write amplification because when a hash
value is updated for a branch node, we must write both key and branch
data - previously we would write only the key
* There's a small shift in CPU usage - instead of performing lookups in
the database, hashes for leaf nodes are (re)-computed on the fly
* We can return to slightly smaller on-disk SST files since there's
fewer of them, which should reduce disk traffic a bit
Internally, there are also other advantages:
* when clearing keys, we no longer have to store a zero hash in memory -
instead, we deduce staleness of the cached key from the presence of an
updated VertexRef - this saves ~1gb of mem overhead during import
* hash key cache becomes dedicated to branch keys since leaf keys are no
longer stored in memory, reducing churn
* key computation is a lot faster thanks to the skipped second disk
traversal - a key computation for mainnet can be completed in 11 hours
instead of ~2 days (!) thanks to better cache usage and less read
amplification - with additional improvements to the on-disk format, we
can probably get rid of the initial full traversal method of seeding the
key cache on first start after import
All in all, this PR reduces the size of a mainnet database from 160gb to
110gb and the peak memory footprint during import by ~1-2gb.
2024-11-20 08:56:27 +00:00
|
|
|
## 0xc0 + yy -- marker(3) + partialPathLen(6)
|
2023-05-11 14:25:29 +00:00
|
|
|
##
|
|
|
|
## For a branch record, the bytes of the `access` array indicate the position
|
2023-06-12 18:16:03 +00:00
|
|
|
## of the Patricia Trie vertex reference. So the `vertexID` with index `n` has
|
2023-05-11 14:25:29 +00:00
|
|
|
## ::
|
|
|
|
## 8 * n * ((access shr (n * 4)) and 15)
|
|
|
|
##
|
Pre-allocate vids for branches (#2882)
Each branch node may have up to 16 sub-items - currently, these are
given VertexID based when they are first needed leading to a
mostly-random order of vertexid for each subitem.
Here, we pre-allocate all 16 vertex ids such that when a branch subitem
is filled, it already has a vertexid waiting for it. This brings several
important benefits:
* subitems are sorted and "close" in their id sequencing - this means
that when rocksdb stores them, they are likely to end up in the same
data block thus improving read efficiency
* because the ids are consequtive, we can store just the starting id and
a bitmap representing which subitems are in use - this reduces disk
space usage for branches allowing more of them fit into a single disk
read, further improving disk read and caching performance - disk usage
at block 18M is down from 84 to 78gb!
* the in-memory footprint of VertexRef reduced allowing more instances
to fit into caches and less memory to be used overall.
Because of the increased locality of reference, it turns out that we no
longer need to iterate over the entire database to efficiently generate
the hash key database because the normal computation is now faster -
this significantly benefits "live" chain processing as well where each
dirtied key must be accompanied by a read of all branch subitems next to
it - most of the performance benefit in this branch comes from this
locality-of-reference improvement.
On a sample resync, there's already ~20% improvement with later blocks
seeing increasing benefit (because the trie is deeper in later blocks
leading to more benefit from branch read perf improvements)
```
blocks: 18729664, baseline: 190h43m49s, contender: 153h59m0s
Time (total): -36h44m48s, -19.27%
```
Note: clients need to be resynced as the PR changes the on-disk format
R.I.P. little bloom filter - your life in the repo was short but
valuable
2024-12-04 10:42:04 +00:00
|
|
|
doAssert vtx.isValid
|
No ext update (#2494)
* Imported/rebase from `no-ext`, PR #2485
Store extension nodes together with the branch
Extension nodes must be followed by a branch - as such, it makes sense
to store the two together both in the database and in memory:
* fewer reads, writes and updates to traverse the tree
* simpler logic for maintaining the node structure
* less space used, both memory and storage, because there are fewer
nodes overall
There is also a downside: hashes can no longer be cached for an
extension - instead, only the extension+branch hash can be cached - this
seems like a fine tradeoff since computing it should be fast.
TODO: fix commented code
* Fix merge functions and `toNode()`
* Update `merkleSignCommit()` prototype
why:
Result is always a 32bit hash
* Update short Merkle hash key generation
details:
Ethereum reference MPTs use Keccak hashes as node links if the size of
an RLP encoded node is at least 32 bytes. Otherwise, the RLP encoded
node value is used as a pseudo node link (rather than a hash.) This is
specified in the yellow paper, appendix D.
Different to the `Aristo` implementation, the reference MPT would not
store such a node on the key-value database. Rather the RLP encoded node value is stored instead of a node link in a parent node
is stored as a node link on the parent database.
Only for the root hash, the top level node is always referred to by the
hash.
* Fix/update `Extension` sections
why:
Were commented out after removal of a dedicated `Extension` type which
left the system disfunctional.
* Clean up unused error codes
* Update unit tests
* Update docu
---------
Co-authored-by: Jacek Sieka <jacek@status.im>
2024-07-16 19:47:59 +00:00
|
|
|
|
Pre-allocate vids for branches (#2882)
Each branch node may have up to 16 sub-items - currently, these are
given VertexID based when they are first needed leading to a
mostly-random order of vertexid for each subitem.
Here, we pre-allocate all 16 vertex ids such that when a branch subitem
is filled, it already has a vertexid waiting for it. This brings several
important benefits:
* subitems are sorted and "close" in their id sequencing - this means
that when rocksdb stores them, they are likely to end up in the same
data block thus improving read efficiency
* because the ids are consequtive, we can store just the starting id and
a bitmap representing which subitems are in use - this reduces disk
space usage for branches allowing more of them fit into a single disk
read, further improving disk read and caching performance - disk usage
at block 18M is down from 84 to 78gb!
* the in-memory footprint of VertexRef reduced allowing more instances
to fit into caches and less memory to be used overall.
Because of the increased locality of reference, it turns out that we no
longer need to iterate over the entire database to efficiently generate
the hash key database because the normal computation is now faster -
this significantly benefits "live" chain processing as well where each
dirtied key must be accompanied by a read of all branch subitems next to
it - most of the performance benefit in this branch comes from this
locality-of-reference improvement.
On a sample resync, there's already ~20% improvement with later blocks
seeing increasing benefit (because the trie is deeper in later blocks
leading to more benefit from branch read perf improvements)
```
blocks: 18729664, baseline: 190h43m49s, contender: 153h59m0s
Time (total): -36h44m48s, -19.27%
```
Note: clients need to be resynced as the PR changes the on-disk format
R.I.P. little bloom filter - your life in the repo was short but
valuable
2024-12-04 10:42:04 +00:00
|
|
|
let
|
|
|
|
bits =
|
|
|
|
case vtx.vType
|
|
|
|
of Branch:
|
|
|
|
let bits =
|
|
|
|
if key.isValid and key.len == 32:
|
|
|
|
# Shorter keys can be loaded from the vertex directly
|
|
|
|
data.add key.data()
|
|
|
|
0b10'u8
|
|
|
|
else:
|
|
|
|
0b00'u8
|
|
|
|
|
|
|
|
data.add vtx.startVid.blobify().data()
|
|
|
|
data.add toBytesBE(vtx.used)
|
|
|
|
bits
|
|
|
|
of Leaf:
|
|
|
|
vtx.lData.blobifyTo(data)
|
|
|
|
0b01'u8
|
|
|
|
|
|
|
|
pSegm =
|
|
|
|
if vtx.pfx.len > 0:
|
|
|
|
vtx.pfx.toHexPrefix(isleaf = vtx.vType == Leaf)
|
|
|
|
else:
|
|
|
|
default(HexPrefixBuf)
|
|
|
|
psLen = pSegm.len.byte
|
|
|
|
|
|
|
|
data &= pSegm.data()
|
|
|
|
data &= [(bits shl 6) or psLen]
|
2023-07-05 20:27:48 +00:00
|
|
|
|
Store keys together with node data (#2849)
Currently, computed hash keys are stored in a separate column family
with respect to the MPT data they're generated from - this has several
disadvantages:
* A lot of space is wasted because the lookup key (`RootedVertexID`) is
repeated in both tables - this is 30% of the `AriKey` content!
* rocksdb must maintain in-memory bloom filters and LRU caches for said
keys, doubling its "minimal efficient cache size"
* An extra disk traversal must be made to check for existence of cached
hash key
* Doubles the amount of files on disk due to each column family being
its own set of files
Here, the two CFs are joined such that both key and data is stored in
`AriVtx`. This means:
* we save ~30% disk space on repeated lookup keys
* we save ~2gb of memory overhead that can be used to cache data instead
of indices
* we can skip storing hash keys for MPT leaf nodes - these are trivial
to compute and waste a lot of space - previously they had to present in
the `AriKey` CF to avoid having to look in two tables on the happy path.
* There is a small increase in write amplification because when a hash
value is updated for a branch node, we must write both key and branch
data - previously we would write only the key
* There's a small shift in CPU usage - instead of performing lookups in
the database, hashes for leaf nodes are (re)-computed on the fly
* We can return to slightly smaller on-disk SST files since there's
fewer of them, which should reduce disk traffic a bit
Internally, there are also other advantages:
* when clearing keys, we no longer have to store a zero hash in memory -
instead, we deduce staleness of the cached key from the presence of an
updated VertexRef - this saves ~1gb of mem overhead during import
* hash key cache becomes dedicated to branch keys since leaf keys are no
longer stored in memory, reducing churn
* key computation is a lot faster thanks to the skipped second disk
traversal - a key computation for mainnet can be completed in 11 hours
instead of ~2 days (!) thanks to better cache usage and less read
amplification - with additional improvements to the on-disk format, we
can probably get rid of the initial full traversal method of seeding the
key cache on first start after import
All in all, this PR reduces the size of a mainnet database from 160gb to
110gb and the peak memory footprint during import by ~1-2gb.
2024-11-20 08:56:27 +00:00
|
|
|
proc blobify*(vtx: VertexRef, key: HashKey): seq[byte] =
|
2023-05-11 14:25:29 +00:00
|
|
|
## Variant of `blobify()`
|
2024-09-02 14:03:10 +00:00
|
|
|
result = newSeqOfCap[byte](128)
|
Pre-allocate vids for branches (#2882)
Each branch node may have up to 16 sub-items - currently, these are
given VertexID based when they are first needed leading to a
mostly-random order of vertexid for each subitem.
Here, we pre-allocate all 16 vertex ids such that when a branch subitem
is filled, it already has a vertexid waiting for it. This brings several
important benefits:
* subitems are sorted and "close" in their id sequencing - this means
that when rocksdb stores them, they are likely to end up in the same
data block thus improving read efficiency
* because the ids are consequtive, we can store just the starting id and
a bitmap representing which subitems are in use - this reduces disk
space usage for branches allowing more of them fit into a single disk
read, further improving disk read and caching performance - disk usage
at block 18M is down from 84 to 78gb!
* the in-memory footprint of VertexRef reduced allowing more instances
to fit into caches and less memory to be used overall.
Because of the increased locality of reference, it turns out that we no
longer need to iterate over the entire database to efficiently generate
the hash key database because the normal computation is now faster -
this significantly benefits "live" chain processing as well where each
dirtied key must be accompanied by a read of all branch subitems next to
it - most of the performance benefit in this branch comes from this
locality-of-reference improvement.
On a sample resync, there's already ~20% improvement with later blocks
seeing increasing benefit (because the trie is deeper in later blocks
leading to more benefit from branch read perf improvements)
```
blocks: 18729664, baseline: 190h43m49s, contender: 153h59m0s
Time (total): -36h44m48s, -19.27%
```
Note: clients need to be resynced as the PR changes the on-disk format
R.I.P. little bloom filter - your life in the repo was short but
valuable
2024-12-04 10:42:04 +00:00
|
|
|
vtx.blobifyTo(key, result)
|
2023-05-11 14:25:29 +00:00
|
|
|
|
Pre-allocate vids for branches (#2882)
Each branch node may have up to 16 sub-items - currently, these are
given VertexID based when they are first needed leading to a
mostly-random order of vertexid for each subitem.
Here, we pre-allocate all 16 vertex ids such that when a branch subitem
is filled, it already has a vertexid waiting for it. This brings several
important benefits:
* subitems are sorted and "close" in their id sequencing - this means
that when rocksdb stores them, they are likely to end up in the same
data block thus improving read efficiency
* because the ids are consequtive, we can store just the starting id and
a bitmap representing which subitems are in use - this reduces disk
space usage for branches allowing more of them fit into a single disk
read, further improving disk read and caching performance - disk usage
at block 18M is down from 84 to 78gb!
* the in-memory footprint of VertexRef reduced allowing more instances
to fit into caches and less memory to be used overall.
Because of the increased locality of reference, it turns out that we no
longer need to iterate over the entire database to efficiently generate
the hash key database because the normal computation is now faster -
this significantly benefits "live" chain processing as well where each
dirtied key must be accompanied by a read of all branch subitems next to
it - most of the performance benefit in this branch comes from this
locality-of-reference improvement.
On a sample resync, there's already ~20% improvement with later blocks
seeing increasing benefit (because the trie is deeper in later blocks
leading to more benefit from branch read perf improvements)
```
blocks: 18729664, baseline: 190h43m49s, contender: 153h59m0s
Time (total): -36h44m48s, -19.27%
```
Note: clients need to be resynced as the PR changes the on-disk format
R.I.P. little bloom filter - your life in the repo was short but
valuable
2024-12-04 10:42:04 +00:00
|
|
|
proc blobifyTo*(lSst: SavedState; data: var seq[byte]) =
|
2024-05-31 17:32:22 +00:00
|
|
|
## Serialise a last saved state record
|
2024-06-28 18:43:04 +00:00
|
|
|
data.add lSst.key.data
|
2024-06-03 20:10:35 +00:00
|
|
|
data.add lSst.serial.toBytesBE
|
|
|
|
data.add @[0x7fu8]
|
2024-05-31 17:32:22 +00:00
|
|
|
|
Pre-allocate vids for branches (#2882)
Each branch node may have up to 16 sub-items - currently, these are
given VertexID based when they are first needed leading to a
mostly-random order of vertexid for each subitem.
Here, we pre-allocate all 16 vertex ids such that when a branch subitem
is filled, it already has a vertexid waiting for it. This brings several
important benefits:
* subitems are sorted and "close" in their id sequencing - this means
that when rocksdb stores them, they are likely to end up in the same
data block thus improving read efficiency
* because the ids are consequtive, we can store just the starting id and
a bitmap representing which subitems are in use - this reduces disk
space usage for branches allowing more of them fit into a single disk
read, further improving disk read and caching performance - disk usage
at block 18M is down from 84 to 78gb!
* the in-memory footprint of VertexRef reduced allowing more instances
to fit into caches and less memory to be used overall.
Because of the increased locality of reference, it turns out that we no
longer need to iterate over the entire database to efficiently generate
the hash key database because the normal computation is now faster -
this significantly benefits "live" chain processing as well where each
dirtied key must be accompanied by a read of all branch subitems next to
it - most of the performance benefit in this branch comes from this
locality-of-reference improvement.
On a sample resync, there's already ~20% improvement with later blocks
seeing increasing benefit (because the trie is deeper in later blocks
leading to more benefit from branch read perf improvements)
```
blocks: 18729664, baseline: 190h43m49s, contender: 153h59m0s
Time (total): -36h44m48s, -19.27%
```
Note: clients need to be resynced as the PR changes the on-disk format
R.I.P. little bloom filter - your life in the repo was short but
valuable
2024-12-04 10:42:04 +00:00
|
|
|
proc blobify*(lSst: SavedState): seq[byte] =
|
2024-05-31 17:32:22 +00:00
|
|
|
## Variant of `blobify()`
|
2024-10-01 21:03:10 +00:00
|
|
|
var data: seq[byte]
|
Pre-allocate vids for branches (#2882)
Each branch node may have up to 16 sub-items - currently, these are
given VertexID based when they are first needed leading to a
mostly-random order of vertexid for each subitem.
Here, we pre-allocate all 16 vertex ids such that when a branch subitem
is filled, it already has a vertexid waiting for it. This brings several
important benefits:
* subitems are sorted and "close" in their id sequencing - this means
that when rocksdb stores them, they are likely to end up in the same
data block thus improving read efficiency
* because the ids are consequtive, we can store just the starting id and
a bitmap representing which subitems are in use - this reduces disk
space usage for branches allowing more of them fit into a single disk
read, further improving disk read and caching performance - disk usage
at block 18M is down from 84 to 78gb!
* the in-memory footprint of VertexRef reduced allowing more instances
to fit into caches and less memory to be used overall.
Because of the increased locality of reference, it turns out that we no
longer need to iterate over the entire database to efficiently generate
the hash key database because the normal computation is now faster -
this significantly benefits "live" chain processing as well where each
dirtied key must be accompanied by a read of all branch subitems next to
it - most of the performance benefit in this branch comes from this
locality-of-reference improvement.
On a sample resync, there's already ~20% improvement with later blocks
seeing increasing benefit (because the trie is deeper in later blocks
leading to more benefit from branch read perf improvements)
```
blocks: 18729664, baseline: 190h43m49s, contender: 153h59m0s
Time (total): -36h44m48s, -19.27%
```
Note: clients need to be resynced as the PR changes the on-disk format
R.I.P. little bloom filter - your life in the repo was short but
valuable
2024-12-04 10:42:04 +00:00
|
|
|
lSst.blobifyTo data
|
|
|
|
data
|
2024-05-31 17:32:22 +00:00
|
|
|
|
2023-07-05 20:27:48 +00:00
|
|
|
# -------------
|
2024-07-02 18:25:06 +00:00
|
|
|
proc deblobify(
|
2024-05-31 17:32:22 +00:00
|
|
|
data: openArray[byte];
|
2024-09-02 14:03:10 +00:00
|
|
|
pyl: var LeafPayload;
|
|
|
|
): Result[void,AristoError] =
|
2023-07-05 20:27:48 +00:00
|
|
|
if data.len == 0:
|
2024-11-02 09:29:16 +00:00
|
|
|
return err(DeblobVtxTooShort)
|
2023-07-05 20:27:48 +00:00
|
|
|
|
|
|
|
let mask = data[^1]
|
2024-07-04 23:48:45 +00:00
|
|
|
if (mask and 0x20) > 0: # Slot storage data
|
2024-09-02 14:03:10 +00:00
|
|
|
pyl = LeafPayload(
|
2024-07-04 23:48:45 +00:00
|
|
|
pType: StoData,
|
|
|
|
stoData: ?deblobify(data.toOpenArray(0, data.len - 2), UInt256))
|
2024-11-02 09:29:16 +00:00
|
|
|
ok()
|
|
|
|
elif (mask and 0xf0) == 0: # Only account fields set
|
|
|
|
pyl = LeafPayload(pType: AccountData)
|
|
|
|
var
|
|
|
|
start = 0
|
|
|
|
lens = uint16.fromBytesBE(data.toOpenArray(data.len - 3, data.len - 2))
|
2024-07-04 23:48:45 +00:00
|
|
|
|
2024-11-02 09:29:16 +00:00
|
|
|
if (mask and 0x01) > 0:
|
|
|
|
let len = lens and 0b111
|
|
|
|
pyl.account.nonce = ? load64(data, start, int(len + 1))
|
2023-07-05 20:27:48 +00:00
|
|
|
|
2024-11-02 09:29:16 +00:00
|
|
|
if (mask and 0x02) > 0:
|
|
|
|
let len = (lens shr 3) and 0b11111
|
|
|
|
pyl.account.balance = ? load256(data, start, int(len + 1))
|
2023-07-05 20:27:48 +00:00
|
|
|
|
2024-11-02 09:29:16 +00:00
|
|
|
if (mask and 0x04) > 0:
|
|
|
|
let len = (lens shr 8) and 0b111
|
|
|
|
pyl.stoID = (true, VertexID(? load64(data, start, int(len + 1))))
|
2024-07-02 18:25:06 +00:00
|
|
|
|
2024-11-02 09:29:16 +00:00
|
|
|
if (mask and 0x08) > 0:
|
|
|
|
if data.len() < start + 32:
|
|
|
|
return err(DeblobCodeLenUnsupported)
|
|
|
|
discard pyl.account.codeHash.data.copyFrom(data.toOpenArray(start, start + 31))
|
|
|
|
else:
|
|
|
|
pyl.account.codeHash = EMPTY_CODE_HASH
|
2024-07-02 18:25:06 +00:00
|
|
|
|
2024-11-02 09:29:16 +00:00
|
|
|
ok()
|
2023-07-05 20:27:48 +00:00
|
|
|
else:
|
2024-11-02 09:29:16 +00:00
|
|
|
err(DeblobUnknown)
|
2023-05-11 14:25:29 +00:00
|
|
|
|
Speed up initial MPT root computation after import (#2788)
When `nimbus import` runs, we end up with a database without MPT roots
leading to long startup times the first time one is needed.
Computing the state root is slow because the on-disk order based on
VertexID sorting does not match the trie traversal order and therefore
makes lookups inefficent.
Here we introduce a helper that speeds up this computation by traversing
the trie in on-disk order and computing the trie hashes bottom up
instead - even though this leads to some redundant reads of nodes that
we cannot yet compute, it's still a net win as leaves and "bottom"
branches make up the majority of the database.
This PR also addresses a few other sources of inefficiency largely due
to the separation of AriKey and AriVtx into their own column families.
Each column family is its own LSM tree that produces hundreds of SST
filtes - with a limit of 512 open files, rocksdb must keep closing and
opening files which leads to expensive metadata reads during random
access.
When rocksdb makes a lookup, it has to read several layers of files for
each lookup. Ribbon filters to skip over files that don't have the
requested data but when these filters are not in memory, reading them is
slow - this happens in two cases: when opening a file and when the
filter has been evicted from the LRU cache. Addressing the open file
limit solves one source of inefficiency, but we must also increase the
block cache size to deal with this problem.
* rocksdb.max_open_files increased to 2048
* per-file size limits increased so that fewer files are created
* WAL size increased to avoid partial flushes which lead to small files
* rocksdb block cache increased
All these increases of course lead to increased memory usage, but at
least performance is acceptable - in the future, we'll need to explore
options such as joining AriVtx and AriKey and/or reducing the row count
(by grouping branch layers under a single vertexid).
With this PR, the mainnet state root can be computed in ~8 hours (down
from 2-3 days) - not great, but still better.
Further, we write all keys to the database, also those that are less
than 32 bytes - because the mpt path is part of the input, it is very
rare that we actually hit a key like this (about 200k such entries on
mainnet), so the code complexity is not worth the benefit really, in the
current database layout / design.
2024-10-27 11:08:37 +00:00
|
|
|
proc deblobifyType*(record: openArray[byte]; T: type VertexRef):
|
|
|
|
Result[VertexType, AristoError] =
|
|
|
|
if record.len < 3: # minimum `Leaf` record
|
|
|
|
return err(DeblobVtxTooShort)
|
|
|
|
|
Pre-allocate vids for branches (#2882)
Each branch node may have up to 16 sub-items - currently, these are
given VertexID based when they are first needed leading to a
mostly-random order of vertexid for each subitem.
Here, we pre-allocate all 16 vertex ids such that when a branch subitem
is filled, it already has a vertexid waiting for it. This brings several
important benefits:
* subitems are sorted and "close" in their id sequencing - this means
that when rocksdb stores them, they are likely to end up in the same
data block thus improving read efficiency
* because the ids are consequtive, we can store just the starting id and
a bitmap representing which subitems are in use - this reduces disk
space usage for branches allowing more of them fit into a single disk
read, further improving disk read and caching performance - disk usage
at block 18M is down from 84 to 78gb!
* the in-memory footprint of VertexRef reduced allowing more instances
to fit into caches and less memory to be used overall.
Because of the increased locality of reference, it turns out that we no
longer need to iterate over the entire database to efficiently generate
the hash key database because the normal computation is now faster -
this significantly benefits "live" chain processing as well where each
dirtied key must be accompanied by a read of all branch subitems next to
it - most of the performance benefit in this branch comes from this
locality-of-reference improvement.
On a sample resync, there's already ~20% improvement with later blocks
seeing increasing benefit (because the trie is deeper in later blocks
leading to more benefit from branch read perf improvements)
```
blocks: 18729664, baseline: 190h43m49s, contender: 153h59m0s
Time (total): -36h44m48s, -19.27%
```
Note: clients need to be resynced as the PR changes the on-disk format
R.I.P. little bloom filter - your life in the repo was short but
valuable
2024-12-04 10:42:04 +00:00
|
|
|
ok if ((record[^1] shr 6) and 0b01'u8) > 0:
|
|
|
|
Leaf
|
Speed up initial MPT root computation after import (#2788)
When `nimbus import` runs, we end up with a database without MPT roots
leading to long startup times the first time one is needed.
Computing the state root is slow because the on-disk order based on
VertexID sorting does not match the trie traversal order and therefore
makes lookups inefficent.
Here we introduce a helper that speeds up this computation by traversing
the trie in on-disk order and computing the trie hashes bottom up
instead - even though this leads to some redundant reads of nodes that
we cannot yet compute, it's still a net win as leaves and "bottom"
branches make up the majority of the database.
This PR also addresses a few other sources of inefficiency largely due
to the separation of AriKey and AriVtx into their own column families.
Each column family is its own LSM tree that produces hundreds of SST
filtes - with a limit of 512 open files, rocksdb must keep closing and
opening files which leads to expensive metadata reads during random
access.
When rocksdb makes a lookup, it has to read several layers of files for
each lookup. Ribbon filters to skip over files that don't have the
requested data but when these filters are not in memory, reading them is
slow - this happens in two cases: when opening a file and when the
filter has been evicted from the LRU cache. Addressing the open file
limit solves one source of inefficiency, but we must also increase the
block cache size to deal with this problem.
* rocksdb.max_open_files increased to 2048
* per-file size limits increased so that fewer files are created
* WAL size increased to avoid partial flushes which lead to small files
* rocksdb block cache increased
All these increases of course lead to increased memory usage, but at
least performance is acceptable - in the future, we'll need to explore
options such as joining AriVtx and AriKey and/or reducing the row count
(by grouping branch layers under a single vertexid).
With this PR, the mainnet state root can be computed in ~8 hours (down
from 2-3 days) - not great, but still better.
Further, we write all keys to the database, also those that are less
than 32 bytes - because the mpt path is part of the input, it is very
rare that we actually hit a key like this (about 200k such entries on
mainnet), so the code complexity is not worth the benefit really, in the
current database layout / design.
2024-10-27 11:08:37 +00:00
|
|
|
else:
|
Pre-allocate vids for branches (#2882)
Each branch node may have up to 16 sub-items - currently, these are
given VertexID based when they are first needed leading to a
mostly-random order of vertexid for each subitem.
Here, we pre-allocate all 16 vertex ids such that when a branch subitem
is filled, it already has a vertexid waiting for it. This brings several
important benefits:
* subitems are sorted and "close" in their id sequencing - this means
that when rocksdb stores them, they are likely to end up in the same
data block thus improving read efficiency
* because the ids are consequtive, we can store just the starting id and
a bitmap representing which subitems are in use - this reduces disk
space usage for branches allowing more of them fit into a single disk
read, further improving disk read and caching performance - disk usage
at block 18M is down from 84 to 78gb!
* the in-memory footprint of VertexRef reduced allowing more instances
to fit into caches and less memory to be used overall.
Because of the increased locality of reference, it turns out that we no
longer need to iterate over the entire database to efficiently generate
the hash key database because the normal computation is now faster -
this significantly benefits "live" chain processing as well where each
dirtied key must be accompanied by a read of all branch subitems next to
it - most of the performance benefit in this branch comes from this
locality-of-reference improvement.
On a sample resync, there's already ~20% improvement with later blocks
seeing increasing benefit (because the trie is deeper in later blocks
leading to more benefit from branch read perf improvements)
```
blocks: 18729664, baseline: 190h43m49s, contender: 153h59m0s
Time (total): -36h44m48s, -19.27%
```
Note: clients need to be resynced as the PR changes the on-disk format
R.I.P. little bloom filter - your life in the repo was short but
valuable
2024-12-04 10:42:04 +00:00
|
|
|
Branch
|
Speed up initial MPT root computation after import (#2788)
When `nimbus import` runs, we end up with a database without MPT roots
leading to long startup times the first time one is needed.
Computing the state root is slow because the on-disk order based on
VertexID sorting does not match the trie traversal order and therefore
makes lookups inefficent.
Here we introduce a helper that speeds up this computation by traversing
the trie in on-disk order and computing the trie hashes bottom up
instead - even though this leads to some redundant reads of nodes that
we cannot yet compute, it's still a net win as leaves and "bottom"
branches make up the majority of the database.
This PR also addresses a few other sources of inefficiency largely due
to the separation of AriKey and AriVtx into their own column families.
Each column family is its own LSM tree that produces hundreds of SST
filtes - with a limit of 512 open files, rocksdb must keep closing and
opening files which leads to expensive metadata reads during random
access.
When rocksdb makes a lookup, it has to read several layers of files for
each lookup. Ribbon filters to skip over files that don't have the
requested data but when these filters are not in memory, reading them is
slow - this happens in two cases: when opening a file and when the
filter has been evicted from the LRU cache. Addressing the open file
limit solves one source of inefficiency, but we must also increase the
block cache size to deal with this problem.
* rocksdb.max_open_files increased to 2048
* per-file size limits increased so that fewer files are created
* WAL size increased to avoid partial flushes which lead to small files
* rocksdb block cache increased
All these increases of course lead to increased memory usage, but at
least performance is acceptable - in the future, we'll need to explore
options such as joining AriVtx and AriKey and/or reducing the row count
(by grouping branch layers under a single vertexid).
With this PR, the mainnet state root can be computed in ~8 hours (down
from 2-3 days) - not great, but still better.
Further, we write all keys to the database, also those that are less
than 32 bytes - because the mpt path is part of the input, it is very
rare that we actually hit a key like this (about 200k such entries on
mainnet), so the code complexity is not worth the benefit really, in the
current database layout / design.
2024-10-27 11:08:37 +00:00
|
|
|
|
2024-07-02 18:25:06 +00:00
|
|
|
proc deblobify*(
|
2024-06-03 20:10:35 +00:00
|
|
|
record: openArray[byte];
|
2024-07-02 18:25:06 +00:00
|
|
|
T: type VertexRef;
|
|
|
|
): Result[T,AristoError] =
|
2023-05-11 14:25:29 +00:00
|
|
|
## De-serialise a data record encoded with `blobify()`. The second
|
|
|
|
## argument `vtx` can be `nil`.
|
Pre-allocate vids for branches (#2882)
Each branch node may have up to 16 sub-items - currently, these are
given VertexID based when they are first needed leading to a
mostly-random order of vertexid for each subitem.
Here, we pre-allocate all 16 vertex ids such that when a branch subitem
is filled, it already has a vertexid waiting for it. This brings several
important benefits:
* subitems are sorted and "close" in their id sequencing - this means
that when rocksdb stores them, they are likely to end up in the same
data block thus improving read efficiency
* because the ids are consequtive, we can store just the starting id and
a bitmap representing which subitems are in use - this reduces disk
space usage for branches allowing more of them fit into a single disk
read, further improving disk read and caching performance - disk usage
at block 18M is down from 84 to 78gb!
* the in-memory footprint of VertexRef reduced allowing more instances
to fit into caches and less memory to be used overall.
Because of the increased locality of reference, it turns out that we no
longer need to iterate over the entire database to efficiently generate
the hash key database because the normal computation is now faster -
this significantly benefits "live" chain processing as well where each
dirtied key must be accompanied by a read of all branch subitems next to
it - most of the performance benefit in this branch comes from this
locality-of-reference improvement.
On a sample resync, there's already ~20% improvement with later blocks
seeing increasing benefit (because the trie is deeper in later blocks
leading to more benefit from branch read perf improvements)
```
blocks: 18729664, baseline: 190h43m49s, contender: 153h59m0s
Time (total): -36h44m48s, -19.27%
```
Note: clients need to be resynced as the PR changes the on-disk format
R.I.P. little bloom filter - your life in the repo was short but
valuable
2024-12-04 10:42:04 +00:00
|
|
|
if record.len < 3: # minimum `Leaf` record
|
2023-11-08 12:18:32 +00:00
|
|
|
return err(DeblobVtxTooShort)
|
Pre-allocate vids for branches (#2882)
Each branch node may have up to 16 sub-items - currently, these are
given VertexID based when they are first needed leading to a
mostly-random order of vertexid for each subitem.
Here, we pre-allocate all 16 vertex ids such that when a branch subitem
is filled, it already has a vertexid waiting for it. This brings several
important benefits:
* subitems are sorted and "close" in their id sequencing - this means
that when rocksdb stores them, they are likely to end up in the same
data block thus improving read efficiency
* because the ids are consequtive, we can store just the starting id and
a bitmap representing which subitems are in use - this reduces disk
space usage for branches allowing more of them fit into a single disk
read, further improving disk read and caching performance - disk usage
at block 18M is down from 84 to 78gb!
* the in-memory footprint of VertexRef reduced allowing more instances
to fit into caches and less memory to be used overall.
Because of the increased locality of reference, it turns out that we no
longer need to iterate over the entire database to efficiently generate
the hash key database because the normal computation is now faster -
this significantly benefits "live" chain processing as well where each
dirtied key must be accompanied by a read of all branch subitems next to
it - most of the performance benefit in this branch comes from this
locality-of-reference improvement.
On a sample resync, there's already ~20% improvement with later blocks
seeing increasing benefit (because the trie is deeper in later blocks
leading to more benefit from branch read perf improvements)
```
blocks: 18729664, baseline: 190h43m49s, contender: 153h59m0s
Time (total): -36h44m48s, -19.27%
```
Note: clients need to be resynced as the PR changes the on-disk format
R.I.P. little bloom filter - your life in the repo was short but
valuable
2024-12-04 10:42:04 +00:00
|
|
|
|
|
|
|
let
|
|
|
|
bits = record[^1] shr 6
|
|
|
|
vType = if (bits and 0b01'u8) > 0: Leaf else: Branch
|
|
|
|
hasKey = (bits and 0b10'u8) > 0
|
|
|
|
psLen = int(record[^1] and 0b00111111)
|
|
|
|
start = if hasKey: 32 else: 0
|
|
|
|
|
|
|
|
if psLen > record.len - 2 or start > record.len - 2 - psLen:
|
|
|
|
return err(DeblobBranchTooShort)
|
|
|
|
|
|
|
|
let
|
|
|
|
psPos = record.len - psLen - 1
|
|
|
|
(_, pathSegment) =
|
|
|
|
NibblesBuf.fromHexPrefix record.toOpenArray(psPos, record.len - 2)
|
|
|
|
|
|
|
|
ok case vType
|
|
|
|
of Branch:
|
|
|
|
var pos = start
|
2023-05-11 14:25:29 +00:00
|
|
|
let
|
Pre-allocate vids for branches (#2882)
Each branch node may have up to 16 sub-items - currently, these are
given VertexID based when they are first needed leading to a
mostly-random order of vertexid for each subitem.
Here, we pre-allocate all 16 vertex ids such that when a branch subitem
is filled, it already has a vertexid waiting for it. This brings several
important benefits:
* subitems are sorted and "close" in their id sequencing - this means
that when rocksdb stores them, they are likely to end up in the same
data block thus improving read efficiency
* because the ids are consequtive, we can store just the starting id and
a bitmap representing which subitems are in use - this reduces disk
space usage for branches allowing more of them fit into a single disk
read, further improving disk read and caching performance - disk usage
at block 18M is down from 84 to 78gb!
* the in-memory footprint of VertexRef reduced allowing more instances
to fit into caches and less memory to be used overall.
Because of the increased locality of reference, it turns out that we no
longer need to iterate over the entire database to efficiently generate
the hash key database because the normal computation is now faster -
this significantly benefits "live" chain processing as well where each
dirtied key must be accompanied by a read of all branch subitems next to
it - most of the performance benefit in this branch comes from this
locality-of-reference improvement.
On a sample resync, there's already ~20% improvement with later blocks
seeing increasing benefit (because the trie is deeper in later blocks
leading to more benefit from branch read perf improvements)
```
blocks: 18729664, baseline: 190h43m49s, contender: 153h59m0s
Time (total): -36h44m48s, -19.27%
```
Note: clients need to be resynced as the PR changes the on-disk format
R.I.P. little bloom filter - your life in the repo was short but
valuable
2024-12-04 10:42:04 +00:00
|
|
|
svLen = psPos - pos - 2
|
|
|
|
startVid = VertexID(?load64(record, pos, svLen))
|
|
|
|
used = uint16.fromBytesBE(record.toOpenArray(pos, pos + 1))
|
2023-09-12 18:45:12 +00:00
|
|
|
|
Pre-allocate vids for branches (#2882)
Each branch node may have up to 16 sub-items - currently, these are
given VertexID based when they are first needed leading to a
mostly-random order of vertexid for each subitem.
Here, we pre-allocate all 16 vertex ids such that when a branch subitem
is filled, it already has a vertexid waiting for it. This brings several
important benefits:
* subitems are sorted and "close" in their id sequencing - this means
that when rocksdb stores them, they are likely to end up in the same
data block thus improving read efficiency
* because the ids are consequtive, we can store just the starting id and
a bitmap representing which subitems are in use - this reduces disk
space usage for branches allowing more of them fit into a single disk
read, further improving disk read and caching performance - disk usage
at block 18M is down from 84 to 78gb!
* the in-memory footprint of VertexRef reduced allowing more instances
to fit into caches and less memory to be used overall.
Because of the increased locality of reference, it turns out that we no
longer need to iterate over the entire database to efficiently generate
the hash key database because the normal computation is now faster -
this significantly benefits "live" chain processing as well where each
dirtied key must be accompanied by a read of all branch subitems next to
it - most of the performance benefit in this branch comes from this
locality-of-reference improvement.
On a sample resync, there's already ~20% improvement with later blocks
seeing increasing benefit (because the trie is deeper in later blocks
leading to more benefit from branch read perf improvements)
```
blocks: 18729664, baseline: 190h43m49s, contender: 153h59m0s
Time (total): -36h44m48s, -19.27%
```
Note: clients need to be resynced as the PR changes the on-disk format
R.I.P. little bloom filter - your life in the repo was short but
valuable
2024-12-04 10:42:04 +00:00
|
|
|
pos += 2
|
|
|
|
|
|
|
|
VertexRef(vType: Branch, pfx: pathSegment, startVid: startVid, used: used)
|
|
|
|
of Leaf:
|
|
|
|
let vtx = VertexRef(vType: Leaf, pfx: pathSegment)
|
|
|
|
|
|
|
|
?record.toOpenArray(start, psPos - 1).deblobify(vtx.lData)
|
|
|
|
vtx
|
2023-05-11 14:25:29 +00:00
|
|
|
|
Store keys together with node data (#2849)
Currently, computed hash keys are stored in a separate column family
with respect to the MPT data they're generated from - this has several
disadvantages:
* A lot of space is wasted because the lookup key (`RootedVertexID`) is
repeated in both tables - this is 30% of the `AriKey` content!
* rocksdb must maintain in-memory bloom filters and LRU caches for said
keys, doubling its "minimal efficient cache size"
* An extra disk traversal must be made to check for existence of cached
hash key
* Doubles the amount of files on disk due to each column family being
its own set of files
Here, the two CFs are joined such that both key and data is stored in
`AriVtx`. This means:
* we save ~30% disk space on repeated lookup keys
* we save ~2gb of memory overhead that can be used to cache data instead
of indices
* we can skip storing hash keys for MPT leaf nodes - these are trivial
to compute and waste a lot of space - previously they had to present in
the `AriKey` CF to avoid having to look in two tables on the happy path.
* There is a small increase in write amplification because when a hash
value is updated for a branch node, we must write both key and branch
data - previously we would write only the key
* There's a small shift in CPU usage - instead of performing lookups in
the database, hashes for leaf nodes are (re)-computed on the fly
* We can return to slightly smaller on-disk SST files since there's
fewer of them, which should reduce disk traffic a bit
Internally, there are also other advantages:
* when clearing keys, we no longer have to store a zero hash in memory -
instead, we deduce staleness of the cached key from the presence of an
updated VertexRef - this saves ~1gb of mem overhead during import
* hash key cache becomes dedicated to branch keys since leaf keys are no
longer stored in memory, reducing churn
* key computation is a lot faster thanks to the skipped second disk
traversal - a key computation for mainnet can be completed in 11 hours
instead of ~2 days (!) thanks to better cache usage and less read
amplification - with additional improvements to the on-disk format, we
can probably get rid of the initial full traversal method of seeding the
key cache on first start after import
All in all, this PR reduces the size of a mainnet database from 160gb to
110gb and the peak memory footprint during import by ~1-2gb.
2024-11-20 08:56:27 +00:00
|
|
|
proc deblobify*(record: openArray[byte], T: type HashKey): Opt[HashKey] =
|
Pre-allocate vids for branches (#2882)
Each branch node may have up to 16 sub-items - currently, these are
given VertexID based when they are first needed leading to a
mostly-random order of vertexid for each subitem.
Here, we pre-allocate all 16 vertex ids such that when a branch subitem
is filled, it already has a vertexid waiting for it. This brings several
important benefits:
* subitems are sorted and "close" in their id sequencing - this means
that when rocksdb stores them, they are likely to end up in the same
data block thus improving read efficiency
* because the ids are consequtive, we can store just the starting id and
a bitmap representing which subitems are in use - this reduces disk
space usage for branches allowing more of them fit into a single disk
read, further improving disk read and caching performance - disk usage
at block 18M is down from 84 to 78gb!
* the in-memory footprint of VertexRef reduced allowing more instances
to fit into caches and less memory to be used overall.
Because of the increased locality of reference, it turns out that we no
longer need to iterate over the entire database to efficiently generate
the hash key database because the normal computation is now faster -
this significantly benefits "live" chain processing as well where each
dirtied key must be accompanied by a read of all branch subitems next to
it - most of the performance benefit in this branch comes from this
locality-of-reference improvement.
On a sample resync, there's already ~20% improvement with later blocks
seeing increasing benefit (because the trie is deeper in later blocks
leading to more benefit from branch read perf improvements)
```
blocks: 18729664, baseline: 190h43m49s, contender: 153h59m0s
Time (total): -36h44m48s, -19.27%
```
Note: clients need to be resynced as the PR changes the on-disk format
R.I.P. little bloom filter - your life in the repo was short but
valuable
2024-12-04 10:42:04 +00:00
|
|
|
if record.len > 33 and (((record[^1] shr 6) and 0b10'u8) > 0):
|
|
|
|
HashKey.fromBytes(record.toOpenArray(0, 31))
|
Store keys together with node data (#2849)
Currently, computed hash keys are stored in a separate column family
with respect to the MPT data they're generated from - this has several
disadvantages:
* A lot of space is wasted because the lookup key (`RootedVertexID`) is
repeated in both tables - this is 30% of the `AriKey` content!
* rocksdb must maintain in-memory bloom filters and LRU caches for said
keys, doubling its "minimal efficient cache size"
* An extra disk traversal must be made to check for existence of cached
hash key
* Doubles the amount of files on disk due to each column family being
its own set of files
Here, the two CFs are joined such that both key and data is stored in
`AriVtx`. This means:
* we save ~30% disk space on repeated lookup keys
* we save ~2gb of memory overhead that can be used to cache data instead
of indices
* we can skip storing hash keys for MPT leaf nodes - these are trivial
to compute and waste a lot of space - previously they had to present in
the `AriKey` CF to avoid having to look in two tables on the happy path.
* There is a small increase in write amplification because when a hash
value is updated for a branch node, we must write both key and branch
data - previously we would write only the key
* There's a small shift in CPU usage - instead of performing lookups in
the database, hashes for leaf nodes are (re)-computed on the fly
* We can return to slightly smaller on-disk SST files since there's
fewer of them, which should reduce disk traffic a bit
Internally, there are also other advantages:
* when clearing keys, we no longer have to store a zero hash in memory -
instead, we deduce staleness of the cached key from the presence of an
updated VertexRef - this saves ~1gb of mem overhead during import
* hash key cache becomes dedicated to branch keys since leaf keys are no
longer stored in memory, reducing churn
* key computation is a lot faster thanks to the skipped second disk
traversal - a key computation for mainnet can be completed in 11 hours
instead of ~2 days (!) thanks to better cache usage and less read
amplification - with additional improvements to the on-disk format, we
can probably get rid of the initial full traversal method of seeding the
key cache on first start after import
All in all, this PR reduces the size of a mainnet database from 160gb to
110gb and the peak memory footprint during import by ~1-2gb.
2024-11-20 08:56:27 +00:00
|
|
|
else:
|
|
|
|
Opt.none(HashKey)
|
|
|
|
|
2024-06-03 20:10:35 +00:00
|
|
|
proc deblobify*(
|
|
|
|
data: openArray[byte];
|
2024-07-02 18:25:06 +00:00
|
|
|
T: type SavedState;
|
|
|
|
): Result[SavedState,AristoError] =
|
2024-05-31 17:32:22 +00:00
|
|
|
## De-serialise the last saved state data record previously encoded with
|
|
|
|
## `blobify()`.
|
2024-06-28 18:43:04 +00:00
|
|
|
if data.len != 41:
|
2024-05-31 17:32:22 +00:00
|
|
|
return err(DeblobWrongSize)
|
|
|
|
if data[^1] != 0x7f:
|
|
|
|
return err(DeblobWrongType)
|
|
|
|
|
2024-07-02 18:25:06 +00:00
|
|
|
ok(SavedState(
|
2024-09-29 12:37:09 +00:00
|
|
|
key: Hash32(array[32, byte].initCopyFrom(data.toOpenArray(0, 31))),
|
2024-07-02 18:25:06 +00:00
|
|
|
serial: uint64.fromBytesBE data.toOpenArray(32, 39)))
|
2024-05-31 17:32:22 +00:00
|
|
|
|
2023-05-11 14:25:29 +00:00
|
|
|
# ------------------------------------------------------------------------------
|
|
|
|
# End
|
|
|
|
# ------------------------------------------------------------------------------
|