nimbus-eth1/nimbus/db/aristo/aristo_init/memory_db.nim

274 lines
8.0 KiB
Nim
Raw Normal View History

# nimbus-eth1
# Copyright (c) 2023-2024 Status Research & Development GmbH
# 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.
## In-memory backend for Aristo DB
## ===============================
##
## The iterators provided here are currently available only by direct
## backend access
## ::
## import
## aristo/aristo_init,
## aristo/aristo_init/aristo_memory
##
## let rc = newAristoDbRef(BackendMemory)
## if rc.isOk:
## let be = rc.value.to(MemBackendRef)
## for (n, key, vtx) in be.walkVtx:
## ...
##
{.push raises: [].}
import
std/[algorithm, options, sequtils, tables],
eth/common,
results,
../aristo_constants,
../aristo_desc,
../aristo_desc/desc_backend,
Aristo db update for short nodes key edge cases (#1887) * Aristo: Provide key-value list signature calculator detail: Simple wrappers around `Aristo` core functionality * Update new API for `CoreDb` details: + Renamed new API functions `contains()` => `hasKey()` or `hasPath()` which disables the `in` operator on non-boolean `contains()` functions + The functions `get()` and `fetch()` always return a not-found error if there is no item, available. The new functions `getOrEmpty()` and `mergeOrEmpty()` return an an empty `Blob` if there is no such key found. * Rewrite `core_apps.nim` using new API from `CoreDb` * Use `Aristo` functionality for calculating Merkle signatures details: For debugging, the `VerifyAristoForMerkleRootCalc` can be set so that `Aristo` results will be verified against the legacy versions. * Provide general interface for Merkle signing key-value tables details: Export `Aristo` wrappers * Activate `CoreDb` tests why: Now, API seems to be stable enough for general tests. * Update `toHex()` usage why: Byteutils' `toHex()` is superior to `toSeq.mapIt(it.toHex(2)).join` * Split `aristo_transcode` => `aristo_serialise` + `aristo_blobify` why: + Different modules for different purposes + `aristo_serialise`: RLP encoding/decoding + `aristo_blobify`: Aristo database encoding/decoding * Compacted representation of small nodes' links instead of Keccak hashes why: Ethereum 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.) Such a node is nor stored on key-value database. Rather the RLP encoded node value is stored instead of a lode link in a parent node instead. Only for the root hash, the top level node is always referred to by the hash. This feature needed an abstraction of the `HashKey` object which is now either a hash or a blob of length at most 31 bytes. This leaves two ways of representing an empty/void `HashKey` type, either as an empty blob of zero length, or the hash of an empty blob. * Update `CoreDb` interface (mainly reducing logger noise) * Fix copyright years (to make `Lint` happy)
2023-11-08 12:18:32 +00:00
../aristo_blobify,
./init_common
const
extraTraceMessages = false # or true
## Enabled additional logging noise
type
MemDbRef = ref object
## Database
sTab: Table[RootedVertexID,seq[byte]] ## Structural vertex table making up a trie
kMap: Table[RootedVertexID,HashKey] ## Merkle hash key mapping
tUvi: Option[VertexID] ## Top used vertex ID
lSst: Opt[SavedState] ## Last saved state
MemBackendRef* = ref object of TypedBackendRef
## Inheriting table so access can be extended for debugging purposes
mdb: MemDbRef ## Database
MemPutHdlRef = ref object of TypedPutHdlRef
sTab: Table[RootedVertexID,seq[byte]]
kMap: Table[RootedVertexID,HashKey]
2024-06-04 15:05:13 +00:00
tUvi: Option[VertexID]
lSst: Opt[SavedState]
when extraTraceMessages:
import chronicles
logScope:
topics = "aristo-backend"
# ------------------------------------------------------------------------------
# Private helpers
# ------------------------------------------------------------------------------
proc newSession(db: MemBackendRef): MemPutHdlRef =
new result
result.TypedPutHdlRef.beginSession db
proc getSession(hdl: PutHdlRef; db: MemBackendRef): MemPutHdlRef =
hdl.TypedPutHdlRef.verifySession db
hdl.MemPutHdlRef
proc endSession(hdl: PutHdlRef; db: MemBackendRef): MemPutHdlRef =
hdl.TypedPutHdlRef.finishSession db
hdl.MemPutHdlRef
# ------------------------------------------------------------------------------
# Private functions: interface
# ------------------------------------------------------------------------------
proc getVtxFn(db: MemBackendRef): GetVtxFn =
result =
proc(rvid: RootedVertexID, flags: set[GetVtxFlag]): Result[VertexRef,AristoError] =
# Fetch serialised data record
let data = db.mdb.sTab.getOrDefault(rvid, EmptyBlob)
if 0 < data.len:
let rc = data.deblobify(VertexRef)
when extraTraceMessages:
if rc.isErr:
trace logTxt "getVtxFn() failed", error=rc.error
return rc
err(GetVtxNotFound)
proc getKeyFn(db: MemBackendRef): GetKeyFn =
result =
proc(rvid: RootedVertexID): Result[HashKey,AristoError] =
let key = db.mdb.kMap.getOrVoid rvid
if key.isValid:
return ok key
err(GetKeyNotFound)
2024-06-04 15:05:13 +00:00
proc getTuvFn(db: MemBackendRef): GetTuvFn =
result =
2024-06-04 15:05:13 +00:00
proc(): Result[VertexID,AristoError]=
if db.mdb.tUvi.isSome:
return ok db.mdb.tUvi.unsafeGet
err(GetTuvNotFound)
proc getLstFn(db: MemBackendRef): GetLstFn =
result =
proc(): Result[SavedState,AristoError]=
if db.mdb.lSst.isSome:
return ok db.mdb.lSst.unsafeGet
err(GetLstNotFound)
# -------------
proc putBegFn(db: MemBackendRef): PutBegFn =
result =
proc(): Result[PutHdlRef,AristoError] =
ok db.newSession()
proc putVtxFn(db: MemBackendRef): PutVtxFn =
result =
proc(hdl: PutHdlRef; rvid: RootedVertexID; vtx: VertexRef) =
let hdl = hdl.getSession db
if hdl.error.isNil:
if vtx.isValid:
hdl.sTab[rvid] = vtx.blobify()
else:
hdl.sTab[rvid] = EmptyBlob
proc putKeyFn(db: MemBackendRef): PutKeyFn =
result =
proc(hdl: PutHdlRef; rvid: RootedVertexID, key: HashKey) =
let hdl = hdl.getSession db
if hdl.error.isNil:
hdl.kMap[rvid] = key
2024-06-04 15:05:13 +00:00
proc putTuvFn(db: MemBackendRef): PutTuvFn =
result =
2024-06-04 15:05:13 +00:00
proc(hdl: PutHdlRef; vs: VertexID) =
let hdl = hdl.getSession db
if hdl.error.isNil:
2024-06-04 15:05:13 +00:00
hdl.tUvi = some(vs)
proc putLstFn(db: MemBackendRef): PutLstFn =
result =
proc(hdl: PutHdlRef; lst: SavedState) =
let hdl = hdl.getSession db
if hdl.error.isNil:
let rc = lst.blobify # test
if rc.isOk:
hdl.lSst = Opt.some(lst)
else:
hdl.error = TypedPutHdlErrRef(
pfx: AdmPfx,
aid: AdmTabIdLst,
code: rc.error)
proc putEndFn(db: MemBackendRef): PutEndFn =
result =
proc(hdl: PutHdlRef): Result[void,AristoError] =
let hdl = hdl.endSession db
if not hdl.error.isNil:
when extraTraceMessages:
case hdl.error.pfx:
of VtxPfx, KeyPfx: trace logTxt "putEndFn: vtx/key failed",
pfx=hdl.error.pfx, vid=hdl.error.vid, error=hdl.error.code
of AdmPfx: trace logTxt "putEndFn: admin failed",
pfx=AdmPfx, aid=hdl.error.aid.uint64, error=hdl.error.code
of Oops: trace logTxt "putEndFn: failed",
pfx=hdl.error.pfx, error=hdl.error.code
return err(hdl.error.code)
for (vid,data) in hdl.sTab.pairs:
if 0 < data.len:
db.mdb.sTab[vid] = data
else:
db.mdb.sTab.del vid
for (vid,key) in hdl.kMap.pairs:
if key.isValid:
db.mdb.kMap[vid] = key
else:
db.mdb.kMap.del vid
2024-06-04 15:05:13 +00:00
let tuv = hdl.tUvi.get(otherwise = VertexID(0))
if tuv.isValid:
db.mdb.tUvi = some(tuv)
if hdl.lSst.isSome:
db.mdb.lSst = hdl.lSst
ok()
# -------------
proc closeFn(db: MemBackendRef): CloseFn =
result =
proc(ignore: bool) =
discard
# ------------------------------------------------------------------------------
# Public functions
# ------------------------------------------------------------------------------
proc memoryBackend*(): BackendRef =
let db = MemBackendRef(
beKind: BackendMemory,
mdb: MemDbRef())
db.getVtxFn = getVtxFn db
db.getKeyFn = getKeyFn db
2024-06-04 15:05:13 +00:00
db.getTuvFn = getTuvFn db
db.getLstFn = getLstFn db
db.putBegFn = putBegFn db
db.putVtxFn = putVtxFn db
db.putKeyFn = putKeyFn db
2024-06-04 15:05:13 +00:00
db.putTuvFn = putTuvFn db
db.putLstFn = putLstFn db
db.putEndFn = putEndFn db
db.closeFn = closeFn db
db
proc dup*(db: MemBackendRef): MemBackendRef =
## Duplicate descriptor shell as needed for API debugging
new result
init_common.init(result[], db[])
result.mdb = db.mdb
# ------------------------------------------------------------------------------
# Public iterators (needs direct backend access)
# ------------------------------------------------------------------------------
iterator walkVtx*(
be: MemBackendRef;
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
kinds = {Branch, Leaf};
): tuple[rvid: RootedVertexID, vtx: VertexRef] =
## Iteration over the vertex sub-table.
for n,rvid in be.mdb.sTab.keys.toSeq.mapIt(it).sorted:
let data = be.mdb.sTab.getOrDefault(rvid, EmptyBlob)
if 0 < data.len:
let rc = data.deblobify VertexRef
if rc.isErr:
when extraTraceMessages:
debug logTxt "walkVtxFn() skip", n, rvid, error=rc.error
else:
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
if rc.value.vType in kinds:
yield (rvid, rc.value)
iterator walkKey*(
be: MemBackendRef;
): tuple[rvid: RootedVertexID, key: HashKey] =
## Iteration over the Markle hash sub-table.
for rvid in be.mdb.kMap.keys.toSeq.mapIt(it).sorted:
let key = be.mdb.kMap.getOrVoid(rvid)
if key.isValid:
yield (rvid, key)
# ------------------------------------------------------------------------------
# End
# ------------------------------------------------------------------------------