Skip to content

Commit 6ac05e2

Browse files
committed
perf improvements RAM
1 parent 9bad32d commit 6ac05e2

File tree

9 files changed

+47
-30
lines changed

9 files changed

+47
-30
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 & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ import Cardano.Slotting.Slot (
6565
at,
6666
fromWithOrigin,
6767
)
68+
import Codec.CBOR.Write (toBuilder)
6869
import Control.Concurrent.Class.MonadSTM.Strict (
6970
atomically,
7071
newTVarIO,
@@ -74,6 +75,7 @@ import Control.Concurrent.Class.MonadSTM.Strict (
7475
import Control.Concurrent.STM.TBQueue (TBQueue, newTBQueueIO, readTBQueue, writeTBQueue)
7576
import qualified Control.Exception as Exception
7677
import qualified Data.ByteString.Base16 as Base16
78+
import qualified Data.ByteString.Builder as Builder
7779
import qualified Data.ByteString.Char8 as BS
7880
import qualified Data.ByteString.Lazy.Char8 as LBS
7981
import qualified Data.ByteString.Short as SBS
@@ -121,6 +123,7 @@ import Ouroboros.Network.Block (HeaderHash, Point (..))
121123
import qualified Ouroboros.Network.Point as Point
122124
import System.Directory (doesFileExist, listDirectory, removeFile)
123125
import System.FilePath (dropExtension, takeExtension, (</>))
126+
import qualified System.IO as IO
124127
import System.Mem (performMajorGC)
125128
import Prelude (String, id)
126129

@@ -376,26 +379,24 @@ ledgerStateWriteLoop tracer swQueue codecConfig =
376379
writeLedgerStateFile :: FilePath -> CardanoLedgerState -> IO ()
377380
writeLedgerStateFile file ledger = do
378381
startTime <- getCurrentTime
379-
-- TODO: write the builder directly.
380-
-- BB.writeFile file $ toBuilder $
381-
LBS.writeFile file $
382-
Serialize.serialize $
383-
encodeCardanoLedgerState
384-
( Consensus.encodeExtLedgerState
385-
(encodeDisk codecConfig)
386-
(encodeDisk codecConfig)
387-
(encodeDisk codecConfig)
388-
. forgetLedgerTables
389-
)
390-
ledger
382+
-- Use streaming builder to avoid loading entire state into memory
383+
IO.withBinaryFile file IO.WriteMode $ \h -> do
384+
let encoding =
385+
encodeCardanoLedgerState
386+
( Consensus.encodeExtLedgerState
387+
(encodeDisk codecConfig)
388+
(encodeDisk codecConfig)
389+
(encodeDisk codecConfig)
390+
)
391+
ledger
392+
Builder.hPutBuilder h (toBuilder encoding)
391393
endTime <- getCurrentTime
392394
logInfo tracer $
393395
mconcat
394396
[ "Asynchronously wrote a ledger snapshot to "
395397
, Text.pack file
396398
, " in "
397399
, textShow (diffUTCTime endTime startTime)
398-
, "."
399400
]
400401

401402
mkLedgerStateFilename :: LedgerStateDir -> ExtLedgerState CardanoBlock mk -> Maybe EpochNo -> WithOrigin FilePath
@@ -641,12 +642,13 @@ loadLedgerStateFromFile tracer config delete point lsf = do
641642
safeReadFile :: FilePath -> IO (Either Text CardanoLedgerState)
642643
safeReadFile fp = do
643644
startTime <- getCurrentTime
644-
mbs <- Exception.try $ BS.readFile fp
645+
-- Use lazy ByteString to enable streaming read
646+
mbs <- Exception.try $ LBS.readFile fp
645647
case mbs of
646648
Left (err :: IOException) -> pure $ Left (Text.pack $ displayException err)
647-
Right bs -> do
649+
Right lbs -> do
648650
mediumTime <- getCurrentTime
649-
case decode bs of
651+
case decode lbs of
650652
Left err -> pure $ Left $ textShow err
651653
Right ls -> do
652654
endTime <- getCurrentTime
@@ -656,7 +658,7 @@ loadLedgerStateFromFile tracer config delete point lsf = do
656658
, renderPoint point
657659
, ". It took "
658660
, textShow (diffUTCTime mediumTime startTime)
659-
, " to read from disk and "
661+
, " to read from disk (streaming) and "
660662
, textShow (diffUTCTime endTime mediumTime)
661663
, " to parse."
662664
]
@@ -665,12 +667,11 @@ loadLedgerStateFromFile tracer config delete point lsf = do
665667
codecConfig :: CodecConfig CardanoBlock
666668
codecConfig = configCodec config
667669

668-
decode :: ByteString -> Either DecoderError CardanoLedgerState
669-
decode = do
670+
decode :: LBS.ByteString -> Either DecoderError CardanoLedgerState
671+
decode =
670672
Serialize.decodeFullDecoder
671673
"Ledger state file"
672674
decodeState
673-
. LBS.fromStrict
674675

675676
decodeState :: (forall s. Decoder s CardanoLedgerState)
676677
decodeState =

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ import Prelude (fail, id)
6262
--------------------------------------------------------------------------
6363

6464
data HasLedgerEnv = HasLedgerEnv
65-
{ leTrace :: Trace IO Text
65+
{ leTrace :: !(Trace IO Text)
6666
, leUseLedger :: !Bool
6767
, leHasRewards :: !Bool
6868
, leProtocolInfo :: !(Consensus.ProtocolInfo CardanoBlock)
@@ -195,8 +195,8 @@ updatedCommittee membersToRemove membersToAdd newQuorum committee =
195195
newCommitteeMembers
196196
newQuorum
197197

198-
newtype LedgerDB = LedgerDB
199-
{ ledgerDbCheckpoints :: AnchoredSeq (WithOrigin SlotNo) CardanoLedgerState CardanoLedgerState
198+
data LedgerDB = LedgerDB
199+
{ ledgerDbCheckpoints :: !(AnchoredSeq (WithOrigin SlotNo) CardanoLedgerState CardanoLedgerState)
200200
}
201201

202202
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)