Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
# Copyright (c) 2026, Kirillov Vyacheslav by AI, QDB Development Group
#
# src/test/recovery/t/505_cfs_replication.pl
#
# CFS tables under physical replication.
#
# CFS relations store their data in sidecar files (.cfp/.cfsmap/.cfsjrn)
# next to the (empty) main fork, so every replication mechanism has to
# carry both the base files and the sidecars, and WAL redo on a standby
# has to write pages through the CFS path.  This test checks the whole
# matrix:
#
#   * pg_basebackup copies the sidecar files, a standby built from the
#     backup reads CFS tables, and WAL replay keeps it in sync — including
#     CFS tables created while the standby is already streaming;
#   * a standby without the named compression codec degrades new writes
#     to RAW with a warning instead of dying during redo;
#   * a promoted standby keeps its CFS data readable and writable on the
#     new timeline;
#   * cascading replication (primary -> standby -> standby) carries CFS
#     data to the bottom of the cascade, also across a promote of the
#     intermediate node;
#   * a replica built WITHOUT CFS refuses a CFS primary in a managed way
#     (connect-time rejection when streaming, a clear FATAL during archive
#     redo) instead of crashing with a PANIC;
#   * hot standby recovery conflicts (buffer pin, snapshot) cancel
#     standby queries on CFS pages correctly and leave the sidecars
#     structurally valid;
#   * a physical replication slot maintains correct WAL retention across
#     checkpoints that flush CFS sidecars.
 
use strict;
use warnings FATAL => 'all';
 
use PostgreSQL::Test::Utils;
use PostgreSQL::Test::Cluster;
use Test::More;
 
