Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: speed up ydb insert #1793

Merged
merged 1 commit into from
Nov 1, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 45 additions & 61 deletions extern/boostd-data/yugabyte/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (
"github.com/filecoin-project/go-address"
"github.com/ipfs/go-cid"
logging "github.com/ipfs/go-log/v2"
"github.com/multiformats/go-multihash"
mh "github.com/multiformats/go-multihash"
"github.com/yugabyte/gocql"
"github.com/yugabyte/pgx/v4/pgxpool"
Expand All @@ -30,6 +29,10 @@ const defaultKeyspace = "idx"

const CqlTimeout = 60

// The Cassandra driver has a 50k limit on batch statements. Keeping
// batch size small makes sure we're under the limit.
const InsertBatchSize = 10000

type DBSettings struct {
// The cassandra hosts to connect to
Hosts []string
Expand All @@ -39,6 +42,8 @@ type DBSettings struct {
PayloadPiecesParallelism int
// CQL timeout in seconds
CQLTimeout int
// Number of records per insert batch
InsertBatchSize int
}

type StoreOpt func(*Store)
Expand All @@ -65,6 +70,9 @@ func NewStore(settings DBSettings, migrator *Migrator, opts ...StoreOpt) *Store
if settings.PayloadPiecesParallelism == 0 {
settings.PayloadPiecesParallelism = 16
}
if settings.InsertBatchSize == 0 {
settings.InsertBatchSize = InsertBatchSize
}

cluster := gocql.NewCluster(settings.Hosts...)
cluster.Timeout = time.Duration(settings.CQLTimeout) * time.Second
Expand Down Expand Up @@ -290,7 +298,7 @@ func (s *Store) GetIndex(ctx context.Context, pieceCid cid.Cid) (<-chan types.In
}

// Parse the multihash bytes
_, pmh, err := multihash.MHFromBytes(payloadMHBz)
_, pmh, err := mh.MHFromBytes(payloadMHBz)
if err != nil {
records <- types.IndexRecord{Error: err}
return
Expand Down Expand Up @@ -442,54 +450,63 @@ func (s *Store) addMultihashesToPieces(ctx context.Context, pieceCid cid.Cid, re
ctx, span := tracing.Tracer.Start(ctx, "store.add_index.payloadpiece")
defer span.End()

var count float64
return s.execParallel(ctx, recs, s.settings.PayloadPiecesParallelism, func(rec model.Record) error {
multihashBytes := rec.Cid.Hash()
q := `INSERT INTO PayloadToPieces (PayloadMultihash, PieceCid) VALUES (?, ?)`
err := s.session.Query(q, trimMultihash(multihashBytes), pieceCid.Bytes()).Exec()
if err != nil {
return fmt.Errorf("inserting into PayloadToPieces: %w", err)
insertPieceOffsetsQry := `INSERT INTO PayloadToPieces (PayloadMultihash, PieceCid) VALUES (?, ?)`
pieceCidBytes := pieceCid.Bytes()

var batch *gocql.Batch
for allIdx, rec := range recs {
if batch == nil {
batch = s.session.NewBatch(gocql.UnloggedBatch).WithContext(ctx)
batch.Entries = make([]gocql.BatchEntry, 0, s.settings.InsertBatchSize)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Size should be whatever is left, which is at most insertBatchSize, not always.

}

count++
progress(count / float64(len(recs)))
return nil
})
batch.Entries = append(batch.Entries, gocql.BatchEntry{
Stmt: insertPieceOffsetsQry,
Args: []interface{}{trimMultihash(rec.Cid.Hash()), pieceCidBytes},
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Args: []interface{}{trimMultihash(rec.Cid.Hash()), pieceCidBytes},
Args: []any{trimMultihash(rec.Cid.Hash()), pieceCidBytes},

Idempotent: true,
})

if allIdx == len(recs)-1 || len(batch.Entries) == s.settings.InsertBatchSize {
err := s.session.ExecuteBatch(batch)
if err != nil {
return fmt.Errorf("inserting into PayloadToPieces: %w", err)
}
batch = nil

progress(float64(allIdx+1) / float64(len(recs)))
}
}
return nil
}

func (s *Store) addPieceInfos(ctx context.Context, pieceCid cid.Cid, recs []model.Record, progress func(addProgress float64)) error {
ctx, span := tracing.Tracer.Start(ctx, "store.add_index.pieceinfo")
defer span.End()

batchEntries := make([]gocql.BatchEntry, 0, len(recs))
insertPieceOffsetsQry := `INSERT INTO PieceBlockOffsetSize (PieceCid, PayloadMultihash, BlockOffset, BlockSize) VALUES (?, ?, ?, ?)`
for _, rec := range recs {
batchEntries = append(batchEntries, gocql.BatchEntry{
Stmt: insertPieceOffsetsQry,
Args: []interface{}{pieceCid.Bytes(), rec.Cid.Hash(), rec.Offset, rec.Size},
Idempotent: true,
})
}
pieceCidBytes := pieceCid.Bytes()

// The Cassandra driver has a 50k limit on batch statements. Keeping
// batch size small makes sure we're under the limit.
const batchSize = 5000
var batch *gocql.Batch
for allIdx, entry := range batchEntries {
for allIdx, rec := range recs {
if batch == nil {
batch = s.session.NewBatch(gocql.UnloggedBatch).WithContext(ctx)
batch.Entries = make([]gocql.BatchEntry, 0, s.settings.InsertBatchSize)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ditto re slice size.

Would be nice to reduce duplicate code in working with batches.

}

batch.Entries = append(batch.Entries, entry)
batch.Entries = append(batch.Entries, gocql.BatchEntry{
Stmt: insertPieceOffsetsQry,
Args: []any{pieceCidBytes, rec.Cid.Hash(), rec.Offset, rec.Size},
Idempotent: true,
})

if allIdx == len(batchEntries)-1 || len(batch.Entries) == batchSize {
if allIdx == len(recs)-1 || len(batch.Entries) == s.settings.InsertBatchSize {
err := s.session.ExecuteBatch(batch)
if err != nil {
return fmt.Errorf("executing offset / size batch insert for piece %s: %w", pieceCid, err)
}
batch = nil

progress((float64(allIdx+1) / float64(len(batchEntries))))
progress(float64(allIdx+1) / float64(len(recs)))
}
}

Expand Down Expand Up @@ -655,36 +672,3 @@ func (s *Store) RemoveIndexes(ctx context.Context, pieceCid cid.Cid) error {

return nil
}

func (s *Store) execParallel(ctx context.Context, recs []model.Record, parallelism int, f func(record model.Record) error) error {
queue := make(chan model.Record, len(recs))
for _, rec := range recs {
queue <- rec
}
close(queue)

var eg errgroup.Group
for i := 0; i < parallelism; i++ {
eg.Go(func() error {
for ctx.Err() == nil {
select {
case <-ctx.Done():
return ctx.Err()
case rec, ok := <-queue:
if !ok {
// Finished adding all the queued items, exit the thread
return nil
}

err := f(rec)
if err != nil {
return err
}
}
}

return ctx.Err()
})
}
return eg.Wait()
}