Исходный код СУБД 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
# Copyright (c) 2026, Kirillov Vyacheslav by AI, QDB Development Group
#
# src/test/recovery/t/508_cfs_wal.pl
#
# WAL generation, replay and decoding for CFS-compressed relations.
#
# The scenarios cover: WAL-skip optimizations for new relfilenodes (when
# a transaction skips WAL for a relfilenode it created, the commit is
# responsible for getting the sidecar trio to durable storage — checked
# under wal_level=minimal and wal_level=replica with an immediate
# shutdown in between), relfilenode reuse (database drop/recreate with
# the same OID, VACUUM FULL, REINDEX, tablespace moves — no stale
# sidecar state may leak into a relation reusing the number), replay of
# CREATE/DROP DATABASE/TABLESPACE records against already-removed
# directories, replay of PRUNE/TRUNCATE/DROP records against truncated
# or dropped relations, and logical decoding from a CFS table across a
# restart.  Surviving relations are checked for contents and sidecar
# integrity; dropped ones must not leave orphaned sidecar files behind.
 
use strict;
use warnings FATAL => 'all';
 
use PostgreSQL::Test::Cluster;
use PostgreSQL::Test::Utils;
use Test::More;
 
# No CFS sidecar file in pg_default may reference a relfilenode that is
# not alive in pg_class.
sub check_orphan_cfs_sidecars
{
    local $Test::Builder::Level = $Test::Builder::Level + 1;
 
    my ($node, $test_name) = @_;
 
    my $db_oid = $node->safe_psql('postgres',
        "SELECT oid FROM pg_database WHERE datname = 'postgres'");
    my $prefix = "base/$db_oid/";
 
    # Base names of all sidecar files on disk.
    my %on_disk;
    for my $f (
        grep(/\.(cfp|cfsmap|cfsjrn)(\.[0-9]+)?$/,
            slurp_dir($node->data_dir . "/$prefix")))
    {
        $f =~ s/\.(cfp|cfsmap|cfsjrn)(\.[0-9]+)?$//;
        $on_disk{$f} = 1;
    }
 
    # Relfilenodes of all non-temp relations in pg_default.
    my %alive;
    for my $r (
        split /\n/,
        $node->safe_psql(
            'postgres', "
           SELECT relfilenode::text FROM pg_class
           WHERE reltablespace = 0 AND relpersistence <> 't';"))
    {
        $alive{$r} = 1;
    }
 
    my @orphans = sort grep { !$alive{$_} } keys %on_disk;
    is_deeply(\@orphans, [], $test_name);
    return;
}
 
# ----------------------------------------------------------------------
# WAL-skip optimizations on CFS relations.  Each scenario commits,
# crashes with an immediate shutdown and then verifies not just the rows
# but also the structural integrity of the sidecars — and that no
# orphaned .cfp/.cfsmap/.cfsjrn files are left behind in pg_default.
# Runs under both wal_level=minimal and wal_level=replica.
# ----------------------------------------------------------------------
sub run_cfs_wal_optimize
{
    my $wal_level = shift;
 
    my $node = PostgreSQL::Test::Cluster->new("node_$wal_level");
    $node->init;
    $node->append_conf(
        'postgresql.conf', qq(
wal_level = $wal_level
wal_log_hints = on
wal_skip_threshold = 0
));
    $node->start;
 
    my $tablespace_dir = $node->basedir . '/tablespace_other';
    mkdir($tablespace_dir);
    $node->safe_psql('postgres',
        "CREATE TABLESPACE other LOCATION '$tablespace_dir'");
 
    # Data file for the COPY commands below.
    my $copy_file = $node->basedir . "/copy_data.txt";
    PostgreSQL::Test::Utils::append_to_file(
        $copy_file, qq(20000,30000
20001,30001
20002,30002));
 
    # CREATE + TRUNCATE + INSERT in one transaction: everything happens
    # on a relfilenode for which WAL was skipped.
    $node->safe_psql(
        'postgres', "
        BEGIN;
        CREATE TABLE trunc_ins (id serial PRIMARY KEY, payload text)
          WITH (algorithm = 'lz4');
        INSERT INTO trunc_ins SELECT g, md5(g::text)
          FROM generate_series(1, 1000) g;
        TRUNCATE trunc_ins;
        INSERT INTO trunc_ins SELECT g, md5(g::text)
          FROM generate_series(2001, 2100) g;
        COMMIT;");
    $node->stop('immediate');
    $node->start;
    is( $node->safe_psql(
            'postgres', "SELECT count(*), min(id) FROM trunc_ins"),
        qq(100|2001),
        "wal_level = $wal_level, TRUNCATE INSERT");
    is( $node->safe_psql(
            'postgres',
            "SELECT ok FROM pg_cfs_check('trunc_ins'::regclass, true)"),
        't',
        "wal_level = $wal_level, TRUNCATE INSERT sidecars");
 
    # CREATE + COPY (bulk, WAL-skipped) + INSERT in one transaction.
    $node->safe_psql(
        'postgres', "
        BEGIN;
        CREATE TABLE ins_copy (id int, id2 int) WITH (algorithm = 'zstd');
        INSERT INTO ins_copy VALUES (1, 1);
        COPY ins_copy FROM '$copy_file' DELIMITER ',';
        COMMIT;");
    $node->stop('immediate');
    $node->start;
    is($node->safe_psql('postgres', "SELECT count(*) FROM ins_copy"),
        qq(4), "wal_level = $wal_level, INSERT COPY");
    is( $node->safe_psql(
            'postgres',
            "SELECT ok FROM pg_cfs_check('ins_copy'::regclass, true)"),
        't',
        "wal_level = $wal_level, INSERT COPY sidecars");
 
    # SET TABLESPACE on a CFS table rolled back in a subtransaction:
    # the sidecars must stay in pg_default.
    $node->safe_psql(
        'postgres', "
        BEGIN;
        CREATE TABLE spc_abort (id serial PRIMARY KEY, id2 int)
          WITH (algorithm = 'lz4');
        INSERT INTO spc_abort VALUES (DEFAULT, generate_series(1,3000));
        TRUNCATE spc_abort;
        SAVEPOINT s;
          ALTER TABLE spc_abort SET TABLESPACE other; ROLLBACK TO s;
        COPY spc_abort FROM '$copy_file' DELIMITER ',';
        COMMIT;");
    $node->stop('immediate');
    $node->start;
    is($node->safe_psql('postgres', "SELECT count(*) FROM spc_abort"),
        qq(3), "wal_level = $wal_level, SET TABLESPACE abort subtransaction");
    is( $node->safe_psql(
            'postgres',
            "SELECT ok FROM pg_cfs_check('spc_abort'::regclass, true)"),
        't',
        "wal_level = $wal_level, SET TABLESPACE abort sidecars");
 
    # Same, but the move is committed: the sidecars must follow into the
    # other tablespace.
    $node->safe_psql(
        'postgres', "
        BEGIN;
        CREATE TABLE spc_commit (id serial PRIMARY KEY, id2 int)
          WITH (algorithm = 'lz4');
        INSERT INTO spc_commit VALUES (DEFAULT, generate_series(1,3000));
        TRUNCATE spc_commit;
        SAVEPOINT s; ALTER TABLE spc_commit SET TABLESPACE other; RELEASE s;
        COPY spc_commit FROM '$copy_file' DELIMITER ',';
        COMMIT;");
    $node->stop('immediate');
    $node->start;
    is($node->safe_psql('postgres', "SELECT count(*) FROM spc_commit"),
        qq(3),
        "wal_level = $wal_level, SET TABLESPACE commit subtransaction");
    is( $node->safe_psql(
            'postgres',
            "SELECT ok FROM pg_cfs_check('spc_commit'::regclass, true)"),
        't',
        "wal_level = $wal_level, SET TABLESPACE commit sidecars");
 
    # Sidecar files must not be orphaned in pg_default by any of the
    # relfilenode swaps above (file removal is checkpoint-deferred).
    $node->safe_psql('postgres', 'CHECKPOINT');
    check_orphan_cfs_sidecars($node,
        "wal_level = $wal_level, no orphan CFS sidecars remain");
 
    $node->stop('fast');
 
    return;
}
 
run_cfs_wal_optimize("minimal");
run_cfs_wal_optimize("replica");
 
# ----------------------------------------------------------------------
# Relfilenode reuse: CFS sidecar files must survive the core
# relfilenode-reuse scenarios without stale-state confusion — DROP
# DATABASE + CREATE DATABASE reusing the same database OID, VACUUM FULL,
# and ALTER DATABASE ... SET TABLESPACE.  Content checks are paired with
# pg_cfs_check() on both primary and standby.
# ----------------------------------------------------------------------
my $psql_timeout;
 
# Send query, wait until string matches
sub send_query_and_wait
{
    my ($psql, $query, $untl) = @_;
 
    # For each query we run, we'll restart the timeout.  Otherwise the
    # timeout would apply to the whole test script, and would need to be
    # set very high to survive when running under Valgrind.
    $psql_timeout->reset();
    $psql_timeout->start();
 
    # send query
    $$psql{stdin} .= $query;
    $$psql{stdin} .= "\n";
 
    # wait for query results
    $$psql{run}->pump_nb();
    while (1)
    {
        last if $$psql{stdout} =~ /$untl/;
 
        if ($psql_timeout->is_expired)
        {
            BAIL_OUT("aborting wait: program timed out\n"
                  . "stream contents: >>$$psql{stdout}<<\n"
                  . "pattern searched for: $untl\n");
            return 0;
        }
        if (not $$psql{run}->pumpable())
        {
            BAIL_OUT("aborting wait: program died\n"
                  . "stream contents: >>$$psql{stdout}<<\n"
                  . "pattern searched for: $untl\n");
            return 0;
        }
        $$psql{run}->pump();
    }
 
    $$psql{stdout} = '';
 
    return 1;
}
 
sub cause_eviction
{
    my ($psql_primary, $psql_standby) = @_;
 
    send_query_and_wait(
        $psql_primary,
        q[SELECT SUM(pg_prewarm(oid)) warmed_buffers FROM pg_class WHERE pg_relation_filenode(oid) != 0;],
        qr/warmed_buffers/m);
 
    send_query_and_wait(
        $psql_standby,
        q[SELECT SUM(pg_prewarm(oid)) warmed_buffers FROM pg_class WHERE pg_relation_filenode(oid) != 0;],
        qr/warmed_buffers/m);
}
 
sub verify
{
    my ($primary, $standby, $counter, $message) = @_;
 
    my $query =
      "SELECT datab, count(*) FROM large GROUP BY 1 ORDER BY 1 LIMIT 10";
    is($primary->safe_psql('conflict_db', $query),
        "$counter|4000", "primary: $message");
    is( $primary->safe_psql(
            'conflict_db',
            "SELECT ok FROM pg_cfs_check('large'::regclass, true)"),
        't',
        "primary sidecars: $message");
 
    $primary->wait_for_catchup($standby);
    is($standby->safe_psql('conflict_db', $query),
        "$counter|4000", "standby: $message");
    is( $standby->safe_psql(
            'conflict_db',
            "SELECT ok FROM pg_cfs_check('large'::regclass, true)"),
        't',
        "standby sidecars: $message");
}
 
{
    my $node_primary = PostgreSQL::Test::Cluster->new('reuse_primary');
    $node_primary->init(allows_streaming => 1);
    $node_primary->append_conf(
        'postgresql.conf', q[
allow_in_place_tablespaces = true
log_connections=receipt
# to avoid "repairing" corruption
full_page_writes=off
log_min_messages=debug2
shared_buffers=1MB
]);
    $node_primary->start;
 
    # Create streaming standby linking to primary
    my $backup_name = 'my_backup';
    $node_primary->backup($backup_name);
    my $node_standby = PostgreSQL::Test::Cluster->new('reuse_standby');
    $node_standby->init_from_backup($node_primary, $backup_name,
        has_streaming => 1);
    $node_standby->start;
 
    # We'll reset this timeout for each individual query we run.
    $psql_timeout =
      IPC::Run::timer($PostgreSQL::Test::Utils::timeout_default);
 
    my %psql_primary = (stdin => '', stdout => '', stderr => '');
    $psql_primary{run} = IPC::Run::start(
        [
            'psql', '--no-psqlrc', '--no-align',
            '--file' => '-',
            '--dbname' => $node_primary->connstr('postgres')
        ],
        '<' => \$psql_primary{stdin},
        '>' => \$psql_primary{stdout},
        '2>' => \$psql_primary{stderr},
        $psql_timeout);
 
    my %psql_standby = ('stdin' => '', 'stdout' => '', 'stderr' => '');
    $psql_standby{run} = IPC::Run::start(
        [
            'psql', '--no-psqlrc', '--no-align',
            '--file' => '-',
            '--dbname' => $node_standby->connstr('postgres')
        ],
        '<' => \$psql_standby{stdin},
        '>' => \$psql_standby{stdout},
        '2>' => \$psql_standby{stderr},
        $psql_timeout);
 
    # Create template database with a table that we'll update, to trigger
    # dirty rows.  Using a template database + preexisting rows makes it
    # a bit easier to reproduce, because there's no cache invalidations
    # generated.
    $node_primary->safe_psql('postgres',
        "CREATE DATABASE conflict_db_template OID = 50000;");
    $node_primary->safe_psql(
        'conflict_db_template', q[
    CREATE TABLE large(id serial primary key, dataa text, datab text) WITH (algorithm = 'lz4');
    INSERT INTO large(dataa, datab) SELECT g.i::text, 1 FROM generate_series(1, 4000) g(i);]
    );
    $node_primary->safe_psql('postgres',
        "CREATE DATABASE conflict_db TEMPLATE conflict_db_template OID = 50001;"
    );
 
    $node_primary->safe_psql(
        'postgres', q[
    CREATE EXTENSION pg_prewarm;
    CREATE TABLE replace_sb(data text);
    INSERT INTO replace_sb(data) SELECT random()::text FROM generate_series(1, 15000);]
    );
 
    $node_primary->wait_for_catchup($node_standby);
 
    # Use longrunning transactions, so that AtEOXact_SMgr doesn't close
    # files
    send_query_and_wait(\%psql_primary, q[BEGIN;], qr/BEGIN/m);
    send_query_and_wait(\%psql_standby, q[BEGIN;], qr/BEGIN/m);
 
    # Cause lots of dirty rows in shared_buffers
    $node_primary->safe_psql('conflict_db', "UPDATE large SET datab = 1;");
 
    # Now do a bunch of work in another database.  That will end up
    # needing to write back dirty data from the previous step, opening
    # the relevant file descriptors
    cause_eviction(\%psql_primary, \%psql_standby);
 
    # drop and recreate database
    $node_primary->safe_psql('postgres', "DROP DATABASE conflict_db;");
    $node_primary->safe_psql('postgres',
        "CREATE DATABASE conflict_db TEMPLATE conflict_db_template OID = 50001;"
    );
 
    verify($node_primary, $node_standby, 1, "initial contents as expected");
 
    # Again cause lots of dirty rows in shared_buffers, but use a
    # different update value so we can check everything is OK
    $node_primary->safe_psql('conflict_db', "UPDATE large SET datab = 2;");
 
    # Again cause a lot of IO.  That'll again write back dirty data, but
    # uses newly opened file descriptors, so we don't confuse old files
    # with new files despite recycling relfilenodes.
    cause_eviction(\%psql_primary, \%psql_standby);
 
    verify($node_primary, $node_standby, 2,
        "update to reused relfilenode (due to DB oid conflict) is not lost");
 
    $node_primary->safe_psql('conflict_db', "VACUUM FULL large;");
    $node_primary->safe_psql('conflict_db', "UPDATE large SET datab = 3;");
 
    verify($node_primary, $node_standby, 3, "restored contents as expected");
 
    # Test for old filehandles after moving a database in / out of
    # tablespace
    $node_primary->safe_psql('postgres',
        q[CREATE TABLESPACE test_tablespace LOCATION '']);
 
    # cause dirty buffers
    $node_primary->safe_psql('conflict_db', "UPDATE large SET datab = 4;");
    # cause files to be opened in backend in other database
    cause_eviction(\%psql_primary, \%psql_standby);
 
    # move database back / forth
    $node_primary->safe_psql('postgres',
        'ALTER DATABASE conflict_db SET TABLESPACE test_tablespace');
    $node_primary->safe_psql('postgres',
        'ALTER DATABASE conflict_db SET TABLESPACE pg_default');
 
    # cause dirty buffers
    $node_primary->safe_psql('conflict_db', "UPDATE large SET datab = 5;");
    cause_eviction(\%psql_primary, \%psql_standby);
 
    verify($node_primary, $node_standby, 5, "post move contents as expected");
 
    $node_primary->safe_psql('postgres',
        'ALTER DATABASE conflict_db SET TABLESPACE test_tablespace');
 
    $node_primary->safe_psql('conflict_db', "UPDATE large SET datab = 7;");
    cause_eviction(\%psql_primary, \%psql_standby);
    $node_primary->safe_psql('conflict_db', "UPDATE large SET datab = 8;");
    $node_primary->safe_psql('postgres', 'DROP DATABASE conflict_db');
    $node_primary->safe_psql('postgres', 'DROP TABLESPACE test_tablespace');
 
    $node_primary->safe_psql('postgres', 'REINDEX TABLE pg_database');
 
    # explicitly shut down psql instances gracefully - to avoid hangs
    # or worse on windows
    $psql_primary{stdin} .= "\\q\n";
    $psql_primary{run}->finish;
    $psql_standby{stdin} .= "\\q\n";
    $psql_standby{run}->finish;
 
    $node_primary->stop();
    $node_standby->stop();
 
    # Make sure that there weren't crashes during shutdown
    command_like(
        [ 'pg_controldata', $node_primary->data_dir ],
        qr/Database cluster state:\s+shut down\n/,
        'primary shut down ok');
    command_like(
        [ 'pg_controldata', $node_standby->data_dir ],
        qr/Database cluster state:\s+shut down in recovery\n/,
        'standby shut down ok');
}
 
# ----------------------------------------------------------------------
# Replay of tablespace/database create/drop with CFS relations inside.
# The standby is crashed so that CREATE/DROP WAL records replay against
# already-removed directories; after replay the standby must not only
# start — it must have removed the sidecar files together with the
# relations.  No orphaned sidecar may survive in the standby's
# pg_default.
# ----------------------------------------------------------------------
sub test_tablespace
{
    my ($strategy) = @_;
 
    my $node_primary = PostgreSQL::Test::Cluster->new("primary1_$strategy");
    $node_primary->init(allows_streaming => 1);
    $node_primary->start;
    $node_primary->psql(
        'postgres',
        qq[
            SET allow_in_place_tablespaces=on;
            CREATE TABLESPACE dropme_ts1 LOCATION '';
            CREATE TABLESPACE dropme_ts2 LOCATION '';
            CREATE TABLESPACE source_ts  LOCATION '';
            CREATE TABLESPACE target_ts  LOCATION '';
            CREATE DATABASE template_db IS_TEMPLATE = true;
            SELECT pg_create_physical_replication_slot('slot', true);
        ]);
    my $backup_name = 'my_backup';
    $node_primary->backup($backup_name);
 
    my $node_standby = PostgreSQL::Test::Cluster->new("standby2_$strategy");
    $node_standby->init_from_backup($node_primary, $backup_name,
        has_streaming => 1);
    $node_standby->append_conf('postgresql.conf',
        "allow_in_place_tablespaces = on");
    $node_standby->append_conf('postgresql.conf', "primary_slot_name = slot");
    $node_standby->start;
 
    # Make sure the connection is made
    $node_primary->wait_for_catchup($node_standby, 'write');
 
    # CFS tables: one inside the tablespace that will be dropped, one in
    # pg_default of the postgres database.
    $node_primary->safe_psql(
        'postgres',
        q[
            CREATE TABLE t_cfs_ts (a int, payload text)
              WITH (algorithm = 'lz4') TABLESPACE dropme_ts2;
            INSERT INTO t_cfs_ts SELECT g, md5(g::text)
              FROM generate_series(1, 300) g;
            CREATE TABLE t_cfs_base (a int, payload text)
              WITH (algorithm = 'zstd');
            INSERT INTO t_cfs_base SELECT g, md5(g::text)
              FROM generate_series(1, 300) g;
            CHECKPOINT;
        ]);
 
    # Do immediate shutdown just after a sequence of CREATE DATABASE /
    # DROP DATABASE / DROP TABLESPACE.  This causes CREATE DATABASE WAL
    # records to be applied to already-removed directories.
    my $query = q[
        CREATE DATABASE dropme_db1 WITH TABLESPACE dropme_ts1 STRATEGY=<STRATEGY>;
        CREATE TABLE t (a int) TABLESPACE dropme_ts2;
        CREATE DATABASE dropme_db2 WITH TABLESPACE dropme_ts2 STRATEGY=<STRATEGY>;
        CREATE DATABASE moveme_db TABLESPACE source_ts STRATEGY=<STRATEGY>;
        ALTER DATABASE moveme_db SET TABLESPACE target_ts;
        CREATE DATABASE newdb TEMPLATE template_db STRATEGY=<STRATEGY>;
        ALTER DATABASE template_db IS_TEMPLATE = false;
        DROP DATABASE dropme_db1;
        DROP TABLE t_cfs_ts;
        DROP TABLE t;
        DROP TABLE t_cfs_base;
        DROP DATABASE dropme_db2; DROP TABLESPACE dropme_ts2;
        DROP TABLESPACE source_ts;
        DROP DATABASE template_db;
    ];
    $query =~ s/<STRATEGY>/$strategy/g;
 
    $node_primary->safe_psql('postgres', $query);
    $node_primary->wait_for_catchup($node_standby, 'write');
 
    # show "create missing directory" log message
    $node_standby->safe_psql('postgres',
        "ALTER SYSTEM SET log_min_messages TO debug1;");
    $node_standby->stop('immediate');
    # Should restart ignoring directory creation error.
    is($node_standby->start(fail_ok => 1),
        1, "standby node started for $strategy");
 
    # No orphaned CFS sidecar files may survive in the standby's
    # pg_default: every sidecar base name must be a live relfilenode.
    check_orphan_cfs_sidecars($node_standby,
        "no orphan CFS sidecars on standby for $strategy");
 
    $node_standby->stop('immediate');
    $node_primary->stop('fast');
}
 
test_tablespace("FILE_COPY");
test_tablespace("WAL_LOG");
 
# ----------------------------------------------------------------------
# Replay of PRUNE / TRUNCATE / DROP WAL records for CFS relations
# against relations whose files are shorter than the WAL stream assumes.
# Replay must keep the logical block map and the sidecar files
# consistent, and a dropped relation must not leave orphaned sidecars
# behind.
# ----------------------------------------------------------------------
{
    my $node = PostgreSQL::Test::Cluster->new('n1');
 
    $node->init();
 
    # Disable autovacuum to guarantee VACUUM can remove rows / truncate
    # relations
    $node->append_conf(
        'postgresql.conf', qq[
wal_level = 'replica'
autovacuum = off
]);
 
    $node->start();
 
    # Test: Replay of PRUNE records for a pre-existing, then dropped,
    # relation
 
    $node->safe_psql(
        'postgres', qq[
CREATE TABLE truncme(i int) WITH (fillfactor = 50, algorithm = 'lz4');
INSERT INTO truncme SELECT generate_series(1, 1000);
UPDATE truncme SET i = 1;
CHECKPOINT; -- ensure relation exists at start of recovery
VACUUM truncme; -- generate prune records
DROP TABLE truncme;
]);
 
    $node->stop('immediate');
 
    ok($node->start(),
        'replay of PRUNE records for a pre-existing, then dropped, relation');
 
    check_orphan_cfs_sidecars($node,
        'no orphan sidecars for dropped pre-existing relation');
 
    # Test: Replay of PRUNE records for a newly created, then dropped,
    # relation
 
    $node->safe_psql(
        'postgres', qq[
CREATE TABLE truncme(i int) WITH (fillfactor = 50, algorithm = 'lz4');
INSERT INTO truncme SELECT generate_series(1, 1000);
UPDATE truncme SET i = 1;
VACUUM truncme; -- generate prune records
DROP TABLE truncme;
]);
 
    $node->stop('immediate');
 
    ok($node->start(),
        'replay of PRUNE records for a newly created, then dropped, relation'
    );
 
    check_orphan_cfs_sidecars($node,
        'no orphan sidecars for dropped new relation');
 
    # Test: Replay of PRUNE records affecting truncated block.  With FPIs
    # used for PRUNE.
 
    $node->safe_psql(
        'postgres', qq[
CREATE TABLE truncme(i int) WITH (fillfactor = 50, algorithm = 'lz4');
INSERT INTO truncme SELECT generate_series(1, 1000);
UPDATE truncme SET i = 1;
CHECKPOINT; -- generate FPIs
VACUUM truncme; -- generate prune records
TRUNCATE truncme; -- make blocks non-existing
INSERT INTO truncme SELECT generate_series(1, 10);
]);
 
    $node->stop('immediate');
 
    ok($node->start(),
        'replay of PRUNE records affecting truncated block (FPIs)');
 
    is( $node->safe_psql('postgres', 'select count(*), sum(i) FROM truncme'),
        '10|55',
        'table contents as expected after recovery');
    is( $node->safe_psql(
            'postgres',
            "SELECT ok FROM pg_cfs_check('truncme'::regclass, true)"),
        't',
        'sidecars intact after PRUNE+TRUNCATE replay (FPIs)');
    $node->safe_psql('postgres', 'DROP TABLE truncme');
 
    # Test replay of PRUNE records for blocks that are later truncated.
    # Without FPIs used for PRUNE.
 
    $node->safe_psql(
        'postgres', qq[
CREATE TABLE truncme(i int) WITH (fillfactor = 50, algorithm = 'lz4');
INSERT INTO truncme SELECT generate_series(1, 1000);
UPDATE truncme SET i = 1;
VACUUM truncme; -- generate prune records
TRUNCATE truncme; -- make blocks non-existing
INSERT INTO truncme SELECT generate_series(1, 10);
]);
 
    $node->stop('immediate');
 
    ok($node->start(),
        'replay of PRUNE records affecting truncated block (no FPIs)');
 
    is( $node->safe_psql('postgres', 'select count(*), sum(i) FROM truncme'),
        '10|55',
        'table contents as expected after recovery');
    is( $node->safe_psql(
            'postgres',
            "SELECT ok FROM pg_cfs_check('truncme'::regclass, true)"),
        't',
        'sidecars intact after PRUNE+TRUNCATE replay (no FPIs)');
    $node->safe_psql('postgres', 'DROP TABLE truncme');
 
    # Test: Replay of partial truncation via VACUUM (the CFS RESIZE path)
 
    $node->safe_psql(
        'postgres', qq[
CREATE TABLE truncme(i int) WITH (fillfactor = 50, algorithm = 'lz4');
INSERT INTO truncme SELECT generate_series(1, 1000);
UPDATE truncme SET i = i + 1;
-- ensure a mix of pre/post truncation rows
DELETE FROM truncme WHERE i > 500;
 
VACUUM truncme; -- should truncate relation
 
-- rows at TIDs that previously existed
INSERT INTO truncme SELECT generate_series(1000, 1010);
]);
 
    $node->stop('immediate');
 
    ok($node->start(), 'replay of partial truncation via VACUUM');
 
    is( $node->safe_psql(
            'postgres',
            'select count(*), sum(i), min(i), max(i) FROM truncme'),
        '510|136304|2|1010',
        'table contents as expected after recovery');
    is( $node->safe_psql(
            'postgres',
            "SELECT ok FROM pg_cfs_check('truncme'::regclass, true)"),
        't',
        'sidecars intact after partial truncation replay');
    $node->safe_psql('postgres', 'DROP TABLE truncme');
 
    $node->stop('fast');
}
 
# ----------------------------------------------------------------------
# Logical decoding from a CFS table: the decoder must read tuple data
# through CFS decompression, and a restart must not repeat
# already-consumed changes.
# ----------------------------------------------------------------------
subtest 'logical decoding from a CFS table' => sub {
    my $node_primary = PostgreSQL::Test::Cluster->new('dec_primary');
    $node_primary->init(allows_streaming => 1);
    $node_primary->append_conf('postgresql.conf', "wal_level = logical");
    $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 WAL tests';
    }
 
    # CFS table (the table the decoder will read from)
    $node_primary->safe_psql('postgres',
        qq[CREATE TABLE decoding_test(x integer, y text) WITH (algorithm = 'lz4');]
    );
 
    $node_primary->safe_psql('postgres',
        qq[SELECT pg_create_logical_replication_slot('test_slot', 'test_decoding');]
    );
 
    # Insert data — the decoder must detoast/read through CFS
    # decompression
    $node_primary->safe_psql('postgres',
        qq[INSERT INTO decoding_test(x,y) SELECT s, s::text FROM generate_series(1,10) s;]
    );
 
    # Basic decoding works (12 rows: 10 INSERT + BEGIN + COMMIT)
    my $result = $node_primary->safe_psql('postgres',
        qq[SELECT pg_logical_slot_get_changes('test_slot', NULL, NULL);]);
    is(scalar(split(/^/m, $result)),
        12,
        'Logical decoding from CFS table produced 12 rows inc BEGIN/COMMIT');
 
    # Restart — the slot progress must survive and no changes must be
    # repeated
    $node_primary->restart;
 
    # After restart, there are no new writes, so the result should be
    # empty.  This verifies that the logical slot's confirmed flush LSN
    # survived the restart and the CFS journal was replayed consistently
    # with WAL.
    $result = $node_primary->safe_psql('postgres',
        qq[SELECT pg_logical_slot_get_changes('test_slot', NULL, NULL);]);
    chomp($result);
    is($result, '', 'Decoding from CFS table after restart repeats no rows');
 
    # More inserts, then decode again to confirm the slot still works
    $node_primary->safe_psql('postgres',
        qq[INSERT INTO decoding_test(x,y) SELECT s, s::text FROM generate_series(11,20) s;]
    );
 
    $result = $node_primary->safe_psql('postgres',
        qq[SELECT pg_logical_slot_get_changes('test_slot', NULL, NULL);]);
    is( scalar(split(/^/m, $result)),
        12,
        'Logical decoding from CFS table after restart produced 12 more rows'
    );
 
    # Verify the actual data in the CFS table is intact
    $result = $node_primary->safe_psql('postgres',
        "SELECT count(*) FROM decoding_test");
    is($result, '20', 'CFS table has 20 rows after decoding cycles');
 
    $node_primary->safe_psql('postgres',
        qq[SELECT pg_drop_replication_slot('test_slot');]);
 
    $node_primary->stop;
};
 
done_testing();