Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 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
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
<!--
  doc/src/sgml/cfs.sgml
-->
 
<sect1 id="storage-cfs">
 <title>Compressed File Store</title>
 
 <indexterm>
  <primary>Compressed File Store</primary>
 </indexterm>
 <indexterm><primary>CFS</primary><see>Compressed File Store</see></indexterm>
 
 <para>
  The Compressed File Store (<acronym>CFS</acronym>) provides transparent,
  page-level compression for heap, index, materialized view, and
  <acronym>TOAST</acronym> relations.  Compression and decompression happen
  only at the storage-manager boundary, so the shared buffer cache, the
  write-ahead log, and every higher layer continue to operate on ordinary
  uncompressed <literal>BLCKSZ</literal> pages and are unaffected by CFS.
 </para>
 
 <para>
  When a relation is enabled for CFS, its main fork is stored in three
  <firstterm>sidecar</firstterm> files kept alongside the (otherwise empty)
  base main-fork file.  The sidecar files are created when the relation's
  compression policy is published: at relation creation, at every
  relfilenumber rewrite, and whenever relation data is copied to a new
  relfilenumber (tablespace copies and <command>CREATE DATABASE ...
  STRATEGY WAL_LOG</command>).  They exist even before the first write, the
  same way the base file exists from creation.  The free-space map, visibility
  map, and init forks are never compressed.  Temporary
  (<literal>TEMP</literal>) and unlogged (<literal>UNLOGGED</literal>)
  relations cannot use CFS.
 </para>
 
 <table id="storage-cfs-files">
  <title>CFS Sidecar Files</title>
  <tgroup cols="2">
   <thead>
    <row>
     <entry>Suffix</entry>
     <entry>Purpose</entry>
    </row>
   </thead>
   <tbody>
    <row>
     <entry><filename>.cfp</filename></entry>
     <entry>
      Append-only compressed page data.  Each record is a
      <structname>CfsCompressedBlockHeader</structname> followed by the
      (possibly compressed) payload and alignment padding.
     </entry>
    </row>
    <row>
     <entry><filename>.cfsmap</filename></entry>
     <entry>
      Page map snapshot: a dense array of <structname>CfsMapEntry</structname>
      records, indexed by logical block number.
     </entry>
    </row>
    <row>
     <entry><filename>.cfsjrn</filename></entry>
     <entry>
      Page map journal: a crash-safe, append-only sequence of mapping
      updates applied on top of the last snapshot.
     </entry>
    </row>
   </tbody>
  </tgroup>
 </table>
 
 <para>
  At checkpoint time the sidecar files are persisted in the order
  <filename>.cfp</filename>, then <filename>.cfsjrn</filename>, then
  <filename>.cfsmap</filename>.  This ordering guarantees that a map entry
  never points at a compressed record that has not reached durable storage.
  Recovery starts from the latest <filename>.cfsmap</filename> snapshot and
  folds the <filename>.cfsjrn</filename> journal into it row by row; the
  fold is idempotent by <literal>(block number, generation)</literal> and
  stops cleanly at the first torn record.
 </para>
 
 <para>
  Like ordinary relation files, the <filename>.cfp</filename> data file is
  segmented at 1 <acronym>GB</acronym> boundaries
  (<literal>RELSEG_SIZE</literal> blocks): the first segment is named
  <filename>.cfp</filename>, subsequent ones
  <filename>.cfp.<replaceable>N</replaceable></filename>.  The
  <structfield>physical_offset</structfield> stored in
  <structname>CfsMapEntry</structname> is a global byte offset across the
  whole segment chain; a record never crosses a segment boundary — when it
  would not fit, the append cursor advances to the next boundary, leaving a
  short unwritten padding at the segment tail.  Because offsets were always
  global, a <filename>.cfp</filename> written before segmentation needs no
  conversion: every offset in it is below the boundary and therefore
  addresses segment 0.  A segment larger than
  <literal>CFS_SEGMENT_SIZE</literal> is treated as corruption at open
  time, since the engine never produces one.  Compaction, checkpoint fsync,
  relation drop, <application>pg_upgrade</application> and the integrity
  checker all walk the segment chain transparently.  The map and journal
  files are single-segment by design.
 </para>
 
 <para>
  The write-ahead log is unchanged: logical WAL records and full-page images
  describe uncompressed pages, so CFS is an implementation detail of the
  storage manager and does not affect WAL record format.
 </para>
 
 <sect2 id="storage-cfs-build">
  <title>Build Configuration</title>
 
  <para>
   CFS is enabled by default.  It can be disabled entirely at build time, in
   which case the <filename>src/backend/storage/cfs/</filename> subsystem is
   omitted and every integration point in the core server is compiled out under
   the <symbol>USE_CFS</symbol> preprocessor guard; the resulting server then
   behaves like upstream <productname>PostgreSQL</productname> and contains no
   CFS symbols.
  </para>
 
  <table id="storage-cfs-build-options">
   <title>CFS Build Options</title>
   <tgroup cols="3">
    <thead>
     <row>
      <entry>Build System</entry>
      <entry>Enable (Default)</entry>
      <entry>Disable</entry>
     </row>
    </thead>
    <tbody>
     <row>
      <entry>autoconf</entry>
      <entry><option>--with-dia-cfs</option></entry>
      <entry><option>--without-dia-cfs</option></entry>
     </row>
     <row>
      <entry>meson</entry>
      <entry><option>-Ddia_cfs=enabled</option> or <option>-Ddia_cfs=auto</option></entry>
      <entry><option>-Ddia_cfs=disabled</option></entry>
     </row>
    </tbody>
   </tgroup>
  </table>
 
  <para>
   CFS does not depend on an external library of its own; it combines with
   <option>--with-lz4</option> and/or <option>--with-zstd</option> the same
   way <acronym>TOAST</acronym> compression does.  When neither is given, the
   built-in <literal>raw</literal> (pass-through) codec remains available and
   only the <literal>lz4</literal> / <literal>zstd</literal> algorithms become
   unavailable.
  </para>
 
  <para>
   Removing a codec that was available when existing CFS relations were
   populated does not make those relations disappear, but it does make their
   already-compressed pages unreadable: any attempt to read a block stored
   with an algorithm the running binary no longer has fails with an error,
   even though the relation's <literal>algorithm</literal> reloption still
   names it.  Rebuilding with the original library, or rewriting the affected
   relations with <command>ALTER TABLE ... SET (algorithm = ...)</command>
   before removing it, avoids this.
  </para>
 </sect2>
 
 <sect2 id="storage-cfs-policy">
  <title>Enabling CFS for a Relation</title>
 
  <para>
   CFS is enabled for a relation by setting the <literal>algorithm</literal>
   reloption.  Its absence means the relation uses ordinary uncompressed
   storage; the global parameters below never enable CFS by themselves.
  </para>
 
  <variablelist>
   <varlistentry>
    <term><literal>algorithm</literal> (<type>enum</type>)</term>
    <listitem>
     <para>
      Compression algorithm.  Accepted values are <literal>lz4</literal> and
      <literal>zstd</literal>.  Setting this option makes the relation a CFS
      relation.  The internal <literal>raw</literal> mode is not a user-visible
      choice.
     </para>
    </listitem>
   </varlistentry>
    <varlistentry>
     <term><literal>level</literal> (<type>integer</type>)</term>
     <listitem>
      <para>
       Compression level.  <literal>lz4</literal> accepts
       <literal>1</literal> to <literal>12</literal>, <literal>zstd</literal>
       accepts <literal>1</literal> to <literal>22</literal>.  When omitted,
       the level is resolved at physical write time from the writing process's
       <varname>cfs_default_lz4_level</varname> or
       <varname>cfs_default_zstd_level</varname>, whichever matches the
       algorithm.
      </para>
     </listitem>
    </varlistentry>
    <varlistentry>
     <term><literal>min_gain_bytes</literal> (<type>integer</type>)</term>
     <listitem>
      <para>
       Minimum byte savings required for a page to be stored compressed instead
       of raw.  Only meaningful together with <literal>algorithm</literal>.
       When omitted, the value is resolved at physical write time from the writing process's
       <varname>cfs_default_min_gain_bytes</varname>.
      </para>
     </listitem>
    </varlistentry>
   </variablelist>
 
   <para>
    The catalog stores only what was spelled out in the reloptions:
    <literal>algorithm</literal> is the CFS marker, and
    <literal>level</literal> / <literal>min_gain_bytes</literal> are optional.
    A partial set of options is valid; nothing is copied from the
    configuration parameters at DDL time.  The following parameters supply
    the runtime values used when an optional reloption is not specified, and
    never enable CFS:
   </para>
 
   <variablelist>
    <varlistentry>
     <term><varname>cfs_default_lz4_level</varname> (<type>integer</type>, default 1)</term>
     <listitem>
      <para>
       Compression level used for <literal>lz4</literal> relations that do
       not store an explicit <literal>level</literal>.  The default follows
       the library's fast mode (<literal>LZ4_compress_default</literal>).
       Range 1 to 12.
      </para>
     </listitem>
    </varlistentry>
    <varlistentry>
     <term><varname>cfs_default_zstd_level</varname> (<type>integer</type>, default 3)</term>
     <listitem>
      <para>
       Compression level used for <literal>zstd</literal> relations that do
       not store an explicit <literal>level</literal>.  Range 1 to 22.
      </para>
     </listitem>
    </varlistentry>
    <varlistentry>
     <term><varname>cfs_default_min_gain_bytes</varname> (<type>integer</type>, default 512)</term>
     <listitem>
      <para>
       Minimum byte savings used for relations that do not store an explicit
       <literal>min_gain_bytes</literal>.
      </para>
     </listitem>
    </varlistentry>
   </variablelist>
 
   <para>
    Unset fields are resolved by the process performing the physical write.
    A backend writing a page itself uses its session settings, while the
    checkpointer and background writer use their own settings from the
    server configuration.  A session <command>SET</command> does not set
    the compression level of a later background write, including a write
    requested by <command>CHECKPOINT</command>.
    This is safe — every compressed record carries its own algorithm
    marker, and decompression never needs the level, so reads never
    depend on any configuration parameter — and the effective policy for the calling session is observable
    through <function>pg_cfs_relation_info</function> (see
    <xref linkend="storage-cfs-monitoring"/>).  Setting an explicit
    <literal>level</literal> (or <literal>min_gain_bytes</literal>) pins the
    value for every writer; <command>ALTER TABLE ... RESET</command> removes
    it and returns the field to runtime resolution.
   </para>
 
  <para>
   The <literal>algorithm</literal>, <literal>level</literal> and
   <literal>min_gain_bytes</literal> reloptions apply uniformly to every
   built-in index access method (<literal>btree</literal>,
   <literal>hash</literal>, <literal>gin</literal>, <literal>gist</literal>,
   <literal>spgist</literal>, <literal>brin</literal>); CFS is not limited to
   a specific index type.
  </para>
 
   <para>
    An index is a CFS relation if and only if its own reloptions carry a
    policy.  An index without an explicit <literal>algorithm</literal>
    inherits, at <command>CREATE INDEX</command> time, the parent table's
    stored <literal>algorithm</literal> together with only those
    <literal>level</literal> / <literal>min_gain_bytes</literal> values
    the table stores explicitly; the index's own unset fields resolve at
    runtime.  After that the index is independent of the table: a later
    <command>ALTER TABLE ... SET (algorithm = ...)</command> changes only
    the table and never the indexes that already exist, and
    <command>ALTER INDEX ... RESET (algorithm)</command> disables index
    compression for good — a subsequent <command>REINDEX</command> keeps
    the index plain.  A <acronym>TOAST</acronym> relation never
    stores CFS options of its own: its effective policy is resolved
    through the owning table at the moment of each operation.  Specifying
    CFS reloptions in the <literal>toast.</literal> namespace (for
    example <literal>toast.algorithm='lz4'</literal>) is rejected with an
    error, whether in <command>CREATE TABLE</command>, <command>CREATE
    TABLE AS</command>, or a later <command>ALTER TABLE ... SET
    (toast.algorithm=...)</command>.
    A partitioned table may store an explicit default policy (only the
    keys spelled out on the parent) for future partitions but is never
    itself a physical CFS relation.
   </para>
 
   <para>
    CFS remains unsupported for <literal>TEMP</literal> and
    <literal>UNLOGGED</literal> relations; the persistence check is repeated
    during the rewrite phase of <command>ALTER TABLE</command>, so a combined
    <command>ALTER TABLE ... SET (algorithm = ...), SET UNLOGGED</command>
    cannot create the forbidden configuration.
   </para>
 
   <para>
    For example, a table enabled without an explicit
    <literal>level</literal> follows the session parameter of every writer:
   </para>
 