# ---------------------------------------------------------------------------
# Base backup and physical streaming replication.
#
# Verifies that:
#   * pg_basebackup (via the test framework's backup()) copies CFS sidecar
#     files (.cfp/.cfsmap/.cfsjrn);
#   * a standby initialised from the backup can read CFS tables;
#   * WAL replay on the standby writes dirty pages through CFS;
#   * query results on primary and standby match for CFS tables;
#   * a standby built without the codec named by a replayed CFS policy
#     degrades new writes to RAW (with a warning) instead of dying with
#     ERROR during WAL redo.
# ---------------------------------------------------------------------------
{
    # Initialize the primary node.
    my $primary = PostgreSQL::Test::Cluster->new('cfs_primary');
    $primary->init(allows_streaming => 1);
    $primary->append_conf('postgresql.conf', "checkpoint_timeout = 30s");
    $primary->start;
 
    # Skip when LZ4 is not compiled in.
    my $configure = $primary->safe_psql('postgres',
        "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'");
    if ($configure !~ /--with-lz4/)
    {
        plan skip_all =>
          'LZ4 support not built, skipping CFS replication test';
    }
 
    # Create a CFS table on the primary and populate it.
    $primary->safe_psql('postgres',
        "CREATE TABLE cfs_repl (id int, payload text) WITH (algorithm = 'lz4')"
    );
    $primary->safe_psql('postgres',
            "INSERT INTO cfs_repl SELECT g, repeat('r' || g, 100) "
          . "FROM generate_series(1, 500) g");
 
    $primary->safe_psql('postgres', "CHECKPOINT");
 
    # Verify sidecar files exist on the primary.
    my $primary_path = $primary->safe_psql('postgres',
        "SELECT pg_relation_filepath('cfs_repl')");
    my $primary_dir = $primary->data_dir;
    ok( -f "$primary_dir/$primary_path.cfp",
        'CFS table has .cfp sidecar on primary');
    ok( -f "$primary_dir/$primary_path.cfsmap",
        'CFS table has .cfsmap sidecar on primary');
 
    # Capture the primary checksum for comparison.
    my $primary_checksum = $primary->safe_psql('postgres',
        "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_repl");
 
    # Take a base backup and create a standby.
    $primary->backup('my_backup');
    my $standby = PostgreSQL::Test::Cluster->new('cfs_standby');
    $standby->init_from_backup($primary, 'my_backup', has_streaming => 1);
    $standby->start;
 
    # Verify sidecar files were included in the base backup on standby.
    $primary->wait_for_catchup($standby);
 
    my $standby_path = $standby->safe_psql('postgres',
        "SELECT pg_relation_filepath('cfs_repl')");
    my $standby_dir = $standby->data_dir;
    ok(-f "$standby_dir/$standby_path.cfp",
        'CFS .cfp sidecar present on standby via basebackup');
    ok(-f "$standby_dir/$standby_path.cfsmap",
        'CFS .cfsmap sidecar present on standby via basebackup');
 
    # The standby should be able to read the CFS table.
    my $standby_checksum = $standby->safe_psql('postgres',
        "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_repl");
    is($standby_checksum, $primary_checksum,
        'CFS table checksum matches between primary and standby');
 
    # Write more data on the primary; standby must catch up via WAL
    # replay.
    $primary->safe_psql('postgres',
            "INSERT INTO cfs_repl SELECT g, repeat('n' || g, 100) "
          . "FROM generate_series(501, 1000) g");
 
    $primary->wait_for_catchup($standby);
 
    my $standby_count =
      $standby->safe_psql('postgres', "SELECT count(*) FROM cfs_repl");
    is($standby_count, '1000',
        'Standby has 1000 rows after WAL replay (CFS write path)');
 
    # Checksum comparison after WAL replay.
    my $primary_checksum2 = $primary->safe_psql('postgres',
        "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_repl");
    my $standby_checksum2 = $standby->safe_psql('postgres',
        "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_repl");
    is($standby_checksum2, $primary_checksum2,
        'CFS table checksum matches after WAL replay');
 
    # Redo-only CREATE: a CFS table created while the standby is already
    # streaming must keep its CFS status through WAL replay.
    #
    # On the standby the startup process has no relcache entry for the new
    # relation when XLOG_SMGR_CREATE replays, so the CFS policy must arrive
    # via WAL itself.  A regression here makes replay take the plain md
    # path: the pages land raw in the base file, the sidecars are never
    # created, and the first hot-standby read (which resolves CFS from
    # reloptions) sees an empty relation.
    $primary->safe_psql('postgres',
        "CREATE TABLE cfs_repl_new (id int, payload text) WITH (algorithm = 'lz4')"
    );
    $primary->safe_psql('postgres', "CHECKPOINT");
 
    $primary->wait_for_catchup($standby);
 
    # Restart the standby between the CREATE and the first INSERT: the
    # shared-memory policy published by the CFS policy record's replay is
    # lost, so after the restart redo must recognise the relation as CFS
    # from the eagerly created sidecar files alone.
    $standby->restart;
 
    $primary->safe_psql('postgres',
            "INSERT INTO cfs_repl_new SELECT g, repeat('w' || g, 100) "
          . "FROM generate_series(1, 300) g");
 
    $primary->wait_for_catchup($standby);
 
    my $standby_new_path = $standby->safe_psql('postgres',
        "SELECT pg_relation_filepath('cfs_repl_new')");
    ok(-f "$standby_dir/$standby_new_path.cfp",
        'redo-only CREATE: .cfp sidecar created on standby during replay');
    ok( -f "$standby_dir/$standby_new_path.cfsmap",
        'redo-only CREATE: .cfsmap sidecar created on standby during replay');
 
    my $standby_new_count =
      $standby->safe_psql('postgres', "SELECT count(*) FROM cfs_repl_new");
    is($standby_new_count, '300',
        'redo-only CREATE: standby reads 300 rows via the CFS path');
 
    my $primary_new_checksum = $primary->safe_psql('postgres',
        "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_repl_new");
    my $standby_new_checksum = $standby->safe_psql('postgres',
        "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_repl_new");
    is($standby_new_checksum, $primary_new_checksum,
        'redo-only CREATE: checksum matches between primary and standby');
 
    # Codec mismatch: a standby built without the codec named by a
    # replayed CFS policy must degrade new writes to RAW (with a warning)
    # instead of dying with ERROR during WAL redo.
    #
    # The codec-less build is simulated with the debug GUC
    # cfs_debug_disable_codecs (bits 1 << CFS_ALGORITHM_LZ4 and
    # 1 << CFS_ALGORITHM_ZSTD), which makes both real codecs report
    # themselves as not compiled in.  A tiny shared_buffers forces redo to
    # evict (and therefore compress) dirty pages while replaying —
    # exactly the path that used to raise the fatal ERROR.
    #
    # The table is created only now, while the standby is already
    # streaming, so the standby learns the policy solely from the
    # XLOG_SMGR_CFS_POLICY record and builds the sidecar files from
    # scratch: every block in them is then written by the codec-less
    # standby itself.  With both codecs disabled any compressed block
    # would be unreadable, so the successful reads below prove that every
    # flushed page — including the ones evicted by auxiliary processes at
    # the restartpoint — really went through the RAW fallback.
    my $log_offset = -s $standby->logfile;
    $standby->append_conf('postgresql.conf',
        "cfs_debug_disable_codecs = 6\nshared_buffers = 1MB");
    $standby->restart;
 
    $primary->safe_psql('postgres',
        "CREATE TABLE cfs_repl_nocodec (id int, payload text) WITH (algorithm = 'lz4')"
    );
    $primary->safe_psql('postgres',
        "INSERT INTO cfs_repl_nocodec SELECT g, repeat('m' || (g % 100), 200) "
          . "FROM generate_series(1, 30000) g");
 
    # Redo must survive: replay catches up even though the standby cannot
    # compress with LZ4.
    $primary->wait_for_catchup($standby);
 
    my $standby_nc_count = $standby->safe_psql('postgres',
        "SELECT count(*) FROM cfs_repl_nocodec");
    is($standby_nc_count, '30000',
        'codec-less standby replays CFS table (RAW fallback during redo)');
 
    # A standby restart forces a shutdown restartpoint that flushes the
    # remaining dirty pages through the CFS write path, and the following
    # recovery must read back the RAW blocks written by the codec-less
    # redo.
    $standby->restart;
 
    my $primary_nc_checksum = $primary->safe_psql('postgres',
        "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_repl_nocodec"
    );
    my $standby_nc_checksum = $standby->safe_psql('postgres',
        "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_repl_nocodec"
    );
    is($standby_nc_checksum, $primary_nc_checksum,
        'codec-less standby: checksum matches after restart');
 
    ok( $standby->log_contains(
            qr/CFS compression algorithm "lz4" is not available in this build/,
            $log_offset),
        'codec-less standby logged the RAW fallback warning');
 
    $standby->stop('fast');
    $primary->stop('fast');
}
 
