-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathrefresh.c
More file actions
1638 lines (1478 loc) · 56.3 KB
/
Copy pathrefresh.c
File metadata and controls
1638 lines (1478 loc) · 56.3 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 <access/xact.h>
#include <executor/spi.h>
#include <executor/tuptable.h>
#include <fmgr.h>
#include <miscadmin.h>
#include <storage/lmgr.h>
#include <utils/acl.h>
#include <utils/builtins.h>
#include <utils/date.h>
#include <utils/fmgrprotos.h>
#include <utils/guc.h>
#include <utils/lsyscache.h>
#include <utils/snapmgr.h>
#include <utils/tuplestore.h>
#include "bgw_policy/policies_v2.h"
#include "debug_point.h"
#include "dimension.h"
#include "dimension_slice.h"
#include "guc.h"
#include "hypertable.h"
#include "invalidation.h"
#include "invalidation_threshold.h"
#include "jsonb_utils.h"
#include "materialize.h"
#include "process_utility.h"
#include "refresh.h"
#include "time_bucket.h"
#include "time_utils.h"
#include "ts_catalog/catalog.h"
#include "ts_catalog/continuous_agg.h"
#include "ts_catalog/continuous_aggs_jobs_refresh_ranges.h"
#define CAGG_REFRESH_LOG_LEVEL \
(context.callctx == CAGG_REFRESH_POLICY || context.callctx == CAGG_REFRESH_POLICY_BATCHED ? \
LOG : \
DEBUG1)
typedef struct ContinuousAggRefreshState
{
ContinuousAgg cagg;
Hypertable *cagg_ht;
InternalTimeRange refresh_window;
SchemaAndName partial_view;
bool bucketing_refresh_window;
} ContinuousAggRefreshState;
typedef struct CaggRefreshSpiContext
{
const char *old_decompression_limit;
int save_nestlevel;
} CaggRefreshSpiContext;
static Hypertable *cagg_get_hypertable_or_fail(int32 hypertable_id);
static InternalTimeRange get_largest_bucketed_window(Oid timetype, int64 bucket_width);
static InternalTimeRange
compute_inscribed_bucketed_refresh_window(const InternalTimeRange *const refresh_window,
const ContinuousAggBucketFunction *bucket_function);
static void continuous_agg_refresh_init(ContinuousAggRefreshState *refresh,
const ContinuousAgg *cagg,
const InternalTimeRange *refresh_window,
bool bucketing_refresh_window);
static void continuous_agg_refresh_execute(const ContinuousAggRefreshState *refresh,
const InternalTimeRange *bucketed_refresh_window);
static void log_refresh_window(int elevel, const ContinuousAgg *cagg,
const InternalTimeRange *refresh_window,
ContinuousAggRefreshContext context);
static void continuous_agg_refresh_execute_wrapper(const InternalTimeRange *bucketed_refresh_window,
const ContinuousAggRefreshContext context,
const long iteration, void *arg1_refresh);
static void continuous_agg_refresh_with_window(const ContinuousAgg *cagg,
const InternalTimeRange *refresh_window,
const InvalidationStore *invalidations,
const ContinuousAggRefreshContext context,
bool bucketing_refresh_window);
static bool process_cagg_invalidations_and_refresh(const ContinuousAgg *cagg,
const InternalTimeRange *refresh_window,
const ContinuousAggRefreshContext context,
bool bucketing_refresh_window);
static Hypertable *
cagg_get_hypertable_or_fail(int32 hypertable_id)
{
Hypertable *ht = ts_hypertable_get_by_id(hypertable_id);
if (NULL == ht)
{
ereport(ERROR,
(errcode(ERRCODE_INTERNAL_ERROR),
errmsg("invalid continuous aggregate state"),
errdetail("A continuous aggregate references a hypertable that does not exist.")));
}
return ht;
}
/*
* Compute the largest possible bucketed window given the time type and
* internal restrictions.
*
* The largest bucketed window is governed by restrictions set by the type and
* internal, TimescaleDB-specific legacy details (see get_max_window above for
* further explanation).
*/
static InternalTimeRange
get_largest_bucketed_window(Oid timetype, int64 bucket_width)
{
InternalTimeRange maxwindow = {
.type = timetype,
.start = ts_time_get_min(timetype),
.end = ts_time_get_end_or_max(timetype),
};
InternalTimeRange maxbuckets = {
.type = timetype,
};
/* For the MIN value, the corresponding bucket either falls on the exact
* MIN or it will be below it. Therefore, we add (bucket_width - 1) to
* move to the next bucket to be within the allowed range. */
maxwindow.start = ts_time_saturating_add(maxwindow.start, bucket_width - 1, timetype);
maxbuckets.start = ts_time_bucket_by_type(bucket_width, maxwindow.start, timetype);
maxbuckets.end = ts_time_get_end_or_max(timetype);
return maxbuckets;
}
/*
* Adjust the refresh window to align with inscribed buckets, so it includes buckets, which are
* fully covered by the refresh window.
*
* Bucketing refresh window is necessary for a continuous aggregate refresh, which can refresh only
* entire buckets. The result of the function is a bucketed window, where its start is at the start
* of the first bucket, which is fully inside the refresh window, and its end is at the end of the
* last fully covered bucket.
*
* Example1, the window needs to shrink:
* [---------) - given refresh window
* .|....|....|....|. - buckets
* [----) - inscribed bucketed window
*
* Example2, the window is already aligned:
* [----) - given refresh window
* .|....|....|....|. - buckets
* [----) - inscribed bucketed window
*
* This function is called for the continuous aggregate policy and manual refresh. In such case
* excluding buckets, which are not fully covered by the refresh window, avoids refreshing a bucket,
* where part of its data were dropped by a retention policy. See #2198 for details.
*/
static InternalTimeRange
compute_inscribed_bucketed_refresh_window(const InternalTimeRange *const refresh_window,
const ContinuousAggBucketFunction *bucket_function)
{
Assert(bucket_function != NULL);
if (bucket_function->bucket_fixed_interval == false)
{
InternalTimeRange result = *refresh_window;
ts_compute_inscribed_bucketed_refresh_window_variable(&result.start,
&result.end,
bucket_function);
return result;
}
int64 bucket_width = ts_continuous_agg_fixed_bucket_width(bucket_function);
Assert(bucket_width > 0);
InternalTimeRange result = *refresh_window;
InternalTimeRange largest_bucketed_window =
get_largest_bucketed_window(refresh_window->type, bucket_width);
if (refresh_window->start <= largest_bucketed_window.start)
{
result.start = largest_bucketed_window.start;
}
else
{
/* The start time needs to be aligned with the first fully enclosed bucket.
* So the original window start is moved to next bucket, except if the start is
* already aligned with a bucket, thus 1 is subtracted to avoid moving into next
* bucket in the aligned case. */
int64 included_bucket =
ts_time_saturating_add(refresh_window->start, bucket_width - 1, refresh_window->type);
/* Get the start of the included bucket. */
result.start =
cagg_fixed_current_bucket_start(included_bucket, refresh_window->type, bucket_function);
}
if (refresh_window->end >= largest_bucketed_window.end)
{
result.end = largest_bucketed_window.end;
}
else
{
/* The window is reduced to the beginning of the bucket, which contains the exclusive
* end of the refresh window. */
result.end = cagg_fixed_current_bucket_start(refresh_window->end,
refresh_window->type,
bucket_function);
}
return result;
}
/*
* Get the offset as Datum value of an integer based bucket
*/
static Datum
int_bucket_offset_to_datum(Oid type, const ContinuousAggBucketFunction *bucket_function)
{
Assert(bucket_function->bucket_time_based == false);
switch (type)
{
case INT2OID:
return Int16GetDatum(bucket_function->bucket_integer_offset);
case INT4OID:
return Int32GetDatum(bucket_function->bucket_integer_offset);
case INT8OID:
return Int64GetDatum(bucket_function->bucket_integer_offset);
default:
elog(ERROR, "invalid integer time_bucket type \"%s\"", format_type_be(type));
pg_unreachable();
}
}
/*
* Get a NullableDatum for offset and origin based on the CAgg information
*/
static void
fill_bucket_offset_origin(const ContinuousAggBucketFunction *bucket_function, Oid type,
NullableDatum *offset, NullableDatum *origin)
{
Assert(bucket_function != NULL);
Assert(offset != NULL);
Assert(origin != NULL);
Assert(offset->isnull);
Assert(origin->isnull);
if (bucket_function->bucket_time_based)
{
if (bucket_function->bucket_time_offset != NULL)
{
offset->isnull = false;
offset->value = IntervalPGetDatum(bucket_function->bucket_time_offset);
}
if (TIMESTAMP_NOT_FINITE(bucket_function->bucket_time_origin) == false)
{
origin->isnull = false;
if (type == DATEOID)
{
/* Date was converted into a timestamp in process_additional_timebucket_parameter(),
* build a Date again */
origin->value =
DirectFunctionCall1(timestamp_date,
TimestampGetDatum(bucket_function->bucket_time_origin));
}
else
{
origin->value = TimestampGetDatum(bucket_function->bucket_time_origin);
}
}
}
else
{
if (bucket_function->bucket_integer_offset != 0)
{
offset->isnull = false;
offset->value = int_bucket_offset_to_datum(type, bucket_function);
}
}
}
/*
* Compute the start of the bucket containing the given timestamp, accounting
* for the CAgg's offset and origin.
*
* This is a convenience wrapper that combines fill_bucket_offset_origin and
* ts_time_bucket_by_type_extended for fixed-interval buckets.
*/
int64
cagg_fixed_current_bucket_start(int64 timestamp, Oid type,
const ContinuousAggBucketFunction *bucket_function)
{
int64 bucket_width = ts_continuous_agg_fixed_bucket_width(bucket_function);
Assert(bucket_width > 0);
NullableDatum offset = INIT_NULL_DATUM;
NullableDatum origin = INIT_NULL_DATUM;
fill_bucket_offset_origin(bucket_function, type, &offset, &origin);
Assert(offset.isnull == true || origin.isnull == true);
return ts_time_bucket_by_type_extended(bucket_width, timestamp, type, offset, origin);
}
/*
* Compute the start of the bucket immediately following the bucket that
* contains the given timestamp. Equivalently, this is the exclusive end of
* the bucket containing timestamp.
*
* This is a convenience wrapper used when the caller needs to advance past the
* current bucket (e.g. computing an invalidation threshold or the exclusive
* upper bound of a circumscribed refresh window).
*/
int64
cagg_fixed_next_bucket_start(int64 timestamp, Oid type,
const ContinuousAggBucketFunction *bucket_function)
{
int64 bucket_width = ts_continuous_agg_fixed_bucket_width(bucket_function);
Assert(bucket_width > 0);
int64 bucket_start = cagg_fixed_current_bucket_start(timestamp, type, bucket_function);
return ts_time_saturating_add(bucket_start, bucket_width, type);
}
/*
* Compute the start of the bucket containing the given timestamp, dispatching
* to the fixed-interval or variable-interval implementation as appropriate.
*/
int64
cagg_current_bucket_start(int64 timestamp, Oid type,
const ContinuousAggBucketFunction *bucket_function)
{
if (bucket_function->bucket_fixed_interval)
{
return cagg_fixed_current_bucket_start(timestamp, type, bucket_function);
}
return ts_cagg_variable_current_bucket_start(timestamp, bucket_function);
}
/*
* Compute the start of the bucket immediately following the bucket containing
* the given timestamp, dispatching to the fixed-interval or variable-interval
* implementation as appropriate.
*/
int64
cagg_next_bucket_start(int64 timestamp, Oid type,
const ContinuousAggBucketFunction *bucket_function)
{
if (bucket_function->bucket_fixed_interval)
{
return cagg_fixed_next_bucket_start(timestamp, type, bucket_function);
}
return ts_cagg_variable_next_bucket_start(timestamp, bucket_function);
}
/*
* Adjust the refresh window to align with circumscribed buckets, so it includes buckets, which
* fully cover the refresh window.
*
* Bucketing refresh window is necessary for a continuous aggregate refresh, which can refresh only
* entire buckets. The result of the function is a bucketed window, where its start is at the start
* of a bucket, which contains the start of the refresh window, and its end is at the end of a
* bucket, which contains the end of the refresh window.
*
* Example1, the window needs to expand:
* [---------) - given refresh window
* .|....|....|....|. - buckets
* [--------------) - circumscribed bucketed window
*
* Example2, the window is already aligned:
* [----) - given refresh window
* .|....|....|....|. - buckets
* [----) - inscribed bucketed window
*
* This function is called for an invalidation window before refreshing it and after the
* invalidation window was adjusted to be fully inside a refresh window. In the case of a
* continuous aggregate policy or manual refresh, the refresh window is the inscribed bucketed
* window.
*
* The circumscribed behaviour is also used for a refresh on drop, when the refresh is called during
* dropping chunks manually or as part of retention policy.
*/
InternalTimeRange
compute_circumscribed_bucketed_refresh_window(const InternalTimeRange *const refresh_window,
const ContinuousAggBucketFunction *bucket_function)
{
Assert(bucket_function != NULL);
if (bucket_function->bucket_fixed_interval == false)
{
InternalTimeRange result = *refresh_window;
ts_compute_circumscribed_bucketed_refresh_window_variable(&result.start,
&result.end,
bucket_function);
return result;
}
/* Interval is fixed */
int64 bucket_width = ts_continuous_agg_fixed_bucket_width(bucket_function);
Assert(bucket_width > 0);
InternalTimeRange result = *refresh_window;
InternalTimeRange largest_bucketed_window =
get_largest_bucketed_window(refresh_window->type, bucket_width);
if (refresh_window->start <= largest_bucketed_window.start)
{
result.start = largest_bucketed_window.start;
}
else
{
/* For alignment with a bucket, which includes the start of the refresh window, we just
* need to get start of the bucket. */
result.start = cagg_fixed_current_bucket_start(refresh_window->start,
refresh_window->type,
bucket_function);
}
if (refresh_window->end >= largest_bucketed_window.end)
{
result.end = largest_bucketed_window.end;
}
else
{
Assert(refresh_window->end > result.start);
int64 exclusive_end;
/* The end of the window is non-inclusive so subtract one before
* bucketing in case we're already at the end of the bucket (we don't
* want to add an extra bucket). */
exclusive_end = ts_time_saturating_sub(refresh_window->end, 1, refresh_window->type);
result.end =
cagg_fixed_next_bucket_start(exclusive_end, refresh_window->type, bucket_function);
}
return result;
}
/*
* Initialize the refresh state for a continuous aggregate.
*
* The state holds information for executing a refresh of a continuous aggregate.
*/
static void
continuous_agg_refresh_init(ContinuousAggRefreshState *refresh, const ContinuousAgg *cagg,
const InternalTimeRange *refresh_window, bool bucketing_refresh_window)
{
MemSet(refresh, 0, sizeof(*refresh));
refresh->cagg = *cagg;
refresh->cagg_ht = cagg_get_hypertable_or_fail(cagg->data.mat_hypertable_id);
refresh->refresh_window = *refresh_window;
refresh->bucketing_refresh_window = bucketing_refresh_window;
refresh->partial_view.schema = &refresh->cagg.data.partial_view_schema;
refresh->partial_view.name = &refresh->cagg.data.partial_view_name;
}
/*
* Execute a refresh.
*
* The refresh will materialize the area given by the refresh window in the
* refresh state.
*/
static void
continuous_agg_refresh_execute(const ContinuousAggRefreshState *refresh,
const InternalTimeRange *bucketed_refresh_window)
{
SchemaAndName cagg_hypertable_name = {
.schema = &refresh->cagg_ht->fd.schema_name,
.name = &refresh->cagg_ht->fd.table_name,
};
const Dimension *time_dim = hyperspace_get_open_dimension(refresh->cagg_ht->space, 0);
Assert(time_dim != NULL);
continuous_agg_update_materialization(refresh->cagg_ht,
&refresh->cagg,
refresh->partial_view,
cagg_hypertable_name,
&time_dim->fd.column_name,
*bucketed_refresh_window);
}
static void
log_refresh_window(int elevel, const ContinuousAgg *cagg, const InternalTimeRange *refresh_window,
ContinuousAggRefreshContext context)
{
const char *msg = "continuous aggregate refresh (individual invalidation) on";
if (context.callctx == CAGG_REFRESH_POLICY_BATCHED)
{
elog(elevel,
"%s \"%s\" in window [ %s, %s ] (batch %d of %d)",
msg,
NameStr(cagg->data.user_view_name),
ts_internal_to_time_string(refresh_window->start, refresh_window->type),
ts_internal_to_time_string(refresh_window->end, refresh_window->type),
context.processing_batch,
context.number_of_batches);
}
else
{
elog(elevel,
"%s \"%s\" in window [ %s, %s ]",
msg,
NameStr(cagg->data.user_view_name),
ts_internal_to_time_string(refresh_window->start, refresh_window->type),
ts_internal_to_time_string(refresh_window->end, refresh_window->type));
}
}
typedef void (*scan_refresh_ranges_funct_t)(const InternalTimeRange *bucketed_refresh_window,
const ContinuousAggRefreshContext context,
const long iteration, /* 0 is first range */
void *arg1);
static void
continuous_agg_refresh_execute_wrapper(const InternalTimeRange *bucketed_refresh_window,
const ContinuousAggRefreshContext context,
const long iteration, void *arg1_refresh)
{
const ContinuousAggRefreshState *refresh = (const ContinuousAggRefreshState *) arg1_refresh;
(void) iteration;
log_refresh_window(CAGG_REFRESH_LOG_LEVEL, &refresh->cagg, bucketed_refresh_window, context);
continuous_agg_refresh_execute(refresh, bucketed_refresh_window);
}
static long
continuous_agg_scan_refresh_window_ranges(const ContinuousAgg *cagg,
const InternalTimeRange *refresh_window,
const InvalidationStore *invalidations,
const ContinuousAggRefreshContext context,
scan_refresh_ranges_funct_t exec_func, void *func_arg1)
{
TupleTableSlot *slot;
long count = 0;
ContinuousAggRefreshState *refresh = (ContinuousAggRefreshState *) func_arg1;
slot = MakeSingleTupleTableSlot(invalidations->tupdesc, &TTSOpsMinimalTuple);
while (tuplestore_gettupleslot(invalidations->tupstore,
true /* forward */,
false /* copy */,
slot))
{
bool isnull;
Datum start = slot_getattr(
slot,
Anum_continuous_aggs_materialization_invalidation_log_lowest_modified_value,
&isnull);
Datum end = slot_getattr(
slot,
Anum_continuous_aggs_materialization_invalidation_log_greatest_modified_value,
&isnull);
InternalTimeRange invalidation = {
.type = refresh_window->type,
.start = DatumGetInt64(start),
/* Invalidations are inclusive at the end, while refresh windows
* aren't, so add one to the end of the invalidated region */
.end = ts_time_saturating_add(DatumGetInt64(end), 1, refresh_window->type),
};
InternalTimeRange bucketed_refresh_window = {
.type = invalidation.type,
.start = invalidation.start,
.end = invalidation.end,
};
if (refresh->bucketing_refresh_window)
{
bucketed_refresh_window =
compute_circumscribed_bucketed_refresh_window(&invalidation, cagg->bucket_function);
}
(*exec_func)(&bucketed_refresh_window, context, count, func_arg1);
count++;
}
ExecDropSingleTupleTableSlot(slot);
return count;
}
/*
* Execute refreshes based on the processed invalidations.
*
* The given refresh window covers a set of buckets, some of which are
* out-of-date (invalid) and some which are up-to-date (valid). Invalid
* buckets that are adjacent form larger ranges, as shown below.
*
* Refresh window: [-----------------------------------------)
* Invalid ranges: [-----] [-] [--] [-] [---]
* Merged range: [---------------------------)
*
* The maximum number of individual (non-mergeable) ranges are
* #buckets_in_window/2 (i.e., every other bucket is invalid).
*
* Since it might not be efficient to materialize a lot buckets separately
* when there are many invalid (non-adjecent) buckets/ranges, we put a limit
* on the number of individual materializations we do. This limit is
* determined by the MATERIALIZATIONS_PER_REFRESH_WINDOW setting.
*
* Thus, if the refresh window covers a large number of buckets, but only a
* few of them are invalid, it is likely beneficial to materialized these
* separately to avoid materializing a lot of buckets that are already
* up-to-date. But if the number of invalid buckets/ranges go above the
* threshold, we materialize all of them in one go using the "merged range",
* as illustrated above.
*/
static void
continuous_agg_refresh_with_window(const ContinuousAgg *cagg,
const InternalTimeRange *refresh_window,
const InvalidationStore *invalidations,
const ContinuousAggRefreshContext context,
bool bucketing_refresh_window)
{
ContinuousAggRefreshState refresh;
continuous_agg_refresh_init(&refresh, cagg, refresh_window, bucketing_refresh_window);
long count pg_attribute_unused();
count = continuous_agg_scan_refresh_window_ranges(cagg,
refresh_window,
invalidations,
context,
continuous_agg_refresh_execute_wrapper,
(void *) &refresh /* arg1 */);
Assert(count);
}
#define REFRESH_FUNCTION_NAME "refresh_continuous_aggregate()"
/*
* Refresh a continuous aggregate over a window, splitting it into batches when
* incremental refresh is enabled.
*
* This is the shared entry point used by both the manual refresh
* (refresh_continuous_aggregate) and the continuous aggregate refresh policy.
*
* For a normal refresh, batching is driven by the invalidation logs, so it only
* produces batches for the regions that actually need to be refreshed. A forced
* refresh ignores the invalidation logs and instead batches every bucket-aligned
* chunk of the window that contains data, so the whole window is re-materialized.
* Set buckets_per_batch to 0 for a single atomic pass.
*/
void
continuous_agg_refresh_batched(ContinuousAgg *cagg, InternalTimeRange *refresh_window,
ContinuousAggRefreshContext context, bool extend_last_bucket)
{
List *refresh_window_list = continuous_agg_split_refresh_window(cagg,
refresh_window,
context.buckets_per_batch,
context.force);
bool batched = (refresh_window_list != NIL);
if (!batched)
{
/* No batching: refresh the whole window as a single batch */
refresh_window_list = lappend(refresh_window_list, refresh_window);
}
else
{
/* Batches are already bucket-aligned by the split function */
switch (context.callctx)
{
case CAGG_REFRESH_POLICY:
context.callctx = CAGG_REFRESH_POLICY_BATCHED;
break;
case CAGG_REFRESH_WINDOW:
context.callctx = CAGG_REFRESH_WINDOW_BATCHED;
break;
default:
break;
}
}
context.number_of_batches = list_length(refresh_window_list);
/*
* The list is always built oldest-first. When refresh_newest_first is true we
* iterate from the last element down to the first using index-based access so
* that no reversal copy of the list is needed.
*/
int32 processing_batch = 0;
int32 nbatches = context.number_of_batches;
int32 batch_start = context.refresh_newest_first ? nbatches - 1 : 0;
int32 batch_end = context.refresh_newest_first ? -1 : nbatches;
int32 batch_step = context.refresh_newest_first ? -1 : 1;
bool any_refreshed = false;
for (int32 batch_idx = batch_start; batch_idx != batch_end; batch_idx += batch_step)
{
InternalTimeRange *batch_window =
(InternalTimeRange *) list_nth(refresh_window_list, batch_idx);
elog(DEBUG1,
"refreshing continuous aggregate \"%s\" from %s to %s",
NameStr(cagg->data.user_view_name),
ts_internal_to_time_string(batch_window->start, batch_window->type),
ts_internal_to_time_string(batch_window->end, batch_window->type));
context.processing_batch = ++processing_batch;
/* extend_last_bucket must only apply to the boundary batch -- the one
* whose window abuts the adjacent policy. For newest-first ordering
* that is batch 1; for oldest-first it is the final batch.
* In non-batched mode (single batch) the one batch is always the boundary. */
bool apply_extend =
extend_last_bucket &&
(context.refresh_newest_first ? processing_batch == 1 :
processing_batch == context.number_of_batches);
any_refreshed |= continuous_agg_refresh_internal(cagg,
batch_window,
context,
!batched, /* bucketing_refresh_window */
apply_extend);
DEBUG_ERROR_INJECTION(psprintf("cagg_policy_batch_%d_after_refresh", processing_batch));
if (context.max_batches_per_execution > 0 &&
processing_batch >= context.max_batches_per_execution &&
processing_batch < context.number_of_batches)
{
elog(LOG,
"reached maximum number of batches per execution (%d), batches not processed (%d)",
context.max_batches_per_execution,
context.number_of_batches - processing_batch);
break;
}
}
if (!any_refreshed)
{
emit_up_to_date_notice(cagg, context);
}
}
/*
* Refresh a continuous aggregate across the given window.
*/
Datum
continuous_agg_refresh(PG_FUNCTION_ARGS)
{
Oid cagg_relid = PG_ARGISNULL(0) ? InvalidOid : PG_GETARG_OID(0);
bool force = PG_ARGISNULL(3) ? false : PG_GETARG_BOOL(3);
ContinuousAgg *cagg;
InternalTimeRange refresh_window = {
.type = InvalidOid,
};
ts_feature_flag_check(FEATURE_CAGG);
cagg = cagg_get_by_relid_or_fail(cagg_relid);
refresh_window.type = cagg->partition_type;
/*
* Check ownership up front, before any work that touches the source
* hypertable (e.g. computing the batches for an incremental refresh).
*/
if (!object_ownercheck(RelationRelationId, cagg_relid, GetUserId()))
{
aclcheck_error(ACLCHECK_NOT_OWNER,
get_relkind_objtype(get_rel_relkind(cagg_relid)),
get_rel_name(cagg_relid));
}
if (!PG_ARGISNULL(1))
{
refresh_window.start = ts_time_value_from_arg(PG_GETARG_DATUM(1),
get_fn_expr_argtype(fcinfo->flinfo, 1),
refresh_window.type,
true);
}
else
{
/* get min time for a cagg depending of the primary partition type */
refresh_window.start = cagg_get_time_min(cagg);
refresh_window.start_isnull = true;
}
if (!PG_ARGISNULL(2))
{
refresh_window.end = ts_time_value_from_arg(PG_GETARG_DATUM(2),
get_fn_expr_argtype(fcinfo->flinfo, 2),
refresh_window.type,
true);
}
else
{
refresh_window.end = ts_time_get_noend_or_max(refresh_window.type);
refresh_window.end_isnull = true;
}
/*
* Manual refreshes batch by default (DEFAULT_BUCKETS_PER_BATCH), matching the
* continuous aggregate policy. Callers can override through the options JSONB;
* set buckets_per_batch to 0 to force a single-pass atomic refresh.
*/
int32 buckets_per_batch = DEFAULT_BUCKETS_PER_BATCH;
int32 max_batches_per_execution = 0;
bool refresh_newest_first = DEFAULT_REFRESH_NEWEST_FIRST;
if (!PG_ARGISNULL(4))
{
Jsonb *options = PG_GETARG_JSONB_P(4);
bool found;
int32 v = ts_jsonb_get_int32_field(options, POL_REFRESH_CONF_KEY_BUCKETS_PER_BATCH, &found);
if (found)
{
buckets_per_batch = v;
}
v = ts_jsonb_get_int32_field(options,
POL_REFRESH_CONF_KEY_MAX_BATCHES_PER_EXECUTION,
&found);
if (found)
{
max_batches_per_execution = v;
}
bool b =
ts_jsonb_get_bool_field(options, POL_REFRESH_CONF_KEY_REFRESH_NEWEST_FIRST, &found);
if (found)
{
refresh_newest_first = b;
}
}
if (buckets_per_batch < 0)
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("invalid buckets per batch"),
errdetail("buckets_per_batch: %d", buckets_per_batch),
errhint("The buckets per batch should be greater than or equal to zero.")));
}
if (max_batches_per_execution < 0)
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("invalid max batches per execution"),
errdetail("max_batches_per_execution: %d", max_batches_per_execution),
errhint(
"The max batches per execution should be greater than or equal to zero.")));
}
ContinuousAggRefreshContext context = {
.callctx = CAGG_REFRESH_WINDOW,
.buckets_per_batch = buckets_per_batch,
.max_batches_per_execution = max_batches_per_execution,
.refresh_newest_first = refresh_newest_first,
.force = force,
};
continuous_agg_refresh_batched(cagg, &refresh_window, context, false /*extend_last_bucket*/);
DEBUG_WAITPOINT("after_cagg_refresh_window");
PG_RETURN_VOID();
}
static bool
process_cagg_invalidations_and_refresh(const ContinuousAgg *cagg,
const InternalTimeRange *refresh_window,
const ContinuousAggRefreshContext context,
bool bucketing_refresh_window)
{
/* Lock the continuous aggregate's catalog table entry to protect against concurrent refreshes
* on the same cagg processing the cagg invalidation logs for that CAgg.
*/
bool found = ts_lock_continuous_agg_tuple(cagg->data.mat_hypertable_id);
Ensure(found,
"continuous aggregate with mat_hypertable_id %d not found",
cagg->data.mat_hypertable_id);
invalidation_process_cagg_log(cagg, refresh_window);
DEBUG_ERROR_INJECTION("cagg_refresh_fail_in_txn2");
DEBUG_WAITPOINT("before_process_cagg_invalidations_for_refresh_lock");
SPI_commit_and_chain();
DEBUG_ERROR_INJECTION("cagg_refresh_fail_in_txn3");
DEBUG_WAITPOINT("after_process_cagg_invalidations_for_refresh_lock");
InvalidationStore *invalidations =
collect_and_delete_cagg_invalidations_in_window(cagg, refresh_window, context.force);
if (invalidations != NULL)
{
if (context.callctx == CAGG_REFRESH_CREATION)
{
Assert(OidIsValid(cagg->relid));
ereport(NOTICE,
(errmsg("refreshing continuous aggregate \"%s\"", get_rel_name(cagg->relid)),
errhint("Use WITH NO DATA if you do not want to refresh the continuous "
"aggregate on creation.")));
}
continuous_agg_refresh_with_window(cagg,
refresh_window,
invalidations,
context,
bucketing_refresh_window);
invalidation_store_free(invalidations);
}
return invalidations != NULL;
}
static void
cleanup_before_cagg_refresh_exit(const ContinuousAgg *cagg,
const CaggRefreshSpiContext *cagg_spi_ctx)
{
/* Remove the refresh window registration inserted above so it does
* not block future refreshes from the same backend. */
ts_cagg_jobs_refresh_ranges_delete_by_pid(cagg->data.mat_hypertable_id, MyProcPid);
SetConfigOption("timescaledb.max_tuples_decompressed_per_dml_transaction",
cagg_spi_ctx->old_decompression_limit,
PGC_USERSET,
PGC_S_SESSION);
/* Restore search_path */
AtEOXact_GUC(false, cagg_spi_ctx->save_nestlevel);
}
static void
continuous_agg_refresh_spi_setup_and_connect(CaggRefreshSpiContext *cagg_spi_ctx)
{
bool nonatomic = ts_process_utility_is_context_nonatomic();
/* Reset the saved ProcessUtilityContext value promptly before
* calling Prevent* checks so the potential unsupported (atomic)
* value won't linger there in case of ereport exit.
* See: https://github.com/timescale/timescaledb/pull/7566
*/
ts_process_utility_context_reset();
PreventCommandIfReadOnly(REFRESH_FUNCTION_NAME);
/* Prevent running refresh if we're in a transaction block since a refresh
* can run two transactions and might take a long time to release locks if
* there's a lot to materialize. Strictly, it is optional to prohibit
* transaction blocks since there will be only one transaction if the
* invalidation threshold needs no update. However, materialization might
* still take a long time and it is probably best for consistency to always
* prevent transaction blocks. */
PreventInTransactionBlock(nonatomic, REFRESH_FUNCTION_NAME);
/*
* We don't cagg refresh to fail because of decompression limit. So disable
* the decompression limit for the duration of the refresh.
*/
cagg_spi_ctx->old_decompression_limit =
GetConfigOption("timescaledb.max_tuples_decompressed_per_dml_transaction", false, false);
SetConfigOption("timescaledb.max_tuples_decompressed_per_dml_transaction",
"0",
PGC_USERSET,
PGC_S_SESSION);
/* Connect to SPI manager due to the underlying SPI calls */
int rc = SPI_connect_ext(SPI_OPT_NONATOMIC);
if (rc != SPI_OK_CONNECT)
{
elog(ERROR, "SPI_connect failed: %s", SPI_result_code_string(rc));
}
/* Lock down search_path */
cagg_spi_ctx->save_nestlevel = NewGUCNestLevel();
RestrictSearchPath();
}
/* rollback and cleanup after the failed refresh transaction */
static void
rollback_and_error(const ContinuousAgg *cagg, CaggRefreshSpiContext *cagg_spi_ctx, ErrorData *edata)
{
/*
* Every spi_execute pushes a snapshot on the stack (unless a snapshot
* is explicitly passed to it). This is usually cleaned up after a
* successful execute. However, if this fails, the longjmp skips the
* cleanup step.
* As a result, when SPI_rollback_and_chain is called after the longjmp, it
* can find snapshots that were left behind (resulting in
* "portal snapshots did not account for all active snapshots" error).
* The rollback cleans up the snapshot stack and then throws an error.
* So we use a try-catch block around SPI_rollback_and_chain to ignore this
* error.
*/
PG_TRY();
{
SPI_rollback_and_chain();
}
PG_CATCH();
{
FlushErrorState();
}
PG_END_TRY();
/* Commit the cleanup transaction, then throw the original error. */
cleanup_before_cagg_refresh_exit(cagg, cagg_spi_ctx);
SPI_commit();
ThrowErrorData(edata);
}
bool
continuous_agg_refresh_internal(const ContinuousAgg *cagg_arg,