Skip to content

Commit cc58d4e

Browse files
committed
perf improvements RAM
1 parent 57f9329 commit cc58d4e

File tree

9 files changed

+47
-29
lines changed

9 files changed

+47
-29
lines changed

cardano-db-sync/src/Cardano/DbSync/Api.hs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -320,12 +320,12 @@ mkSyncEnv metricSetters trce dbEnv syncOptions protoInfo nw nwMagic systemStart
320320
newEmptyCache
321321
CacheCapacity
322322
{ cacheCapacityAddress = 50000
323-
, cacheCapacityStake = 50000
323+
, cacheCapacityStake = 150000
324324
, cacheCapacityDatum = 125000
325325
, cacheCapacityMultiAsset = 125000
326326
, cacheCapacityTx = 50000
327327
, cacheOptimisePools = 50000
328-
, cacheOptimiseStake = 50000
328+
, cacheOptimiseStake = 150000
329329
}
330330
else pure useNoCache
331331
consistentLevelVar <- newTVarIO Unchecked

cardano-db-sync/src/Cardano/DbSync/Api/Ledger.hs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import Numeric
2929
import Ouroboros.Consensus.Cardano.Block hiding (CardanoBlock)
3030
import Ouroboros.Consensus.Ledger.Extended (ExtLedgerState, ledgerState)
3131
import qualified Ouroboros.Consensus.Shelley.Ledger.Ledger as Consensus
32+
import System.Mem (performMinorGC)
3233

3334
import qualified Cardano.Db as DB
3435
import Cardano.DbSync.Api
@@ -132,6 +133,7 @@ storePage syncEnv percQuantum (n, ls) = do
132133
txOutIds <- lift $ DB.insertBulkTxOut False $ etoTxOut . fst <$> txOuts
133134
let maTxOuts = concatMap (mkmaTxOuts txOutVariantType) $ zip txOutIds (snd <$> txOuts)
134135
void . lift $ DB.insertBulkMaTxOutPiped [maTxOuts]
136+
liftIO performMinorGC
135137
where
136138
txOutVariantType = getTxOutVariantType syncEnv
137139
trce = getTrace syncEnv

cardano-db-sync/src/Cardano/DbSync/Cache.hs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -192,9 +192,16 @@ queryStakeAddrWithCacheRetBs syncEnv cacheUA ra@(Ledger.RewardAccount _ cred) =
192192
case queryRes of
193193
Nothing -> pure queryRes
194194
Just stakeAddrsId -> do
195-
let !stakeCache' = case cacheUA of
195+
let stable = scStableCache stakeCache
196+
maxSize = 150000
197+
trimSize = 145000 -- Trim to 145k when hitting 150k (less aggressive, better hit rate)
198+
trimmedStable =
199+
if Map.size stable >= maxSize
200+
then Map.fromList $ take trimSize $ Map.toList stable
201+
else stable
202+
!stakeCache' = case cacheUA of
196203
UpdateCache -> stakeCache {scLruCache = LRU.insert cred stakeAddrsId (scLruCache stakeCache)}
197-
UpdateCacheStrong -> stakeCache {scStableCache = Map.insert cred stakeAddrsId (scStableCache stakeCache)}
204+
UpdateCacheStrong -> stakeCache {scStableCache = Map.insert cred stakeAddrsId trimmedStable}
198205
_otherwise -> stakeCache
199206
liftIO $
200207
atomically $

cardano-db-sync/src/Cardano/DbSync/Era/Universal/Block.hs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,8 +64,8 @@ insertBlockUniversal ::
6464
insertBlockUniversal syncEnv shouldLog withinTwoMins withinHalfHour blk details isMember applyResult = do
6565
-- if we're syncing within 2 mins of the tip, we clean certain caches for tip following.
6666
when (isSyncedWithintwoMinutes details) $ cleanCachesForTip cache
67-
-- Optimise caches every 100k blocks to prevent unbounded growth
68-
when (unBlockNo (Generic.blkBlockNo blk) `mod` 100000 == 0) $ optimiseCaches cache
67+
-- Optimise caches every 50k blocks to prevent unbounded growth
68+
when (unBlockNo (Generic.blkBlockNo blk) `mod` 50000 == 0) $ optimiseCaches cache
6969
do
7070
pbid <- case Generic.blkPreviousHash blk of
7171
Nothing -> liftDbLookup mkSyncNodeCallStack $ DB.queryGenesis $ renderErrorMessage (Generic.blkEra blk) -- this is for networks that fork from Byron on epoch 0.