# ---------------------------------------------------------------------------
# Promote of a standby holding CFS-compressed relations.
#
# Verifies that after pg_ctl promote:
#   * CFS tables are readable on the new primary;
#   * new writes go through the CFS write path (sidecar files grow);
#   * a restart on the new timeline preserves the data (crash recovery of
#     the sidecar files on a promoted node);
#   * structural fsck of the sidecar files passes.
# ---------------------------------------------------------------------------
subtest 'promote of a standby with CFS relations' => sub {
    my $primary = PostgreSQL::Test::Cluster->new('cfs_promo_primary');
    $primary->init(allows_streaming => 1);
    $primary->append_conf('postgresql.conf', "checkpoint_timeout = 30s\n");
    $primary->start;
 
    my $configure = $primary->safe_psql('postgres',
        "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'");
    if ($configure !~ /--with-lz4/)
    {
        plan skip_all => 'LZ4 support not built, skipping CFS promote test';
    }
 
    # Populate a CFS table on the primary.
    $primary->safe_psql('postgres',
        "CREATE TABLE cfs_promo (id int, payload text) WITH (algorithm = 'lz4')"
    );
    $primary->safe_psql('postgres',
            "INSERT INTO cfs_promo SELECT g, repeat('a' || g, 100) "
          . "FROM generate_series(1, 500) g");
    $primary->safe_psql('postgres', "CHECKPOINT");
 
    my $before_checksum = $primary->safe_psql('postgres',
        "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_promo");
 
    # Create and promote a standby.
    $primary->backup('my_backup');
    my $standby = PostgreSQL::Test::Cluster->new('cfs_promo_standby');
    $standby->init_from_backup($primary, 'my_backup', has_streaming => 1);
    $standby->start;
 
    $primary->wait_for_catchup($standby);
    $primary->stop('fast');
    $standby->promote;
    $standby->poll_query_until('postgres', "SELECT NOT pg_is_in_recovery()")
      or die "standby did not promote";
 
    # CFS table must be readable on the promoted node.
    my $promoted_checksum = $standby->safe_psql('postgres',
        "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_promo");
    is($promoted_checksum, $before_checksum,
        'CFS table readable after promote');
 
    # New writes must use the CFS write path on the new primary.
    my $standby_dir = $standby->data_dir;
    my $rel_path = $standby->safe_psql('postgres',
        "SELECT pg_relation_filepath('cfs_promo')");
    $standby->safe_psql('postgres',
            "INSERT INTO cfs_promo SELECT g, repeat('b' || g, 100) "
          . "FROM generate_series(501, 900) g");
    $standby->safe_psql('postgres', "CHECKPOINT");
 
    my $count =
      $standby->safe_psql('postgres', "SELECT count(*) FROM cfs_promo");
    is($count, '900', 'writes on promoted node go through CFS');
 
    my $cfp_size = -s "$standby_dir/$rel_path.cfp";
    ok($cfp_size > 0, '.cfp sidecar keeps growing on promoted node');
 
    # Restart on the new timeline: crash/recovery of the sidecar files
    # must preserve the data.
    $standby->restart;
    my $restart_checksum = $standby->safe_psql('postgres',
        "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_promo");
    my $expected = $standby->safe_psql('postgres',
        "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_promo");
    is($restart_checksum, $expected,
        'CFS table survives restart on the new timeline');
 
    my $fsck = $standby->safe_psql('postgres',
        "SELECT ok FROM pg_cfs_check('cfs_promo')");
    is($fsck, 't', 'pg_cfs_check passes after promote and restart');
 
    $standby->stop('fast');
};
 
# ---------------------------------------------------------------------------
# Cascading physical replication with CFS-compressed relations:
# primary -> standby1 -> standby2.
#
# Verifies that CFS data flows down the cascade, that standby2 serves CFS
# reads, and that standby2 keeps replaying CFS writes after standby1 is
# promoted (cascading from a promoted intermediate node).
# ---------------------------------------------------------------------------
subtest 'cascading physical replication with CFS relations' => sub {
    my $primary = PostgreSQL::Test::Cluster->new('cfs_casc_primary');
    $primary->init(allows_streaming => 1);
    $primary->append_conf('postgresql.conf', "checkpoint_timeout = 30s\n");
    $primary->start;
 
    my $configure = $primary->safe_psql('postgres',
        "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'");
    if ($configure !~ /--with-lz4/)
    {
        plan skip_all => 'LZ4 support not built, skipping CFS cascade test';
    }
 
    $primary->safe_psql('postgres',
        "CREATE TABLE cfs_casc (id int, payload text) WITH (algorithm = 'lz4')"
    );
    $primary->safe_psql('postgres',
            "INSERT INTO cfs_casc SELECT g, repeat('a' || g, 100) "
          . "FROM generate_series(1, 300) g");
    $primary->safe_psql('postgres', "CHECKPOINT");
 
    # First level of the cascade.
    $primary->backup('my_backup');
    my $standby1 = PostgreSQL::Test::Cluster->new('cfs_casc_standby1');
    $standby1->init_from_backup($primary, 'my_backup', has_streaming => 1);
    $standby1->start;
    $primary->wait_for_catchup($standby1);
 
    # Second level: standby2 follows standby1.
    $standby1->backup('casc_backup');
    my $standby2 = PostgreSQL::Test::Cluster->new('cfs_casc_standby2');
    $standby2->init_from_backup($standby1, 'casc_backup', has_streaming => 1);
    $standby2->start;
 
    # CFS data must reach the bottom of the cascade.
    $primary->safe_psql('postgres',
            "INSERT INTO cfs_casc SELECT g, repeat('b' || g, 100) "
          . "FROM generate_series(301, 600) g");
    $primary->wait_for_catchup($standby1);
    $standby1->wait_for_catchup($standby2);
 
    my $checksum = $primary->safe_psql('postgres',
        "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_casc");
    my $checksum2 = $standby2->safe_psql('postgres',
        "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_casc");
    is($checksum2, $checksum,
        'CFS checksum matches at the bottom of the cascade');
 
    my $standby2_dir = $standby2->data_dir;
    my $rel_path = $standby2->safe_psql('postgres',
        "SELECT pg_relation_filepath('cfs_casc')");
    ok(-f "$standby2_dir/$rel_path.cfp",
        'CFS sidecar present at the bottom of the cascade');
 
    # Promote the intermediate node; standby2 must keep replaying CFS
    # writes through the new timeline.
    $standby1->promote;
    $standby1->poll_query_until('postgres', "SELECT NOT pg_is_in_recovery()")
      or die "standby1 did not promote";
 
    $standby1->safe_psql('postgres',
            "INSERT INTO cfs_casc SELECT g, repeat('c' || g, 100) "
          . "FROM generate_series(601, 900) g");
    $standby1->wait_for_catchup($standby2);
 
    my $count2 =
      $standby2->safe_psql('postgres', "SELECT count(*) FROM cfs_casc");
    is($count2, '900',
        'cascaded standby replays CFS writes after intermediate promote');
 
    my $checksum1 = $standby1->safe_psql('postgres',
        "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_casc");
    $checksum2 = $standby2->safe_psql('postgres',
        "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_casc");
    is($checksum2, $checksum1,
        'CFS checksum matches after intermediate promote');
 
    my $fsck = $standby2->safe_psql('postgres',
        "SELECT ok FROM pg_cfs_check('cfs_casc')");
    is($fsck, 't', 'pg_cfs_check passes at the bottom of the cascade');
 
    $standby2->stop('fast');
    $standby1->stop('fast');
    $primary->stop('fast');
};
 
