diff --git a/examples/simple_plugin/go.mod b/examples/simple_plugin/go.mod index 28f7e544ba..fe05e1ccc1 100644 --- a/examples/simple_plugin/go.mod +++ b/examples/simple_plugin/go.mod @@ -60,6 +60,7 @@ require ( github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 // indirect github.com/spf13/cobra v1.10.2 // indirect github.com/spf13/pflag v1.0.9 // indirect + github.com/stoewer/go-strcase v1.3.1 // indirect github.com/stretchr/testify v1.12.1 // indirect github.com/thoas/go-funk v0.9.3 // indirect github.com/zeebo/xxh3 v1.1.0 // indirect diff --git a/examples/simple_plugin/go.sum b/examples/simple_plugin/go.sum index f5c22ca2cf..fdea44d535 100644 --- a/examples/simple_plugin/go.sum +++ b/examples/simple_plugin/go.sum @@ -64,6 +64,7 @@ github.com/cloudquery/plugin-sdk/v2 v2.7.0 h1:hRXsdEiaOxJtsn/wZMFQC9/jPfU1MeMK3K github.com/cloudquery/plugin-sdk/v2 v2.7.0/go.mod h1:pAX6ojIW99b/Vg4CkhnsGkRIzNaVEceYMR+Bdit73ug= github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI= @@ -148,8 +149,13 @@ github.com/spkg/bom v0.0.0-20160624110644-59b7046e48ad/go.mod h1:qLr4V1qq6nMqFKk github.com/stoewer/go-strcase v1.3.1 h1:iS0MdW+kVTxgMoE1LAZyMiYJFKlOzLooE4MxjirtkAs= github.com/stoewer/go-strcase v1.3.1/go.mod h1:fAH5hQ5pehh+j3nZfvwdk2RgEgQjAoM8wodgtPmh1xo= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= github.com/thoas/go-funk v0.9.3 h1:7+nAEx3kn5ZJcnDm2Bh23N2yOtweO14bi//dvRtgLpw= @@ -232,5 +238,6 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EV gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/batch/negative_bytes_test.go b/internal/batch/negative_bytes_test.go new file mode 100644 index 0000000000..ef1273f72a --- /dev/null +++ b/internal/batch/negative_bytes_test.go @@ -0,0 +1,55 @@ +package batch + +import ( + "testing" + + "github.com/apache/arrow-go/v18/arrow" + "github.com/apache/arrow-go/v18/arrow/array" + "github.com/apache/arrow-go/v18/arrow/memory" + "github.com/apache/arrow-go/v18/arrow/util" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func boolRecord(t *testing.T, rows int) arrow.RecordBatch { + t.Helper() + + sc := arrow.NewSchema([]arrow.Field{{Name: "b", Type: arrow.FixedWidthTypes.Boolean}}, nil) + builder := array.NewRecordBuilder(memory.DefaultAllocator, sc) + defer builder.Release() + + for range rows { + builder.Field(0).(*array.BooleanBuilder).Append(true) + } + return builder.NewRecordBatch() +} + +func TestSlicedRecordBytesNeverNegative(t *testing.T) { + const rows = 20000 + record := boolRecord(t, rows) + t.Logf("real size: %d bytes for %d rows", util.TotalRecordSize(record), record.NumRows()) + + limit := CappedAt(18000, 0) + limit.bytes.current = 4000 + + add, toFlush, rest := SliceRecord(record, limit) + + require.NotNil(t, add) + assert.GreaterOrEqual(t, add.Bytes, int64(0), "add.Bytes must not be negative") + if rest != nil { + t.Logf("rest: %d rows, %d bytes", rest.NumRows(), rest.Bytes) + assert.GreaterOrEqual(t, rest.Bytes, int64(0), "rest.Bytes must not be negative") + } + + var total int64 + if add != nil { + total += add.NumRows() + } + for _, r := range toFlush { + total += r.NumRows() + } + if rest != nil { + total += rest.NumRows() + } + assert.Equal(t, int64(rows), total, "no rows may be lost") +} diff --git a/internal/batch/slice.go b/internal/batch/slice.go index c032411126..ffd227b70c 100644 --- a/internal/batch/slice.go +++ b/internal/batch/slice.go @@ -66,7 +66,7 @@ func (s *SlicedRecord) getAdd(limit *Cap) *SlicedRecord { bytesPerRow: s.bytesPerRow, } s.RecordBatch = s.NewSlice(rows, s.NumRows()) - s.Bytes -= res.Bytes + s.Bytes = max(s.Bytes-res.Bytes, 0) return &res } @@ -84,7 +84,10 @@ func (s *SlicedRecord) getToFlush(limit *Cap) []arrow.RecordBatch { case rows == 0: // not even a single row fits // we still need to process this, so slice by single row - return s.slice() + res := s.slice() + s.RecordBatch = nil + s.Bytes = 0 + return res case rows < 0: // as s.Record != nil we know that the limits are there in place & the s.Record.NumRows() > 0 panic("should never be here") @@ -129,7 +132,7 @@ func newSlicedRecord(r arrow.RecordBatch) *SlicedRecord { RecordBatch: r, Bytes: util.TotalRecordSize(r), } - res.bytesPerRow = res.Bytes / r.NumRows() + res.bytesPerRow = max(res.Bytes/r.NumRows(), 1) return &res } @@ -143,3 +146,20 @@ func SliceRecord(r arrow.RecordBatch, limit *Cap) (add *SlicedRecord, flush []ar l := *limit // copy value return newSlicedRecord(r).split(&l) } + +func SplitRecord(r arrow.RecordBatch, limit *Cap) []arrow.RecordBatch { + if r.NumRows() == 0 { + return []arrow.RecordBatch{r} + } + + add, toFlush, rest := SliceRecord(r, limit) + records := make([]arrow.RecordBatch, 0, len(toFlush)+2) + if add != nil { + records = append(records, add.RecordBatch) + } + records = append(records, toFlush...) + if rest != nil { + records = append(records, rest.RecordBatch) + } + return records +} diff --git a/internal/batch/split_test.go b/internal/batch/split_test.go new file mode 100644 index 0000000000..a787ee65e5 --- /dev/null +++ b/internal/batch/split_test.go @@ -0,0 +1,78 @@ +package batch + +import ( + "testing" + "time" + + "github.com/apache/arrow-go/v18/arrow" + "github.com/apache/arrow-go/v18/arrow/util" + "github.com/cloudquery/plugin-sdk/v4/schema" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func testRecord(t *testing.T, rows int) arrow.RecordBatch { + t.Helper() + + table := schema.TestTable("test_table", schema.TestSourceOptions{}) + return schema.NewTestDataGenerator(0).Generate(table, schema.GenTestDataOptions{ + MaxRows: rows, + SourceName: "test", + SyncTime: time.Now(), + }) +} + +func totalRows(records []arrow.RecordBatch) int64 { + var rows int64 + for _, record := range records { + rows += record.NumRows() + } + return rows +} + +func TestSplitRecord(t *testing.T) { + const rows = 20 + record := testRecord(t, rows) + bytesPerRow := util.TotalRecordSize(record) / record.NumRows() + + t.Run("no limit", func(t *testing.T) { + records := SplitRecord(record, CappedAt(0, 0)) + require.Len(t, records, 1) + assert.Equal(t, int64(rows), records[0].NumRows()) + }) + + t.Run("limit above record size", func(t *testing.T) { + records := SplitRecord(record, CappedAt(0, 2*rows)) + require.Len(t, records, 1) + assert.Equal(t, int64(rows), records[0].NumRows()) + }) + + t.Run("rows limit", func(t *testing.T) { + records := SplitRecord(record, CappedAt(0, 6)) + assert.Equal(t, int64(rows), totalRows(records)) + for _, r := range records { + assert.LessOrEqual(t, r.NumRows(), int64(6)) + } + }) + + t.Run("bytes limit", func(t *testing.T) { + records := SplitRecord(record, CappedAt(5*bytesPerRow, 0)) + assert.Equal(t, int64(rows), totalRows(records)) + for _, r := range records { + assert.LessOrEqual(t, r.NumRows(), int64(5)) + } + }) + + t.Run("no single row fits", func(t *testing.T) { + records := SplitRecord(record, CappedAt(1, 0)) + assert.Len(t, records, int(record.NumRows()), "each row gets a record of its own") + assert.Equal(t, record.NumRows(), totalRows(records)) + }) + + t.Run("empty record", func(t *testing.T) { + empty := testRecord(t, 0) + records := SplitRecord(empty, CappedAt(1, 1)) + require.Len(t, records, 1) + assert.Equal(t, int64(0), records[0].NumRows()) + }) +} diff --git a/internal/servers/plugin/v3/plugin.go b/internal/servers/plugin/v3/plugin.go index df5c42dbd5..a5cf5c1ffd 100644 --- a/internal/servers/plugin/v3/plugin.go +++ b/internal/servers/plugin/v3/plugin.go @@ -8,6 +8,7 @@ import ( "github.com/apache/arrow-go/v18/arrow" pb "github.com/cloudquery/plugin-pb-go/pb/plugin/v3" + "github.com/cloudquery/plugin-sdk/v4/internal/batch" "github.com/cloudquery/plugin-sdk/v4/message" "github.com/cloudquery/plugin-sdk/v4/plugin" "github.com/cloudquery/plugin-sdk/v4/schema" @@ -28,6 +29,15 @@ type Server struct { Plugin *plugin.Plugin Logger zerolog.Logger Directory string + + MaxMsgSize int +} + +func (s *Server) maxMsgSize() int { + if s.MaxMsgSize > 0 { + return s.MaxMsgSize + } + return MaxMsgSize } func (s *Server) GetTables(ctx context.Context, req *pb.GetTables_Request) (*pb.GetTables_Response, error) { @@ -215,15 +225,10 @@ func (s *Server) Sync(req *pb.Sync_Request, stream pb.Plugin_SyncServer) error { } case *message.SyncInsert: - recordBytes, err := pb.RecordToBytes(m.Record) - if err != nil { - return status.Errorf(codes.Internal, "failed to encode record: %v", err) - } - pbMsg.Message = &pb.Sync_Response_Insert{ - Insert: &pb.Sync_MessageInsert{ - Record: recordBytes, - }, + if err := s.sendInsert(stream, m.Record); err != nil { + return err } + continue case *message.SyncDeleteRecord: whereClause := make([]*pb.PredicatesGroup, len(m.WhereClause)) for j, predicateGroup := range m.WhereClause { @@ -273,10 +278,8 @@ func (s *Server) Sync(req *pb.Sync_Request, stream pb.Plugin_SyncServer) error { return status.Errorf(codes.Internal, "unknown message type: %T", msg) } - size := proto.Size(pbMsg) - if size > MaxMsgSize { - s.Logger.Error().Int("bytes", size).Msg("Message exceeds max size") - continue + if size := proto.Size(pbMsg); size > s.maxMsgSize() { + return status.Errorf(codes.Internal, "message of type %T exceeds max message size: %d bytes > %d bytes", msg, size, s.maxMsgSize()) } if err := stream.Send(pbMsg); err != nil { return status.Errorf(codes.Internal, "failed to send message: %v", err) @@ -290,6 +293,64 @@ func (s *Server) Sync(req *pb.Sync_Request, stream pb.Plugin_SyncServer) error { return syncErr } +func (s *Server) sendInsert(stream pb.Plugin_SyncServer, record arrow.RecordBatch) error { + maxMsgSize := s.maxMsgSize() + pending := []arrow.RecordBatch{record} + for len(pending) > 0 { + current := pending[0] + pending = pending[1:] + + recordBytes, err := pb.RecordToBytes(current) + if err != nil { + return status.Errorf(codes.Internal, "failed to encode record for table %q: %v", recordTableName(current), err) + } + pbMsg := &pb.Sync_Response{ + Message: &pb.Sync_Response_Insert{ + Insert: &pb.Sync_MessageInsert{ + Record: recordBytes, + }, + }, + } + + size := proto.Size(pbMsg) + if size <= maxMsgSize { + if err := stream.Send(pbMsg); err != nil { + return status.Errorf(codes.Internal, "failed to send message: %v", err) + } + continue + } + + tableName := recordTableName(current) + if current.NumRows() <= 1 { + return status.Errorf(codes.Internal, "table %q: single row exceeds max message size: %d bytes > %d bytes", tableName, size, maxMsgSize) + } + + rowsPerMessage := maxRowsPerMessage(size, current.NumRows(), maxMsgSize) + s.Logger.Warn(). + Str("table", tableName). + Int("bytes", size). + Int64("rows", current.NumRows()). + Int64("rows_per_message", rowsPerMessage). + Msg("Message exceeds max size, splitting into smaller messages") + pending = append(batch.SplitRecord(current, batch.CappedAt(0, rowsPerMessage)), pending...) + } + + return nil +} + +func maxRowsPerMessage(size int, rows int64, maxMsgSize int) int64 { + perMessage := rows * int64(maxMsgSize) * 9 / (int64(size) * 10) + if perMessage >= rows { + perMessage = rows / 2 + } + return max(perMessage, 1) +} + +func recordTableName(record arrow.RecordBatch) string { + name, _ := record.Schema().Metadata().GetValue(schema.MetadataTableName) + return name +} + func (s *Server) Write(stream pb.Plugin_WriteServer) error { msgs := make(chan message.WriteMessage) ctx := stream.Context() diff --git a/internal/servers/plugin/v3/plugin_msgsize_test.go b/internal/servers/plugin/v3/plugin_msgsize_test.go new file mode 100644 index 0000000000..c0af39d191 --- /dev/null +++ b/internal/servers/plugin/v3/plugin_msgsize_test.go @@ -0,0 +1,115 @@ +package plugin + +import ( + "strings" + "testing" + + "github.com/apache/arrow-go/v18/arrow" + "github.com/apache/arrow-go/v18/arrow/array" + "github.com/apache/arrow-go/v18/arrow/memory" + pb "github.com/cloudquery/plugin-pb-go/pb/plugin/v3" + "github.com/cloudquery/plugin-sdk/v4/schema" + "github.com/rs/zerolog" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" +) + +type recordingSyncServer struct { + mockSyncServer + sent []*pb.Sync_Response +} + +func (s *recordingSyncServer) Send(msg *pb.Sync_Response) error { + s.sent = append(s.sent, msg) + return nil +} + +func newTestRecord(t *testing.T, tableName string, rows int, valueSize int) arrow.RecordBatch { + t.Helper() + + table := schema.Table{ + Name: tableName, + Columns: []schema.Column{{Name: "data", Type: arrow.BinaryTypes.String}}, + } + builder := array.NewRecordBuilder(memory.DefaultAllocator, table.ToArrowSchema()) + defer builder.Release() + + for i := range rows { + builder.Field(0).(*array.StringBuilder).Append(strings.Repeat(string(rune('a'+i%26)), valueSize)) + } + + return builder.NewRecordBatch() +} + +func TestSendInsertSplitsOversizedRecord(t *testing.T) { + t.Parallel() + + const ( + rows = 40 + valueSize = 1024 + maxMsgSize = 8 * 1024 + ) + record := newTestRecord(t, "test_table", rows, valueSize) + s := &Server{Logger: zerolog.Nop(), MaxMsgSize: maxMsgSize} + stream := &recordingSyncServer{} + + require.NoError(t, s.sendInsert(stream, record)) + require.Greater(t, len(stream.sent), 1, "oversized record should be split into several messages") + + var gotRows int64 + for _, msg := range stream.sent { + require.LessOrEqual(t, proto.Size(msg), maxMsgSize) + + sentRecord, err := pb.NewRecordFromBytes(msg.GetInsert().GetRecord()) + require.NoError(t, err) + gotRows += sentRecord.NumRows() + } + require.Equal(t, int64(rows), gotRows, "no rows may be dropped when splitting") +} + +func TestSendInsertFitsInSingleMessage(t *testing.T) { + t.Parallel() + + record := newTestRecord(t, "test_table", 10, 16) + s := &Server{Logger: zerolog.Nop()} + stream := &recordingSyncServer{} + + require.NoError(t, s.sendInsert(stream, record)) + require.Len(t, stream.sent, 1) +} + +func TestSendInsertSingleRowTooLarge(t *testing.T) { + t.Parallel() + + record := newTestRecord(t, "huge_table", 1, 4*1024) + s := &Server{Logger: zerolog.Nop(), MaxMsgSize: 1024} + stream := &recordingSyncServer{} + + err := s.sendInsert(stream, record) + require.Error(t, err, "a row that cannot be split must fail the sync instead of being dropped") + require.Contains(t, err.Error(), "huge_table") + require.Empty(t, stream.sent) +} + +func TestMaxRowsPerMessage(t *testing.T) { + t.Parallel() + + const maxMsgSize = 1000 + + for _, tc := range []struct { + name string + size int + rows int64 + }{ + {name: "slightly over", size: 1001, rows: 100}, + {name: "twice over", size: 2000, rows: 100}, + {name: "far over", size: 1_000_000, rows: 100}, + {name: "two rows", size: 5000, rows: 2}, + } { + t.Run(tc.name, func(t *testing.T) { + got := maxRowsPerMessage(tc.size, tc.rows, maxMsgSize) + require.GreaterOrEqual(t, got, int64(1), "must make progress") + require.Less(t, got, tc.rows, "must shrink the batch") + }) + } +} diff --git a/scheduler/batch.go b/scheduler/batch.go index 41c8ec9fa0..f869dac9a8 100644 --- a/scheduler/batch.go +++ b/scheduler/batch.go @@ -7,6 +7,8 @@ import ( "github.com/apache/arrow-go/v18/arrow/array" "github.com/apache/arrow-go/v18/arrow/memory" + "github.com/apache/arrow-go/v18/arrow/util" + "github.com/cloudquery/plugin-sdk/v4/internal/batch" "github.com/cloudquery/plugin-sdk/v4/message" "github.com/cloudquery/plugin-sdk/v4/scalar" "github.com/cloudquery/plugin-sdk/v4/schema" @@ -15,14 +17,16 @@ import ( ) const ( - DefaultBatchMaxRows = 50 - DefaultBatchTimeout = 5 * time.Second + DefaultBatchMaxRows = 50 + DefaultBatchTimeout = 5 * time.Second + DefaultBatchMaxSizeBytes = 50 * 1024 * 1024 ) type ( BatchSettings struct { - MaxRows int - Timeout time.Duration + MaxRows int + MaxSizeBytes int64 + Timeout time.Duration } BatchOption func(settings *BatchSettings) @@ -51,6 +55,12 @@ func WithBatchMaxRows(rows int) BatchOption { } } +func WithBatchMaxSizeBytes(size int64) BatchOption { + return func(s *BatchSettings) { + s.MaxSizeBytes = size + } +} + func WithBatchTimeout(timeout time.Duration) BatchOption { return func(s *BatchSettings) { s.Timeout = timeout @@ -63,11 +73,12 @@ func (s *BatchSettings) getBatcher(ctx context.Context, res chan<- message.SyncM } return &batcher{ - done: ctx.Done(), - res: res, - maxRows: s.MaxRows, - timeout: s.Timeout, - logger: logger.With().Int("max_rows", s.MaxRows).Dur("timeout_ms", s.Timeout).Logger(), + done: ctx.Done(), + res: res, + maxRows: s.MaxRows, + maxSizeBytes: s.MaxSizeBytes, + timeout: s.Timeout, + logger: logger.With().Int("max_rows", s.MaxRows).Int64("max_size_bytes", s.MaxSizeBytes).Dur("timeout_ms", s.Timeout).Logger(), } } @@ -93,8 +104,9 @@ type batcher struct { res chan<- message.SyncMessage - maxRows int - timeout time.Duration + maxRows int + maxSizeBytes int64 + timeout time.Duration // using sync primitives by value here implies that batcher is to be used by pointer only // workers is a sync.Map rather than a map + mutex pair @@ -110,6 +122,8 @@ type worker struct { ch chan *schema.Resource flush chan chan struct{} curRows, maxRows int + maxSizeBytes int64 + bytesPerRow int64 builder *array.RecordBuilder // we can reuse that res chan<- message.SyncMessage @@ -120,11 +134,35 @@ type worker struct { // send must be called on len(rows) > 0 func (w *worker) send() { - w.logger.Trace().Str("table", w.tableName).Int("rows", w.curRows).Msg("sending sync insert for rows batch") - w.res <- &message.SyncInsert{Record: w.builder.NewRecordBatch()} - // we need to reserve here as NewRecord (& underlying NewArray calls) reset the memory + record := w.builder.NewRecordBatch() + // we need to reserve here as NewRecordBatch (& underlying NewArray calls) reset the memory w.builder.Reserve(w.maxRows) w.curRows = 0 // reset + + if w.maxSizeBytes <= 0 || record.NumRows() == 0 { + w.logger.Trace().Str("table", w.tableName).Int64("rows", record.NumRows()).Msg("sending sync insert for rows batch") + w.res <- &message.SyncInsert{Record: record} + return + } + + totalBytes := util.TotalRecordSize(record) + w.bytesPerRow = totalBytes / record.NumRows() + + if totalBytes <= w.maxSizeBytes { + w.logger.Trace().Str("table", w.tableName).Int64("rows", record.NumRows()).Int64("bytes", totalBytes).Msg("sending sync insert for rows batch") + w.res <- &message.SyncInsert{Record: record} + return + } + + records := batch.SplitRecord(record, batch.CappedAt(w.maxSizeBytes, 0)) + w.logger.Debug().Str("table", w.tableName).Int64("rows", record.NumRows()).Int64("bytes", totalBytes).Int("messages", len(records)).Msg("splitting oversized rows batch") + for _, r := range records { + w.res <- &message.SyncInsert{Record: r} + } +} + +func (w *worker) reachedSizeLimit() bool { + return w.maxSizeBytes > 0 && w.bytesPerRow > 0 && int64(w.curRows)*w.bytesPerRow >= w.maxSizeBytes } func (w *worker) work(done <-chan struct{}, timeout time.Duration) { @@ -146,7 +184,7 @@ func (w *worker) work(done <-chan struct{}, timeout time.Duration) { scalar.AppendToRecordBuilder(w.builder, r.GetValues()) w.curRows++ // check if we need to flush - if w.maxRows > 0 && w.curRows == w.maxRows { + if (w.maxRows > 0 && w.curRows == w.maxRows) || w.reachedSizeLimit() { w.send() ticker.Reset(timeout) } @@ -199,6 +237,7 @@ func (b *batcher) process(res *schema.Resource) { // fill in the worker fields wr.flush = make(chan chan struct{}) wr.maxRows = b.maxRows + wr.maxSizeBytes = b.maxSizeBytes wr.builder = array.NewRecordBuilder(memory.DefaultAllocator, table.ToArrowSchema()) wr.res = b.res wr.builder.Reserve(b.maxRows) diff --git a/scheduler/batch_size_test.go b/scheduler/batch_size_test.go new file mode 100644 index 0000000000..871226435d --- /dev/null +++ b/scheduler/batch_size_test.go @@ -0,0 +1,122 @@ +package scheduler + +import ( + "context" + "strings" + "testing" + "time" + + "github.com/apache/arrow-go/v18/arrow" + "github.com/apache/arrow-go/v18/arrow/util" + "github.com/cloudquery/plugin-sdk/v4/message" + "github.com/cloudquery/plugin-sdk/v4/schema" + "github.com/rs/zerolog" + "github.com/stretchr/testify/require" +) + +func collectBatches(t *testing.T, settings BatchSettings, rows int, valueSize int) message.SyncInserts { + t.Helper() + + table := &schema.Table{ + Name: "test_table", + Columns: []schema.Column{{Name: "data", Type: arrow.BinaryTypes.String}}, + } + + res := make(chan message.SyncMessage, rows) + batcher := settings.getBatcher(context.Background(), res, zerolog.Nop()) + for range rows { + resource := schema.NewResourceData(table, nil, nil) + require.NoError(t, resource.Set("data", strings.Repeat("a", valueSize))) + batcher.process(resource) + } + batcher.close() + close(res) + + var inserts message.SyncInserts + for msg := range res { + insert, ok := msg.(*message.SyncInsert) + require.True(t, ok) + inserts = append(inserts, insert) + } + return inserts +} + +func TestBatcherMaxSizeBytes(t *testing.T) { + const ( + rows = 40 + valueSize = 1024 + maxSizeBytes = 8 * 1024 + ) + settings := BatchSettings{ + MaxRows: rows, + MaxSizeBytes: maxSizeBytes, + Timeout: time.Hour, + } + + unsplit := collectBatches(t, BatchSettings{MaxRows: rows, Timeout: time.Hour}, rows, valueSize) + require.Len(t, unsplit, 1) + bytesPerRow := util.TotalRecordSize(unsplit[0].Record) / unsplit[0].Record.NumRows() + + inserts := collectBatches(t, settings, rows, valueSize) + require.Greater(t, len(inserts), 1, "oversized batch should be split into several messages") + + var gotRows int64 + for _, insert := range inserts { + require.LessOrEqual(t, insert.Record.NumRows()*bytesPerRow, int64(maxSizeBytes)) + gotRows += insert.Record.NumRows() + } + require.Equal(t, int64(rows), gotRows, "no rows may be dropped when splitting") +} + +func TestBatcherWithoutMaxSizeBytes(t *testing.T) { + const rows = 40 + settings := BatchSettings{MaxRows: rows, Timeout: time.Hour} + + inserts := collectBatches(t, settings, rows, 1024) + require.Len(t, inserts, 1) + require.Equal(t, int64(rows), inserts[0].Record.NumRows()) +} + +func TestBatcherTableWithoutColumns(t *testing.T) { + table := &schema.Table{Name: "no_columns"} + res := make(chan message.SyncMessage, 16) + batcher := (&BatchSettings{MaxRows: 2, MaxSizeBytes: 1024, Timeout: time.Hour}). + getBatcher(context.Background(), res, zerolog.Nop()) + + batcher.process(schema.NewResourceData(table, nil, nil)) + batcher.close() + close(res) + + for msg := range res { + insert, ok := msg.(*message.SyncInsert) + require.True(t, ok) + require.Equal(t, int64(0), insert.Record.NumRows()) + } +} + +func TestBatcherMoreRowsThanBytes(t *testing.T) { + const rows = 20000 + table := &schema.Table{ + Name: "bools", + Columns: []schema.Column{{Name: "b", Type: arrow.FixedWidthTypes.Boolean}}, + } + res := make(chan message.SyncMessage, 4*rows) + batcher := (&BatchSettings{MaxRows: rows, MaxSizeBytes: 64, Timeout: time.Hour}). + getBatcher(context.Background(), res, zerolog.Nop()) + + for range rows { + resource := schema.NewResourceData(table, nil, nil) + require.NoError(t, resource.Set("b", true)) + batcher.process(resource) + } + batcher.close() + close(res) + + var gotRows int64 + for msg := range res { + insert, ok := msg.(*message.SyncInsert) + require.True(t, ok) + gotRows += insert.Record.NumRows() + } + require.Equal(t, int64(rows), gotRows) +} diff --git a/scheduler/scheduler.go b/scheduler/scheduler.go index 13913dbc80..b5e04aba75 100644 --- a/scheduler/scheduler.go +++ b/scheduler/scheduler.go @@ -177,8 +177,9 @@ func NewScheduler(opts ...Option) *Scheduler { singleResourceMaxConcurrency: DefaultSingleResourceMaxConcurrency, singleNestedTableMaxConcurrency: DefaultSingleNestedTableMaxConcurrency, batchSettings: &BatchSettings{ - MaxRows: DefaultBatchMaxRows, - Timeout: DefaultBatchTimeout, + MaxRows: DefaultBatchMaxRows, + MaxSizeBytes: DefaultBatchMaxSizeBytes, + Timeout: DefaultBatchTimeout, }, } for _, opt := range opts { diff --git a/writers/batchwriter/batchwriter_test.go b/writers/batchwriter/batchwriter_test.go index 91af9e11a4..2e35998892 100644 --- a/writers/batchwriter/batchwriter_test.go +++ b/writers/batchwriter/batchwriter_test.go @@ -35,6 +35,16 @@ func (c *testBatchClient) InsertsLen() int { return len(c.inserts) } +func (c *testBatchClient) InsertedRows() int64 { + c.mutex.Lock() + defer c.mutex.Unlock() + var rows int64 + for _, insert := range c.inserts { + rows += insert.Record.NumRows() + } + return rows +} + func (c *testBatchClient) DeleteStalesLen() int { c.mutex.Lock() defer c.mutex.Unlock() @@ -282,6 +292,9 @@ func TestBatchNoEmptyFlush(t *testing.T) { if testClient.InsertsLen() == 0 { t.Fatalf("expected at least 1 insert message, got 0") } + if got := testClient.InsertedRows(); got != numRows { + t.Fatalf("expected %d written rows, got %d", numRows, got) + } } func getRecord(sc *arrow.Schema, rows int) arrow.RecordBatch {