cardano-db-sync/src/Cardano/DbSync/Era/Universal/Epoch.hs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ import Cardano.Ledger.Conway.PParams (DRepVotingThresholds (..))
3939
import Cardano.Ledger.Conway.Rules (RatifyState (..))
4040
import Cardano.Prelude
4141
import Cardano.Slotting.Slot (EpochNo (..), SlotNo)
42+
import System.Mem (performMinorGC)
4243

4344
import qualified Cardano.Db as DB
4445
import Cardano.DbSync.Api
@@ -222,6 +223,8 @@ insertEpochStake syncEnv nw epochNo stakeChunk = do
222223

223224
-- minimising the bulk inserts into hundred thousand chunks to improve performance with pipeline
224225
lift $ DB.insertBulkEpochStakePiped dbConstraintEpochStake chunckDbStakes
226+
227+
liftIO performMinorGC
225228
where
226229
mkStake ::
227230
(StakeCred, (Shelley.Coin, PoolKeyHash)) ->
@@ -252,6 +255,8 @@ insertRewards syncEnv nw earnedEpoch spendableEpoch rewardsChunk = do
252255
let chunckDbRewards = DB.chunkForBulkQuery (Proxy @DB.Reward) Nothing dbRewards
253256
-- minimising the bulk inserts into hundred thousand chunks to improve performance with pipeline
254257
lift $ DB.insertBulkRewardsPiped dbConstraintRewards chunckDbRewards
258+
259+
liftIO performMinorGC
255260
where
256261
mkRewards ::
257262
(StakeCred, Set Generic.Reward) ->

cardano-db-sync/src/Cardano/DbSync/Era/Universal/Insert/GovAction.hs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ import qualified Data.ByteString.Lazy.Char8 as LBS
6666
import qualified Data.Map.Strict as Map
6767
import qualified Data.Text.Encoding as Text
6868
import Ouroboros.Consensus.Cardano.Block (ConwayEra)
69+
import System.Mem (performMinorGC)
6970

7071
insertGovActionProposal ::
7172
SyncEnv ->
@@ -383,6 +384,7 @@ insertDrepDistr e pSnapshot = do
383384
allDrepDistrs <- mapM processChunk drepChunks
384385
-- Insert all chunks in a single pipeline operation
385386
lift $ DB.insertBulkDrepDistrPiped allDrepDistrs
387+
liftIO performMinorGC
386388
where
387389
processChunk = mapM mkEntry
388390

cardano-db-sync/src/Cardano/DbSync/Ledger/State.hs