# ---------------------------------------------------------------------------
# Cross-build mismatch: non-CFS replica against a CFS primary.
#
# A physical replica built WITHOUT CFS (--without-dia-cfs) must not crash
# with PANIC when its CFS-enabled primary emits an XLOG_SMGR_CFS_POLICY
# record.  Instead it must stop in a managed, informative way:
#
#   * streaming: reject the CFS primary at connect time (ERROR in
#     libpqrcv_connect, via the "dia_cfs" GUC_REPORT parameter), exactly
#     like a system-identifier mismatch, before any WAL replay;
#   * archive/PITR recovery: fail redo with FATAL "cannot replay CFS WAL
#     record" instead of "PANIC: smgr_redo: unknown op code".
#
# Two builds are required: the build under test (a CFS build) as primary,
# plus a pre-built --without-dia-cfs installation pointed to by the
# CFS_NON_CFS_INSTALL environment variable.  The single-build TAP harness
# cannot produce a non-CFS binary in one run, so the test skips cleanly
# when that variable is unset.
# ---------------------------------------------------------------------------
subtest 'non-CFS replica against a CFS primary' => sub {
    my $noncfs_install = $ENV{CFS_NON_CFS_INSTALL};
    unless (defined $noncfs_install
        && -d "$noncfs_install/bin"
        && -x "$noncfs_install/bin/postgres")
    {
        plan skip_all =>
          'CFS_NON_CFS_INSTALL does not point at a non-CFS install; '
          . 'skipping cross-build CFS mismatch test '
          . '(the single-build TAP harness cannot build a non-CFS binary)';
    }
 
    # Poll a node's logfile until $pattern appears or we time out.  The
    # node may be a standby that never accepts queries (it FATALs during
    # recovery), so we cannot use poll_query_until here.
    sub wait_log_like
    {
        my ($node, $pattern, $offset, $timeout) = @_;
 
        $timeout //= $PostgreSQL::Test::Utils::timeout_default;
        for (my $i = 0; $i < $timeout; $i++)
        {
            return 1 if $node->log_contains($pattern, $offset);
            sleep 1;
        }
        return 0;
    }
 
    # Primary uses the build under test (expected to be a CFS build).
    my $primary = PostgreSQL::Test::Cluster->new('mm_primary');
    $primary->init(has_archiving => 1, allows_streaming => 1);
    $primary->start;
 
    my $configure = $primary->safe_psql('postgres',
        "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'");
    if ($configure =~ /--without-dia-cfs/)
    {
        plan skip_all =>
          'build under test is itself non-CFS; it cannot act as a CFS primary';
    }
 
    # Sanity-check the second install really is a non-CFS build.
    my $noncfs_cfg = `$noncfs_install/bin/pg_config --configure`;
    if ($noncfs_cfg !~ /--without-dia-cfs/)
    {
        plan skip_all =>
          "CFS_NON_CFS_INSTALL is not a non-CFS build (configure: $noncfs_cfg)";
    }
 
    note("primary configure: $configure");
    note("non-CFS install:   $noncfs_install (configure: $noncfs_cfg)");
 
    # Detect an available codec for the primary, used only by the
    # redo-path phase (a real XLOG_SMGR_CFS_POLICY record is needed
    # there).
    my $algo;
    $algo = 'lz4' if $configure =~ /--with-lz4/;
    $algo //= 'zstd' if $configure =~ /--with-zstd/;
 
    # A clean base backup taken before any CFS relation exists serves both
    # phases: it carries neither the policy record nor CFS sidecar files.
    $primary->backup('clean_backup');
 
    # Part A: connect-time rejection (streaming).
    #
    # No CFS table is required: the primary reports dia_cfs=on merely by
    # being a CFS build (the GUC_REPORT parameter is sent during connection
    # startup), so a non-CFS standby must be rejected in libpqrcv_connect
    # before a single WAL record is streamed or replayed.
    {
        my $stb = PostgreSQL::Test::Cluster->new('mm_stream_standby',
            install_path => $noncfs_install);
        $stb->init_from_backup(
            $primary, 'clean_backup',
            has_streaming => 1,
            has_restoring => 0);
 
        # The standby itself stays up (recovery reaches consistency); it
        # is the walreceiver that keeps failing to connect.
        ok($stb->start,
            'non-CFS streaming standby starts (connect check is async)');
 
        ok( wait_log_like(
                $stb, qr/CFS support differs between primary and standby/),
            'non-CFS standby reports CFS build mismatch at connect time');
        ok(!$stb->log_contains(qr/unknown op code/),
            'no "unknown op code" PANIC on the streaming standby');
 
        $stb->stop('immediate');
    }
 
    # Part B: redo-time FATAL (archive recovery).
    #
    # A real XLOG_SMGR_CFS_POLICY record must be replayed, so the primary
    # needs a compression codec.  The non-CFS node recovers purely from the
    # WAL archive (no streaming connection, hence no connect-time check)
    # and must hit the policy record during redo.
  SKIP:
    {
        skip "no CFS compression codec on the primary", 2
          unless defined $algo;
 
        $primary->safe_psql('postgres',
            "CREATE TABLE mm_cfs(id int, p text) WITH (algorithm = '$algo')");
 
        # Force the segment carrying the policy record into the WAL
        # archive.
        my $walfile = $primary->safe_psql('postgres',
            "SELECT pg_walfile_name(pg_current_wal_lsn())");
        $primary->safe_psql('postgres', "SELECT pg_switch_wal()");
        $primary->poll_query_until('postgres',
            "SELECT '$walfile' <= last_archived_wal FROM pg_stat_archiver")
          or die "timed out waiting for the CFS policy WAL to be archived";
 
        my $node = PostgreSQL::Test::Cluster->new('mm_pitr_node',
            install_path => $noncfs_install);
        $node->init_from_backup(
            $primary, 'clean_backup',
            standby => 0,
            has_restoring => 1);
 
        # The node is expected to FATAL during initial redo, so a
        # "successful" start is neither required nor expected.
        $node->start(fail_ok => 1);
 
        ok( wait_log_like($node, qr/cannot replay CFS WAL record/),
            'non-CFS node FATALs with a clear message on the CFS policy record'
        );
        ok( !$node->log_contains(qr/PANIC: smgr_redo: unknown op code/),
            'no "smgr_redo: unknown op code" PANIC on the redo path');
 
        $node->teardown_node(fail_ok => 1);
    }
 
    $primary->stop('fast');
};
 
