forked from timescale/timescaledb
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcolumnar_scan.c
More file actions
3187 lines (2843 loc) · 102 KB
/
Copy pathcolumnar_scan.c
File metadata and controls
3187 lines (2843 loc) · 102 KB
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
/*
* This file and its contents are licensed under the Timescale License.
* Please see the included NOTICE for copyright information and
* LICENSE-TIMESCALE for a copy of the license.
*/
#include <postgres.h>
#include "chunk.h"
#include "hypertable_cache.h"
#include <catalog/pg_operator.h>
#include <math.h>
#include <miscadmin.h>
#include <nodes/bitmapset.h>
#include <nodes/makefuncs.h>
#include <nodes/nodeFuncs.h>
#include <optimizer/clauses.h>
#include <optimizer/cost.h>
#include <optimizer/optimizer.h>
#include <optimizer/pathnode.h>
#include <optimizer/paths.h>
#include <parser/parse_relation.h>
#include <parser/parsetree.h>
#include <planner/planner.h>
#include <storage/lockdefs.h>
#include <utils/builtins.h>
#include <utils/lsyscache.h>
#include <utils/syscache.h>
#include <utils/typcache.h>
#if PG16_GE
#include <nodes/multibitmapset.h>
#endif
#include <planner.h>
#include "compat/compat.h"
#include "compression/compression.h"
#include "compression/create.h"
#include "cross_module_fn.h"
#include "custom_type_cache.h"
#include "debug_assert.h"
#include "import/allpaths.h"
#include "import/planner.h"
#include "nodes/columnar_scan/columnar_scan.h"
#include "nodes/columnar_scan/planner.h"
#include "nodes/columnar_scan/qual_pushdown.h"
#include "ts_catalog/array_utils.h"
#include "utils.h"
static CustomPathMethods columnar_scan_path_methods = {
.CustomName = "ColumnarScan",
.PlanCustomPath = columnar_scan_plan_create,
};
typedef struct SortInfo
{
List *required_compressed_pathkeys;
List *required_eq_classes;
bool needs_sequence_num;
bool use_compressed_sort; /* sort can be pushed below ColumnarScan */
bool use_batch_sorted_merge;
bool reverse;
List *decompressed_sort_pathkeys;
QualCost decompressed_sort_pathkeys_cost;
} SortInfo;
static RangeTblEntry *columnar_scan_make_rte(Oid compressed_relid, LOCKMODE lockmode, Query *parse);
static void create_compressed_scan_paths(PlannerInfo *root, RelOptInfo *compressed_rel,
const CompressionInfo *compression_info,
const SortInfo *sort_info);
static ColumnarScanPath *columnar_scan_path_create(PlannerInfo *root, const CompressionInfo *info,
Path *compressed_path);
static void columnar_scan_add_plannerinfo(PlannerInfo *root, CompressionInfo *info,
const Chunk *chunk, RelOptInfo *chunk_rel,
bool needs_sequence_num);
static SortInfo build_sortinfo(PlannerInfo *root, const Chunk *chunk, RelOptInfo *chunk_rel,
const CompressionInfo *info, List *pathkeys);
static Bitmapset *find_const_segmentby(RelOptInfo *chunk_rel, const CompressionInfo *info);
static EquivalenceClass *
append_ec_for_seqnum(PlannerInfo *root, const CompressionInfo *info, const SortInfo *sort_info,
Var *var, Oid sortop, bool nulls_first)
{
MemoryContext oldcontext = MemoryContextSwitchTo(root->planner_cxt);
Oid opfamily, opcintype, equality_op;
CompareType strategy;
List *opfamilies;
EquivalenceClass *newec = makeNode(EquivalenceClass);
EquivalenceMember *em = makeNode(EquivalenceMember);
/* Find the operator in pg_amop --- failure shouldn't happen */
if (!get_ordering_op_properties(sortop, &opfamily, &opcintype, &strategy))
{
elog(ERROR, "operator %u is not a valid ordering operator", sortop);
}
/*
* EquivalenceClasses need to contain opfamily lists based on the family
* membership of mergejoinable equality operators, which could belong to
* more than one opfamily. So we have to look up the opfamily's equality
* operator and get its membership.
*/
equality_op = get_opfamily_member(opfamily, opcintype, opcintype, BTEqualStrategyNumber);
if (!OidIsValid(equality_op)) /* shouldn't happen */
{
elog(ERROR,
"missing operator %d(%u,%u) in opfamily %u",
BTEqualStrategyNumber,
opcintype,
opcintype,
opfamily);
}
opfamilies = get_mergejoin_opfamilies(equality_op);
if (!opfamilies) /* certainly should find some */
{
elog(ERROR, "could not find opfamilies for equality operator %u", equality_op);
}
em->em_expr = (Expr *) var;
em->em_relids = bms_make_singleton(info->compressed_rel->relid);
#if PG16_LT
em->em_nullable_relids = NULL;
#endif
em->em_is_const = false;
em->em_is_child = false;
em->em_datatype = INT4OID;
newec->ec_opfamilies = list_copy(opfamilies);
newec->ec_collation = 0;
newec->ec_members = list_make1(em);
newec->ec_sources = NIL;
newec->ec_derives_list = NIL;
newec->ec_relids = bms_make_singleton(info->compressed_rel->relid);
newec->ec_has_const = false;
newec->ec_has_volatile = false;
#if PG16_LT
newec->ec_below_outer_join = false;
#endif
newec->ec_broken = false;
newec->ec_sortref = 0;
newec->ec_min_security = UINT_MAX;
newec->ec_max_security = 0;
newec->ec_merged = NULL;
info->compressed_rel->eclass_indexes =
bms_add_member(info->compressed_rel->eclass_indexes, list_length(root->eq_classes));
root->eq_classes = lappend(root->eq_classes, newec);
MemoryContextSwitchTo(oldcontext);
return newec;
}
static EquivalenceClass *
append_ec_for_metadata_col(PlannerInfo *root, const CompressionInfo *info, Expr *expr, PathKey *pk,
Oid em_datatype)
{
MemoryContext oldcontext = MemoryContextSwitchTo(root->planner_cxt);
EquivalenceMember *em = makeNode(EquivalenceMember);
em->em_expr = expr;
em->em_relids = bms_make_singleton(info->compressed_rel->relid);
em->em_is_const = false;
em->em_is_child = false;
em->em_datatype = em_datatype;
EquivalenceClass *ec = makeNode(EquivalenceClass);
ec->ec_opfamilies = pk->pk_eclass->ec_opfamilies;
ec->ec_collation = pk->pk_eclass->ec_collation;
ec->ec_members = list_make1(em);
ec->ec_sources = list_copy(pk->pk_eclass->ec_sources);
ec->ec_derives_list = list_copy(pk->pk_eclass->ec_derives_list);
ec->ec_relids = bms_make_singleton(info->compressed_rel->relid);
ec->ec_has_const = pk->pk_eclass->ec_has_const;
ec->ec_has_volatile = pk->pk_eclass->ec_has_volatile;
#if PG16_LT
ec->ec_below_outer_join = pk->pk_eclass->ec_below_outer_join;
#endif
ec->ec_broken = pk->pk_eclass->ec_broken;
ec->ec_sortref = pk->pk_eclass->ec_sortref;
ec->ec_min_security = pk->pk_eclass->ec_min_security;
ec->ec_max_security = pk->pk_eclass->ec_max_security;
ec->ec_merged = pk->pk_eclass->ec_merged;
root->eq_classes = lappend(root->eq_classes, ec);
MemoryContextSwitchTo(oldcontext);
info->compressed_rel->eclass_indexes =
bms_add_member(info->compressed_rel->eclass_indexes, root->eq_classes->length - 1);
return ec;
}
static List *
build_compressed_scan_pathkeys(const SortInfo *sort_info, PlannerInfo *root, List *chunk_pathkeys,
const CompressionInfo *info)
{
Var *var;
int varattno;
List *required_compressed_pathkeys = NIL;
ListCell *lc = NULL;
PathKey *pk;
/*
* all segmentby columns need to be prefix of pathkeys
* except those with equality constraint in baserestrictinfo
*/
if (info->num_segmentby_columns > 0)
{
TimescaleDBPrivate *compressed_fdw_private =
(TimescaleDBPrivate *) info->compressed_rel->fdw_private;
/*
* We don't need any sorting for the segmentby columns that are equated
* to a constant. The respective constant ECs are excluded from
* canonical pathkeys, so we won't see these columns here. Count them as
* seen from the start, so that we arrive at the proper counts of seen
* segmentby columns in the end.
*/
for (lc = list_head(chunk_pathkeys); lc; lc = lnext(chunk_pathkeys, lc))
{
PathKey *pk = lfirst(lc);
EquivalenceMember *compressed_em = NULL;
ListCell *ec_em_pair_cell;
foreach (ec_em_pair_cell, compressed_fdw_private->compressed_ec_em_pairs)
{
List *pair = lfirst(ec_em_pair_cell);
if (linitial(pair) == pk->pk_eclass)
{
compressed_em = lsecond(pair);
break;
}
}
/*
* We should exit the loop after we've seen all required segmentby
* columns. If we haven't seen them all, but the next pathkey
* already refers a compressed column, it is a bug. See
* build_sortinfo().
*/
if (!compressed_em)
{
break;
}
required_compressed_pathkeys = lappend(required_compressed_pathkeys, pk);
}
}
/*
* If pathkeys contains non-segmentby columns the rest of the ordering
* requirements will be satisfied by ordering by sequence_num.
*/
if (sort_info->needs_sequence_num)
{
/* TODO: split up legacy sequence number path and non-sequence number path into dedicated
* functions. */
if (info->has_seq_num)
{
bool nulls_first;
Oid sortop;
varattno = get_attnum(info->compressed_rte->relid,
COMPRESSION_COLUMN_METADATA_SEQUENCE_NUM_NAME);
var = makeVar(info->compressed_rel->relid, varattno, INT4OID, -1, InvalidOid, 0);
if (sort_info->reverse)
{
sortop = get_commutator(Int4LessOperator);
nulls_first = true;
}
else
{
sortop = Int4LessOperator;
nulls_first = false;
}
/*
* Create the EquivalenceClass for the sequence number column of this
* compressed chunk, so that we can build the PathKey that refers to it.
*/
EquivalenceClass *ec =
append_ec_for_seqnum(root, info, sort_info, var, sortop, nulls_first);
/* Find the operator in pg_amop --- failure shouldn't happen. */
Oid opfamily, opcintype;
CompareType strategy;
if (!get_ordering_op_properties(sortop, &opfamily, &opcintype, &strategy))
{
elog(ERROR, "operator %u is not a valid ordering operator", sortop);
}
pk = make_canonical_pathkey(root, ec, opfamily, strategy, nulls_first);
required_compressed_pathkeys = lappend(required_compressed_pathkeys, pk);
}
else
{
/* If there are no segmentby pathkeys, start from the beginning of the list */
if (info->num_segmentby_columns == 0)
{
lc = list_head(chunk_pathkeys);
}
Assert(lc != NULL);
Expr *expr;
char *column_name;
for (; lc != NULL; lc = lnext(chunk_pathkeys, lc))
{
pk = lfirst(lc);
EquivalenceMember *chunk_em = ts_find_em_for_rel(pk->pk_eclass, info->chunk_rel);
Assert(chunk_em);
expr = chunk_em->em_expr;
/*
* Use em_datatype from the original equivalence member as the
* opcintype. For polymorphic types like anyenum,
* canonicalize_ec_expression will not add a RelabelType (it
* replaces polymorphic req_type with the concrete type), so we
* must explicitly pass the correct em_datatype to the metadata
* column EC.
*/
Oid opcintype = chunk_em->em_datatype;
Oid collation = exprCollation((Node *) expr);
expr = (Expr *) strip_implicit_coercions((Node *) expr);
var = castNode(Var, expr);
Assert(var->varattno > 0);
column_name = get_attname(info->chunk_rte->relid, var->varattno, false);
int16 orderby_index = ts_array_position(info->settings->fd.orderby, column_name);
varattno =
get_attnum(info->compressed_rte->relid, column_segment_min_name(orderby_index));
Assert(orderby_index != 0);
bool orderby_desc =
ts_array_get_element_bool(info->settings->fd.orderby_desc, orderby_index);
bool orderby_nullsfirst =
ts_array_get_element_bool(info->settings->fd.orderby_nullsfirst, orderby_index);
bool nulls_first;
CompareType strategy;
if (sort_info->reverse)
{
strategy = orderby_desc ? BTLessStrategyNumber : BTGreaterStrategyNumber;
nulls_first = !orderby_nullsfirst;
}
else
{
strategy = orderby_desc ? BTGreaterStrategyNumber : BTLessStrategyNumber;
nulls_first = orderby_nullsfirst;
}
Var *metadata_var = makeVar(info->compressed_rel->relid,
varattno,
var->vartype,
var->vartypmod,
var->varcollid,
var->varlevelsup);
Expr *min_expr =
canonicalize_ec_expression((Expr *) metadata_var, opcintype, collation);
EquivalenceClass *min_ec =
append_ec_for_metadata_col(root, info, min_expr, pk, opcintype);
PathKey *min =
make_canonical_pathkey(root, min_ec, pk->pk_opfamily, strategy, nulls_first);
required_compressed_pathkeys = lappend(required_compressed_pathkeys, min);
varattno =
get_attnum(info->compressed_rte->relid, column_segment_max_name(orderby_index));
metadata_var = makeVar(info->compressed_rel->relid,
varattno,
var->vartype,
var->vartypmod,
var->varcollid,
var->varlevelsup);
Expr *max_expr =
canonicalize_ec_expression((Expr *) metadata_var, opcintype, collation);
EquivalenceClass *max_ec =
append_ec_for_metadata_col(root, info, max_expr, pk, opcintype);
PathKey *max =
make_canonical_pathkey(root, max_ec, pk->pk_opfamily, strategy, nulls_first);
required_compressed_pathkeys = lappend(required_compressed_pathkeys, max);
}
}
}
return required_compressed_pathkeys;
}
ColumnarScanPath *
copy_columnar_scan_path(ColumnarScanPath *src)
{
Assert(ts_is_columnar_scan_path(&src->custom_path.path));
ColumnarScanPath *dst = palloc(sizeof(ColumnarScanPath));
memcpy(dst, src, sizeof(ColumnarScanPath));
return dst;
}
/*
* Maps the attno of the min metadata column in the compressed chunk to the
* attno of the corresponding max metadata column. Zero if none or not applicable.
*/
typedef struct SelectivityEstimationContext
{
AttrNumber *min_to_max;
AttrNumber *max_to_min;
List *vars;
} SelectivityEstimationContext;
/*
* Collect the Vars referencing the "min" metadata columns into the context->vars.
*/
static bool
min_metadata_vars_collector(Node *orig_node, SelectivityEstimationContext *context)
{
if (orig_node == NULL)
{
/*
* An expression node can have a NULL field and the mutator will be
* still called for it, so we have to handle this.
*/
return false;
}
if (!IsA(orig_node, Var))
{
/*
* Recurse.
*/
return expression_tree_walker(orig_node, min_metadata_vars_collector, context);
}
Var *orig_var = castNode(Var, orig_node);
if (orig_var->varattno <= 0)
{
/*
* We don't handle special variables. Not sure how it could happen though.
*/
return false;
}
AttrNumber replaced_attno = context->min_to_max[orig_var->varattno];
if (replaced_attno == InvalidAttrNumber)
{
/*
* No replacement for this column.
*/
return false;
}
context->vars = lappend(context->vars, orig_var);
return false;
}
static void
set_compressed_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel,
CompressionInfo *compression_info)
{
/*
* We need some custom selectivity estimation code for the compressed chunk
* table, because some pushed down filters require special handling.
*
* An equality condition can be pushed down to the minmax sparse index
* condition, and becomes x_min <= const and const <= x_max. Postgres
* treats the part of this condition as independent, which leads to
* significant overestimates when x has high cardinality, and therefore
* not using the Index Scan. This stems from the fact that Postgres doesn't
* know that x_max is always just very slightly more than x_min for the
* given compressed batch.
* To work around this, temporarily replace all conditions on x_min with
* conditions on x_max before feeding them to the Postgres clauselist
* selectivity functions. Since the range of x_min to x_max for a given
* batch is small relative to the range of x in the entire chunk, this
* should not introduce much error, but at the same time allow Postgres to
* see the correlation.
*
* We do this here for the entire baserestrictinfo and not per-rinfo as we
* add them during filter pushdown, because the Postgres clauselist
* selectivity estimator must see the entire clause list to detect the range
* conditions.
*
* First, build the correspondence of min metadata attno -> max metadata
* attno for all minmax metadata.
*/
const int storage_elements = 2 * (compression_info->compressed_rel->max_attr + 1);
AttrNumber *storage = palloc0(storage_elements * sizeof(*storage));
SelectivityEstimationContext context = {
.min_to_max = &storage[0],
.max_to_min = &storage[compression_info->compressed_rel->max_attr],
};
for (int uncompressed_attno = 1; uncompressed_attno <= compression_info->chunk_rel->max_attr;
uncompressed_attno++)
{
if (get_rte_attribute_is_dropped(compression_info->chunk_rte, uncompressed_attno))
{
/* Skip the dropped column. */
continue;
}
const char *attname = get_attname(compression_info->chunk_rte->relid,
uncompressed_attno,
/* missing_ok = */ false);
const int16 orderby_pos =
ts_array_position(compression_info->settings->fd.orderby, attname);
if (orderby_pos == 0)
{
/*
* This reasoning is only applicable to orderby columns, where each
* batch is a thin slice of the entire range of the column. It also does
* not have many intersections, because the compressed batches mostly
* follow the total order of orderby columns, that is relaxed for the
* last orderby columns or unordered chunks.This does not necessarily
* hold for non-orderby columns that can also have a sparse index.
*/
continue;
}
AttrNumber min_attno =
compressed_column_metadata_attno(compression_info->settings,
compression_info->chunk_rte->relid,
uncompressed_attno,
compression_info->compressed_rte->relid,
"min");
AttrNumber max_attno =
compressed_column_metadata_attno(compression_info->settings,
compression_info->chunk_rte->relid,
uncompressed_attno,
compression_info->compressed_rte->relid,
"max");
if (min_attno == InvalidAttrNumber || max_attno == InvalidAttrNumber)
{
continue;
}
Assert(&context.min_to_max[min_attno] < &storage[storage_elements]);
Assert(&context.max_to_min[max_attno] < &storage[storage_elements]);
context.min_to_max[min_attno] = max_attno;
context.max_to_min[max_attno] = min_attno;
}
/*
* Then, replace all conditions on min metadata column with conditions on
* max metadata column.
*/
ListCell *lc;
foreach (lc, rel->baserestrictinfo)
{
RestrictInfo *orig_restrictinfo = castNode(RestrictInfo, lfirst(lc));
Node *orig_clause = (Node *) orig_restrictinfo->clause;
expression_tree_walker(orig_clause, min_metadata_vars_collector, &context);
}
/*
* Temporarily replace "min" with "max" in-place to save on memory allocations.
*/
foreach (lc, context.vars)
{
Var *var = castNode(Var, lfirst(lc));
Assert(var->varattno != InvalidAttrNumber);
Assert(context.min_to_max[var->varattno] != InvalidAttrNumber);
Assert(context.max_to_min[context.min_to_max[var->varattno]] == var->varattno);
var->varattno = context.min_to_max[var->varattno];
}
/*
* Compute selectivity with the updated filters.
*/
set_baserel_size_estimates(root, rel);
/*
* Replace the Vars back.
*/
foreach (lc, context.vars)
{
Var *var = castNode(Var, lfirst(lc));
var->varattno = context.max_to_min[var->varattno];
}
pfree(storage);
}
static CompressionInfo *
build_compressioninfo(PlannerInfo *root, const Hypertable *ht, const Chunk *chunk,
RelOptInfo *chunk_rel)
{
AppendRelInfo *appinfo;
CompressionInfo *info = palloc0(sizeof(CompressionInfo));
info->compresseddata_oid = ts_custom_type_cache_get(CUSTOM_TYPE_COMPRESSED_DATA)->type_oid;
info->chunk_rel = chunk_rel;
info->chunk_rte = planner_rt_fetch(chunk_rel->relid, root);
info->settings = ts_compression_settings_get(chunk->table_id);
if (chunk_rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
{
appinfo = ts_get_appendrelinfo(root, chunk_rel->relid, false);
RangeTblEntry *rte = planner_rt_fetch(appinfo->parent_relid, root);
if (rte->rtekind == RTE_RELATION)
{
info->ht_rte = rte;
info->ht_rel = root->simple_rel_array[appinfo->parent_relid];
}
else
{
/* In UNION queries referencing chunks directly, the parent rel can be a subquery */
Assert(rte->rtekind == RTE_SUBQUERY);
info->single_chunk = true;
info->ht_rte = info->chunk_rte;
info->ht_rel = info->chunk_rel;
}
}
else
{
Assert(chunk_rel->reloptkind == RELOPT_BASEREL);
info->single_chunk = true;
info->ht_rte = info->chunk_rte;
info->ht_rel = info->chunk_rel;
}
info->hypertable_id = ht->fd.id;
info->num_orderby_columns = ts_array_length(info->settings->fd.orderby);
info->num_segmentby_columns = ts_array_length(info->settings->fd.segmentby);
if (info->num_segmentby_columns)
{
ArrayIterator it = array_create_iterator(info->settings->fd.segmentby, 0, NULL);
Datum datum;
bool isnull;
while (array_iterate(it, &datum, &isnull))
{
Ensure(!isnull, "NULL element in catalog array");
AttrNumber chunk_attno = get_attnum(info->chunk_rte->relid, TextDatumGetCString(datum));
info->chunk_segmentby_attnos =
bms_add_member(info->chunk_segmentby_attnos, chunk_attno);
}
}
info->has_seq_num =
get_attnum(info->settings->fd.compress_relid,
COMPRESSION_COLUMN_METADATA_SEQUENCE_NUM_NAME) != InvalidAttrNumber;
info->chunk_const_segmentby = find_const_segmentby(chunk_rel, info);
/*
* If the chunk is member of hypertable expansion or a UNION, find its
* parent relation ids. We will use it later to filter out some parameterized
* paths.
*/
if (chunk_rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
{
info->parent_relids = find_childrel_parents(root, chunk_rel);
}
info->chunk_status = chunk->fd.status;
return info;
}
/*
* Estimate the average count of elements in the compressed batch based on the
* Postgres statistics for _ts_meta_count column.
* Returns TARGET_COMPRESSED_BATCH_SIZE when no pg_statistic entry exists.
*/
double
ts_columnar_estimate_compressed_batch_size(const Oid relid)
{
AttrNumber attnum = get_attnum(relid, "_ts_meta_count");
if (attnum == InvalidAttrNumber)
{
return TARGET_COMPRESSED_BATCH_SIZE;
}
/* fetch statistics */
HeapTuple statsTuple = SearchSysCache3(STATRELATTINH,
ObjectIdGetDatum(relid),
Int16GetDatum(attnum),
BoolGetDatum(false));
if (!HeapTupleIsValid(statsTuple))
{
return TARGET_COMPRESSED_BATCH_SIZE;
}
double mcv_sum = 0.0;
double mcv_freq = 0.0;
/* exact MCV contribution */
AttStatsSlot mcvslot;
if (get_attstatsslot(&mcvslot,
statsTuple,
STATISTIC_KIND_MCV,
InvalidOid,
ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS))
{
for (int i = 0; i < mcvslot.nvalues; i++)
{
double val = (double) DatumGetInt32(mcvslot.values[i]);
double freq = (double) mcvslot.numbers[i];
mcv_sum += val * freq;
mcv_freq += freq;
}
free_attstatsslot(&mcvslot);
}
double hist_sum = 0.0;
/* histogram contribution */
AttStatsSlot histslot;
if (get_attstatsslot(&histslot,
statsTuple,
STATISTIC_KIND_HISTOGRAM,
InvalidOid,
ATTSTATSSLOT_VALUES))
{
int buckets = histslot.nvalues - 1;
if (buckets > 0 && mcv_freq < 1.0)
{
for (int i = 0; i < buckets; i++)
{
double lo = (double) DatumGetInt32(histslot.values[i]);
double hi = (double) DatumGetInt32(histslot.values[i + 1]);
hist_sum += (lo + hi) / 2.0;
}
hist_sum *= (1.0 - mcv_freq) / buckets;
}
free_attstatsslot(&histslot);
}
ReleaseSysCache(statsTuple);
const double final_result = mcv_sum + hist_sum;
if (final_result == 0)
{
/*
* For tables with few rows, the statistics tuple will contain all zero
* values. We shouldn't return zero in this case to avoid weird behavior.
*/
return TARGET_COMPRESSED_BATCH_SIZE;
}
return final_result;
}
/*
* calculate cost for ColumnarScanPath
*
* since we have to read whole batch before producing tuple
* we put cost of 1 tuple of compressed_scan as startup cost
*/
static void
cost_columnar_scan(const CompressionInfo *compression_info, ColumnarScanPath *columnar_scan,
Path *compressed_path)
{
Path *path = &columnar_scan->custom_path.path;
const double compressed_rows = Max(1, compressed_path->rows);
/*
* Startup cost is cost before fetching the first tuple. For the columnar
* scan, it is composed of:
*
* 1) cost before fetching the first compressed tuple.
*/
path->startup_cost = compressed_path->startup_cost;
/*
* 2) cost of actually fetching the first compressed tuple.
*/
path->startup_cost +=
(compressed_path->total_cost - compressed_path->startup_cost) / compressed_rows;
/*
* 3) in case of bulk decompression, cost of fully decompressing the first
* batch.
*/
if (columnar_scan->enable_bulk_decompression)
{
path->startup_cost += compression_info->compressed_batch_size * cpu_tuple_cost;
}
/*
* Estimate the resulting number of rows based on the batch size statistics.
*/
path->rows = compressed_path->rows * compression_info->compressed_batch_size;
/*
* Bulk decompression is about 10x more efficient than row-by-row
* decompression. In the startup cost calculation above, we assume the cost
* of producing one uncompressed row by bulk decompression to be
* cpu_tuple_cost.
*/
const double decompression_cost_per_uncompressed_row =
columnar_scan->enable_bulk_decompression ? cpu_tuple_cost : 10. * cpu_tuple_cost;
/*
* total_cost is cost for fetching all tuples.
*/
path->total_cost =
compressed_path->total_cost + path->rows * decompression_cost_per_uncompressed_row;
#if PG18_GE
/* PG18 changes the way we handle disabled nodes so we
* need to take those into account as well.
*
* https://github.com/postgres/postgres/commit/e2225346
*/
path->disabled_nodes = compressed_path->disabled_nodes;
#endif
}
/* Smoothstep function S1 (the h01 cubic Hermite spline). */
static double
smoothstep(double x, double start, double end)
{
x = (x - start) / (end - start);
if (x < 0)
{
x = 0;
}
else if (x > 1)
{
x = 1;
}
return x * x * (3.0F - 2.0F * x);
}
/*
* If the query 'order by' is prefix of the compression 'order by' (or equal), we can exploit
* the ordering of the individual batches to create a total ordered result without resorting
* the tuples. This speeds up all queries that use this ordering (because no sort node is
* needed). In particular, queries that use a LIMIT are speed-up because only the top elements
* of the affected batches needs to be decompressed. Without the optimization, the entire batches
* are decompressed, sorted, and then the top elements are taken from the result.
*
* The idea is to do something similar to the MergeAppend node; a BinaryHeap is used
* to merge the per segment by column sorted individual batches into a sorted result. So, we end
* up which a data flow which looks as follows:
*
* ColumnarScan
* * Decompress Batch 1
* * Decompress Batch 2
* * Decompress Batch 3
* [....]
* * Decompress Batch N
*
* Using the presorted batches, we are able to open these batches dynamically. If we don't presort
* them, we would have to open all batches at the same time. This would be similar to the work the
* MergeAppend does, but this is not needed in our case and we could reduce the size of the heap and
* the amount of parallel open batches.
*
* The algorithm works as follows:
*
* (1) A sort node is placed below the decompress scan node and on top of the scan
* on the compressed chunk. This sort node uses the min/max values of the 'order by'
* columns from the metadata of the batch to get them into an order which can be
* used to merge them.
*
* [Scan on compressed chunk] -> [Sort on min/max values] -> [Decompress and merge]
*
* For example, the batches are sorted on the min value of the 'order by' metadata
* column: [0, 3] [0, 5] [3, 7] [6, 10]
*
* (2) The decompress chunk node initializes a binary heap, opens the first batch and
* decompresses the first tuple from the batch. The tuple is put on the heap. In addition
* the opened batch is marked as the most recent batch (MRB).
*
* (3) As soon as a tuple is requested from the heap, the following steps are performed:
* (3a) If the heap is empty, we are done.
* (3b) The top tuple from the heap is taken. It is checked if this tuple is from the
* MRB. If this is the case, the next batch is opened, the first tuple is decompressed,
* placed on the heap and this batch is marked as MRB. This is repeated until the
* top tuple from the heap is not from the MRB. After the top tuple is not from the
* MRB, all batches (and one ahead) which might contain the most recent tuple are
* opened and placed on the heap.
*
* In the example above, the first three batches are opened because the first two
* batches might contain tuples with a value of 0.
* (3c) The top element from the heap is removed, the next tuple from the batch is
* decompressed (if present) and placed on the heap.
* (3d) The former top tuple of the heap is returned.
*
* This function calculate the costs for retrieving the decompressed in-order
* using a binary heap.
*/
static void
cost_batch_sorted_merge(PlannerInfo *root, const CompressionInfo *compression_info,
ColumnarScanPath *dcpath, Path *compressed_path)
{
Path sort_path; /* dummy for result of cost_sort */
/*
* Don't disable the compressed batch sorted merge plan with the enable_sort
* GUC. We have a separate GUC for it, and this way you can try to force the
* batch sorted merge plan by disabling sort.
*/
const bool old_enable_sort = enable_sort;
enable_sort = true;
cost_sort(&sort_path,
root,
dcpath->required_compressed_pathkeys,
#if PG18_GE
compressed_path->disabled_nodes,
#endif
compressed_path->total_cost,
compressed_path->rows,
compressed_path->pathtarget->width,
0.0,
work_mem,
-1);
enable_sort = old_enable_sort;
/*
* In compressed batch sorted merge, for each distinct segmentby value we
* have to keep the corresponding latest batch open. Estimate the number of
* these batches with the usual Postgres estimator for grouping cardinality.
*/
List *segmentby_groupexprs = NIL;
for (int segmentby_attno = bms_next_member(compression_info->chunk_segmentby_attnos, -1);
segmentby_attno > 0;
segmentby_attno =
bms_next_member(compression_info->chunk_segmentby_attnos, segmentby_attno))
{
char *colname = get_attname(compression_info->chunk_rte->relid,
segmentby_attno,
/* missing_ok = */ false);
AttrNumber compressed_attno = get_attnum(compression_info->compressed_rte->relid, colname);
Ensure(compressed_attno != InvalidAttrNumber,
"segmentby column %s not found in compressed chunk %d",
colname,
compression_info->compressed_rte->relid);
Var *var = palloc(sizeof(Var));
*var = (Var){ .xpr.type = T_Var,
.varno = compression_info->compressed_rel->relid,
.varattno = compressed_attno };
segmentby_groupexprs = lappend(segmentby_groupexprs, var);
}
const double open_batches_estimated =
estimate_num_groups(root, segmentby_groupexprs, dcpath->custom_path.path.rows, NULL, NULL);
Assert(open_batches_estimated > 0);
/*
* We can't have more open batches than the total number of compressed rows,
* so clamp it for sanity of the following calculations.
*/
const double open_batches_clamped = Min(open_batches_estimated, sort_path.rows);
/*
* Keeping a lot of batches open might use a lot of memory. The batch sorted
* merge can't offload anything to disk, so we just penalize it heavily if
* we expect it to go over the work_mem. First, estimate the amount of
* memory we'll need. We do this on the basis of uncompressed chunk width,
* as if we had to materialize entire decompressed batches. This might
* be less precise when bulk decompression is not used, because we
* materialize only the compressed data which is smaller. But it accounts
* for projections, which is probably more important than precision, because
* we often read a small subset of columns in analytical queries. The
* compressed chunk is never projected so we can't use it for that.
*/
const double work_mem_bytes = work_mem * 1024.0;
const double needed_memory_bytes = open_batches_clamped *
compression_info->compressed_batch_size *
dcpath->custom_path.path.pathtarget->width;
/*
* Next, calculate the cost penalty. It is a smooth step, starting at 75% of
* work_mem, and ending at 125%. We want to effectively disable this plan
* if it doesn't fit into the available memory, so the penalty should be
* comparable to disable_cost but still less than it, so that the
* manual disables still have priority.
*/
const double work_mem_penalty =
0.1 * disable_cost *
smoothstep(needed_memory_bytes, 0.75 * work_mem_bytes, 1.25 * work_mem_bytes);
Assert(work_mem_penalty >= 0);
/*
* startup_cost is cost before fetching first tuple. Batch sorted merge has
* to load at least the number of batches we expect to be open
* simultaneously, before it can produce the first row.
*/
const double sort_path_cost_for_startup =
sort_path.startup_cost +
((sort_path.total_cost - sort_path.startup_cost) * (open_batches_clamped / sort_path.rows));
Assert(sort_path_cost_for_startup >= 0);
dcpath->custom_path.path.startup_cost = sort_path_cost_for_startup + work_mem_penalty;
/*
* Finally, to run this path to completion, we have to complete the
* underlying sort path, and return all uncompressed rows. Getting one