<programlisting>
CREATE TABLE events (id int, payload text) WITH (algorithm = 'zstd');
 
SET cfs_default_zstd_level = 7;
INSERT INTO events SELECT g, 'row ' || g FROM generate_series(1, 100) g;
 
SET cfs_default_zstd_level = 11;
INSERT INTO events SELECT g, 'row ' || g FROM generate_series(101, 200) g;
-- both batches are readable regardless of the parameter value
 
ALTER TABLE events SET (level = 9);   -- pin an explicit level for everyone
ALTER TABLE events RESET (level);     -- back to runtime resolution
</programlisting>
  </sect2>
 
 <sect2 id="storage-cfs-i-o">
  <title>Page I/O</title>
 
  <para>
   Each storage-manager operation (<function>smgrreadv</function>,
   <function>smgrwritev</function>, <function>smgrextend</function>,
   <function>smgrzeroextend</function>, <function>smgrtruncate</function>,
   <function>smgrnblocks</function>, <function>smgrprefetch</function>,
   <function>smgrimmedsync</function>) consults the
   <function>smgriscfsenabled()</function> predicate and, for a compressed main
   fork, routes the call through the <type>CfsStorageOps</type> dispatch table
   instead of the regular <filename>md</filename> path.  Non-compressed forks
   and ordinary relations are entirely unaffected.
  </para>
 
  <para>
   <emphasis>Write path.</emphasis>
   <function>FlushBuffer()</function> applies the normal page checksum with
   <function>PageSetChecksumCopy()</function> and then calls
   <function>smgrwritev()</function>; the CFS write path compresses that
   already-checksummed page, appends the record to
   <filename>.cfp</filename>, appends a journal update, and updates the
   in-memory map.  The previous record is left in place and becomes
   unreachable until compaction reclaims it.
  </para>
 
   <para>
    <emphasis>Read path.</emphasis>
    On a cache miss the asynchronous read entry point
    <function>smgrstartreadv()</function> looks up the page map, reads the
    compressed record from <filename>.cfp</filename>, verifies the block and
    payload checksums, and decompresses the page directly into the caller's
    buffer.  <function>PageIsVerified()</function> then still performs its
    header sanity checks; with <varname>cfs_skip_page_checksum</varname> on
    (the default) the redundant cluster page-checksum computation is skipped
    for these pages, and turning the parameter off restores the exact
    ordinary-relation validation.  Blocks whose records are
    physically contiguous in one <filename>.cfp</filename> segment (for
    example after a compaction, or in a relation whose pages were flushed
    in block order, such as a freshly built index) are batched:
    <function>smgrmaxcombine()</function> reports the length of the
    contiguous run, and one <function>pread()</function> serves the whole
    run, with each record still validated and decompressed individually.
    Blocks that cannot join a run — rewritten pages, extension holes,
    segment boundaries — are read per-block exactly as before, and the
    grouping is re-derived at read time, so it never affects correctness.
   </para>
 
   <para>
    Because a compressed page cannot be served by a raw
    <function>pread()</function> alone, <function>smgrstartreadv()</function>
    decompresses the requested blocks synchronously in the originating backend
    and completes the <acronym>AIO</acronym> handle inline; batching removes
    the per-record <function>pread()</function> calls, not the synchronous
    decompression.  <function>smgrprefetch()</function> advises the operating
    system to read the <filename>.cfp</filename> ranges backing the requested
    blocks into the page cache (<function>posix_fadvise()</function> with
    <literal>POSIX_FADV_WILLNEED</literal>, one advice per contiguous record
    run): decompression itself still cannot be deferred to an asynchronous
    I/O callback and happens synchronously wherever the page is actually
    needed, but the advice warms the page cache those decompressing reads
    consume, so read-ahead hints do benefit CFS relations —
    <literal>pg_prewarm(..., 'prefetch')</literal> works for them like for
    ordinary relations.  <function>smgrwriteback()</function>, driven by
    <varname>bgwriter_flush_after</varname>,
    <varname>checkpoint_flush_after</varname> and
    <varname>backend_flush_after</varname>, likewise starts kernel writeback
    of the dirty <filename>.cfp</filename> ranges
    (<function>sync_file_range()</function>, Linux only; a no-op elsewhere).
    Both are scheduling hints without any fsync semantics — durability
    remains the checkpoint's business.  The
    <literal>read_stream</literal> pipeline still helps CFS tables only
    through the combined transfers (bounded by
    <varname>io_combine_limit</varname>): the decompression time itself
    stays in the originating backend.  Longer term, hosting codec state in
    I/O workers remains the upgrade path.  When a batched multi-block read
    fails, the synchronous path reports the exact failing block, while the
    <acronym>AIO</acronym> result channel has no room for a block number
    and the report names the first block of the I/O.
   </para>
 
   <para>
    When the cluster is initialised with <option>--data-checksums</option>, the
    page checksum is part of the stored payload and survives the
    compress/decompress round-trip.  The additional CFS
    <structfield>orig_crc</structfield> field is an independent integrity check,
    verified during decompression <emphasis>before</emphasis> the buffer manager
    checks the page checksum: with <varname>cfs_skip_page_checksum</varname> on
    (the default) that later check is skipped as redundant, because the CRC
    chain has already verified the exact page bytes, and setting the parameter
    to off restores it.
   </para>
  </sect2>
 
  <sect2 id="storage-cfs-checkpoint">
   <title>Checkpoint, fsync and Background Compaction</title>
 
   <para>
    CFS sidecar files (<filename>.cfp</filename>,
    <filename>.cfsmap</filename>, <filename>.cfsjrn</filename>) are registered
    in the standard sync queue through a dedicated
    <literal>SYNC_HANDLER_CFS</literal> handler, so the checkpointer fsyncs
    them at checkpoint time exactly like ordinary relation segments.  Unlink of
    permanent sidecar files is deferred to the next checkpoint; in redo and temp
    paths the files are removed immediately.
   </para>
 
   <para>
    At checkpoint time <function>CfsCheckpoint()</function> folds the journal
    of every relation written since the previous checkpoint into its
    <filename>.cfsmap</filename> in place: the volume of map writes is
    proportional to the number of changed blocks, not to the relation size
    (the cumulative <structfield>checkpoint_map_rows_written</structfield>
    counter of <xref linkend="storage-cfs-monitoring"/>
    shows the exact number).  The fold phase runs without the append lock -
    writers keep appending during it - and each rewritten row carries its own
    checksum, so a crash mid-fold leaves torn rows that the intact journal
    repairs on the next load.  A short phase under the exclusive append lock
    then folds the records appended after the first phase stopped, fsyncs
    their data and the journal first, and resets the journal to a bare
    header; only a torn tail - the crash artifact, with nothing valid behind
    it - is dropped by that reset.  The reset header carries the bumped
    incarnation plus the generation watermark of the map
    state the reset leaves behind.  The durability sequence
    <literal>fsync(.cfp) -> fsync(.cfsjrn) -> fold .cfsmap -> reset
    .cfsjrn</literal> therefore never loses a record a concurrent writer
    appended.
   </para>
 
   <para>
    The <firstterm>CFS background compaction worker</firstterm> is a launcher
    that, like the autovacuum launcher, is not bound to any particular
    database: every <varname>cfs_bg_period_ms</varname> it enumerates the
    databases of the cluster from <literal>pg_database</literal> (databases
    with <structfield>datallowconn</structfield> set to false are not
    serviced) and, one database at a time, starts a short-lived worker that
    connects to the database, scans its <literal>pg_class</literal> for CFS
    relations whose dead-space ratio exceeds
    <varname>cfs_bg_threshold</varname> and compacts their sidecar files
    under a <literal>ShareUpdateExclusiveLock</literal> (online compaction,
    <varname>cfs_compact_online</varname>; ordinary reads and writes of the
    relation are not blocked, only short exclusive windows around the
    snapshot and the final swap remain).  The same compaction can
    be triggered synchronously with the SQL function
    <function>pg_cfs_compact(regclass)</function>.  Compaction does not
    change the <literal>relfilenode</literal> and generates no WAL.  Every
   <varname>cfs_bg_*</varname> parameter (and
   <varname>cfs_compact_online</varname>) can be changed with a
   configuration reload (<literal>SIGHUP</literal>), unlike
   <varname>cfs_map_cache_rels_per_partition</varname> and
   <varname>cfs_stats_slots_per_partition</varname>, which are fixed at
   server start.
   </para>
 
   <variablelist>
    <varlistentry>
     <term><varname>cfs_map_cache_rels_per_partition</varname> (<type>integer</type>)</term>
     <listitem>
      <para>
       Number of relation-metadata slots per shared-memory map-cache
       partition.  The map cache tracks, for every known CFS relation, its
       logical size and the dirty-for-checkpoint flag that
       <function>CfsCheckpoint()</function> uses to decide which relations
       need a fresh <filename>.cfsmap</filename> snapshot and a journal
       truncate.  The total number of CFS relations tracked cluster-wide is
       64 times this value.  Each slot also holds the relation's
       <literal>append_lock</literal>, so a relation cannot be written or
       checkpointed without one: when every slot of a partition is pinned
       or dirty, an attempt to use a new relation fails with an error
       naming this parameter instead of silently skipping the relation.
       Default <literal>16</literal>, range <literal>1</literal> to
       <literal>64</literal>.  This parameter is set at server start.
      </para>
     </listitem>
    </varlistentry>
    <varlistentry>
     <term><varname>cfs_stats_slots_per_partition</varname> (<type>integer</type>)</term>
     <listitem>
      <para>
       Number of relation-statistics slots per shared-memory statistics
       partition; the total number of CFS relations tracked in
       <link linkend="storage-cfs-monitoring"><structname>pg_stat_cfs</structname></link>
       is 64 times this value.  Counters are atomic and updated under a
       shared partition lock, so accounting does not serialize concurrent
       readers and writers.  When more CFS relations than the capacity are
       active, statistics rows evict each other: the least recently used
       row is reset to zero and reused for a new relation, so the view
       silently loses older counters.  Raise this parameter to cover the
       working set of compressed relations.  Default <literal>16</literal>
       (1024 relations cluster-wide), range <literal>4</literal> to
       <literal>128</literal>.  This parameter is set at server start.
       Lowering the value discards the persisted statistics on the next
       restart when the saved entry count exceeds the new capacity: the
       saved file is validated against the new capacity as a whole and is
       then dropped.
      </para>
     </listitem>
    </varlistentry>
    <varlistentry>
      <term><varname>cfs_map_memory</varname> (<type>integer</type>)</term>
      <listitem>
        <para>
         Size in megabytes of the shared block-map segment pool, modelled
         after <varname>shared_buffers</varname>.  The pool holds the
         per-relation <quote>logical block to <filename>.cfp</filename>
         offset</quote> map in fixed 768 kB segments in shared memory,
         shared by all backends instead of per-process private copies.  A
         segment is loaded from the <filename>.cfsmap</filename> snapshot on
         first use and stays resident across checkpoints; a full pool evicts
         segments by a clock sweep: every lookup and every write bumps the
         segment's usage counter, the sweep decrements counters and reuses
         the first segment whose counter reached zero.  All resident
         segments compete equally, regardless of whether their relation
         currently has an open handle: an open handle pins the relation's
         metadata slot, not its pool segments, and a scan's working set is
         kept resident by the usage counters alone, exactly like the buffer
         cache.
        </para>
        <para>
         Sizing lower bound: the pool must hold the segment
         <emphasis>working set</emphasis> you want to keep warm, where the
         bound is measured in <emphasis>segments</emphasis>, not relations:
         with the default segment span a 100 GiB relation is about 400
         segments.  A pool smaller than the working set evicts and reloads
         cold segments (one 768 kB <filename>.cfsmap</filename> range plus
         the journal delta per reload), which costs extra I/O but never
         correctness, and the pool keeps adapting to whatever is actually
         read.  Only when every segment is in flight or hot (no victim for
         the sweep) does a read fall back to the authoritative on-disk
         state, counted in <structfield>fallback_reads</structfield> of
         <function>pg_cfs_map_pool</function>(): one 768 kB
         <filename>.cfsmap</filename> range plus the journal delta is read
         per miss, and nothing is published into the pool.  Size the pool
         for the segments you want to keep warm.
        </para>
       <para>
        Read-mostly relations whose working set is larger than the pool
        can thrash it: lookups bump a segment's usage counter under the
        segment lock, but a segment that is not looked up during a full
        clock revolution is evicted in favour of the next segment that is
        loaded.  The counter is reset when a segment is evicted or its
        relation is invalidated, so a recycled pool slot always starts
        cold.  This costs extra I/O, never correctness; size the pool for
        the working set you want to keep warm.
       </para>
       <para>
        The actual shared-memory reservation is somewhat larger than
        <varname>cfs_map_memory</varname>: the parameter buys the segment
        data itself, and the server additionally reserves the segment
        descriptors, one lock per segment, the segment lookup and
        per-relation index hashes, and the in-flight reservation table.
       </para>
       <para>
        The pool is sized and its shared memory is reserved at server
        start, even when no CFS relation is opened.  This reservation is
        deliberate: the pool is part of the server's fixed shared-memory
        budget and its size must not depend on when the first CFS relation
        appears.  A value with a unit suffix is accepted, for example
        <literal>128MB</literal>; a bare number is taken as megabytes.
       </para>
       <para>
        Setting the parameter to <literal>0</literal> disables the pool
        entirely: every handle then carries its own full private map, as
        before the pool existed, and every block entry is resolved through
        that map.  Default <literal>128</literal>, range
        <literal>0</literal> to <literal>1048576</literal>.  This
        parameter is set at server start.
       </para>
       <para>
        The default stays at <literal>128</literal>: measurements with
        <literal>32</literal>, <literal>64</literal> and
        <literal>128</literal> megabytes showed no throughput or residency
        difference for a working set that already fits the smallest pool,
        so the larger default is kept as headroom for many concurrently
        open relations.
       </para>
      </listitem>
    </varlistentry>
    <varlistentry>
     <term><varname>cfs_bg_threshold</varname> (<type>integer</type>)</term>
     <listitem>
      <para>
       Minimum dead-space percentage for a relation to be a compaction
       candidate.  The percentage is computed against the live volume
       (the sidecar size minus the counted dead bytes), so a relation
       whose live tail has been rewritten away is not masked by the dead
       space compaction is about to reclaim.  Default <literal>10</literal>.
      </para>
     </listitem>
    </varlistentry>
    <varlistentry>
     <term><varname>cfs_compact_online</varname> (<type>boolean</type>)</term>
     <listitem>
      <para>
       Enables online compaction.  When on (the default), the background
       worker and <function>pg_cfs_compact()</function> take
       <literal>ShareUpdateExclusiveLock</literal> on the relation and
       copy it in three phases with only short exclusive append-lock
       windows at the start and the end, so ordinary reads and writes of
       the relation keep running during the copy.  When off, the same
       <literal>ShareUpdateExclusiveLock</literal> is taken, but the
       internal append lock is held for the whole operation, so writes to
       the sidecar files are serialized until compaction finishes (plain
       reads are not blocked).  This parameter can be changed at any time
       by reloading the configuration (it is signaled with
       <literal>SIGHUP</literal>).
      </para>
     </listitem>
    </varlistentry>
    <varlistentry>
     <term><varname>cfs_bg_respond_time_s</varname> (<type>integer</type>)</term>
     <listitem>
      <para>
       Timeout in seconds for the background worker to acquire the
       compaction lock on a relation
       (<literal>ShareUpdateExclusiveLock</literal> in both modes); on
       timeout the candidate is skipped.  The manual
       <function>pg_cfs_compact()</function> call blocks until the lock
       is granted.  Default <literal>5</literal>.
      </para>
     </listitem>
    </varlistentry>
    <varlistentry>
     <term><varname>cfs_bg_delay_ms</varname> (<type>integer</type>)</term>
     <listitem>
      <para>
       Pause in milliseconds between compactions of relations in one pass.
       Default <literal>100</literal>.
      </para>
     </listitem>
    </varlistentry>
    <varlistentry>
     <term><varname>cfs_bg_period_ms</varname> (<type>integer</type>)</term>
     <listitem>
      <para>
       Interval in milliseconds between compaction passes.  Default
       <literal>3600000</literal> (one hour).
      </para>
     </listitem>
    </varlistentry>
    <varlistentry>
     <term><varname>cfs_bg_min_interval_s</varname> (<type>integer</type>)</term>
     <listitem>
      <para>
       Minimum interval in seconds between compactions of the same relation.
       Default <literal>86400</literal> (one day).
      </para>
     </listitem>
    </varlistentry>
    <varlistentry>
     <term><varname>cfs_bg_max_relations</varname> (<type>integer</type>)</term>
     <listitem>
      <para>
       Maximum number of relations to compact per pass.  Default
       <literal>2</literal>.
      </para>
     </listitem>
    </varlistentry>
   </variablelist>
 
   <para>
    Normal <command>VACUUM</command> (without <literal>FULL</literal>) does not
    trigger CFS compaction and does not interact with the background worker.
    Use <function>pg_cfs_compact()</function> or <command>VACUUM FULL</command>
    / <command>CLUSTER</command> to reclaim dead space.
   </para>
   </sect2>
 
   <sect2 id="storage-cfs-ddl">
    <title>DDL Lifecycle and Object Operations</title>
 
    <para>
     CFS reloptions are stored in <structname>pg_class</structname> and travel
     with the relation through all standard PostgreSQL DDL operations.
     The following commands preserve CFS behaviour automatically:
    </para>
 
    <variablelist>
     <varlistentry>
      <term><command>VACUUM FULL</command> / <command>CLUSTER</command></term>
      <listitem>
       <para>
        Rewrite the heap into a new relfilenumber.  The CFS reloptions are
        copied to the new relation; sidecar files are recreated for the new
        relfilenumber and the old sidecars are removed.  Dead records are not
        copied, so the physical size of <filename>.cfp</filename> shrinks.
       </para>
      </listitem>
     </varlistentry>
     <varlistentry>
      <term><command>REINDEX</command></term>
      <listitem>
       <para>
        Rebuilds the index into a new relfilenumber.  The rebuilt index
        keeps the index's own stored CFS policy: a compressed index is
        rebuilt compressed, and an index without a policy of its own is
        rebuilt plain whatever the parent table's policy is.
       </para>
      </listitem>
     </varlistentry>
      <varlistentry>
       <term><command>ALTER TABLE/INDEX ... SET TABLESPACE</command></term>
       <listitem>
        <para>
         Copies the relation files into the new tablespace.  The relation's
         CFS policy is published for the new relfilenumber before the copy
         starts, so the data is written through the CFS write path and the
         sidecar files are recreated in the new tablespace.  The TOAST table
         and its indexes follow the parent table's policy.
        </para>
       </listitem>
      </varlistentry>
      <varlistentry>
       <term><command>ALTER TABLE ... SET (algorithm = 'lz4'|'zstd')</command></term>
       <listitem>
        <para>
         Changing the algorithm triggers a full table rewrite so that every
         page is stored in the new compression format.  This applies when
         enabling CFS on a plain table, switching between algorithms, or
         resetting the algorithm back to plain storage.  Existing indexes
         are not affected: each index keeps the policy frozen in its own
         reloptions.
        </para>
       </listitem>
      </varlistentry>
      <varlistentry>
       <term><command>ALTER INDEX ... SET/RESET (algorithm)</command></term>
       <listitem>
        <para>
         <command>SET (algorithm = 'lz4'|'zstd')</command> stores the policy
         in the index's own reloptions and triggers an implicit
         <command>REINDEX</command> of that index alone, rather than a
         rewrite of the underlying table.  <command>RESET (algorithm)</command>
         removes the policy and rebuilds the index as a plain relation;
         compression stays disabled for good — a later
         <command>REINDEX</command> rebuilds plain storage again, never the
         table's policy.
        </para>
       </listitem>
      </varlistentry>
      <varlistentry>
       <term><command>ALTER TABLE ... SET (level|min_gain_bytes)</command></term>
       <listitem>
        <para>
         Changing the compression level or minimum gain threshold updates the
         reloptions only; no table rewrite occurs.  The new values apply to
         pages written after the change.
        </para>
       </listitem>
      </varlistentry>
      <varlistentry>
       <term><command>ALTER TABLE ... RESET (level|min_gain_bytes)</command></term>
       <listitem>
        <para>
         Removes the explicit value from the reloptions and returns the field
         to runtime resolution from the session parameters of each writer; no
         table rewrite occurs.  Resetting the
         <literal>algorithm</literal> itself switches the relation back to
         plain storage and requires a rewrite.
        </para>
       </listitem>
      </varlistentry>
     <varlistentry>
      <term><command>CREATE DATABASE ... TEMPLATE</command></term>
      <listitem>
       <para>
        When the template database contains CFS relations, the file-level
        copy publishes each source relation's CFS policy for the
        corresponding relation in the new database before the first page is
        copied, so the copy is written through the CFS write path from the
        start instead of landing in the new relation's plain main fork.
       </para>
      </listitem>
     </varlistentry>
    </variablelist>
 
    <para>
     CFS is not supported for <literal>TEMP</literal> or
     <literal>UNLOGGED</literal> relations.  <command>CREATE TEMP TABLE ...
     WITH (algorithm=...)</command> and <command>CREATE UNLOGGED TABLE ...
     WITH (algorithm=...)</command> are rejected.  <command>ALTER TABLE ...
     SET UNLOGGED</command> on a CFS table is also rejected.
    </para>
 
    <para>
     A partitioned table may store an explicit default policy for future
     partitions.  New partitions created with <command>CREATE TABLE
     ... PARTITION OF ...</command> inherit exactly the keys the parent
     stores explicitly — the <literal>algorithm</literal> plus, when set on
     the parent, <literal>level</literal> and
     <literal>min_gain_bytes</literal> — unless they specify their own CFS
     reloptions.  Unset fields on either side resolve at runtime from the
     physical writer's parameters.  Changing the partitioned root's default
     is a catalog-only change: it does not rewrite or otherwise affect
     existing partitions.
    </para>
 
    <para>
     Normal <command>VACUUM</command> (without <literal>FULL</literal>) does
     not trigger CFS compaction (see <xref linkend="storage-cfs-checkpoint"/>)
     and does not modify the <filename>.cfp</filename> file; it updates the
     visibility map and statistics by the same rules as for an ordinary
     table.
    </para>
   </sect2>
 
   <sect2 id="storage-cfs-recovery">
   <title>Crash Recovery, WAL and Replication</title>
 
   <para>
    CFS does not introduce its own WAL resource manager.  The WAL stream
    always contains standard uncompressed page images; compression happens
    only at the storage-manager write boundary.  Durability of CFS sidecar
    files is achieved through the append-only <filename>.cfp</filename>
    data file, the idempotent <filename>.cfsjrn</filename> journal, and the
    checkpoint-snapshot <filename>.cfsmap</filename>.
   </para>
 
   <para>
    On startup after a crash, <function>CfsRecoveryInit()</function>
    scans the data directories for <filename>.cfsjrn</filename> files and
    folds each journal into its page map row by row, through the same
    engine the checkpoint uses, before accepting client connections.  The
    fold is idempotent and handles torn final records gracefully; only the
    rows the journal names are rewritten, so the recovery scan's cost is
    proportional to the journal (the changes since the last checkpoint),
    never to the relation size: the scan itself loads no map into memory
    and rewrites no snapshot.  In a clean restart this is a fast
    no-op because journals were truncated at the last checkpoint.  As a
    consequence, a <filename>.cfsmap</filename> row corrupted without a
    covering journal record is not touched at startup: the damage
    surfaces at the first access of that block, through the normal
    checksum-failure policy.
   </para>
 
   <para>
    The journal records logical-size changes through the
    <literal>RESIZE</literal> operation, ensuring that
    <function>smgrnblocks()</function> returns the correct block count
    after crash recovery even when the last operations before the crash
    were <command>TRUNCATE</command> or <command>COPY</command>
    (zero-extend).
   </para>
 
    <para>
     <command>pg_basebackup</command> copies CFS sidecar files as part of
     the normal backup.  A standby initialised from the backup can read
     CFS tables immediately, and WAL replay writes dirty pages through the
     CFS storage path.  WAL redo prefetching remains a no-op for CFS
     relations — the startup prefetcher skips them, since a compressed
     record cannot be prefetched usefully ahead of the decompressing redo
     read — while user-level read-ahead hints do warm the
     <filename>.cfp</filename> page cache (see <xref
     linkend="storage-cfs-i-o"/>).
    </para>
 
    <para>
     Whether a server was built with CFS support is reported to every
     client, including physical replication connections, as a read-only
     parameter.  When a standby connects to start streaming, it compares
     this value against its own build and refuses the connection if they
     differ, in either direction, before requesting any WAL — a CFS-built
     primary and a non-CFS standby (or vice versa) cannot stream from each
     other.  If the mismatch is only discovered later, for example when
     replaying archived WAL during point-in-time recovery without ever
     opening a streaming connection, replay of the CFS policy record on a
     server without CFS support stops recovery with a clear error instead
     of an unrecognized-record-type failure.  Logical replication is not
     affected, since it never replays physical WAL records.
    </para>
 
    <para>
     Compaction cannot commit while any non-exclusive base backup is in
     progress: swapping the <filename>.cfp</filename>/<filename>.cfsmap</filename>
     pair underneath a running backup would let it assemble a mismatched
     sidecar trio that WAL replay cannot repair.  A manual
     <function>pg_cfs_compact()</function> call fails with an error during
     a backup, and the background compaction worker skips the pass.
    </para>
 
    <para>
     <command>pg_basebackup --incremental</command> handles the
     <filename>.cfp</filename> data files with an append-only tail diff.
     The first bytes of every <filename>.cfp</filename> form a lead-in that
     records the file-creation <firstterm>epoch</firstterm>: it changes only
     when the file is replaced wholesale (relation creation, compaction
     swap), never during append-only growth.  Every backup manifest entry
     for a <filename>.cfp</filename> file carries two fork-specific fields,
     <literal>CFS-Epoch</literal> and <literal>CFS-Logical-Size</literal>.
     When the next incremental backup sees the same epoch and a size not
     smaller than the recorded logical size, only the blocks covering the
     grown tail are sent, inside an incremental file whose header
     (fork-specific magic <literal>INCREMENTAL_CFS_MAGIC</literal>) stores
     the exact byte size of the file; <command>pg_combinebackup</command>
     truncates the reconstruction to that size, because a
     <filename>.cfp</filename> file is not aligned to the block size.
     Otherwise — a legacy file with zero epoch, an epoch mismatch after
     compaction, a shrunk file, or a file missing from the prior manifest —
     the file is backed up fully.  The <filename>.cfsmap</filename> and
     <filename>.cfsjrn</filename> files are rewritten wholesale at
     checkpoints and are always copied fully.  Note that manifests carrying
     the CFS fields are a fork extension of the manifest format and are
     rejected by upstream <productname>PostgreSQL</productname> tools.
    </para>
 
    <para>
     <command>pg_rewind</command> synchronises CFS sidecar files as
     ordinary files, copying them in full from the source; the empty main
     fork marker of a CFS relation never takes part in the per-block
     rewinding.  When the target replays the source WAL from the last
     common checkpoint, every CFS page modified after the copy began is
     rewritten through the CFS storage path, which makes the result
     consistent.  To keep a compaction swap from racing the copy on a
     running source server, <command>pg_rewind</command> holds a
     non-exclusive backup on the source for the duration of the transfer
     whenever CFS sidecar files are present; the connection to the source
     therefore needs privileges to run <function>pg_backup_start()</function>
     and <function>pg_backup_stop()</function> in addition to the usual
     <command>pg_rewind</command> permissions.  A stopped source server
     needs no such quiesce.
    </para>
 
 
   <variablelist>
    <varlistentry>
     <term><varname>cfs_checksum_failure</varname> (<type>enum</type>)</term>
     <listitem>
      <para>
       Controls the severity when a CFS CRC or format check — including
       structural damage such as an invalid <filename>.cfsmap</filename>
       prologue or <filename>.cfsjrn</filename> header — fails during a
       normal backend read.  <literal>error</literal> (default) raises an
       error, and <literal>panic</literal> aborts the server.  This
       parameter is superuser-only and is set at session level.  A
       <literal>warning</literal> mode is intentionally not provided,
       because silently substituting data on corruption would cause
       divergence between primary and standby.
      </para>
     </listitem>
    </varlistentry>
    <varlistentry>
     <term><varname>cfs_skip_page_checksum</varname> (<type>boolean</type>)</term>
     <listitem>
      <para>
       When <literal>true</literal> (the default), the buffer manager skips
       the cluster page-checksum computation for pages delivered by the CFS
       read path, because the CFS CRC chain (header, payload and
       original-image CRCs) has already verified the exact bytes; the
       header sanity checks of <function>PageIsVerified()</function> are
       always performed.  When <literal>false</literal>, the second
       full-page hash is restored (the double-check behaviour).  This
       parameter is superuser-only and is set at session level.  The
       decision is bound at <acronym>I/O</acronym> submit time in the
       originating backend, so a session changing it affects only reads
       whose I/Os are submitted afterwards.
      </para>
     </listitem>
    </varlistentry>
    <varlistentry>
     <term><varname>cfs_recovery_strict</varname> (<type>boolean</type>)</term>
     <listitem>
      <para>
       When <literal>true</literal>, journal record corruption encountered
       during crash recovery is treated as a fatal error rather than being
       tolerated: a skipped record (whose referenced data file contents are
       missing) and a torn record with data still following it both abort
       startup.  A torn <emphasis>final</emphasis> record — the normal
       artifact of a crash mid-append — stays non-fatal in both modes.  A
       corrupt <filename>.cfsmap</filename> or
       <filename>.cfsjrn</filename> header is fatal in every mode,
       independently of this parameter: the map header is a synchronisation
       point whose data WAL does not cover, and a journal header that fails
       validation means the file cannot be trusted to describe itself.
       Default is <literal>false</literal>.  This parameter is set at
       server start.
      </para>
     </listitem>
     </varlistentry>
    </variablelist>
   </sect2>
 
   <sect2 id="storage-cfs-monitoring">
    <title>Monitoring and SQL Interface</title>
 
    <para>
     CFS exposes its configuration, runtime statistics and administration
     surface through a set of system views and functions.  All of them are
     available in the <literal>pg_catalog</literal> schema and visible to
     every role that can see the underlying relation.
    </para>
 
    <para>
     The <literal>pg_cfs_settings</literal> view lists the stored CFS policy
     of every supported relation: whether it is compressed
     (<structfield>is_cfs</structfield>), the
     <structfield>algorithm</structfield>, <structfield>level</structfield>
     and <structfield>min_gain_bytes</structfield>, and the classification
     flags (<structfield>is_toast</structfield>,
     <structfield>is_index</structfield>,
     <structfield>is_partitioned_root</structfield>,
     <structfield>is_supported</structfield>).  A
     <structfield>level</structfield> or
     <structfield>min_gain_bytes</structfield> field the relation does not
     store explicitly is reported as <literal>0</literal>, not resolved from
     the session parameters.  Because <literal>0</literal> is also a valid
     <structfield>min_gain_bytes</structfield> value (its range starts at 0),
     a zero there does not by itself distinguish an unset field from an
     explicit <literal>0</literal>; the
     <structfield>level_effective</structfield> and
     <structfield>min_gain_effective</structfield> columns of
     <function>pg_cfs_relation_info</function> resolve the unset fields from
     the current session's parameters and disambiguate the two cases.
     Ordinary relations appear with <structfield>is_cfs</structfield> set to
     false.
    </para>
 
    <para>
     The <literal>pg_stat_cfs</literal> view reports one row per CFS relation
     with its <structfield>algorithm</structfield>, the logical and physical
     sizes, the number of compressed and uncompressed pages, the dead-space
     counters
     (<structfield>dead_pages</structfield>,
     <structfield>dead_bytes</structfield>), the derived
     <structfield>compression_ratio</structfield> and
     <structfield>space_saved</structfield>, the operation counters
     (<structfield>read_count</structfield>, <structfield>write_count</structfield>,
     <structfield>compress_count</structfield>,
     <structfield>decompress_count</structfield>), the batched-read counters
     (<structfield>read_batch_count</structfield>,
     <structfield>read_batched_pages</structfield>,
     <structfield>read_fallback_pages</structfield>), the number of
     <structfield>crc_failures</structfield>, and the
     <structfield>last_reset</structfield> and
     <structfield>last_compaction</structfield> timestamps.  The
     batched-read counters attribute every page served through the storage
     manager either to a physically contiguous span read (one
     <literal>pread</literal> per run of neighbouring records) or to the
     per-block fallback path; the invariant
     <literal>read_count&nbsp;=&nbsp;read_batched_pages&nbsp;+&nbsp;
     read_fallback_pages</literal>
     holds in both map modes (on a private map the per-block reads are
     counted by neither side, mirroring the historical read_count
     behaviour), and
     <literal>read_batched_pages&nbsp;/&nbsp;read_batch_count</literal> is
     the average span length in pages.
     Both counters describe the last checkpoint:
     <structfield>dead_bytes</structfield> is recomputed from the relation
     map and the physical data size - an advisory snapshot of the
     checkpoint's map refresh, so records a writer appends during the
     checkpoint itself are not yet in it (the value never understates the
     dead space) - and
     <structfield>dead_pages</structfield> accumulates the superseded page
     versions the checkpoint folds carried (a folded record that replaced
     a previously written row is one dead page version).  Between
     checkpoints the counters hold the last checkpoint's values.  The cumulative
     <structfield>checkpoint_map_rows_written</structfield> counter shows
     how many map rows the checkpoints folded into the map for the
     relation: it grows with the number of blocks changed between
     checkpoints, not with the size of the map, because a checkpoint
     writes only the journal's records into the map (the full map
     snapshot is written only by an immediate sync).  The
     counter counts folded journal records, not distinct rows: a block
     rewritten several times between checkpoints adds one per rewrite,
     because the fold carries every record the journal holds.
     The counters are cleared by an explicit
     <function>pg_cfs_reset_stats</function> call; a statistics row evicted
     under capacity pressure also restarts from zero (see below).
     In particular, <structfield>crc_failures</structfield> is not
     cleared when the shared map cache of a relation is invalidated (for
     example after the very read failure that incremented it, or when the
     relation is dropped), so a non-zero value always means real corruption
     was observed since the last explicit reset or eviction of the
     relation's row.
    </para>
 
    <para>
     The view holds one statistics row per relation in a fixed-size
     shared-memory table of
     <varname>cfs_stats_slots_per_partition</varname> slots per partition
     (1024 relations with the default).  When more CFS relations than
     that are active, rows evict each other: the least recently used row
     is reset to zero and its counters are lost; when the relation
     becomes active again, its counters restart from zero.  Counters are
     updated atomically under a shared lock, so the view may combine
     values read at slightly different instants - each counter is exact
     on its own, the same consistency model as cumulative statistics of
     the core server.
    </para>
 
    <para>
     The counters are saved to a file at a regular shutdown and restored
     at the next startup, so a maintenance restart does not lose the
     dead-space bookkeeping the automatic compactor relies on.  After a
     crash (or immediate) restart the restored
     <structfield>dead_bytes</structfield> may predate the crash, so it
     is recomputed from the relation's page map at the first
     measurement: by the background compactor's first full cycle over
     the cluster's databases (relations without a saved entry included)
     and by the relation's next checkpoint, which rebuilds its baseline
     from the map it has just folded.
     <structfield>dead_pages</structfield> cannot be derived from the
     map and keeps the restored value.  A clean restart performs no
     recomputation - the saved values are current - unless the previous
     clean shutdown overtook the recomputation still pending after an
     earlier crash restart, in which case it runs on that clean start
     as well.
    </para>
 
    <para>
     The diagnostic functions are:
    </para>
 
    <variablelist>
      <varlistentry>
       <term><function>pg_cfs_relation_info</function>(<type>regclass</type>)</term>
       <listitem>
        <para>
         Returns a single row describing the effective CFS policy of a relation
         and its classification (heap, index, TOAST, partitioned root,
         supported).  Policy fields the relation does not store explicitly
         are returned as NULL; the
         <structfield>level_effective</structfield> and
         <structfield>min_gain_effective</structfield> columns resolve the
         unset fields from the current session's parameters, the same way
         the write path does.
        </para>
       </listitem>
      </varlistentry>
     <varlistentry>
      <term><function>pg_cfs_relation_size</function>(<type>regclass</type>)</term>
      <listitem>
       <para>
        Returns the logical size and the size of each CFS sidecar file
        (<structfield>cfp_size</structfield>, <structfield>map_size</structfield>,
        <structfield>journal_size</structfield>).
       </para>
      </listitem>
     </varlistentry>
     <varlistentry>
      <term><function>pg_cfs_check</function>(<type>regclass</type>, <type>boolean</type> DEFAULT false)</term>
      <listitem>
       <para>
        Runs the structural integrity checker over the sidecar files.  With
        <literal>deep</literal> set to true every block header in the
        <filename>.cfp</filename> file is validated.  The checker streams the
        files in bounded-size chunks, so sidecars larger than 1
        <acronym>GB</acronym> are validated the same way as small ones, and it
        walks every <filename>.cfp.<replaceable>N</replaceable></filename>
        segment.  A map row that is corrupt but still covered by a journal
        record is reported as healed
        (<literal>healed_entries</literal> in the details) instead of damage,
        and the set of such rows kept in memory is bounded.  Journal records
        are additionally checked for
        <structfield>generation</structfield> monotonicity per block: a zero
        generation is reported as corruption, while a non-increasing
        sequence is counted as an anomaly
        (<structfield>generation_violations</structfield>) without failing
        the check, because concurrent backends may legitimately compute the
        generation from a stale local map.  A non-CFS relation
        returns <literal>ok=true, is_cfs=false</literal> without raising an
        error.  The function is strict: a NULL argument returns NULL.
       </para>
      </listitem>
     </varlistentry>
     <varlistentry>
      <term><function>pg_cfs_estimate_compression</function>(<type>regclass</type>, <type>text</type>, <type>integer</type> DEFAULT NULL, <type>real</type> DEFAULT 10)</term>
      <listitem>
       <para>
        Compresses a random sample of the relation's pages in memory with the
        named algorithm and level and reports the estimated compression ratio
        and space that would be saved, without writing anything to disk or
        changing the reloptions.  Useful to gauge the benefit of CFS before
        running <command>ALTER TABLE ... SET (algorithm=...)</command>.
        The sample is drawn at random, like the one used by
        <command>ANALYZE</command>, so repeated calls on the same relation
        may return slightly different numbers.
         A NULL <literal>relation</literal>, <literal>algorithm</literal> or
         <literal>sample_pct</literal> raises an error; a NULL
         <literal>level</literal> selects the per-algorithm session default.
       </para>
      </listitem>
     </varlistentry>
    </variablelist>
 
    <para>
     The administrative functions <function>pg_cfs_compact</function>,
     <function>pg_cfs_check</function>,
     <function>pg_cfs_estimate_compression</function>,
     <function>pg_cfs_reset_stats</function>,
     <function>pg_cfs_bgworker_pause</function> and
     <function>pg_cfs_bgworker_resume</function> are not executable by
     <literal>PUBLIC</literal>: by default only a superuser can call them,
     and access may be delegated with an explicit
     <command>GRANT EXECUTE</command>.  Independently of the function
     privilege, <function>pg_cfs_compact</function> requires ownership of
     the target relation, mirroring the permission model of
     <command>VACUUM FULL</command> and <command>CLUSTER</command>.
     <function>pg_cfs_check</function> and
     <function>pg_cfs_estimate_compression</function> are closed for the
     same reason as <function>pg_read_file()</function>: the former, with
     <literal>deep=true</literal>, reads and validates every byte of the
     sidecars, and the latter reads and compresses a share of the
     relation's real pages — in both cases a single call costs IO and
     CPU proportional to the sampled data, without requiring any
     privilege on the relation itself.  The lightweight read-only
     diagnostics (<function>pg_cfs_relation_info</function>,
     <function>pg_cfs_bgworker_status</function>) and the monitoring
     views remain available to all roles.
    </para>
 
    <para>
     <function>pg_cfs_reset_stats</function>(<type>regclass</type> DEFAULT
     NULL) clears the <literal>pg_stat_cfs</literal> counters, including
     <structfield>crc_failures</structfield>, for one relation, or for every
     CFS relation in the cluster when called with no argument (or an explicit
     <literal>NULL</literal>).
    </para>
 
    <para>
     Compaction is administered separately from the table reloptions (see
     <xref linkend="storage-cfs-checkpoint"/>).  The synchronous function
     <function>pg_cfs_compact</function>(<type>regclass</type>) rewrites the
     sidecar files of one relation and records the completion time in
     <literal>pg_stat_cfs.last_compaction</literal>.  By default it runs
     online under <literal>ShareUpdateExclusiveLock</literal>
     (<varname>cfs_compact_online</varname> enabled): ordinary reads and
     writes of the relation keep running during the rewrite.  When
     <varname>cfs_compact_online</varname> is off, the same
     <literal>ShareUpdateExclusiveLock</literal> is taken, but the internal
     append lock is held for the whole operation, so writes to the sidecar
     files are serialized until compaction finishes (plain reads are not
     blocked).  The background worker acquires the lock with the
     <varname>cfs_bg_respond_time_s</varname> timeout and skips the
     candidate on timeout; the manual function blocks until the lock is
     granted.  The progress of an in-progress compaction (manual or
     automatic) is visible through
     <literal>pg_stat_progress_cfs_compact</literal>, which reports the
     <structfield>phase</structfield>
     (<literal>initializing</literal>, <literal>copying live blocks</literal>,
     <literal>transferring concurrent appends</literal> or
     <literal>durable swap</literal>), the total and processed block counts
     and the <structfield>started_at</structfield> timestamp.
    </para>
 
    <para>
     The automatic background compactor can be suspended temporarily with
     <function>pg_cfs_bgworker_pause</function>(<type>interval</type>), which
     accepts an optional duration, and resumed with
     <function>pg_cfs_bgworker_resume</function>().  The current state is
     returned by <function>pg_cfs_bgworker_status</function>(), which reports
     whether the worker is currently <structfield>paused</structfield>, the
     <structfield>paused_until</structfield> timestamp if a duration was
     given, and the <structfield>last_cycle_started_at</structfield> and
     <structfield>last_cycle_finished_at</structfield> timestamps of the most
     recent pass.  A pause does
     not interrupt an already-running compaction and does not affect manual
     <function>pg_cfs_compact</function> calls; it is cleared automatically on
     server restart.
    </para>
 
    <para>
     The shared block-map segment pool (see
     <varname>cfs_map_memory</varname>) is observed through
     <function>pg_cfs_map_pool</function>(), a single row with the number of
     segments currently held (<structfield>segments_in_use</structfield>),
     how many were loaded from the <filename>.cfsmap</filename> snapshot
     (<structfield>segment_loads</structfield>), how many were reclaimed by
     eviction (<structfield>segment_evictions</structfield>), the total
     pool capacity (<structfield>pool_segments</structfield>) and how many
     reads were served through a private authoritative map because no
     segment was available (<structfield>fallback_reads</structfield>).  A
     stable <structfield>segment_loads</structfield> across checkpoints
     confirms that resident segments stay warm instead of being re-read by
     every backend; a growing
     <structfield>fallback_reads</structfield> means the pool is undersized
     for the current working set.
    </para>
 
    <para>
     CFS reports six <literal>IO</literal>-class wait events visible in
     <link linkend="monitoring-stats-views"><literal>pg_stat_activity</literal></link>
     and <literal>pg_wait_events</literal>: <literal>CfsRead</literal>,
     <literal>CfsWrite</literal>, <literal>CfsFsync</literal>,
     <literal>CfsJournalReplay</literal>, <literal>CfsCompact</literal> and
     <literal>CfsDecompress</literal>.  <literal>CfsRead</literal> covers
     the <literal>pread</literal> of a record or a record span only, while
     <literal>CfsDecompress</literal> covers the validation and
     decompression of the records, so wait-event sampling can attribute the
     read phase (IO) and the decompression phase (CPU) independently.
    </para>
   </sect2>
 
   <sect2 id="storage-cfs-utilities">
    <title>Standard Utilities and Contrib</title>
 
    <para>
     CFS is designed so that the standard PostgreSQL tooling works on a
     cluster that uses compressed relations without special procedures.  The
     sidecar files live alongside the relation main-fork file and are
     enumerated, copied and verified by the usual mechanisms.
    </para>
 
    <variablelist>
     <varlistentry>
      <term>Size functions</term>
      <listitem>
       <para>
        <function>pg_relation_size</function>(<type>regclass</type>,
        <literal>'main'</literal>) for a CFS relation returns the physical
        on-disk size of the main fork, which includes the
        <filename>.cfp</filename>, <filename>.cfsmap</filename> and
        <filename>.cfsjrn</filename> sidecar files (the base main-fork file is
        only a compatibility marker).  This lets users compare a compressed
        relation against a plain one and see the actual space savings.
        <function>pg_total_relation_size</function>,
        <function>pg_database_size</function> and
        <function>pg_tablespace_size</function> include sidecar bytes through
        the same path or via directory enumeration.
       </para>
      </listitem>
     </varlistentry>
 
     <varlistentry>
      <term>Physical backups</term>
      <listitem>
       <para>
        <link linkend="app-pgbasebackup"><command>pg_basebackup</command></link>
        copies sidecar files as ordinary files (they are not in any exclusion
        list), and the backup manifest records their SHA-256 checksums.  A
        restored backup starts up and reads CFS relations normally.
        <link linkend="app-pgverifybackup"><command>pg_verifybackup</command></link>
        verifies sidecar integrity through the manifest; a corrupted
        <filename>.cfp</filename> is detected exactly like any other file
        mismatch.
       </para>
      </listitem>
     </varlistentry>
 
     <varlistentry>
      <term><command>pg_checksums</command></term>
      <listitem>
       <para>
        Page-level checksums do not apply to sidecar files, which carry their
        own CRC-32C integrity protection.
        <link linkend="app-pgchecksums"><command>pg_checksums</command></link>
        recognises the <filename>.cfp</filename>, <filename>.cfsmap</filename>
        and <filename>.cfsjrn</filename> suffixes (including numbered
        <filename>.cfp.<replaceable>N</replaceable></filename> segments),
        skips them and reports the number of skipped files both in
        <option>--verbose</option> output and in the final summary.
       </para>
      </listitem>
     </varlistentry>
 
     <varlistentry>
      <term><command>pg_upgrade</command></term>
      <listitem>
       <para>
        <link linkend="pgupgrade"><command>pg_upgrade</command></link>
        transfers <filename>.cfp</filename>, <filename>.cfsmap</filename> and
        <filename>.cfsjrn</filename> for every relation using the same
        clone/copy/link mode as the main fork.  Before any file is moved the
        upgrade performs a compatibility scan of the old cluster's
        <filename>.cfsmap</filename> headers and aborts with a clear message if
        an incompatible on-disk format is detected, so that an upgrade never
        leaves a half-migrated cluster.  The on-disk format version is checked
        again by the server when the relation is opened after the upgrade.
       </para>
      </listitem>
     </varlistentry>
 
     <varlistentry>
      <term>Contrib extensions</term>
      <listitem>
       <para>
        <link linkend="pageinspect"><literal>pageinspect</literal></link>,
        <link linkend="amcheck"><literal>amcheck</literal></link> and
        <link linkend="pgstattuple"><literal>pgstattuple</literal></link>
        require no CFS-specific changes: they read pages through the buffer
        manager, which transparently returns decompressed
        <literal>BLCKSZ</literal> pages, so all existing functions
        (<function>get_raw_page</function>, <function>verify_heapam</function>,
        <function>bt_index_check</function>, <function>pgstattuple</function>,
        etc.) work unchanged on CFS tables and CFS-inherited indexes.
       </para>
      </listitem>
     </varlistentry>
    </variablelist>
   </sect2>
 
  </sect1>