# ---------------------------------------------------------------------------
# Hot standby recovery conflicts on CFS tables.
#
# The CFS concern is that buffer-pin and snapshot conflicts on
# decompressed CFS pages must cancel the standby query correctly, and the
# CFS map cache must not leak or corrupt during conflict resolution.
#
# Two conflict types are tested:
#   1. Buffer pin conflict: a cursor on the standby pins a CFS page;
#      VACUUM FREEZE on the primary needs that pin.
#   2. Snapshot conflict: a cursor on the standby holds a snapshot that
#      prevents pruning of dead HOT tuples on a CFS table on the primary.
#
# Each conflict is verified three ways:
#   * check_conflict_log — the standby log contains the exact cancellation
#     message;
#   * check_conflict_stat — pg_stat_database_conflicts shows the conflict
#     type counter incremented;
#   * $psql_standby->reconnect_and_clear — the standby session was
#     actually broken and needs reconnection.
# ---------------------------------------------------------------------------
subtest 'hot standby recovery conflicts on CFS tables' => sub {
    # Set up nodes
    my $node_primary = PostgreSQL::Test::Cluster->new('cfs_confl_primary');
    $node_primary->init(allows_streaming => 1);
 
    $node_primary->append_conf(
        'postgresql.conf', qq[
max_prepared_transactions = 10
max_standby_streaming_delay = 50ms
log_recovery_conflict_waits = on
deadlock_timeout = 10ms
]);
    $node_primary->start;
 
    # Skip when LZ4 is not compiled in
    my $configure = $node_primary->safe_psql('postgres',
        "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'");
    if ($configure !~ /--with-lz4/)
    {
        plan skip_all =>
          'LZ4 support not built, skipping CFS recovery conflict test';
    }
 
    my $backup_name = 'my_backup';
    $node_primary->backup($backup_name);
 
    my $node_standby = PostgreSQL::Test::Cluster->new('cfs_confl_standby');
    $node_standby->init_from_backup($node_primary, $backup_name,
        has_streaming => 1);
    $node_standby->append_conf('postgresql.conf',
        'max_standby_streaming_delay = 50ms');
    $node_standby->start;
 
    my $test_db = "cfs_conflict_db";
 
    # Use a dedicated database so pg_stat_database_conflicts is isolated.
    $node_primary->safe_psql('postgres', "CREATE DATABASE $test_db");
 
    # CFS table with data.  The (a int, b int) layout allows HOT updates
    # in the snapshot test.
    my $table1 = "cfs_conflict_t1";
    $node_primary->safe_psql(
        $test_db, qq[
CREATE TABLE $table1(a int, b int) WITH (algorithm = 'lz4');
INSERT INTO $table1 SELECT i % 3, 0 FROM generate_series(1, 20) i;
]);
    $node_primary->wait_for_replay_catchup($node_standby);
 
    # Long-running background psql on the standby for triggering
    # conflicts.
    my $psql_standby =
      $node_standby->background_psql($test_db, on_error_stop => 0);
 
    my $cursor1 = "cfs_conflict_cursor";
 
    # CONFLICT 1: Buffer pin conflict
    #
    # An aborted INSERT on the primary creates a dead tuple.  A cursor on
    # the standby pins the buffer of that page.  VACUUM FREEZE on the
    # primary needs the pin to prune the dead tuple, triggering a
    # buffer-pin conflict on a decompressed CFS page.
    my $sect = "buffer pin conflict";
 
    # Aborted INSERT + flush (LOCK ensures the WAL is flushed).
    $node_primary->safe_psql(
        $test_db, qq[
BEGIN;
INSERT INTO $table1 VALUES (1, 0);
ROLLBACK;
BEGIN; LOCK $table1; COMMIT;
]);
    $node_primary->wait_for_replay_catchup($node_standby);
 
    # Pin the CFS page on the standby via a cursor.
    my $res = $psql_standby->query_safe(
        qq[
BEGIN;
DECLARE $cursor1 CURSOR FOR SELECT b FROM $table1;
FETCH FORWARD FROM $cursor1;
]);
    like($res, qr/^0$/m, "$sect: cursor with conflicting pin established");
 
    # Record the current standby log offset for conflict-message scanning.
    my $log_location = -s $node_standby->logfile;
 
    my $check_conflict_log = sub {
        my $message = shift;
        my $old_log_location = $log_location;
 
        $log_location =
          $node_standby->wait_for_log(qr/$message/, $log_location);
 
        cmp_ok($log_location, '>', $old_log_location,
            "$sect: logfile contains terminated connection due to recovery conflict"
        );
    };
 
    my $check_conflict_stat = sub {
        my $conflict_type = shift;
        my $count = $node_standby->safe_psql($test_db,
            qq[SELECT confl_$conflict_type FROM pg_stat_database_conflicts WHERE datname='$test_db';]
        );
 
        is($count, 1, "$sect: stats show conflict on standby");
    };
 
    # VACUUM FREEZE needs the pinned buffer.
    $node_primary->safe_psql($test_db, "VACUUM FREEZE $table1;");
    $node_primary->wait_for_replay_catchup($node_standby);
 
    # The standby session must have been cancelled with the buffer-pin
    # message.
    $check_conflict_log->("User was holding shared buffer pin for too long");
    $psql_standby->reconnect_and_clear();
    $check_conflict_stat->("bufferpin");
 
    # CONFLICT 2: Snapshot conflict
    #
    # A cursor on the standby holds a snapshot.  HOT updates + VACUUM
    # FREEZE on the primary prune dead tuples that the standby snapshot
    # still needs to see, triggering a snapshot conflict on a decompressed
    # CFS page.
    $sect = "snapshot conflict";
 
    # More rows so there is something to HOT-update.
    $node_primary->safe_psql($test_db,
        qq[INSERT INTO $table1 SELECT i, 0 FROM generate_series(1, 20) i]);
    $node_primary->wait_for_replay_catchup($node_standby);
 
    # Establish a snapshot on the standby.
    $res = $psql_standby->query_safe(
        qq[
BEGIN;
DECLARE $cursor1 CURSOR FOR SELECT b FROM $table1;
FETCH FORWARD FROM $cursor1;
]);
    like($res, qr/^0$/m,
        "$sect: cursor with conflicting snapshot established");
 
    # HOT updates create dead tuples that VACUUM will prune.
    $node_primary->safe_psql($test_db,
        qq[UPDATE $table1 SET a = a + 1 WHERE a > 2;]);
    $node_primary->safe_psql($test_db, "VACUUM FREEZE $table1;");
    $node_primary->wait_for_replay_catchup($node_standby);
 
    # The standby session must have been cancelled with the snapshot
    # message.
    $check_conflict_log->(
        "User query might have needed to see row versions that must be removed"
    );
    $psql_standby->reconnect_and_clear();
    $check_conflict_stat->("snapshot");
 
    # Verify CFS sidecars are structurally valid after all conflict churn.
    $node_primary->safe_psql($test_db, "CHECKPOINT;");
    $node_primary->wait_for_replay_catchup($node_standby);
    my $result = $node_standby->safe_psql($test_db,
        "SELECT ok FROM pg_cfs_check('$table1'::regclass, true);");
    is($result, 't', 'CFS sidecars valid after recovery conflicts');
 
    # Total conflict count should be 2.
    $result = $node_standby->safe_psql($test_db,
        qq[SELECT conflicts FROM pg_stat_database WHERE datname='$test_db';]);
    is($result, '2', "2 recovery conflicts shown in pg_stat_database");
 
    $psql_standby->quit;
    $node_standby->stop();
    $node_primary->stop();
};
 