Lines changed: 21 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ import Cardano.Slotting.Slot (
6363
at,
6464
fromWithOrigin,
6565
)
66+
import Codec.CBOR.Write (toBuilder)
6667
import Control.Concurrent.Class.MonadSTM.Strict (
6768
atomically,
6869
newTVarIO,
@@ -80,6 +81,7 @@ import Cardano.Ledger.BaseTypes (StrictMaybe)
8081
import Cardano.Ledger.Conway.Core as Shelley
8182
import Cardano.Ledger.Conway.Governance
8283
import qualified Cardano.Ledger.Conway.Governance as Shelley
84+
import qualified Data.ByteString.Builder as Builder
8385
import qualified Data.ByteString.Char8 as BS
8486
import qualified Data.ByteString.Lazy.Char8 as LBS
8587
import qualified Data.ByteString.Short as SBS
@@ -132,6 +134,7 @@ import Ouroboros.Network.Block (HeaderHash, Point (..), blockNo)
132134
import qualified Ouroboros.Network.Point as Point
133135
import System.Directory (doesFileExist, listDirectory, removeFile)
134136
import System.FilePath (dropExtension, takeExtension, (</>))
137+
import qualified System.IO as IO
135138
import System.Mem (performMajorGC)
136139
import Prelude (String, id)
137140

@@ -380,25 +383,24 @@ ledgerStateWriteLoop tracer swQueue codecConfig =
380383
writeLedgerStateFile :: FilePath -> CardanoLedgerState -> IO ()
381384
writeLedgerStateFile file ledger = do
382385
startTime <- getCurrentTime
383-
-- TODO: write the builder directly.
384-
-- BB.writeFile file $ toBuilder $
385-
LBS.writeFile file $
386-
Serialize.serialize $
387-
encodeCardanoLedgerState
388-
( Consensus.encodeExtLedgerState
389-
(encodeDisk codecConfig)
390-
(encodeDisk codecConfig)
391-
(encodeDisk codecConfig)
392-
)
393-
ledger
386+
-- Use streaming builder to avoid loading entire state into memory
387+
IO.withBinaryFile file IO.WriteMode $ \h -> do
388+
let encoding =
389+
encodeCardanoLedgerState
390+
( Consensus.encodeExtLedgerState
391+
(encodeDisk codecConfig)
392+
(encodeDisk codecConfig)
393+
(encodeDisk codecConfig)
394+
)
395+
ledger
396+
Builder.hPutBuilder h (toBuilder encoding)
394397
endTime <- getCurrentTime
395398
logInfo tracer $
396399
mconcat
397400
[ "Asynchronously wrote a ledger snapshot to "
398401
, Text.pack file
399402
, " in "
400403
, textShow (diffUTCTime endTime startTime)
401-
, "."
402404
]
403405

404406
mkLedgerStateFilename :: LedgerStateDir -> ExtLedgerState CardanoBlock -> Maybe EpochNo -> WithOrigin FilePath
@@ -643,12 +645,13 @@ loadLedgerStateFromFile tracer config delete point lsf = do
643645
safeReadFile :: FilePath -> IO (Either Text CardanoLedgerState)
644646
safeReadFile fp = do
645647
startTime <- getCurrentTime
646-
mbs <- Exception.try $ BS.readFile fp
648+
-- Use lazy ByteString to enable streaming read
649+
mbs <- Exception.try $ LBS.readFile fp
647650
case mbs of
648651
Left (err :: IOException) -> pure $ Left (Text.pack $ displayException err)
649-
Right bs -> do
652+
Right lbs -> do
650653
mediumTime <- getCurrentTime
651-
case decode bs of
654+
case decode lbs of
652655
Left err -> pure $ Left $ textShow err
653656
Right ls -> do
654657
endTime <- getCurrentTime
@@ -658,7 +661,7 @@ loadLedgerStateFromFile tracer config delete point lsf = do
658661
, renderPoint point
659662
, ". It took "
660663
, textShow (diffUTCTime mediumTime startTime)
661-
, " to read from disk and "
664+
, " to read from disk (streaming) and "
662665
, textShow (diffUTCTime endTime mediumTime)
663666
, " to parse."
664667
]
@@ -667,12 +670,11 @@ loadLedgerStateFromFile tracer config delete point lsf = do
667670
codecConfig :: CodecConfig CardanoBlock
668671
codecConfig = configCodec config
669672

670-
decode :: ByteString -> Either DecoderError CardanoLedgerState
671-
decode = do
673+
decode :: LBS.ByteString -> Either DecoderError CardanoLedgerState
674+
decode =
672675
Serialize.decodeFullDecoder
673676
"Ledger state file"
674677
decodeState
675-
. LBS.fromStrict
676678

677679
decodeState :: (forall s. Decoder s CardanoLedgerState)
678680
decodeState =

cardano-db-sync/src/Cardano/DbSync/Ledger/Types.hs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ import Prelude (fail, id)
5959
--------------------------------------------------------------------------
6060

6161
data HasLedgerEnv = HasLedgerEnv
62-
{ leTrace :: Trace IO Text
62+
{ leTrace :: !(Trace IO Text)
6363
, leUseLedger :: !Bool
6464
, leHasRewards :: !Bool
6565
, leProtocolInfo :: !(Consensus.ProtocolInfo CardanoBlock)
@@ -186,8 +186,8 @@ updatedCommittee membersToRemove membersToAdd newQuorum committee =
186186
newCommitteeMembers
187187
newQuorum
188188

189-
newtype LedgerDB = LedgerDB
190-
{ ledgerDbCheckpoints :: AnchoredSeq (WithOrigin SlotNo) CardanoLedgerState CardanoLedgerState
189+
data LedgerDB = LedgerDB
190+
{ ledgerDbCheckpoints :: !(AnchoredSeq (WithOrigin SlotNo) CardanoLedgerState CardanoLedgerState)
191191
}
192192

193193
instance Anchorable (WithOrigin SlotNo) CardanoLedgerState CardanoLedgerState where

cardano-db-sync/src/Cardano/DbSync/LocalStateQuery.hs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ import qualified Ouroboros.Network.Protocol.LocalStateQuery.Client as StateQuery
5555
import Ouroboros.Network.Protocol.LocalStateQuery.Type (AcquireFailure, Target (..))
5656

5757
data NoLedgerEnv = NoLedgerEnv
58-
{ nleTracer :: Trace IO Text
58+
{ nleTracer :: !(Trace IO Text)
5959
, nleSystemStart :: !SystemStart
6060
, nleQueryVar :: StateQueryTMVar CardanoBlock CardanoInterpreter
6161
, nleHistoryInterpreterVar :: StrictTVar IO (Strict.Maybe CardanoInterpreter)

0 commit comments

Comments
 (0)