-
Notifications
You must be signed in to change notification settings - Fork 66
/
table.go
1538 lines (1357 loc) · 44.1 KB
/
table.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package frostdb
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"math/rand"
"path/filepath"
"runtime"
"sort"
"sync"
"sync/atomic"
"time"
"github.com/apache/arrow/go/v17/arrow"
"github.com/apache/arrow/go/v17/arrow/array"
"github.com/apache/arrow/go/v17/arrow/memory"
"github.com/apache/arrow/go/v17/arrow/util"
"github.com/dustin/go-humanize"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/oklog/ulid/v2"
"github.com/parquet-go/parquet-go"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"golang.org/x/sync/errgroup"
"google.golang.org/protobuf/proto"
"github.com/polarsignals/frostdb/dynparquet"
schemapb "github.com/polarsignals/frostdb/gen/proto/go/frostdb/schema/v1alpha1"
schemav2pb "github.com/polarsignals/frostdb/gen/proto/go/frostdb/schema/v1alpha2"
tablepb "github.com/polarsignals/frostdb/gen/proto/go/frostdb/table/v1alpha1"
walpb "github.com/polarsignals/frostdb/gen/proto/go/frostdb/wal/v1alpha1"
"github.com/polarsignals/frostdb/index"
"github.com/polarsignals/frostdb/internal/records"
"github.com/polarsignals/frostdb/parts"
"github.com/polarsignals/frostdb/pqarrow"
"github.com/polarsignals/frostdb/query/logicalplan"
"github.com/polarsignals/frostdb/query/physicalplan"
"github.com/polarsignals/frostdb/recovery"
"github.com/polarsignals/frostdb/wal"
walpkg "github.com/polarsignals/frostdb/wal"
)
var (
ErrNoSchema = fmt.Errorf("no schema")
ErrTableClosing = fmt.Errorf("table closing")
)
// DefaultIndexConfig returns the default level configs used. This is a function
// So that any modifications to the result will not affect the default config.
func DefaultIndexConfig() []*index.LevelConfig {
return []*index.LevelConfig{
{Level: index.L0, MaxSize: 1024 * 1024 * 15, Type: index.CompactionTypeParquetMemory}, // Compact to in-memory Parquet buffer after 15MiB of data
{Level: index.L1, MaxSize: 1024 * 1024 * 128, Type: index.CompactionTypeParquetMemory}, // Compact to a single in-memory Parquet buffer after 128MiB of Parquet files
{Level: index.L2, MaxSize: 1024 * 1024 * 512}, // Final level. Rotate after 512MiB of Parquet files
}
}
type ErrWriteRow struct{ err error }
func (e ErrWriteRow) Error() string { return "failed to write row: " + e.err.Error() }
type ErrReadRow struct{ err error }
func (e ErrReadRow) Error() string { return "failed to read row: " + e.err.Error() }
type ErrCreateSchemaWriter struct{ err error }
func (e ErrCreateSchemaWriter) Error() string {
return "failed to create schema write: " + e.err.Error()
}
type TableOption func(*tablepb.TableConfig) error
// WithRowGroupSize sets the size in number of rows for each row group for parquet files. A <= 0 value indicates no limit.
func WithRowGroupSize(numRows int) TableOption {
return func(config *tablepb.TableConfig) error {
config.RowGroupSize = uint64(numRows)
return nil
}
}
// WithBlockReaderLimit sets the limit of go routines that will be used to read persisted block files. A negative number indicates no limit.
func WithBlockReaderLimit(n int) TableOption {
return func(config *tablepb.TableConfig) error {
config.BlockReaderLimit = uint64(n)
return nil
}
}
// WithoutWAL disables the WAL for this table.
func WithoutWAL() TableOption {
return func(config *tablepb.TableConfig) error {
config.DisableWal = true
return nil
}
}
func WithUniquePrimaryIndex(unique bool) TableOption {
return func(config *tablepb.TableConfig) error {
switch e := config.Schema.(type) {
case *tablepb.TableConfig_DeprecatedSchema:
e.DeprecatedSchema.UniquePrimaryIndex = unique
case *tablepb.TableConfig_SchemaV2:
e.SchemaV2.UniquePrimaryIndex = unique
}
return nil
}
}
// FromConfig sets the table configuration from the given config.
// NOTE: that this does not override the schema even though that is included in the passed in config.
func FromConfig(config *tablepb.TableConfig) TableOption {
return func(cfg *tablepb.TableConfig) error {
if config.BlockReaderLimit != 0 { // the zero value is not a valid block reader limit
cfg.BlockReaderLimit = config.BlockReaderLimit
}
cfg.DisableWal = config.DisableWal
cfg.RowGroupSize = config.RowGroupSize
return nil
}
}
func defaultTableConfig() *tablepb.TableConfig {
return &tablepb.TableConfig{
BlockReaderLimit: uint64(runtime.GOMAXPROCS(0)),
}
}
func NewTableConfig(
schema proto.Message,
options ...TableOption,
) *tablepb.TableConfig {
t := defaultTableConfig()
switch v := schema.(type) {
case *schemapb.Schema:
t.Schema = &tablepb.TableConfig_DeprecatedSchema{
DeprecatedSchema: v,
}
case *schemav2pb.Schema:
t.Schema = &tablepb.TableConfig_SchemaV2{
SchemaV2: v,
}
default:
panic(fmt.Sprintf("unsupported schema type: %T", v))
}
for _, opt := range options {
_ = opt(t)
}
return t
}
type completedBlock struct {
prevTx uint64
tx uint64
}
// GenericTable is a wrapper around *Table that writes structs of type T. It
// consist of a generic arrow.Record builder that ingests structs of type T.
// The generated record is then passed to (*Table).InsertRecord.
//
// Struct tag `frostdb` is used to pass options for the schema for T.
//
// This api is opinionated.
//
// - Nested Columns are not supported
//
// # Tags
//
// Use `frostdb` to define tags that customizes field values. You can express
// everything needed to construct schema v1alpha1.
//
// Tags are defined as a comma separated list. The first item is the column
// name. Column name is optional, when omitted it is derived from the field name
// (snake_cased)
//
// Supported Tags
//
// delta_binary_packed | Delta binary packed encoding.
// brotli | Brotli compression.
// asc | Sorts in ascending order.Use asc(n) where n is an integer for sorting order.
// gzip | GZIP compression.
// snappy | Snappy compression.
// delta_length_byte_array | Delta Length Byte Array encoding.
// delta_byte_array | Delta Byte Array encoding.
// desc | Sorts in descending order.Use desc(n) where n is an integer for sorting order
// lz4_raw | LZ4_RAW compression.
// pre_hash | Prehash the column before storing it.
// null_first | When used wit asc nulls are smallest and with des nulls are largest.
// zstd | ZSTD compression.
// rle_dict | Dictionary run-length encoding.
// plain | Plain encoding.
//
// Example tagged Sample struct
//
// type Sample struct {
// ExampleType string `frostdb:"example_type,rle_dict,asc(0)"`
// Labels []Label `frostdb:"labels,rle_dict,null,dyn,asc(1),null_first"`
// Stacktrace []uuid.UUID `frostdb:"stacktrace,rle_dict,asc(3),null_first"`
// Timestamp int64 `frostdb:"timestamp,asc(2)"`
// Value int64 `frostdb:"value"`
// }
//
// # Dynamic columns
//
// Field of type map<string, T> is a dynamic column by default.
//
// type Example struct {
// // Use supported tags to customize the column value
// Labels map[string]string `frostdb:"labels"`
// }
//
// # Repeated columns
//
// Fields of type []int64, []float64, []bool, and []string are supported. These
// are represented as arrow.LIST.
//
// Generated schema for the repeated columns applies all supported tags. By
// default repeated fields are nullable. You can safely pass nil slices for
// repeated columns.
type GenericTable[T any] struct {
*Table
mu sync.Mutex
build *records.Build[T]
}
func (t *GenericTable[T]) Release() {
t.build.Release()
}
// Write builds arrow.Record directly from values and calls (*Table).InsertRecord.
func (t *GenericTable[T]) Write(ctx context.Context, values ...T) (uint64, error) {
t.mu.Lock()
defer t.mu.Unlock()
err := t.build.Append(values...)
if err != nil {
return 0, err
}
return t.InsertRecord(ctx, t.build.NewRecord())
}
func NewGenericTable[T any](db *DB, name string, mem memory.Allocator, options ...TableOption) (*GenericTable[T], error) {
build := records.NewBuild[T](mem)
table, err := db.Table(name, NewTableConfig(build.Schema(name), options...))
if err != nil {
return nil, err
}
return &GenericTable[T]{build: build, Table: table}, nil
}
type Table struct {
db *DB
name string
metrics tableMetrics
logger log.Logger
tracer trace.Tracer
config atomic.Pointer[tablepb.TableConfig]
schema *dynparquet.Schema
pendingBlocks map[*TableBlock]struct{}
completedBlocks []completedBlock
lastCompleted uint64
mtx *sync.RWMutex
active *TableBlock
wal WAL
closing bool
}
type Sync interface {
Sync() error
}
type WAL interface {
Close() error
Log(tx uint64, record *walpb.Record) error
LogRecord(tx uint64, table string, record arrow.Record) error
// Replay replays WAL records from the given first index. If firstIndex is
// 0, the first index read from the WAL is used (i.e. given a truncation,
// using 0 is still valid). If the given firstIndex is less than the WAL's
// first index on disk, the replay happens from the first index on disk.
// If the handler panics, the WAL implementation will truncate the WAL up to
// the last valid index.
Replay(tx uint64, handler wal.ReplayHandlerFunc) error
Truncate(tx uint64) error
Reset(nextTx uint64) error
FirstIndex() (uint64, error)
LastIndex() (uint64, error)
}
type TableBlock struct {
table *Table
logger log.Logger
tracer trace.Tracer
ulid ulid.ULID
minTx uint64
prevTx uint64
// uncompressedInsertsSize keeps track of the cumulative L0 size. This is
// not the size of the block, since these inserts are eventually compressed.
// However, it serves to determine when to perform a snapshot, since these
// uncompressed inserts are stored in the WAL, and if the node crashes, it
// is obliged to re-read all of these uncompressed inserts into memory,
// potentially causing OOMs.
uncompressedInsertsSize atomic.Int64
// lastSnapshotSize keeps track of the uncompressedInsertsSize when a
// snapshot was last triggered.
lastSnapshotSize atomic.Int64
index *index.LSM
pendingWritersWg sync.WaitGroup
pendingReadersWg sync.WaitGroup
mtx *sync.RWMutex
}
type Closer interface {
Close(cleanup bool) error
}
func schemaFromTableConfig(tableConfig *tablepb.TableConfig) (*dynparquet.Schema, error) {
switch schema := tableConfig.Schema.(type) {
case *tablepb.TableConfig_DeprecatedSchema:
return dynparquet.SchemaFromDefinition(schema.DeprecatedSchema)
case *tablepb.TableConfig_SchemaV2:
return dynparquet.SchemaFromDefinition(schema.SchemaV2)
default:
// No schema defined for table; read/only table
return nil, nil
}
}
func newTable(
db *DB,
name string,
tableConfig *tablepb.TableConfig,
metrics tableMetrics,
logger log.Logger,
tracer trace.Tracer,
wal WAL,
) (*Table, error) {
if db.columnStore.indexDegree <= 0 {
msg := fmt.Sprintf("Table's columnStore index degree must be a positive integer (received %d)", db.columnStore.indexDegree)
return nil, errors.New(msg)
}
if db.columnStore.splitSize < 2 {
msg := fmt.Sprintf("Table's columnStore splitSize must be a positive integer > 1 (received %d)", db.columnStore.splitSize)
return nil, errors.New(msg)
}
if tableConfig == nil {
tableConfig = defaultTableConfig()
}
s, err := schemaFromTableConfig(tableConfig)
if err != nil {
return nil, err
}
t := &Table{
db: db,
name: name,
logger: logger,
tracer: tracer,
mtx: &sync.RWMutex{},
wal: wal,
schema: s,
metrics: metrics,
}
// Store the table config
t.config.Store(tableConfig)
// Disable the WAL for this table by replacing any given WAL with a nop wal
if tableConfig.DisableWal {
t.wal = &walpkg.NopWAL{}
}
t.pendingBlocks = make(map[*TableBlock]struct{})
return t, nil
}
func (t *Table) newTableBlock(prevTx, tx uint64, id ulid.ULID) error {
b, err := id.MarshalBinary()
if err != nil {
return err
}
if err := t.wal.Log(tx, &walpb.Record{
Entry: &walpb.Entry{
EntryType: &walpb.Entry_NewTableBlock_{
NewTableBlock: &walpb.Entry_NewTableBlock{
TableName: t.name,
BlockId: b,
Config: t.config.Load(),
},
},
},
}); err != nil {
return err
}
t.active, err = newTableBlock(t, prevTx, tx, id)
if err != nil {
return err
}
return nil
}
func (t *Table) dropPendingBlock(block *TableBlock) {
t.mtx.Lock()
defer t.mtx.Unlock()
delete(t.pendingBlocks, block)
// Wait for outstanding readers/writers to finish with the block before releasing underlying resources.
block.pendingReadersWg.Wait()
block.pendingWritersWg.Wait()
if err := block.index.Close(); err != nil {
level.Error(t.logger).Log("msg", "failed to close index", "err", err)
}
}
func (t *Table) writeBlock(
block *TableBlock, nextTxn uint64, snapshotDB bool, opts ...RotateBlockOption,
) {
rbo := &rotateBlockOptions{}
for _, o := range opts {
o(rbo)
}
if rbo.wg != nil {
defer rbo.wg.Done()
}
level.Debug(t.logger).Log("msg", "syncing block", "next_txn", nextTxn, "ulid", block.ulid, "size", block.index.Size())
block.pendingWritersWg.Wait()
// from now on, the block will no longer be modified, we can persist it to disk
level.Debug(t.logger).Log("msg", "done syncing block", "next_txn", nextTxn, "ulid", block.ulid, "size", block.index.Size())
// Persist the block
var err error
if !rbo.skipPersist && block.index.Size() != 0 {
err = block.Persist()
}
t.dropPendingBlock(block)
if err != nil {
level.Error(t.logger).Log("msg", "failed to persist block")
level.Error(t.logger).Log("msg", err.Error())
return
}
if err := func() error {
tx, _, commit := t.db.begin()
defer commit()
buf, err := block.ulid.MarshalBinary()
if err != nil {
level.Error(t.logger).Log("msg", "failed to record block persistence in WAL: marshal ulid", "err", err)
return err
}
level.Debug(t.logger).Log("msg", "recording block persistence in WAL", "ulid", block.ulid, "txn", tx)
if err := t.wal.Log(tx, &walpb.Record{
Entry: &walpb.Entry{
EntryType: &walpb.Entry_TableBlockPersisted_{
TableBlockPersisted: &walpb.Entry_TableBlockPersisted{
TableName: t.name,
BlockId: buf,
// NOTE: nextTxn is used here instead of tx, since some
// writes could have happened between block rotation
// and the txn beginning above.
NextTx: nextTxn,
},
},
},
}); err != nil {
level.Error(t.logger).Log("msg", "failed to record block persistence in WAL", "err", err)
return err
}
return nil
}(); err != nil {
return
}
t.mtx.Lock()
t.completedBlocks = append(t.completedBlocks, completedBlock{prevTx: block.prevTx, tx: block.minTx})
sort.Slice(t.completedBlocks, func(i, j int) bool {
return t.completedBlocks[i].prevTx < t.completedBlocks[j].prevTx
})
for {
if len(t.completedBlocks) == 0 {
break
}
if t.completedBlocks[0].prevTx != t.lastCompleted {
break
}
t.lastCompleted = t.completedBlocks[0].tx
t.metrics.lastCompletedBlockTx.Set(float64(t.lastCompleted))
t.completedBlocks = t.completedBlocks[1:]
}
t.mtx.Unlock()
t.db.maintainWAL()
if snapshotDB && t.db.columnStore.snapshotTriggerSize != 0 && t.db.columnStore.enableWAL {
func() {
if !t.db.snapshotInProgress.CompareAndSwap(false, true) {
// Snapshot already in progress. This could lead to duplicate
// data when replaying (refer to the snapshot design document),
// but discarding this data on recovery is better than a
// potential additional CPU spike caused by another snapshot.
return
}
defer t.db.snapshotInProgress.Store(false)
// This snapshot snapshots the new, active, table block. Refer to
// the snapshot design document for more details as to why this
// snapshot is necessary.
// context.Background is used here for the snapshot since callers
// might cancel the context when the write is finished but the
// snapshot is not. Note that block.Persist does the same.
// TODO(asubiotto): Eventually we should register a cancel function
// that is called with a grace period on db.Close.
ctx := context.Background()
tx := t.db.beginRead()
if err := t.db.snapshotAtTX(ctx, tx, t.db.snapshotWriter(tx)); err != nil {
level.Error(t.logger).Log(
"msg", "failed to write snapshot on block rotation",
"err", err,
)
}
if err := t.db.reclaimDiskSpace(ctx, nil); err != nil {
level.Error(t.logger).Log(
"msg", "failed to reclaim disk space after snapshot on block rotation",
"err", err,
)
return
}
}()
}
}
type rotateBlockOptions struct {
skipPersist bool
wg *sync.WaitGroup
}
type RotateBlockOption func(*rotateBlockOptions)
// WithRotateBlockSkipPersist instructs the block rotation operation to not
// persist the block to object storage.
func WithRotateBlockSkipPersist() RotateBlockOption {
return func(o *rotateBlockOptions) {
o.skipPersist = true
}
}
// WithRotateBlockWaitGroup provides a WaitGroup. The rotate block operation
// will call wg.Done once the block has been persisted. Otherwise, RotateBlock
// asynchronously persists the block.
func WithRotateBlockWaitGroup(wg *sync.WaitGroup) RotateBlockOption {
return func(o *rotateBlockOptions) {
o.wg = wg
}
}
func (t *Table) RotateBlock(_ context.Context, block *TableBlock, opts ...RotateBlockOption) error {
rbo := &rotateBlockOptions{}
for _, o := range opts {
o(rbo)
}
t.mtx.Lock()
defer t.mtx.Unlock()
// Need to check that we haven't already rotated this block.
if t.active != block {
if rbo.wg != nil {
rbo.wg.Done()
}
return nil
}
level.Debug(t.logger).Log(
"msg", "rotating block",
"ulid", block.ulid,
"size", block.Size(),
"skip_persist", rbo.skipPersist,
)
defer level.Debug(t.logger).Log("msg", "done rotating block", "ulid", block.ulid)
tx, _, commit := t.db.begin()
defer commit()
id := generateULID()
for id.Time() == block.ulid.Time() { // Ensure the new block has a different timestamp.
// Sleep a millisecond to ensure the ULID has a different timestamp.
time.Sleep(time.Millisecond)
id = generateULID()
}
if err := t.newTableBlock(t.active.minTx, tx, id); err != nil {
return err
}
t.metrics.blockRotated.Inc()
t.metrics.numParts.Set(float64(0))
if !rbo.skipPersist {
// If skipping persist, this block rotation is simply a block discard,
// so no need to add this block to pending blocks. Some callers rely
// on the fact that blocks are not available for reads as soon as
// RotateBlock returns with skipPersist=true.
t.pendingBlocks[block] = struct{}{}
}
// We don't check t.db.columnStore.manualBlockRotation here because this is
// the entry point for users to trigger a manual block rotation and they
// will specify through skipPersist if they want the block to be persisted.
go t.writeBlock(block, tx, true, opts...)
return nil
}
func (t *Table) ActiveBlock() *TableBlock {
t.mtx.RLock()
defer t.mtx.RUnlock()
return t.active
}
func (t *Table) ActiveWriteBlock() (*TableBlock, func(), error) {
t.mtx.RLock()
defer t.mtx.RUnlock()
if t.closing {
return nil, nil, ErrTableClosing
}
t.active.pendingWritersWg.Add(1)
return t.active, t.active.pendingWritersWg.Done, nil
}
func (t *Table) Schema() *dynparquet.Schema {
if t.config.Load() == nil {
return nil
}
return t.schema
}
func (t *Table) EnsureCompaction() error {
return t.ActiveBlock().EnsureCompaction()
}
func (t *Table) InsertRecord(ctx context.Context, record arrow.Record) (uint64, error) {
block, finish, err := t.appender(ctx)
if err != nil {
return 0, fmt.Errorf("get appender: %w", err)
}
defer finish()
tx, _, commit := t.db.begin()
defer commit()
preHashedRecord := dynparquet.PrehashColumns(t.schema, record)
defer preHashedRecord.Release()
if err := t.wal.LogRecord(tx, t.name, preHashedRecord); err != nil {
return tx, fmt.Errorf("append to log: %w", err)
}
if err := block.InsertRecord(ctx, tx, preHashedRecord); err != nil {
return tx, fmt.Errorf("insert buffer into block: %w", err)
}
return tx, nil
}
func (t *Table) appender(ctx context.Context) (*TableBlock, func(), error) {
for {
// Using active write block is important because it ensures that we don't
// miss pending writers when synchronizing the block.
block, finish, err := t.ActiveWriteBlock()
if err != nil {
return nil, nil, err
}
uncompressedInsertsSize := block.uncompressedInsertsSize.Load()
if t.db.columnStore.snapshotTriggerSize != 0 &&
// If size-lastSnapshotSize > snapshotTriggerSize (a column store
// option), a new snapshot is triggered. This is basically the size
// of the new data in this block since the last snapshot.
uncompressedInsertsSize-block.lastSnapshotSize.Load() > t.db.columnStore.snapshotTriggerSize {
// context.Background is used here for the snapshot since callers
// might cancel the context when the write is finished but the
// snapshot is not.
// TODO(asubiotto): Eventually we should register a cancel function
// that is called with a grace period on db.Close.
t.db.asyncSnapshot(context.Background(), func() {
level.Debug(t.logger).Log(
"msg", "successful snapshot on block size trigger",
"block_size", humanize.IBytes(uint64(uncompressedInsertsSize)),
"last_snapshot_size", humanize.IBytes(uint64(block.lastSnapshotSize.Load())),
)
block.lastSnapshotSize.Store(uncompressedInsertsSize)
if err := t.db.reclaimDiskSpace(context.Background(), nil); err != nil {
level.Error(t.logger).Log(
"msg", "failed to reclaim disk space after snapshot",
"err", err,
)
return
}
})
}
blockSize := block.Size()
if blockSize < t.db.columnStore.activeMemorySize || t.db.columnStore.manualBlockRotation {
return block, finish, nil
}
// We need to rotate the block and the writer won't actually be used.
finish()
err = t.RotateBlock(ctx, block)
if err != nil {
return nil, nil, fmt.Errorf("rotate block: %w", err)
}
}
}
func (t *Table) View(ctx context.Context, fn func(ctx context.Context, tx uint64) error) error {
ctx, span := t.tracer.Start(ctx, "Table/View")
tx := t.db.beginRead()
span.SetAttributes(attribute.Int64("tx", int64(tx))) // Attributes don't support uint64...
defer span.End()
return fn(ctx, tx)
}
// Iterator iterates in order over all granules in the table. It stops iterating when the iterator function returns false.
func (t *Table) Iterator(
ctx context.Context,
tx uint64,
pool memory.Allocator,
callbacks []logicalplan.Callback,
options ...logicalplan.Option,
) error {
iterOpts := &logicalplan.IterOptions{}
for _, opt := range options {
opt(iterOpts)
}
ctx, span := t.tracer.Start(ctx, "Table/Iterator")
span.SetAttributes(attribute.Int("physicalProjections", len(iterOpts.PhysicalProjection)))
span.SetAttributes(attribute.Int("projections", len(iterOpts.Projection)))
span.SetAttributes(attribute.Int("distinct", len(iterOpts.DistinctColumns)))
defer span.End()
if len(callbacks) == 0 {
return errors.New("no callbacks provided")
}
rowGroups := make(chan any, len(callbacks)*4) // buffer up to 4 row groups per callback
defer func() { // Drain the channel of any leftover parts due to cancellation or error
for rg := range rowGroups {
switch t := rg.(type) {
case index.ReleaseableRowGroup:
t.Release()
case arrow.Record:
t.Release()
}
}
}()
// Previously we sorted all row groups into a single row group here,
// but it turns out that none of the downstream uses actually rely on
// the sorting so it's not worth it in the general case. Physical plans
// can decide to sort if they need to in order to exploit the
// characteristics of sorted data.
// bufferSize specifies a threshold of records past which the
// buffered results are flushed to the next operator.
const bufferSize = 1024
errg, ctx := errgroup.WithContext(ctx)
for _, callback := range callbacks {
callback := callback
errg.Go(recovery.Do(func() error {
converter := pqarrow.NewParquetConverter(pool, *iterOpts)
defer converter.Close()
for {
select {
case <-ctx.Done():
return ctx.Err()
case rg, ok := <-rowGroups:
if !ok {
r := converter.NewRecord()
if r == nil {
return nil
}
defer r.Release()
if r.NumRows() == 0 {
return nil
}
return callback(ctx, r)
}
switch rg := rg.(type) {
case arrow.Record:
defer rg.Release()
r := pqarrow.Project(rg, iterOpts.PhysicalProjection)
defer r.Release()
err := callback(ctx, r)
if err != nil {
return err
}
case index.ReleaseableRowGroup:
defer rg.Release()
if err := converter.Convert(ctx, rg, t.schema); err != nil {
return fmt.Errorf("failed to convert row group to arrow record: %v", err)
}
// This RowGroup had no relevant data. Ignore it.
if len(converter.Fields()) == 0 {
continue
}
if converter.NumRows() >= bufferSize {
err := func() error {
r := converter.NewRecord()
defer r.Release()
converter.Reset() // Reset the converter to drop any dictionaries that were built.
return callback(ctx, r)
}()
if err != nil {
return err
}
}
case dynparquet.DynamicRowGroup:
if err := converter.Convert(ctx, rg, t.schema); err != nil {
return fmt.Errorf("failed to convert row group to arrow record: %v", err)
}
// This RowGroup had no relevant data. Ignore it.
if len(converter.Fields()) == 0 {
continue
}
if converter.NumRows() >= bufferSize {
err := func() error {
r := converter.NewRecord()
defer r.Release()
converter.Reset() // Reset the converter to drop any dictionaries that were built.
return callback(ctx, r)
}()
if err != nil {
return err
}
}
default:
return fmt.Errorf("unknown row group type: %T", t)
}
}
}
}, t.logger))
}
errg.Go(func() error {
defer close(rowGroups)
return t.collectRowGroups(ctx, tx, iterOpts.Filter, iterOpts.ReadMode, rowGroups)
})
return errg.Wait()
}
// SchemaIterator iterates in order over all granules in the table and returns
// all the schemas seen across the table.
func (t *Table) SchemaIterator(
ctx context.Context,
tx uint64,
pool memory.Allocator,
callbacks []logicalplan.Callback,
options ...logicalplan.Option,
) error {
iterOpts := &logicalplan.IterOptions{}
for _, opt := range options {
opt(iterOpts)
}
ctx, span := t.tracer.Start(ctx, "Table/SchemaIterator")
span.SetAttributes(attribute.Int("physicalProjections", len(iterOpts.PhysicalProjection)))
span.SetAttributes(attribute.Int("projections", len(iterOpts.Projection)))
span.SetAttributes(attribute.Int("distinct", len(iterOpts.DistinctColumns)))
defer span.End()
if len(callbacks) == 0 {
return errors.New("no callbacks provided")
}
rowGroups := make(chan any, len(callbacks)*4) // buffer up to 4 row groups per callback
defer func() { // Drain the channel of any leftover parts due to cancellation or error
for rg := range rowGroups {
switch t := rg.(type) {
case index.ReleaseableRowGroup:
t.Release()
case arrow.Record:
t.Release()
}
}
}()
schema := arrow.NewSchema(
[]arrow.Field{
{Name: "name", Type: arrow.BinaryTypes.String},
},
nil,
)
errg, ctx := errgroup.WithContext(ctx)
for _, callback := range callbacks {
callback := callback
errg.Go(recovery.Do(func() error {
for {
select {
case <-ctx.Done():
return ctx.Err()
case rg, ok := <-rowGroups:
if !ok {
return nil // we're done
}
b := array.NewRecordBuilder(pool, schema)
switch t := rg.(type) {
case arrow.Record:
for i := 0; i < t.Schema().NumFields(); i++ {
b.Field(0).(*array.StringBuilder).Append(t.Schema().Field(i).Name)
}
record := b.NewRecord()
err := callback(ctx, record)
record.Release()
t.Release()
if err != nil {
return err
}
case index.ReleaseableRowGroup:
if rg == nil {
return errors.New("received nil rowGroup") // shouldn't happen, but anyway
}
defer t.Release()
parquetFields := t.Schema().Fields()
fieldNames := make([]string, 0, len(parquetFields))
for _, f := range parquetFields {
fieldNames = append(fieldNames, f.Name())
}
b.Field(0).(*array.StringBuilder).AppendValues(fieldNames, nil)
record := b.NewRecord()
if err := callback(ctx, record); err != nil {
return err
}
record.Release()
b.Release()
case dynparquet.DynamicRowGroup:
if rg == nil {
return errors.New("received nil rowGroup") // shouldn't happen, but anyway
}
parquetFields := t.Schema().Fields()
fieldNames := make([]string, 0, len(parquetFields))
for _, f := range parquetFields {
fieldNames = append(fieldNames, f.Name())
}
b.Field(0).(*array.StringBuilder).AppendValues(fieldNames, nil)
record := b.NewRecord()
if err := callback(ctx, record); err != nil {
return err
}
record.Release()
b.Release()
default:
return fmt.Errorf("unknown row group type: %T", t)
}
}
}
}, t.logger))
}
errg.Go(func() error {
if err := t.collectRowGroups(ctx, tx, iterOpts.Filter, iterOpts.ReadMode, rowGroups); err != nil {
return err
}
close(rowGroups)
return nil
})
return errg.Wait()