# ---------------------------------------------------------------------------
# Physical replication slot and checkpoints on a primary with CFS tables.
#
# A physical replication slot must maintain correct WAL retention across
# checkpoints.  The CFS concern is that the checkpoint flush of .cfsmap
# sidecars happens in the correct order relative to the slot's
# restart_lsn, so the standby can always read consistent CFS data.
# ---------------------------------------------------------------------------
subtest 'physical replication slot and checkpoints on a CFS primary' => sub {
    # Primary with a physical replication slot
    my $node_primary = PostgreSQL::Test::Cluster->new('cfs_slot_primary');
    $node_primary->init(allows_streaming => 1);
    $node_primary->append_conf('postgresql.conf', "checkpoint_timeout = 30s");
    $node_primary->start;
 
    # Skip when LZ4 is not compiled in
    my $configure = $node_primary->safe_psql('postgres',
        "SELECT setting FROM pg_config WHERE name = 'CONFIGURE'");
    if ($configure !~ /--with-lz4/)
    {
        plan skip_all =>
          'LZ4 support not built, skipping CFS checkpoint slot test';
    }
 
    # CFS table
    $node_primary->safe_psql(
        'postgres', qq{
CREATE TABLE cfs_slot (id int, payload text) WITH (algorithm = 'lz4');
INSERT INTO cfs_slot SELECT g, md5(g::text) FROM generate_series(1, 200) g;
CHECKPOINT;
});
 
    # Create a physical replication slot
    $node_primary->safe_psql('postgres',
        "SELECT pg_create_physical_replication_slot('slot1');");
 
    my $backup_name = 'my_backup';
    $node_primary->backup($backup_name);
 
    # Standby using the slot
    my $node_standby = PostgreSQL::Test::Cluster->new('cfs_slot_standby');
    $node_standby->init_from_backup($node_primary, $backup_name,
        has_streaming => 1);
    $node_standby->append_conf('postgresql.conf',
        "primary_slot_name = 'slot1'");
    $node_standby->start;
 
    # Wait for catch-up
    $node_primary->wait_for_replay_catchup($node_standby);
 
    # Write more data, then checkpoint (flushes .cfsmap, advances slot
    # restart_lsn)
    for my $round (1 .. 3)
    {
        $node_primary->safe_psql('postgres',
            "INSERT INTO cfs_slot VALUES (1000 + $round, md5('round${round}'));"
        );
        $node_primary->safe_psql('postgres', 'CHECKPOINT;');
        $node_primary->wait_for_replay_catchup($node_standby);
    }
 
    # Verify the standby sees all the data through CFS decompression
    my $result =
      $node_standby->safe_psql('postgres', "SELECT count(*) FROM cfs_slot;");
    is($result, '203',
        'Standby via physical slot sees 203 CFS rows after checkpoints');
 
    my $primary_md5 = $node_primary->safe_psql('postgres',
        "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_slot;");
    my $standby_md5 = $node_standby->safe_psql('postgres',
        "SELECT md5(string_agg(payload, '' ORDER BY id)) FROM cfs_slot;");
    is($standby_md5, $primary_md5,
        'Standby CFS data matches primary across checkpoint/slot cycles');
 
    # Structural check on standby
    $result = $node_standby->safe_psql('postgres',
        "SELECT ok FROM pg_cfs_check('cfs_slot'::regclass, true);");
    is($result, 't', 'CFS sidecars valid on standby after checkpoint cycles');
 
    # Verify the slot's restart_lsn advanced (WAL was not retained
    # unnecessarily)
    $result = $node_primary->safe_psql('postgres',
        "SELECT restart_lsn IS NOT NULL FROM pg_replication_slots WHERE slot_name = 'slot1';"
    );
    is($result, 't',
        'Physical slot has a valid restart_lsn after CFS checkpoints');
 
    $node_standby->stop;
    $node_primary->stop;
};
 
