forked from timescale/timescaledb
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecompress.c
More file actions
2734 lines (2410 loc) · 90.1 KB
/
Copy pathrecompress.c
File metadata and controls
2734 lines (2410 loc) · 90.1 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 "debug_point.h"
#include <access/tableam.h>
#include <catalog/indexing.h>
#include <miscadmin.h>
#include <parser/parse_coerce.h>
#include <parser/parse_relation.h>
#include <storage/latch.h>
#include <storage/lock.h>
#include <utils/datum.h>
#include <utils/inval.h>
#include <utils/lsyscache.h>
#include <utils/rel.h>
#include <utils/relcache.h>
#include <utils/snapmgr.h>
#include <utils/syscache.h>
#include <utils/tuplesort.h>
#include <utils/typcache.h>
#include <utils/wait_event.h>
#include "api.h"
#include "batch_metadata_builder.h"
#include "compression.h"
#include "compression_dml.h"
#include "create.h"
#include "debug_assert.h"
#include "foreach_ptr.h"
#include "guc.h"
#include "hypertable.h"
#include "indexing.h"
#include "recompress.h"
#include "sparse_index_bloom1.h"
#include "ts_catalog/array_utils.h"
#include "ts_catalog/catalog.h"
#include "ts_catalog/chunk_column_stats.h"
#include "ts_catalog/compression_chunk_size.h"
#include "ts_catalog/compression_settings.h"
#include "utils.h"
#include "with_clause/alter_table_with_clause.h"
/*
* Timing parameters for spin locking heuristics.
* These are the same as used by Postgres for truncate locking during lazy vacuum.
* https://github.com/postgres/postgres/blob/4a0650d359c5981270039eeb634c3b7427aa0af5/src/backend/access/heap/vacuumlazy.c#L82
*/
#define RECOMPRESS_EXCLUSIVE_LOCK_WAIT_INTERVAL 50 /* ms */
#ifdef TS_DEBUG
/* Lock timeout reduced for the sake of faster testing. */
#define RECOMPRESS_EXCLUSIVE_LOCK_TIMEOUT 100 /* ms */
#else
#define RECOMPRESS_EXCLUSIVE_LOCK_TIMEOUT 5000 /* ms */
#endif
/*
* Scan state saved by compact_chunk_find_overlapping_batches. The caller can
* inspect the result and then pass the same state to
* compact_chunk_recompress_overlapping_batches to continue without restarting
* the scan.
*/
typedef struct CompactChunkScanState
{
ItemPointerData previous_tid; /* TID of the batch processed just before the current one */
ItemPointerData first_overlap_tid; /* TID of the first overlapping batch */
/* Segmentby key values of the current batch, for segment-group detection. */
Datum *seg_values;
bool *seg_isnull;
/* First-row and last-row orderby tuples of the current batch, read straight
* from the index. */
Datum *curr_first;
bool *curr_first_isnull;
Datum *curr_last;
bool *curr_last_isnull;
/* Max last-row orderby tuple from the batches processed before the current
* one. Holds copies so it survives advancing the index scan. */
Datum *max_last;
bool *max_last_isnull;
bool max_last_set; /* false until the first batch is recorded */
} CompactChunkScanState;
static CompactChunkScanState *
compact_chunk_scan_state_init(RecompressContext *recompress_ctx)
{
CompactChunkScanState *state = palloc(sizeof(CompactChunkScanState));
ItemPointerSetInvalid(&state->previous_tid);
ItemPointerSetInvalid(&state->first_overlap_tid);
state->seg_values = palloc(sizeof(Datum) * recompress_ctx->num_segmentby);
state->seg_isnull = palloc(sizeof(bool) * recompress_ctx->num_segmentby);
state->curr_first = palloc(sizeof(Datum) * recompress_ctx->num_orderby);
state->curr_first_isnull = palloc(sizeof(bool) * recompress_ctx->num_orderby);
state->curr_last = palloc(sizeof(Datum) * recompress_ctx->num_orderby);
state->curr_last_isnull = palloc(sizeof(bool) * recompress_ctx->num_orderby);
state->max_last = palloc0(sizeof(Datum) * recompress_ctx->num_orderby);
state->max_last_isnull = palloc(sizeof(bool) * recompress_ctx->num_orderby);
for (int i = 0; i < recompress_ctx->num_orderby; i++)
{
state->max_last_isnull[i] = true;
}
state->max_last_set = false;
return state;
}
static void
compact_chunk_scan_state_reset(CompactChunkScanState *state, RecompressContext *recompress_ctx)
{
ItemPointerSetInvalid(&state->previous_tid);
ItemPointerSetInvalid(&state->first_overlap_tid);
for (int i = 0; i < recompress_ctx->num_orderby; i++)
{
int key = recompress_ctx->num_segmentby + i;
if (!state->max_last_isnull[i] && !recompress_ctx->key_byval[key] &&
PointerIsValid(DatumGetPointer(state->max_last[i])))
{
pfree(DatumGetPointer(state->max_last[i]));
}
state->max_last[i] = (Datum) 0;
state->max_last_isnull[i] = true;
}
state->max_last_set = false;
}
static bool fetch_uncompressed_chunk_into_tuplesort(Tuplesortstate *tuplesortstate,
Relation uncompressed_chunk_rel,
Snapshot snapshot);
static bool delete_tuple_for_recompression(Relation rel, ItemPointer tid, Snapshot snapshot);
static void update_current_segment(CompressedSegmentInfo *current_segment, Datum *values,
bool *isnulls, int nsegmentby_cols);
static void create_segmentby_scankeys(CompressionSettings *settings, Relation index_rel,
Relation compressed_chunk_rel, ScanKeyData *index_scankeys);
static void create_orderby_scankeys(CompressionSettings *settings, Relation index_rel,
Relation compressed_chunk_rel, ScanKeyData *orderby_scankeys);
static void update_segmentby_scankeys(Datum *values, bool *isnulls, int num_segmentby,
ScanKey index_scankeys, bool *key_byval, int16 *key_typlen);
static void update_orderby_scankeys(Datum *values, bool *isnulls, int num_segmentby,
int num_orderby, ScanKey orderby_scankeys, bool *key_byval,
int16 *key_typlen);
static enum Batch_match_result match_tuple_batch(TupleTableSlot *compressed_slot, int num_orderby,
ScanKey orderby_scankeys, bool *nulls_first);
static bool check_changed_group(CompressedSegmentInfo *current_segment, Datum *values,
bool *isnulls, int nsegmentby_cols);
static void recompress_segment(Tuplesortstate *tuplesortstate, Relation compressed_chunk_rel,
RowCompressor *row_compressor, BulkWriter *writer);
static IndexScanDesc compact_chunk_begin_index_scan(Relation compressed_chunk_rel,
Relation index_rel, Snapshot snapshot);
static void read_batch_firstlast(IndexScanDesc index_scan, RecompressContext *recompress_ctx,
CompactChunkScanState *state);
static void save_new_last(CompactChunkScanState *state, RecompressContext *recompress_ctx);
static bool batches_overlap_firstlast(RecompressContext *recompress_ctx, Datum *prev_last,
bool *prev_last_isnull, Datum *curr_first,
bool *curr_first_isnull);
static void decompress_batch_to_tuplesort(TupleTableSlot *slot, TupleDesc tupdesc,
RowDecompressor *decompressor,
Tuplesortstate *recompress_tuplesortstate,
Relation compressed_chunk_rel, Snapshot snapshot,
int *processed_batches);
static bool compact_chunk_find_overlapping_batches(Relation compressed_chunk_rel,
IndexScanDesc index_scan,
RecompressContext *recompress_ctx,
CompactChunkScanState *state);
static bool compact_chunk_recompress_overlapping_batches(
Relation compressed_chunk_rel, IndexScanDesc index_scan, Snapshot snapshot,
RecompressContext *recompress_ctx, CompactChunkScanState *state, RowCompressor *compressor,
RowDecompressor *decompressor, Tuplesortstate *recompress_tuplesortstate, BulkWriter *writer,
int max_batches);
static void try_updating_chunk_status(Chunk *uncompressed_chunk, Relation uncompressed_chunk_rel);
/*
* Recompress an existing chunk by decompressing the batches
* that are affected by the addition of newer data. The existing
* compressed chunk will not be recreated but modified in place.
*
* 0 uncompressed_relid REGCLASS
* 1 if_not_compressed BOOL = false
*/
Datum
tsl_recompress_chunk_segmentwise(PG_FUNCTION_ARGS)
{
Oid uncompressed_relid = PG_ARGISNULL(0) ? InvalidOid : PG_GETARG_OID(0);
bool if_not_compressed = PG_ARGISNULL(1) ? true : PG_GETARG_BOOL(1);
ts_feature_flag_check(FEATURE_HYPERTABLE_COMPRESSION);
TS_PREVENT_FUNC_IF_READ_ONLY();
Chunk *chunk = ts_chunk_get_by_relid(uncompressed_relid, true);
ts_hypertable_permissions_check(chunk->hypertable_relid, GetUserId());
if (!ts_chunk_is_partial(chunk))
{
int elevel = if_not_compressed ? NOTICE : ERROR;
ereport(elevel,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("nothing to recompress in chunk %s.%s",
ts_chunk_get_schema_name(chunk),
ts_chunk_get_table_name(chunk))));
}
else
{
if (!ts_guc_enable_segmentwise_recompression)
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("segmentwise recompression functionality disabled, "
"enable it by first setting "
"timescaledb.enable_segmentwise_recompression to on")));
}
if (!ts_guc_enable_optimizations)
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("segmentwise recompression functionality disabled, "
"enable it by first setting "
"timescaledb.enable_optimizations to on")));
}
CompressionSettings *settings = ts_compression_settings_get(uncompressed_relid);
if (!settings->fd.orderby)
{
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("segmentwise recompression cannot be applied for "
"compression with no "
"order by")));
}
bool orderby_not_handling_nulls = !is_chunk_orderby_nullhandling(settings);
if (orderby_not_handling_nulls)
{
elog(ts_guc_debug_compression_path_info ? INFO : DEBUG1,
"in-memory recompression is disabled due to nullable order by with no firstlast, "
"performing segmentwise decompress/compress on chunk \"%s.%s\"",
ts_chunk_get_schema_name(chunk),
ts_chunk_get_table_name(chunk));
}
recompress_chunk_segmentwise_impl(chunk, orderby_not_handling_nulls);
}
PG_RETURN_OID(uncompressed_relid);
}
/*
* Compact a chunk by recombining overlapping batches
*
* 0 uncompressed_chunk_id REGCLASS
*/
Datum
tsl_compact_chunk(PG_FUNCTION_ARGS)
{
Oid uncompressed_relid = PG_ARGISNULL(0) ? InvalidOid : PG_GETARG_OID(0);
ts_feature_flag_check(FEATURE_HYPERTABLE_COMPRESSION);
TS_PREVENT_FUNC_IF_READ_ONLY();
if (IsolationUsesXactSnapshot())
{
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("compact_chunk is not supported in REPEATABLE READ or SERIALIZABLE "
"isolation level")));
}
Chunk *chunk = ts_chunk_get_by_relid(uncompressed_relid, true);
ts_hypertable_permissions_check(chunk->hypertable_relid, GetUserId());
if (!ts_chunk_is_compressed(chunk))
{
ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("trying to compact an uncompressed chunk %s.%s",
ts_chunk_get_schema_name(chunk),
ts_chunk_get_table_name(chunk))));
}
if (ts_chunk_is_partial(chunk))
{
ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("trying to compact a partially compressed chunk %s.%s",
ts_chunk_get_schema_name(chunk),
ts_chunk_get_table_name(chunk))));
}
int max_batches = PG_GETARG_INT32(1);
if (max_batches < 0)
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("max_batches must be greater than or equal to 0")));
}
uncompressed_relid = compact_chunk_impl(chunk, max_batches);
PG_RETURN_OID(uncompressed_relid);
}
static RecompressContext *
compress_chunk_populate_recompress_ctx(CompressionSettings *settings,
Relation uncompressed_chunk_rel,
Relation compressed_chunk_rel, Relation index_rel,
const bool for_uncompressed)
{
RecompressContext *recompress_ctx;
int n;
int position;
const char *attname;
AttrNumber col_attno;
Relation chunk_rel = for_uncompressed ? uncompressed_chunk_rel : compressed_chunk_rel;
/* Initialize sort info structure */
recompress_ctx = palloc0(sizeof(RecompressContext));
/* Calculate array sizes */
recompress_ctx->num_segmentby = ts_array_length(settings->fd.segmentby);
recompress_ctx->num_orderby = ts_array_length(settings->fd.orderby);
recompress_ctx->n_keys = recompress_ctx->num_segmentby + recompress_ctx->num_orderby;
/* Allocate arrays */
Assert(recompress_ctx->n_keys <= INDEX_MAX_KEYS);
/* Populate sort information for each column */
for (n = 0; n < recompress_ctx->n_keys; n++)
{
Form_pg_attribute attr;
if (n < recompress_ctx->num_segmentby)
{
position = n + 1;
attname = ts_array_get_element_text(settings->fd.segmentby, position);
col_attno = get_attnum(chunk_rel->rd_id, attname);
recompress_ctx->current_segment[n].chunk_offset = AttrNumberGetAttrOffset(col_attno);
recompress_ctx->current_segment[n].segment_info =
segment_info_new(TupleDescAttr(RelationGetDescr(chunk_rel),
recompress_ctx->current_segment[n].chunk_offset));
}
else
{
position = n - recompress_ctx->num_segmentby + 1;
attname = ts_array_get_element_text(settings->fd.orderby, position);
col_attno = get_attnum(chunk_rel->rd_id, attname);
recompress_ctx->current_segment[n].chunk_offset = AttrNumberGetAttrOffset(col_attno);
}
attr = TupleDescAttr(RelationGetDescr(chunk_rel),
recompress_ctx->current_segment[n].chunk_offset);
recompress_ctx->key_byval[n] = attr->attbyval;
recompress_ctx->key_typlen[n] = attr->attlen;
compress_chunk_populate_sort_info_for_column(settings,
RelationGetRelid(uncompressed_chunk_rel),
attname,
&recompress_ctx->sort_keys[n],
&recompress_ctx->sort_operators[n],
&recompress_ctx->sort_collations[n],
&recompress_ctx->nulls_first[n]);
}
/* Populate scankeys */
create_segmentby_scankeys(settings,
index_rel,
compressed_chunk_rel,
recompress_ctx->index_scankeys);
create_orderby_scankeys(settings,
index_rel,
compressed_chunk_rel,
recompress_ctx->orderby_scankeys);
/* Cache the sort support for each orderby column, used to compare batch
* boundary values during compaction. The ordering operator fills in the
* reverse flag (DESC) and the comparator, while the collation and nulls
* ordering let ApplySortComparator place NULLs in total order for us. */
recompress_ctx->orderby_ssup = palloc0(sizeof(SortSupportData) * recompress_ctx->num_orderby);
for (int i = 0; i < recompress_ctx->num_orderby; i++)
{
int key = recompress_ctx->num_segmentby + i;
SortSupport ssup = &recompress_ctx->orderby_ssup[i];
ssup->ssup_cxt = CurrentMemoryContext;
ssup->ssup_collation = recompress_ctx->sort_collations[key];
ssup->ssup_nulls_first = recompress_ctx->nulls_first[key];
PrepareSortSupportFromOrderingOp(recompress_ctx->sort_operators[key], ssup);
}
/* Resolve the index attnos of the first-row and last-row orderby metadata.
* Only the compaction path reads these, and it requires every orderby
* column to be firstlast; the shared segmentwise recompress path may pass a
* minmax column here, which we skip. Matching by column identity works
* whether the chunk indexes the pair as (first, last) or the legacy
* (last, first). */
for (int i = 0; i < recompress_ctx->num_orderby; i++)
{
position = i + 1;
if (orderby_sparse_kind(settings, position) != ORDERBY_SPARSE_FIRSTLAST)
{
continue;
}
int base = recompress_ctx->num_segmentby + i * 2;
AttrNumber first_attno;
AttrNumber last_attno;
orderby_firstlast_metadata_attnos(settings,
compressed_chunk_rel->rd_id,
position,
&first_attno,
&last_attno);
if (index_rel->rd_index->indkey.values[base] == first_attno)
{
recompress_ctx->orderby_first_index_attno[i] = AttrOffsetGetAttrNumber(base);
recompress_ctx->orderby_last_index_attno[i] = AttrOffsetGetAttrNumber(base) + 1;
}
else
{
recompress_ctx->orderby_last_index_attno[i] = AttrOffsetGetAttrNumber(base);
recompress_ctx->orderby_first_index_attno[i] = AttrOffsetGetAttrNumber(base) + 1;
}
}
return recompress_ctx;
}
static void
free_chunk_recompress_ctx(RecompressContext *recompress_ctx)
{
if (recompress_ctx == NULL)
{
return;
}
for (int i = 0; i < recompress_ctx->num_segmentby; i++)
{
ScanKey key = &recompress_ctx->index_scankeys[i];
if (!(key->sk_flags & SK_ISNULL) && !recompress_ctx->key_byval[i] &&
PointerIsValid(DatumGetPointer(key->sk_argument)))
{
pfree(DatumGetPointer(key->sk_argument));
}
}
/* Free orderby scankey datums (min only — max shares the same pointer). */
for (int i = 0; i < recompress_ctx->num_orderby; i++)
{
int key_idx = recompress_ctx->num_segmentby + i;
ScanKey key = &recompress_ctx->orderby_scankeys[i * 2];
if (!(key->sk_flags & SK_ISNULL) && !recompress_ctx->key_byval[key_idx] &&
PointerIsValid(DatumGetPointer(key->sk_argument)))
{
pfree(DatumGetPointer(key->sk_argument));
}
}
pfree(recompress_ctx->orderby_ssup);
pfree(recompress_ctx);
}
void
recompress_chunk_segmentwise_impl(Chunk *uncompressed_chunk,
bool fullrecompress /* do full decompress/compress segmentwise */)
{
Oid uncompressed_relid = uncompressed_chunk->fd.relid;
/*
* only proceed if status in (3, 9, 11)
* 1: compressed
* 2: compressed_unordered
* 4: frozen
* 8: compressed_partial
*/
if (!ts_chunk_is_compressed(uncompressed_chunk) && ts_chunk_is_partial(uncompressed_chunk))
{
ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("unexpected chunk status %d in chunk %s.%s",
uncompressed_chunk->fd.status,
ts_chunk_get_schema_name(uncompressed_chunk),
ts_chunk_get_table_name(uncompressed_chunk))));
}
/* need it to find the segby cols from the catalog */
CompressionSettings *settings = ts_compression_settings_get(uncompressed_chunk->fd.relid);
/* We should not do segment-wise recompression with empty orderby, see #7748
*/
Ensure(settings->fd.orderby, "empty order by, cannot recompress segmentwise");
ereport(DEBUG1,
(errmsg("acquiring locks for recompression: \"%s.%s\"",
ts_chunk_get_schema_name(uncompressed_chunk),
ts_chunk_get_table_name(uncompressed_chunk))));
LOCKMODE recompression_lockmode =
ts_guc_enable_exclusive_locking_recompression ? ExclusiveLock : ShareUpdateExclusiveLock;
/* lock both chunks, compressed and uncompressed */
Relation uncompressed_chunk_rel =
table_open(uncompressed_chunk->fd.relid, recompression_lockmode);
Relation compressed_chunk_rel = table_open(settings->fd.compress_relid, recompression_lockmode);
bool has_unique_constraints =
ts_indexing_relation_has_primary_or_unique_index(uncompressed_chunk_rel);
int count;
LOCKTAG locktag;
SET_LOCKTAG_RELATION(locktag, MyDatabaseId, uncompressed_relid);
/*
* Recompression does not block inserts but it can interfere with
* constraint checking since it moves uncompressed tuples from
* uncompressed chunk to compressed chunk but the INSERTs check
* tuples in the opposite order.
*
* If there are unique constraints and multiple INSERTs happening at start
* we want to just bail out so not to cause wasted work and bloat.
*/
if (has_unique_constraints)
{
GetLockConflicts(&locktag, ExclusiveLock, &count);
if (count > 1)
{
elog(WARNING,
"skipping recompression of chunk %s.%s due to unique constraints and concurrent "
"DML",
ts_chunk_get_schema_name(uncompressed_chunk),
ts_chunk_get_table_name(uncompressed_chunk));
table_close(uncompressed_chunk_rel, NoLock);
table_close(compressed_chunk_rel, NoLock);
return;
}
}
Hypertable *ht = ts_hypertable_get_by_id(uncompressed_chunk->fd.hypertable_id);
if (ht->range_space)
{
ts_chunk_column_stats_calculate(ht, uncompressed_chunk);
}
TupleDesc compressed_rel_tupdesc = RelationGetDescr(compressed_chunk_rel);
TupleDesc uncompressed_rel_tupdesc = RelationGetDescr(uncompressed_chunk_rel);
/******************** row decompressor **************/
RowDecompressor decompressor = build_decompressor(RelationGetDescr(compressed_chunk_rel),
RelationGetDescr(uncompressed_chunk_rel),
RelationGetRelid(compressed_chunk_rel),
RelationGetRelid(uncompressed_chunk_rel));
/********** row compressor *******************/
RowCompressor row_compressor;
Assert(settings->fd.compress_relid == RelationGetRelid(compressed_chunk_rel));
row_compressor_init(&row_compressor,
settings,
RelationGetDescr(uncompressed_chunk_rel),
RelationGetDescr(compressed_chunk_rel));
BulkWriter writer = bulk_writer_build(compressed_chunk_rel, 0);
Oid index_oid = get_compressed_chunk_index(writer.indexstate, settings);
/* For chunks with no segmentby settings, we can still do segmentwise recompression
* The entire chunk is treated as a single segment
*/
elog(ts_guc_debug_compression_path_info ? INFO : DEBUG1,
"Using index \"%s\" for recompression",
get_rel_name(index_oid));
LOCKMODE index_lockmode =
ts_guc_enable_exclusive_locking_recompression ? ExclusiveLock : RowExclusiveLock;
Relation index_rel = index_open(index_oid, index_lockmode);
ereport(DEBUG1,
(errmsg("locks acquired for recompression: \"%s.%s\"",
ts_chunk_get_schema_name(uncompressed_chunk),
ts_chunk_get_table_name(uncompressed_chunk))));
/* Need to populate recompress context of an uncompressed chunk */
RecompressContext *recompress_ctx =
compress_chunk_populate_recompress_ctx(settings,
uncompressed_chunk_rel,
compressed_chunk_rel,
index_rel,
true);
/* Used for sorting and iterating over all the uncompressed tuples that have
* to be recompressed. These tuples are sorted based on the segmentby and
* orderby settings.
*/
Tuplesortstate *input_tuplesortstate = tuplesort_begin_heap(uncompressed_rel_tupdesc,
recompress_ctx->n_keys,
recompress_ctx->sort_keys,
recompress_ctx->sort_operators,
recompress_ctx->sort_collations,
recompress_ctx->nulls_first,
maintenance_work_mem,
NULL,
false);
/* Used for gathering and resorting the tuples that should be recompressed together.
* Since we are working on a per-segment level here, we only need to sort them
* based on the orderby settings.
*/
Tuplesortstate *recompress_tuplesortstate =
tuplesort_begin_heap(uncompressed_rel_tupdesc,
recompress_ctx->num_orderby,
&recompress_ctx->sort_keys[recompress_ctx->num_segmentby],
&recompress_ctx->sort_operators[recompress_ctx->num_segmentby],
&recompress_ctx->sort_collations[recompress_ctx->num_segmentby],
&recompress_ctx->nulls_first[recompress_ctx->num_segmentby],
maintenance_work_mem,
NULL,
false);
/************** snapshot ****************************/
Snapshot snapshot = RegisterSnapshot(GetTransactionSnapshot());
TupleTableSlot *uncompressed_slot =
MakeTupleTableSlotCompat(uncompressed_rel_tupdesc, &TTSOpsMinimalTuple, 0);
TupleTableSlot *compressed_slot = table_slot_create(compressed_chunk_rel, NULL);
Datum *values = palloc(sizeof(Datum) * recompress_ctx->n_keys);
bool *isnulls = palloc(sizeof(bool) * recompress_ctx->n_keys);
HeapTuple compressed_tuple;
IndexScanDesc index_scan = index_beginscan_compat(compressed_chunk_rel,
index_rel,
snapshot,
NULL,
recompress_ctx->num_segmentby,
0);
bool found_tuple = fetch_uncompressed_chunk_into_tuplesort(input_tuplesortstate,
uncompressed_chunk_rel,
snapshot);
if (!found_tuple)
{
goto finish;
}
tuplesort_performsort(input_tuplesortstate);
for (found_tuple = tuplesort_gettupleslot(input_tuplesortstate,
true /*=forward*/,
false /*=copy*/,
uncompressed_slot,
NULL /*=abbrev*/);
found_tuple;)
{
CHECK_FOR_INTERRUPTS();
for (int i = 0; i < recompress_ctx->n_keys; i++)
{
values[i] = slot_getattr(uncompressed_slot,
AttrOffsetGetAttrNumber(
recompress_ctx->current_segment[i].chunk_offset),
&isnulls[i]);
}
update_current_segment(recompress_ctx->current_segment,
values,
isnulls,
recompress_ctx->num_segmentby);
/* Build scankeys based on uncompressed tuple values */
update_segmentby_scankeys(values,
isnulls,
recompress_ctx->num_segmentby,
recompress_ctx->index_scankeys,
recompress_ctx->key_byval,
recompress_ctx->key_typlen);
/* We do not match orderby boundaries for full recompress,
* so do not need orderby scankeys */
if (!fullrecompress)
{
update_orderby_scankeys(values,
isnulls,
recompress_ctx->num_segmentby,
recompress_ctx->num_orderby,
recompress_ctx->orderby_scankeys,
recompress_ctx->key_byval,
recompress_ctx->key_typlen);
}
index_rescan(index_scan,
recompress_ctx->index_scankeys,
recompress_ctx->num_segmentby,
NULL,
0);
bool done_with_segment = false;
bool tuples_for_recompression = false;
enum Batch_match_result result;
/* For full segmentwise decompress/compress we decompress all batches in
* the current segment (i.e. treat each batch as a match) */
if (fullrecompress)
{
result = Tuple_match;
}
while (index_getnext_slot(index_scan, ForwardScanDirection, compressed_slot))
{
/* Check if the uncompressed tuple is before, inside, or after the compressed batch */
if (!fullrecompress)
{
result =
match_tuple_batch(compressed_slot,
recompress_ctx->num_orderby,
recompress_ctx->orderby_scankeys,
&recompress_ctx->nulls_first[recompress_ctx->num_segmentby]);
}
/* If the tuple is before the batch, add it for recompression
* also keep adding uncompressed tuples while they are:
* - any left
* - before the current batch
* - in the same segment group
*/
while (result == Tuple_before)
{
tuples_for_recompression = true;
tuplesort_puttupleslot(recompress_tuplesortstate, uncompressed_slot);
/* If we happen to hit the end of uncompressed tuples or tuple changed segment group
* we are done with the segment group
*/
found_tuple = tuplesort_gettupleslot(input_tuplesortstate,
true /*=forward*/,
false /*=copy*/,
uncompressed_slot,
NULL /*=abbrev*/);
if (!found_tuple)
{
done_with_segment = true;
break;
}
for (int i = 0; i < recompress_ctx->n_keys; i++)
{
values[i] = slot_getattr(uncompressed_slot,
AttrOffsetGetAttrNumber(
recompress_ctx->current_segment[i].chunk_offset),
&isnulls[i]);
}
done_with_segment = check_changed_group(recompress_ctx->current_segment,
values,
isnulls,
recompress_ctx->num_segmentby);
if (done_with_segment)
{
break;
}
update_orderby_scankeys(values,
isnulls,
recompress_ctx->num_segmentby,
recompress_ctx->num_orderby,
recompress_ctx->orderby_scankeys,
recompress_ctx->key_byval,
recompress_ctx->key_typlen);
result =
match_tuple_batch(compressed_slot,
recompress_ctx->num_orderby,
recompress_ctx->orderby_scankeys,
&recompress_ctx->nulls_first[recompress_ctx->num_segmentby]);
}
/* If we are done with segment, recompress everything we have so far
* and break out of this segment index scan
*/
if (done_with_segment)
{
tuples_for_recompression = false;
recompress_segment(recompress_tuplesortstate,
uncompressed_chunk_rel,
&row_compressor,
&writer);
break;
}
/* If the tuple matches the batch, add the batch for recompression */
/* Potential optimization: merge uncompressed tuples and decompressed tuples
* into the tuplesortstate since they are both already sorted
*/
if (result == Tuple_match)
{
tuples_for_recompression = true;
bool should_free;
compressed_tuple = ExecFetchSlotHeapTuple(compressed_slot, false, &should_free);
heap_deform_tuple(compressed_tuple,
compressed_rel_tupdesc,
decompressor.compressed_datums,
decompressor.compressed_is_nulls);
row_decompressor_decompress_row_to_tuplesort(&decompressor,
recompress_tuplesortstate);
if (!delete_tuple_for_recompression(compressed_chunk_rel,
&(compressed_slot->tts_tid),
snapshot))
{
ereport(ERROR,
(errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
errmsg("aborting recompression due to concurrent updates on "
"compressed data, retrying with next policy run")));
}
CommandCounterIncrement();
if (should_free)
{
heap_freetuple(compressed_tuple);
}
continue;
}
/* At this point, tuple is after the batch
* If there are tuples added for recompression, do it
* and continue to the next batch
*/
if (tuples_for_recompression)
{
tuples_for_recompression = false;
recompress_segment(recompress_tuplesortstate,
uncompressed_chunk_rel,
&row_compressor,
&writer);
}
}
/* End if we are finished with all uncompressed tuples */
if (!found_tuple)
{
break;
}
/* Reset index scan if we are done with this segment */
if (done_with_segment)
{
continue;
}
/* We are done with existing batches for this segment group
* Everything after this point goes into new batches
* until we hit a new segment group or exhaust the uncompressed tuples
*/
while (!check_changed_group(recompress_ctx->current_segment,
values,
isnulls,
recompress_ctx->num_segmentby))
{
tuples_for_recompression = true;
tuplesort_puttupleslot(recompress_tuplesortstate, uncompressed_slot);
found_tuple = tuplesort_gettupleslot(input_tuplesortstate,
true /*=forward*/,
false /*=copy*/,
uncompressed_slot,
NULL /*=abbrev*/);
if (!found_tuple)
{
tuples_for_recompression = false;
recompress_segment(recompress_tuplesortstate,
uncompressed_chunk_rel,
&row_compressor,
&writer);
break;
}
for (int i = 0; i < recompress_ctx->num_segmentby; i++)
{
values[i] = slot_getattr(uncompressed_slot,
AttrOffsetGetAttrNumber(
recompress_ctx->current_segment[i].chunk_offset),
&isnulls[i]);
}
}
if (tuples_for_recompression)
{
recompress_segment(recompress_tuplesortstate,
uncompressed_chunk_rel,
&row_compressor,
&writer);
}
}
finish:
row_compressor_close(&row_compressor);
bulk_writer_close(&writer);
ExecDropSingleTupleTableSlot(uncompressed_slot);
ExecDropSingleTupleTableSlot(compressed_slot);
index_endscan(index_scan);
UnregisterSnapshot(snapshot);
index_close(index_rel, NoLock);
row_decompressor_close(&decompressor);
tuplesort_end(input_tuplesortstate);
tuplesort_end(recompress_tuplesortstate);
free_chunk_recompress_ctx(recompress_ctx);
/* If we can quickly upgrade the lock, lets try updating the chunk status to fully
* compressed. But we need to check if there are any uncompressed tuples in the
* relation since somebody might have inserted new tuples while we were recompressing.
*/
if (ConditionalLockRelation(uncompressed_chunk_rel, ExclusiveLock))
{
try_updating_chunk_status(uncompressed_chunk, uncompressed_chunk_rel);
}
else if (has_unique_constraints)
{
/*
* This can be problematic since we cannot acquire ExclusiveLock meaning its
* possible there are inserts going which need to check unique constraints.
* Due to the reverse direction of tuple movement, concurrent recompression
* and speculative insertion could potentially cause false negatives during
* constraint checking. For now, our best option here is to bail.
*
* We use a spin lock to wait for the ExclusiveLock or bail out if we can't get it in time.
*/
int lock_retry = 0;
while (true)
{
if (ConditionalLockRelation(uncompressed_chunk_rel, ExclusiveLock))
{
try_updating_chunk_status(uncompressed_chunk, uncompressed_chunk_rel);
break;
}
/*
* Check for interrupts while trying to (re-)acquire the exclusive
* lock.
*/
CHECK_FOR_INTERRUPTS();
if (++lock_retry >
(RECOMPRESS_EXCLUSIVE_LOCK_TIMEOUT / RECOMPRESS_EXCLUSIVE_LOCK_WAIT_INTERVAL))
{
/*
* We failed to establish the lock in the specified number of
* retries. This means we give up trying to get the exclusive lock are abort the
* recompression operation
*/
ereport(ERROR,
(errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
errmsg("aborting recompression due to concurrent DML on uncompressed "
"data, retrying with next policy run")));
break;
}
(void) WaitLatch(MyLatch,
WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
RECOMPRESS_EXCLUSIVE_LOCK_WAIT_INTERVAL,
WAIT_EVENT_VACUUM_TRUNCATE);
ResetLatch(MyLatch);
DEBUG_WAITPOINT("chunk_recompress_after_latch");
}
}
table_close(uncompressed_chunk_rel, NoLock);
table_close(compressed_chunk_rel, NoLock);
}
static IndexScanDesc
compact_chunk_begin_index_scan(Relation compressed_chunk_rel, Relation index_rel, Snapshot snapshot)
{
IndexScanDesc index_scan =
index_beginscan_compat(compressed_chunk_rel, index_rel, snapshot, NULL, 0, 0);
/* We use index tuples directly to fetch the values */
index_scan->xs_want_itup = true;
index_rescan(index_scan, NULL, 0, NULL, 0);
return index_scan;
}
/*
* Read the current batch's segmentby key values and the first-row / last-row
* orderby tuples from the index tuple into the scan state.
*
* Index key order is [segby1, ...segbyN, orderby metadata pair 1, ...]. Each
* firstlast orderby column contributes its first-row and last-row values as a
* metadata pair; the index attno of each was resolved up front in the context,
* so curr_first/curr_last are exactly the orderby values in the batch's first
* and last rows.
*/
static void
read_batch_firstlast(IndexScanDesc index_scan, RecompressContext *recompress_ctx,
CompactChunkScanState *state)
{
for (int i = 0; i < recompress_ctx->num_segmentby; i++)
{
state->seg_values[i] = index_getattr(index_scan->xs_itup,
AttrOffsetGetAttrNumber(i),
index_scan->xs_itupdesc,
&state->seg_isnull[i]);
}
for (int i = 0; i < recompress_ctx->num_orderby; i++)
{
state->curr_first[i] = index_getattr(index_scan->xs_itup,
recompress_ctx->orderby_first_index_attno[i],