# ---------------------------------------------------------------------------
# DROP DATABASE must cancel the pending CFS sidecar fsync requests of the
# dropped database on a standby, mirroring what ForgetDatabaseSyncRequests()
# does for md.c.
#
# XLOG_DBASE_DROP replay removes the database directory outright, with no
# checkpoint in between, while the checkpointer's pendingOps may still hold
# the CFS fsync requests of the dropped database — e.g. the ones registered
# when the standby replayed the creation of a CFS relation (sidecar
# materialization registers .cfp/.cfsmap/.cfsjrn).  Without a cancellation
# the next restartpoint tries to fsync the already-removed sidecar files and
# escalates through data_sync_elevel() to PANIC.
#
# The primary-side DROP path cannot reproduce this: its forced checkpoint
# runs before the files are removed and drains the queue while the files
# still exist.  fsync is enabled (TAP clusters default to fsync = off,
# which makes ProcessSyncRequests skip the fsync stage entirely).
# ---------------------------------------------------------------------------
{
    my $primary = PostgreSQL::Test::Cluster->new('dropdb_primary');
    $primary->init(allows_streaming => 1);
    $primary->append_conf('postgresql.conf',
        "checkpoint_timeout = 30s\nfsync = on");
    $primary->start;
 
    $primary->backup('dropdb_backup');
    my $standby = PostgreSQL::Test::Cluster->new('dropdb_standby');
    $standby->init_from_backup($primary, 'dropdb_backup', has_streaming => 1);
    $standby->append_conf('postgresql.conf',
        "checkpoint_timeout = 30s\nfsync = on");
    $standby->start;
 
    # A separate database with a CFS table and some dirty pages.
    $primary->safe_psql('postgres', 'CREATE DATABASE dropdb_cfs');
    $primary->safe_psql('dropdb_cfs',
        "CREATE TABLE drop_t (id int, data text) WITH (algorithm = 'lz4')");
    $primary->safe_psql('dropdb_cfs',
            "INSERT INTO drop_t SELECT g, repeat('x', 200) "
          . "FROM generate_series(1, 50) g");
 
    # Checkpoint the primary so the standby's CHECKPOINT below performs a
    # real restartpoint, then drain the queue: this restartpoint fsyncs
    # (through the sync queue) everything the standby has replayed so far.
    # It doubles as the control case: pending requests for a live database
    # must fsync fine.
    $primary->safe_psql('postgres', 'CHECKPOINT');
    $primary->wait_for_catchup($standby);
    $standby->safe_psql('postgres', 'CHECKPOINT');
    pass('restartpoint succeeds for pending CFS requests of a live database');
 
    # Register fresh CFS fsync requests on the standby: replaying the
    # creation of another CFS relation materializes its sidecars and
    # registers them with the checkpointer.  These requests are the tail
    # the next restartpoint would fsync.
    $primary->safe_psql('dropdb_cfs',
        "CREATE TABLE late_t (id int) WITH (algorithm = 'lz4')");
    $primary->wait_for_catchup($standby);
 
    # Drop the database on the primary.  On the standby, XLOG_DBASE_DROP
    # replay removes the whole database directory (rmtree before any
    # checkpoint), while the CFS fsync requests of the dropped database are
    # still queued — the redo path must cancel them.
    $primary->safe_psql('postgres', 'DROP DATABASE dropdb_cfs');
    $primary->wait_for_catchup($standby);
 
    # The next restartpoint: use the non-fatal psql() so a PANIC (which
    # tears the connection down) does not abort the harness.
    my ($ret, $stdout, $stderr) = $standby->psql('postgres', 'CHECKPOINT');
    is($ret, 0,
        'restartpoint succeeds after DROP DATABASE cancelled CFS sync requests'
    );
 
    if ($ret == 0)
    {
        my $log = $standby->log_content();
 
        unlike($log, qr/PANIC/,
            'no PANIC on a restartpoint after a dropped CFS database');
 
        is( $standby->safe_psql(
                'postgres',
                'SELECT count(*) FROM pg_database WHERE datname = \'dropdb_cfs\''
            ),
            '0',
            'dropped database is gone on the standby');
 
        $standby->stop('fast');
    }
    else
    {
        # Red branch (the bug this test guards against): the restartpoint
        # tried to fsync the sidecars of the removed database.
        like(
            $standby->log_content(),
            qr/PANIC:  could not fsync file ".*\.cfs/,
            'the restartpoint tried to fsync the removed CFS sidecars');
 
        $standby->stop('immediate', fail_ok => 1);
    }
 
    $primary->stop('fast');
}
 
# ---------------------------------------------------------------------------
# Session-level default GUCs of the writer never stick to the standby.
#
# The runtime level resolve happens in the WRITING backend: the level is
# applied when the page is compressed and is not recorded anywhere on
# disk (the .cfp record header stores the algorithm only; decompression
# never needs the level).  The WAL policy record carries just the
# explicit catalog keys with their set-flags, so the writer session's
# cfs_default_*_level value must not leak to the standby: a standby
# session resolves the unset fields from its OWN GUCs, and the stored
# policy shows the 0 sentinel rather than the writer's value.
# ---------------------------------------------------------------------------
{
    my $primary = PostgreSQL::Test::Cluster->new('cfs_guc_leak');
    $primary->init(allows_streaming => 1);
    $primary->start;
 
    # Skip when ZSTD is not compiled in (the block cannot run, and the
    # TAP plan has already started, so skip quietly instead of skip_all).
    my $zstd_ok =
      $primary->psql('postgres',
        "CREATE TABLE guc_probe_avail (i int) WITH (algorithm = 'zstd')") == 0;
 
    if ($zstd_ok)
    {
        $primary->safe_psql('postgres', 'DROP TABLE guc_probe_avail');
 
        $primary->backup('guc_leak_backup');
        my $standby = PostgreSQL::Test::Cluster->new('cfs_guc_leak_standby');
        $standby->init_from_backup($primary, 'guc_leak_backup',
            has_streaming => 1);
        $standby->start;
 
        # The writer compresses with a non-default session level.
        $primary->safe_psql('postgres',
                "CREATE TABLE guc_t (id int, payload text) "
              . "WITH (algorithm = 'zstd')");
        $primary->safe_psql('postgres',
                "SET cfs_default_zstd_level = 19; "
              . "INSERT INTO guc_t SELECT g, 'row ' || g "
              . "FROM generate_series(1, 50) g");
 
        $primary->wait_for_catchup($standby);
 
        # The replayed data is readable on the standby (the compressed
        # pages decode without any level knowledge).
        is($standby->safe_psql('postgres',
                "SELECT count(*) FILTER (WHERE payload = 'row 7') FROM guc_t"),
            '1',
            'pages written under a non-default GUC level replay and read on the standby');
 
        # The writer's GUC value did not stick: the stored policy keeps
        # the 0 sentinel for the unset level, and a standby session
        # resolves the field from its OWN (default) GUCs.
        is($standby->safe_psql('postgres',
                "SELECT level FROM pg_cfs_settings WHERE relname = 'guc_t'"),
            '0',
            'stored policy carries the 0 sentinel, not the writer GUC level');
        is($standby->safe_psql('postgres',
                "SELECT level_effective FROM pg_cfs_relation_info('guc_t')"),
            '3',
            'standby session resolves the unset level from its own GUCs');
 
        $standby->stop('fast');
    }
    else
    {
        diag 'zstd not available, skipping the GUC-leak block';
    }
 
    $primary->stop('fast');
}
 
done_testing();