Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2026-10-06 6bac54b555d27f1a85c1e4f011a6e7bd9111b0d0
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
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
#include "ash.hpp"
 
/*
 * Серверные процессы публикуют текущий SQL-оператор
 * в слотах активности разделяемой памяти.
 *
 * Фоновый процесс периодически сохраняет устойчивые слоты
 * в кольцевой буфер записей ASH. Полный текст SQL хранится
 * отдельно в блочном кэше. При создании снимка AWR выбранные
 * записи переносятся в постоянное историческое хранилище.
 */
 
#include <algorithm>
#include <array>
#include <cctype>
#include <cstddef>
#include <cstdint>
#include <exception>
#include <cstdio>
#include <cstring>
#include <limits>
#include <map>
#include <iterator>
#include <optional>
#include <set>
#include <string>
#include <vector>
 
extern "C"
{
#include "access/subtrans.h"
#include "access/xact.h"
#include "catalog/pg_authid_d.h"
#include "catalog/pg_type_d.h"
#include "commands/dbcommands.h"
#include "common/md5.h"
#include "executor/executor.h"
#include "executor/spi.h"
#include "fmgr.h"
#include "libpq/pqsignal.h"
#include "miscadmin.h"
#include "postmaster/bgworker.h"
#include "postmaster/interrupt.h"
#include "portability/instr_time.h"
#include "storage/ipc.h"
#include "storage/latch.h"
#include "storage/lwlock.h"
#include "storage/proc.h"
#include "storage/procsignal.h"
#include "storage/shmem.h"
#include "tcop/tcopprot.h"
#include "tcop/utility.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/date.h"
#include "utils/elog.h"
#include "utils/guc.h"
#include "utils/guc_hooks.h"
#include "utils/memutils.h"
#include "utils/ps_status.h"
#include "utils/rudb_ash_startup.h"
#include "utils/snapmgr.h"
#include "utils/timestamp.h"
#include "utils/wait_event.h"
}
 
namespace
{
constexpr uint32 kAshMagic = 0x52554442U;
constexpr uint32 kAshVersion = 2;
constexpr int kDefaultRetentionSeconds = 86400;
constexpr int kDefaultSampleIntervalMs = 1000;
constexpr uint32 kMaxModuleNameLength = NAMEDATALEN;
constexpr uint32 kMaxEventLength = 96;
constexpr uint32 kMaxStateLength = 24;
constexpr uint32 kSampleCapacity = 8192;
constexpr uint32 kSqlCacheCapacity = 1024;
constexpr uint32 kSqlChunkCapacity = 8192;
constexpr uint32 kSqlChunkPayloadLength = 256;
constexpr uint64 kMaxSqlTextBytes =
    static_cast<uint64>(kSqlChunkCapacity) * kSqlChunkPayloadLength;
constexpr uint32 kInvalidChunkIndex = std::numeric_limits<uint32>::max();
constexpr uint32 kSampleSequenceCounterBits = 20;
constexpr uint64 kSampleSequenceCounterLimit = UINT64CONST(1) << kSampleSequenceCounterBits;
constexpr uint32 kWorkerLockCount = 1;
constexpr const char* kAshShmemName = "rudb_ash";
constexpr const char* kAshTrancheName = "rudb_ash";
constexpr const char* kHistorySampleTable = "pg_catalog.rudb_ash_history_samples";
constexpr const char* kHistorySqlTextTable = "pg_catalog.rudb_ash_history_sqltext";
constexpr const char* kAwrSnapshotTable = "pg_catalog.rudb_awr_snapshots";
constexpr const char* kAwrSnapshotSequence = "pg_catalog.rudb_awr_snapshot_id_seq";
 
struct ResolutionInfo
{
    const char* name;
    int bucket_count;
};
 
struct AshActivitySlot
{
    /*
     * Один слот соответствует одному серверному процессу.
     * Нечётное значение `publish_seq` означает запись,
     * чётное позволяет читателю проверить устойчивость данных.
     */
    pg_atomic_uint64 generation;
    pg_atomic_uint64 publish_seq;
    pg_atomic_uint64 started_at;
    pg_atomic_uint32 active;
    uint32 wait_event_info;
    int pid;
    int proc_number;
    int64 session_generation;
    int backend_type;
    Oid user_id;
    Oid database_id;
    uint32 sql_cache_slot;
    uint64 sql_cache_generation;
    char sql_id[MD5_DIGEST_LENGTH * 2 + 1];
    char module_name[kMaxModuleNameLength];
    char application_name[kMaxModuleNameLength];
    char state[kMaxStateLength];
};
 
struct ActivitySlotSnapshot
{
    uint64 generation = 0;
    uint64 started_at = 0;
    uint32 active = 0;
    uint32 wait_event_info = 0;
    int pid = 0;
    int proc_number = 0;
    int64 session_generation = 0;
    int backend_type = 0;
    Oid user_id = InvalidOid;
    Oid database_id = InvalidOid;
    uint32 sql_cache_slot = kSqlCacheCapacity;
    uint64 sql_cache_generation = 0;
    char sql_id[MD5_DIGEST_LENGTH * 2 + 1];
    char module_name[kMaxModuleNameLength];
    char application_name[kMaxModuleNameLength];
    char state[kMaxStateLength];
};
 
struct AshSharedSample
{
    /* `sample_sequence` однозначно определяет запись ASH, а
     * `sample_generation` защищает повторное использование ячейки кольцевого буфера. */
    uint64 sample_sequence;
    uint64 sample_generation;
    uint64 activity_generation;
    TimestampTz sample_time;
    int64 dbid;
    int64 instance_number;
    int64 session_id;
    int64 session_serial;
    int64 session_generation;
    TimestampTz started_at;
    int backend_type;
    int64 snap_id;
    Oid user_id;
    uint32 wait_event_info;
    bool is_awr_sample;
    bool sql_text_complete;
    uint32 sql_cache_slot;
    uint64 sql_cache_generation;
    char sql_id[MD5_DIGEST_LENGTH * 2 + 1];
    char module_name[kMaxModuleNameLength];
    char application_name[kMaxModuleNameLength];
    char state[kMaxStateLength];
    char command_type[16];
};
 
struct AshSharedSqlTextEntry
{
    /*
     * Каталог содержит метаданные текста SQL, а сами данные
     * размещаются в цепочке блоков. Запись нельзя вытеснять,
     * пока её счётчик ссылок больше нуля.
     */
    uint64 generation;
    TimestampTz first_seen;
    TimestampTz last_seen;
    int64 dbid;
    Oid user_id;
    uint64 refcount;
    uint32 head_chunk;
    uint32 byte_length;
    bool complete;
    char sql_id[MD5_DIGEST_LENGTH * 2 + 1];
    char command_type[16];
};
 
struct AshSharedSqlTextChunk
{
    /* Полный текст SQL хранится цепочкой блоков; при совпадении SQL_ID
     * с другим текстом SQL источник возвращает пустой результат. */
    uint32 next_chunk;
    uint32 used_bytes;
    char payload[kSqlChunkPayloadLength];
};
 
struct AshSharedHeader
{
    uint32 magic;
    uint32 version;
    uint32 activity_slot_count;
    uint32 sample_capacity;
    uint32 sql_cache_capacity;
    uint32 sample_interval_ms;
    uint32 retention_seconds;
    pid_t worker_pid;
    uint64 sample_sequence_epoch_milliseconds;
    uint64 next_local_sample_sequence;
    /* Последовательность определяет запись ASH, а позиция — физическую
     * ячейку кольцевого буфера фиксированного размера. */
    uint64 next_ring_position;
    uint64 next_sample_generation;
    uint64 next_sql_cache_generation;
    uint64 last_sample_time;
    uint64 worker_cycles;
    uint64 dropped_samples;
    uint64 active_slots_seen;
    uint64 samples_written;
    uint64 reject_unstable_publication;
    uint64 reject_inactive_slot;
    uint64 reject_invalid_proc_number;
    uint64 reject_missing_pgproc;
    uint64 reject_pid_mismatch;
    uint64 reject_self_pid;
    uint64 reject_invalid_database;
    uint64 reject_sql_cache_reference;
    /* Список свободных блоков текста SQL изменяется под `g_ash_lock`. */
    uint32 free_sql_chunk_head;
    uint32 free_sql_chunk_count;
};
 
struct ReportStats
{
    std::size_t sample_count_total = 0;
    std::size_t sample_count_matched = 0;
    std::size_t sql_text_entry_count = 0;
    std::size_t distinct_sql_id_count_matched = 0;
    std::optional<std::string> top_sql_id;
    std::optional<std::string> top_wait_class;
};
 
struct MemoryArchiveCandidate
{
    rudb::ash::SampleRow row;
    uint64 sample_generation = 0;
    uint64 activity_generation = 0;
    uint32 sql_cache_slot = kSqlCacheCapacity;
    uint64 sql_cache_generation = 0;
};
 
struct SharedSampleSnapshot
{
    AshSharedSample sample;
    bool sql_reference_retained = false;
};
 
struct PendingArchiveMark
{
    uint64 sample_sequence = 0;
    uint64 sample_generation = 0;
    uint64 activity_generation = 0;
    int64 snap_id = 0;
    SubTransactionId subxid = InvalidSubTransactionId;
};
 
struct PendingSnapshotClearMark
{
    int64 dbid = 0;
    int64 low_snap_id = 0;
    int64 high_snap_id = 0;
    SubTransactionId subxid = InvalidSubTransactionId;
};
 
struct ActivityFrame
{
    std::string normalized_sql;
    std::string sql_id;
    std::string command_type;
    std::string state;
    std::string module_name;
    std::string application_name;
    TimestampTz started_at = 0;
    uint32 sql_cache_slot = 0;
    uint64 sql_cache_generation = 0;
    int nest_level = 0;
    SubTransactionId subxid = InvalidSubTransactionId;
    const void* owner = nullptr;
    bool published = false;
};
 
enum class SlotReadResult
{
    SampleReady,
    Inactive,
    UnstablePublication,
    InvalidProcNumber,
    MissingProc,
    PidMismatch,
    SelfPid,
    InvalidDatabase
};
 
bool g_gucs_defined = false;
bool g_postmaster_initialized = false;
bool g_backend_initialized = false;
bool g_archive_backend_initialized = false;
bool g_hooks_installed = false;
bool g_xact_callbacks_installed = false;
bool g_subxact_callbacks_installed = false;
volatile sig_atomic_t g_worker_shutdown_requested = false;
int g_retention_seconds = kDefaultRetentionSeconds;
int g_sample_interval_ms = kDefaultSampleIntervalMs;
bool g_capture_enabled = false;
 
shmem_request_hook_type g_prev_shmem_request_hook = nullptr;
shmem_startup_hook_type g_prev_shmem_startup_hook = nullptr;
ExecutorStart_hook_type g_prev_executor_start_hook = nullptr;
ExecutorEnd_hook_type g_prev_executor_end_hook = nullptr;
ProcessUtility_hook_type g_prev_process_utility_hook = nullptr;
 
AshSharedHeader* g_shared = nullptr;
LWLock* g_ash_lock = nullptr;
 
std::vector<PendingArchiveMark>&
pending_archive_marks(void)
{
    static auto* marks = new std::vector<PendingArchiveMark>();
    return *marks;
}
 
std::vector<PendingSnapshotClearMark>&
pending_snapshot_clear_marks(void)
{
    static auto* marks = new std::vector<PendingSnapshotClearMark>();
    return *marks;
}
 
std::vector<ActivityFrame>&
activity_stack(void)
{
    static auto* frames = new std::vector<ActivityFrame>();
    return *frames;
}
 
inline uint32
activity_slot_count(void)
{
    return static_cast<uint32>(MaxBackends + NUM_AUXILIARY_PROCS);
}
 
inline Size
activity_slots_size(void)
{
    return mul_size(activity_slot_count(), sizeof(AshActivitySlot));
}
 
inline Size
sample_ring_size(void)
{
    return mul_size(kSampleCapacity, sizeof(AshSharedSample));
}
 
inline Size
sql_cache_size(void)
{
    return mul_size(kSqlCacheCapacity, sizeof(AshSharedSqlTextEntry));
}
 
inline Size
sql_chunk_arena_size(void)
{
    return mul_size(kSqlChunkCapacity, sizeof(AshSharedSqlTextChunk));
}
 
Size
shared_state_size(void)
{
    Size size = MAXALIGN(sizeof(AshSharedHeader));
    size = add_size(size, activity_slots_size());
    size = add_size(size, sample_ring_size());
    size = add_size(size, sql_cache_size());
    size = add_size(size, sql_chunk_arena_size());
    return MAXALIGN(size);
}
 
inline AshActivitySlot*
activity_slots(void)
{
    return reinterpret_cast<AshActivitySlot*>(
        reinterpret_cast<char*>(g_shared) + MAXALIGN(sizeof(AshSharedHeader)));
}
 
inline AshSharedSample*
sample_ring(void)
{
    return reinterpret_cast<AshSharedSample*>(
        reinterpret_cast<char*>(activity_slots()) + activity_slots_size());
}
 
inline AshSharedSqlTextEntry*
sql_cache(void)
{
    return reinterpret_cast<AshSharedSqlTextEntry*>(
        reinterpret_cast<char*>(sample_ring()) + sample_ring_size());
}
 
inline AshSharedSqlTextChunk*
sql_chunk_arena(void)
{
    return reinterpret_cast<AshSharedSqlTextChunk*>(
        reinterpret_cast<char*>(sql_cache()) + sql_cache_size());
}
 
std::string
trim_ascii_copy(const std::string& value)
{
    std::size_t begin = 0;
    std::size_t end = value.size();
 
    while (begin < end && std::isspace(static_cast<unsigned char>(value[begin])) != 0)
        ++begin;
 
    while (end > begin && std::isspace(static_cast<unsigned char>(value[end - 1])) != 0)
        --end;
 
    return value.substr(begin, end - begin);
}
 
std::string
uppercase_ascii_copy(const std::string& value)
{
    std::string result = value;
    std::transform(result.begin(), result.end(), result.begin(),
                   [](unsigned char ch) { return static_cast<char>(std::toupper(ch)); });
    return result;
}
 
std::string
xml_escape(const std::string& value)
{
    std::string result;
    result.reserve(value.size());
 
    for (const char ch : value)
    {
        switch (ch)
        {
            case '&':
                result += "&amp;";
                break;
            case '<':
                result += "&lt;";
                break;
            case '>':
                result += "&gt;";
                break;
            case '"':
                result += "&quot;";
                break;
            case '\'':
                result += "&apos;";
                break;
            default:
                result.push_back(ch);
                break;
        }
    }
 
    return result;
}
 
void
copy_cstring_field(char* dest, std::size_t capacity, const std::string& value)
{
    if (capacity == 0)
        return;
 
    snprintf(dest, capacity, "%s", value.c_str());
}
 
void
copy_cstring_field(char* dest, std::size_t capacity, const char* value)
{
    if (capacity == 0)
        return;
 
    snprintf(dest, capacity, "%s", value != nullptr ? value : "");
}
 
std::string
cstring_field_to_string(const char* value)
{
    return value == nullptr ? std::string() : std::string(value);
}
 
bool
is_valid_chunk_index(uint32 chunk_index)
{
    return chunk_index < kSqlChunkCapacity;
}
 
void
push_free_chunk(uint32 chunk_index)
{
    if (!is_valid_chunk_index(chunk_index))
        return;
 
    AshSharedSqlTextChunk& chunk = sql_chunk_arena()[chunk_index];
    std::memset(&chunk, 0, sizeof(chunk));
    if (g_shared->free_sql_chunk_count >= kSqlChunkCapacity)
        return;
    chunk.next_chunk = g_shared->free_sql_chunk_head;
    g_shared->free_sql_chunk_head = chunk_index;
    ++g_shared->free_sql_chunk_count;
}
 
bool
free_list_contains_chunk(uint32 chunk_index)
{
    uint32 current = g_shared->free_sql_chunk_head;
    uint32 visited = 0;
 
    while (current != kInvalidChunkIndex)
    {
        if (!is_valid_chunk_index(current) || visited >= kSqlChunkCapacity)
            return false;
        if (current == chunk_index)
            return true;
 
        current = sql_chunk_arena()[current].next_chunk;
        ++visited;
    }
 
    return false;
}
 
std::optional<uint32>
pop_free_chunk(void)
{
    if (g_shared->free_sql_chunk_head == kInvalidChunkIndex || g_shared->free_sql_chunk_count == 0)
        return std::nullopt;
 
    const uint32 chunk_index = g_shared->free_sql_chunk_head;
    if (!is_valid_chunk_index(chunk_index))
    {
        g_shared->free_sql_chunk_head = kInvalidChunkIndex;
        g_shared->free_sql_chunk_count = 0;
        return std::nullopt;
    }
 
    AshSharedSqlTextChunk& chunk = sql_chunk_arena()[chunk_index];
    g_shared->free_sql_chunk_head = chunk.next_chunk;
    --g_shared->free_sql_chunk_count;
    std::memset(&chunk, 0, sizeof(chunk));
    chunk.next_chunk = kInvalidChunkIndex;
    return chunk_index;
}
 
bool
read_sql_text_from_entry(const AshSharedSqlTextEntry& entry, std::string* result)
{
    // Проверяем всю цепочку текущего поколения до выделения памяти,
    // чтобы повреждённые метаданные не увеличили размер отчёта.
    if (result == nullptr)
        return false;
 
    result->clear();
    if (entry.generation == 0 || !entry.complete || entry.byte_length > kMaxSqlTextBytes)
        return false;
    if (entry.byte_length == 0)
        return entry.head_chunk == kInvalidChunkIndex;
    if (!is_valid_chunk_index(entry.head_chunk))
        return false;
 
    uint64 required_chunks =
        (static_cast<uint64>(entry.byte_length) + kSqlChunkPayloadLength - 1) /
        kSqlChunkPayloadLength;
    if (required_chunks == 0 || required_chunks > kSqlChunkCapacity)
        return false;
 
    uint32 chunk_index = entry.head_chunk;
    uint64 consumed_bytes = 0;
    for (uint64 chunk_no = 0; chunk_no < required_chunks; ++chunk_no)
    {
        if (!is_valid_chunk_index(chunk_index))
            return false;
 
        const AshSharedSqlTextChunk& chunk = sql_chunk_arena()[chunk_index];
        if (chunk.used_bytes > kSqlChunkPayloadLength)
            return false;
        if (consumed_bytes > entry.byte_length ||
            chunk.used_bytes > entry.byte_length - consumed_bytes)
            return false;
        consumed_bytes += chunk.used_bytes;
        if (chunk_no + 1 == required_chunks)
        {
            if (chunk.next_chunk != kInvalidChunkIndex)
                return false;
        }
        else if (chunk.next_chunk == kInvalidChunkIndex)
            return false;
 
        chunk_index = chunk.next_chunk;
    }
 
    if (consumed_bytes != entry.byte_length)
        return false;
 
    result->reserve(entry.byte_length);
    chunk_index = entry.head_chunk;
    while (chunk_index != kInvalidChunkIndex)
    {
        const AshSharedSqlTextChunk& chunk = sql_chunk_arena()[chunk_index];
        result->append(chunk.payload, chunk.used_bytes);
        chunk_index = chunk.next_chunk;
    }
    return true;
}
 
void
release_chunk_chain(uint32 head_chunk)
{
    // Блоки возвращаются после удаления ссылки каталога под `g_ash_lock`.
    uint32 chunk_index = head_chunk;
    uint32 released = 0;
 
    while (chunk_index != kInvalidChunkIndex && released < kSqlChunkCapacity)
    {
        if (!is_valid_chunk_index(chunk_index))
            return;
        if (free_list_contains_chunk(chunk_index))
            return;
 
        AshSharedSqlTextChunk& chunk = sql_chunk_arena()[chunk_index];
        const uint32 next_chunk = chunk.next_chunk;
        push_free_chunk(chunk_index);
        chunk_index = next_chunk;
        ++released;
    }
}
 
struct SqlChunkChain
{
    uint32 head = kInvalidChunkIndex;
    uint32 tail = kInvalidChunkIndex;
    uint32 chunk_count = 0;
};
 
std::optional<SqlChunkChain>
allocate_chunk_chain(const std::string& sql_text)
{
    // Берёт блоки из списка свободных ячеек целиком, чтобы запись
    // каталога не указывала на неполный текст SQL.
    SqlChunkChain chain;
 
    if (sql_text.empty())
        return chain;
    if (sql_text.size() > std::numeric_limits<uint32>::max())
    {
        ereport(ERROR,
                (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                 errmsg("SQL text RUDB ASH превышает поддерживаемый размер")));
    }
 
    const std::size_t required_chunk_count =
        (sql_text.size() / kSqlChunkPayloadLength) +
        (sql_text.size() % kSqlChunkPayloadLength == 0 ? 0 : 1);
    if (required_chunk_count > std::numeric_limits<uint32>::max())
    {
        ereport(ERROR,
                (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                 errmsg("переполнено число chunks RUDB ASH SQL text")));
    }
    const uint32 required_chunks = static_cast<uint32>(required_chunk_count);
    if (required_chunks == 0 || required_chunks > g_shared->free_sql_chunk_count)
        return std::nullopt;
 
    for (uint32 idx = 0; idx < required_chunks; ++idx)
    {
        const std::optional<uint32> chunk_index = pop_free_chunk();
        if (!chunk_index.has_value())
        {
            release_chunk_chain(chain.head);
            return std::nullopt;
        }
 
        if (chain.head == kInvalidChunkIndex)
            chain.head = *chunk_index;
        else
            sql_chunk_arena()[chain.tail].next_chunk = *chunk_index;
        chain.tail = *chunk_index;
        ++chain.chunk_count;
    }
 
    std::size_t offset = 0;
    for (uint32 chunk_index = chain.head;
         chunk_index != kInvalidChunkIndex;
         chunk_index = sql_chunk_arena()[chunk_index].next_chunk)
    {
        AshSharedSqlTextChunk& chunk = sql_chunk_arena()[chunk_index];
        const std::size_t used =
            std::min<std::size_t>(sql_text.size() - offset, kSqlChunkPayloadLength);
        std::memcpy(chunk.payload, sql_text.data() + offset, used);
        chunk.used_bytes = static_cast<uint32>(used);
        offset += used;
    }
 
    return chain;
}
 
void
reset_sql_text_entry(AshSharedSqlTextEntry& entry)
{
    if (entry.head_chunk != kInvalidChunkIndex)
        release_chunk_chain(entry.head_chunk);
 
    std::memset(&entry, 0, sizeof(entry));
    entry.head_chunk = kInvalidChunkIndex;
}
 
bool
sql_text_entry_matches(const AshSharedSqlTextEntry& entry, const std::string& sql_id, int64 dbid)
{
    return entry.generation != 0 &&
           entry.dbid == dbid &&
           std::strcmp(entry.sql_id, sql_id.c_str()) == 0;
}
 
bool
retain_sql_text_reference_locked(uint32 slot, uint64 generation)
{
    if (slot >= kSqlCacheCapacity)
        return false;
 
    AshSharedSqlTextEntry& entry = sql_cache()[slot];
    if (entry.generation == generation && entry.generation != 0)
    {
        ++entry.refcount;
        return true;
    }
 
    return false;
}
 
void
release_sql_text_reference_locked(uint32 slot, uint64 generation)
{
    if (slot >= kSqlCacheCapacity)
        return;
 
    AshSharedSqlTextEntry& entry = sql_cache()[slot];
    if (entry.generation == generation && entry.generation != 0 && entry.refcount > 0)
        --entry.refcount;
}
 
int64
local_dbid_impl(Oid database_id)
{
    const uint64 db_oid = static_cast<uint64>(database_id == InvalidOid ? 1 : database_id);
    return static_cast<int64>((db_oid << 32) | 1ULL);
}
 
ResolutionInfo
normalize_resolution(const std::string& value)
{
    if (pg_strcasecmp(value.c_str(), "LOW") == 0)
        return {"LOW", 120};
 
    if (pg_strcasecmp(value.c_str(), "HIGH") == 0)
        return {"HIGH", 360};
 
    return {"MEDIUM", 180};
}
 
int64
ceil_div(int64 numerator, int64 denominator)
{
    return denominator == 0 ? 0 : (numerator + denominator - 1) / denominator;
}
 
const char*
command_type_for_operation(CmdType operation)
{
    switch (operation)
    {
        case CMD_SELECT:
            return "SELECT";
        case CMD_UPDATE:
            return "UPDATE";
        case CMD_INSERT:
            return "INSERT";
        case CMD_DELETE:
            return "DELETE";
        case CMD_UTILITY:
            return "UTILITY";
        default:
            return "SQL";
    }
}
 
std::string
normalize_command_type(const std::optional<std::string>& command_type)
{
    if (!command_type.has_value())
        return "SQL";
 
    const std::string trimmed = trim_ascii_copy(*command_type);
    return trimmed.empty() ? "SQL" : uppercase_ascii_copy(trimmed);
}
 
std::string
wait_class_for_info(uint32 wait_event_info)
{
    const char* wait_type = pgstat_get_wait_event_type(wait_event_info);
 
    if (wait_type == nullptr || wait_type[0] == '\0')
        return "CPU";
 
    if (pg_strcasecmp(wait_type, "Activity") == 0)
        return "Idle";
 
    return std::string(wait_type);
}
 
std::string
wait_event_for_info(uint32 wait_event_info)
{
    const char* wait_event = pgstat_get_wait_event(wait_event_info);
    return wait_event == nullptr ? std::string() : std::string(wait_event);
}
 
void
ash_worker_die(SIGNAL_ARGS)
{
    int save_errno = errno;
    g_worker_shutdown_requested = true;
    if (MyLatch != nullptr)
        SetLatch(MyLatch);
    errno = save_errno;
}
 
void
define_gucs(void)
{
    if (g_gucs_defined)
        return;
 
    DefineCustomBoolVariable("dbms_ash.enabled",
                             "Enable RUDB ASH runtime.",
                             "Controls publication and sampling of active statements.",
                             &g_capture_enabled,
                             false,
                             PGC_SUSET,
                             0,
                             nullptr,
                             nullptr,
                             nullptr);
 
    DefineCustomIntVariable("dbms_ash.retention",
                            "Retention of RUDB ASH samples in seconds.",
                            "Time eligibility for ASH samples; the 8192-slot shared-memory ring can evict samples early, counted by ash_dropped_samples.",
                            &g_retention_seconds,
                            kDefaultRetentionSeconds,
                            1,
                            std::numeric_limits<int>::max(),
                            PGC_SIGHUP,
                            0,
                            nullptr,
                            nullptr,
                            nullptr);
 
    DefineCustomIntVariable("dbms_ash.sample_interval_ms",
                            "RUDB ASH sampler interval in milliseconds.",
                            "Controls the sampling interval of the shared-memory ASH worker.",
                            &g_sample_interval_ms,
                            kDefaultSampleIntervalMs,
                            100,
                            60000,
                            PGC_POSTMASTER,
                            0,
                            nullptr,
                            nullptr,
                            nullptr);
 
    g_gucs_defined = true;
}
 
void
request_shared_resources(void)
{
    if (g_prev_shmem_request_hook != nullptr)
        g_prev_shmem_request_hook();
 
    RequestAddinShmemSpace(shared_state_size());
    RequestNamedLWLockTranche(kAshTrancheName, kWorkerLockCount);
}
 
void
initialize_shared_state(bool found)
{
    g_ash_lock = &GetNamedLWLockTranche(kAshTrancheName)[0].lock;
 
    if (found)
        return;
 
    std::memset(g_shared, 0, shared_state_size());
    g_shared->magic = kAshMagic;
    g_shared->version = kAshVersion;
    g_shared->activity_slot_count = activity_slot_count();
    g_shared->sample_capacity = kSampleCapacity;
    g_shared->sql_cache_capacity = kSqlCacheCapacity;
    g_shared->sample_interval_ms = static_cast<uint32>(g_sample_interval_ms);
    g_shared->retention_seconds = static_cast<uint32>(g_retention_seconds);
    g_shared->worker_pid = 0;
    g_shared->sample_sequence_epoch_milliseconds =
        static_cast<uint64>(GetCurrentTimestamp() / INT64CONST(1000));
    g_shared->next_local_sample_sequence = 0;
    g_shared->next_ring_position = 0;
    g_shared->next_sample_generation = 1;
    g_shared->next_sql_cache_generation = 1;
    g_shared->free_sql_chunk_head = kSqlChunkCapacity == 0 ? kInvalidChunkIndex : 0;
    g_shared->free_sql_chunk_count = kSqlChunkCapacity;
 
    for (uint32 idx = 0; idx < kSqlCacheCapacity; ++idx)
        sql_cache()[idx].head_chunk = kInvalidChunkIndex;
 
    for (uint32 idx = 0; idx < g_shared->activity_slot_count; ++idx)
    {
        AshActivitySlot& slot = activity_slots()[idx];
        pg_atomic_init_u64(&slot.generation, 0);
        pg_atomic_init_u64(&slot.publish_seq, 0);
        pg_atomic_init_u64(&slot.started_at, 0);
        pg_atomic_init_u32(&slot.active, 0);
        slot.sql_cache_slot = kSqlCacheCapacity;
    }
 
    for (uint32 idx = 0; idx < kSqlChunkCapacity; ++idx)
    {
        AshSharedSqlTextChunk& chunk = sql_chunk_arena()[idx];
        std::memset(&chunk, 0, sizeof(chunk));
        chunk.next_chunk = idx + 1 < kSqlChunkCapacity ? idx + 1 : kInvalidChunkIndex;
    }
}
 
void
startup_shared_state(void)
{
    bool found = false;
 
    if (g_prev_shmem_startup_hook != nullptr)
        g_prev_shmem_startup_hook();
 
    LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
    g_shared = static_cast<AshSharedHeader*>(ShmemInitStruct(kAshShmemName,
                                                             shared_state_size(),
                                                             &found));
    initialize_shared_state(found);
    LWLockRelease(AddinShmemInitLock);
}
 
void
register_worker(void)
{
    BackgroundWorker worker;
    std::memset(&worker, 0, sizeof(worker));
 
    snprintf(worker.bgw_name, BGW_MAXLEN, "RUDB ASH sampler");
    snprintf(worker.bgw_type, BGW_MAXLEN, "RUDB ASH sampler");
    snprintf(worker.bgw_library_name, BGW_MAXLEN, "postgres");
    snprintf(worker.bgw_function_name, BGW_MAXLEN, "rudb_ash_worker_main");
    worker.bgw_flags = BGWORKER_SHMEM_ACCESS;
    worker.bgw_start_time = BgWorkerStart_PostmasterStart;
    worker.bgw_restart_time = 1;
    worker.bgw_notify_pid = 0;
    worker.bgw_main_arg = (Datum) 0;
    RegisterBackgroundWorker(&worker);
}
 
void
ensure_shared_state_attached(void)
{
    bool found = false;
 
    if (g_shared != nullptr && g_ash_lock != nullptr)
        return;
 
    g_shared = static_cast<AshSharedHeader*>(ShmemInitStruct(kAshShmemName,
                                                             shared_state_size(),
                                                             &found));
    g_ash_lock = &GetNamedLWLockTranche(kAshTrancheName)[0].lock;
}
 
struct SqlCacheRef
{
    uint32 slot = kSqlCacheCapacity;
    uint64 generation = 0;
    bool complete = false;
};
 
SqlCacheRef
invalid_sql_cache_ref(void)
{
    return {};
}
 
bool
sql_text_entry_complete_match(const AshSharedSqlTextEntry& entry, const std::string& sql_text)
{
    if (!entry.complete || entry.byte_length != sql_text.size())
        return false;
 
    if (entry.generation == 0 || !entry.complete || entry.byte_length > kMaxSqlTextBytes)
        return false;
    if (entry.byte_length == 0)
        return entry.head_chunk == kInvalidChunkIndex;
    if (!is_valid_chunk_index(entry.head_chunk))
        return false;
 
    const uint64 required_chunks =
        (static_cast<uint64>(entry.byte_length) + kSqlChunkPayloadLength - 1) /
        kSqlChunkPayloadLength;
    if (required_chunks == 0 || required_chunks > kSqlChunkCapacity)
        return false;
 
    uint32 chunk_index = entry.head_chunk;
    std::size_t compared_bytes = 0;
    for (uint64 chunk_no = 0; chunk_no < required_chunks; ++chunk_no)
    {
        if (!is_valid_chunk_index(chunk_index))
            return false;
 
        const AshSharedSqlTextChunk& chunk = sql_chunk_arena()[chunk_index];
        if (chunk.used_bytes > kSqlChunkPayloadLength)
            return false;
        if (compared_bytes > sql_text.size() ||
            chunk.used_bytes > sql_text.size() - compared_bytes)
            return false;
        if (std::memcmp(chunk.payload, sql_text.data() + compared_bytes, chunk.used_bytes) != 0)
            return false;
        compared_bytes += chunk.used_bytes;
        if (chunk_no + 1 == required_chunks)
        {
            if (chunk.next_chunk != kInvalidChunkIndex)
                return false;
        }
        else if (chunk.next_chunk == kInvalidChunkIndex)
            return false;
 
        chunk_index = chunk.next_chunk;
    }
 
    return compared_bytes == sql_text.size();
}
 
SqlCacheRef
update_sql_cache_locked(const std::string& sql_id,
                        const std::string& sql_text,
                        const std::string& command_type,
                        Oid user_id,
                        int64 dbid,
                        TimestampTz now)
{
    // Повторно используется только запись без ссылок; при совпадении SQL_ID
    // с другим текстом SQL источник возвращает пустой результат.
    AshSharedSqlTextEntry* cache = sql_cache();
    uint32 target = kSqlCacheCapacity;
    uint64 oldest_generation = std::numeric_limits<uint64>::max();
 
    for (uint32 idx = 0; idx < g_shared->sql_cache_capacity; ++idx)
    {
        if (sql_text_entry_matches(cache[idx], sql_id, dbid))
        {
            if (sql_text_entry_complete_match(cache[idx], sql_text))
            {
                cache[idx].last_seen = now;
                cache[idx].user_id = user_id;
                copy_cstring_field(cache[idx].command_type, sizeof(cache[idx].command_type), command_type);
                return {idx, cache[idx].generation, cache[idx].complete};
            }
 
            return invalid_sql_cache_ref();
        }
 
        if (cache[idx].generation == 0)
        {
            target = idx;
            break;
        }
 
        if (cache[idx].refcount == 0 && cache[idx].generation < oldest_generation)
        {
            oldest_generation = cache[idx].generation;
            target = idx;
        }
    }
 
    if (target >= g_shared->sql_cache_capacity)
        return invalid_sql_cache_ref();
 
    AshSharedSqlTextEntry& entry = cache[target];
    const std::optional<SqlChunkChain> chain = allocate_chunk_chain(sql_text);
    if (!chain.has_value())
        return invalid_sql_cache_ref();
 
    if (entry.generation != 0 && entry.refcount != 0)
    {
        release_chunk_chain(chain->head);
        return invalid_sql_cache_ref();
    }
 
    reset_sql_text_entry(entry);
 
    if (g_shared->next_sql_cache_generation == std::numeric_limits<uint64>::max())
    {
        release_chunk_chain(chain->head);
        ereport(ERROR,
                (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                 errmsg("переполнен счётчик поколений RUDB ASH SQL cache")));
    }
    entry.generation = g_shared->next_sql_cache_generation++;
    entry.first_seen = now;
    entry.last_seen = now;
    entry.dbid = dbid;
    entry.user_id = user_id;
    entry.refcount = 0;
    entry.complete = true;
    entry.byte_length = static_cast<uint32>(sql_text.size());
    entry.head_chunk = chain->head;
    copy_cstring_field(entry.sql_id, sizeof(entry.sql_id), sql_id);
    copy_cstring_field(entry.command_type, sizeof(entry.command_type), command_type);
 
    return {target, entry.generation, entry.complete};
}
 
void
begin_slot_publication(AshActivitySlot& slot, uint64 next_generation, TimestampTz started_at)
{
    pg_atomic_write_u64(&slot.publish_seq, next_generation * 2 - 1);
    pg_memory_barrier();
    pg_atomic_write_u64(&slot.started_at, static_cast<uint64>(started_at));
    pg_atomic_write_u64(&slot.generation, next_generation);
}
 
void
finish_slot_publication(AshActivitySlot& slot, bool active)
{
    pg_memory_barrier();
    pg_atomic_write_u32(&slot.active, active ? 1U : 0U);
    pg_atomic_write_u64(&slot.publish_seq, pg_atomic_read_u64(&slot.generation) * 2);
}
 
ActivityFrame
build_activity_frame(const std::string& sql_text,
                     const std::string& command_type,
                     const std::string& state)
{
    ActivityFrame frame;
    frame.normalized_sql = trim_ascii_copy(sql_text);
    if (frame.normalized_sql.empty())
        return frame;
 
    frame.sql_id = rudb::ash::compute_sql_id(frame.normalized_sql);
    frame.command_type = command_type;
    frame.state = state;
    frame.module_name = application_name != nullptr ? application_name : "";
    frame.application_name = application_name != nullptr ? application_name : "";
    frame.started_at = GetCurrentTimestamp();
    frame.nest_level = GetCurrentTransactionNestLevel();
    frame.subxid = GetCurrentSubTransactionId();
    return frame;
}
 
void
publish_frame_locked(ActivityFrame& frame)
{
    // Слот активности и ссылка на текст SQL изменяются под одной
    // блокировкой, чтобы фоновый процесс не увидел данные разных поколений.
    AshActivitySlot& slot = activity_slots()[MyProcNumber];
    const uint32 previous_sql_cache_slot = slot.sql_cache_slot;
    const uint64 previous_sql_cache_generation = slot.sql_cache_generation;
    const SqlCacheRef sql_cache_ref =
        update_sql_cache_locked(frame.sql_id,
                                frame.normalized_sql,
                                frame.command_type,
                                GetUserId(),
                                local_dbid_impl(MyDatabaseId),
                                frame.started_at);
    const bool retained = sql_cache_ref.generation != 0 &&
        retain_sql_text_reference_locked(sql_cache_ref.slot, sql_cache_ref.generation);
    const SqlCacheRef published_ref = retained ? sql_cache_ref : invalid_sql_cache_ref();
 
    const uint64 next_generation = pg_atomic_read_u64(&slot.generation) + 1;
    begin_slot_publication(slot, next_generation, frame.started_at);
    copy_cstring_field(slot.sql_id, sizeof(slot.sql_id), frame.sql_id);
    copy_cstring_field(slot.module_name, sizeof(slot.module_name), frame.module_name);
    copy_cstring_field(slot.application_name, sizeof(slot.application_name), frame.application_name);
    copy_cstring_field(slot.state, sizeof(slot.state), frame.state);
    slot.sql_cache_slot = published_ref.slot;
    slot.sql_cache_generation = published_ref.generation;
    slot.wait_event_info = MyProc->wait_event_info;
    slot.pid = MyProcPid;
    slot.proc_number = MyProcNumber;
    slot.session_generation = static_cast<int64>(MyStartTimestamp);
    slot.backend_type = static_cast<int>(MyBackendType);
    slot.user_id = GetUserId();
    slot.database_id = MyDatabaseId;
    finish_slot_publication(slot, true);
 
    if (previous_sql_cache_generation != 0)
        release_sql_text_reference_locked(previous_sql_cache_slot, previous_sql_cache_generation);
 
    frame.sql_cache_slot = published_ref.slot;
    frame.sql_cache_generation = published_ref.generation;
    frame.published = true;
}
 
void
publish_frame(ActivityFrame& frame)
{
    if (!g_capture_enabled || !AmRegularBackendProcess() || MyProc == nullptr ||
        frame.normalized_sql.empty())
        return;
 
    ensure_shared_state_attached();
    LWLockAcquire(g_ash_lock, LW_EXCLUSIVE);
    publish_frame_locked(frame);
    LWLockRelease(g_ash_lock);
}
 
void clear_activity(void);
 
void
restore_outer_activity(void)
{
    if (!g_capture_enabled)
    {
        clear_activity();
        return;
    }
 
    if (activity_stack().empty())
        return;
 
    ActivityFrame& outer = activity_stack().back();
    if (outer.published)
        publish_frame(outer);
}
 
void
finish_current_activity_frame(const void* owner)
{
    if (activity_stack().empty() || activity_stack().back().owner != owner)
        return;
 
    activity_stack().pop_back();
    if (activity_stack().empty())
        clear_activity();
    else
        restore_outer_activity();
}
 
void
clear_activity_locked(void)
{
    // Освобождает ссылку слота активности; ссылка записи ASH сохраняется
    // до вытеснения из кольцевого буфера.
    AshActivitySlot& slot = activity_slots()[MyProcNumber];
    const uint32 previous_sql_cache_slot = slot.sql_cache_slot;
    const uint64 previous_sql_cache_generation = slot.sql_cache_generation;
 
    begin_slot_publication(slot, pg_atomic_read_u64(&slot.generation) + 1, 0);
    slot.wait_event_info = 0;
    slot.sql_cache_slot = kSqlCacheCapacity;
    slot.sql_cache_generation = 0;
    slot.pid = MyProcPid;
    slot.proc_number = MyProcNumber;
    slot.session_generation = static_cast<int64>(MyStartTimestamp);
    slot.backend_type = static_cast<int>(MyBackendType);
    slot.state[0] = '\0';
    slot.sql_id[0] = '\0';
    slot.module_name[0] = '\0';
    slot.application_name[0] = '\0';
    slot.user_id = InvalidOid;
    slot.database_id = InvalidOid;
    finish_slot_publication(slot, false);
 
    if (previous_sql_cache_generation != 0)
        release_sql_text_reference_locked(previous_sql_cache_slot, previous_sql_cache_generation);
}
 
void
clear_stale_activity_locked(AshActivitySlot& slot)
{
    const uint32 previous_sql_cache_slot = slot.sql_cache_slot;
    const uint64 previous_sql_cache_generation = slot.sql_cache_generation;
 
    begin_slot_publication(slot, pg_atomic_read_u64(&slot.generation) + 1, 0);
    slot.wait_event_info = 0;
    slot.sql_cache_slot = kSqlCacheCapacity;
    slot.sql_cache_generation = 0;
    slot.pid = 0;
    slot.proc_number = -1;
    slot.session_generation = 0;
    slot.backend_type = 0;
    slot.state[0] = '\0';
    slot.sql_id[0] = '\0';
    slot.module_name[0] = '\0';
    slot.application_name[0] = '\0';
    slot.user_id = InvalidOid;
    slot.database_id = InvalidOid;
    finish_slot_publication(slot, false);
 
    if (previous_sql_cache_generation != 0)
        release_sql_text_reference_locked(previous_sql_cache_slot, previous_sql_cache_generation);
}
 
void
clear_activity(void)
{
    if (!g_backend_initialized || !AmRegularBackendProcess() || MyProc == nullptr)
        return;
 
    ensure_shared_state_attached();
    LWLockAcquire(g_ash_lock, LW_EXCLUSIVE);
    clear_activity_locked();
    LWLockRelease(g_ash_lock);
}
 
void
backend_shutdown(int, Datum)
{
    pending_archive_marks().clear();
    pending_snapshot_clear_marks().clear();
    activity_stack().clear();
    clear_activity();
}
 
bool
sql_cache_reference_matches(const AshSharedSample& sample, const AshSharedSqlTextEntry& entry)
{
    return entry.generation == sample.sql_cache_generation &&
           entry.dbid == sample.dbid &&
           entry.complete &&
           std::strcmp(entry.sql_id, sample.sql_id) == 0;
}
 
bool
populate_sample_sql_reference_locked(AshSharedSample* sample)
{
    if (sample == nullptr || sample->sql_cache_generation == 0)
        return false;
    if (sample->sql_cache_slot >= g_shared->sql_cache_capacity)
        return false;
 
    AshSharedSqlTextEntry& entry = sql_cache()[sample->sql_cache_slot];
    if (!sql_cache_reference_matches(*sample, entry))
        return false;
    if (!retain_sql_text_reference_locked(sample->sql_cache_slot, sample->sql_cache_generation))
        return false;
 
    sample->sql_text_complete = true;
    return true;
}
 
SlotReadResult
read_published_slot(AshActivitySlot& slot, AshSharedSample* sample, TimestampTz sample_time)
{
    ActivitySlotSnapshot snapshot{};
 
    for (int attempt = 0; attempt < 3; ++attempt)
    {
        const uint64 begin_seq = pg_atomic_read_u64(&slot.publish_seq);
        if ((begin_seq & 1U) != 0)
            return SlotReadResult::UnstablePublication;
 
        pg_memory_barrier();
        snapshot.wait_event_info = slot.wait_event_info;
        snapshot.pid = slot.pid;
        snapshot.proc_number = slot.proc_number;
        snapshot.session_generation = slot.session_generation;
        snapshot.backend_type = slot.backend_type;
        snapshot.user_id = slot.user_id;
        snapshot.database_id = slot.database_id;
        snapshot.sql_cache_slot = slot.sql_cache_slot;
        snapshot.sql_cache_generation = slot.sql_cache_generation;
        std::memcpy(snapshot.sql_id, slot.sql_id, sizeof(snapshot.sql_id));
        std::memcpy(snapshot.module_name, slot.module_name, sizeof(snapshot.module_name));
        std::memcpy(snapshot.application_name, slot.application_name, sizeof(snapshot.application_name));
        std::memcpy(snapshot.state, slot.state, sizeof(snapshot.state));
        snapshot.generation = pg_atomic_read_u64(&slot.generation);
        snapshot.started_at = pg_atomic_read_u64(&slot.started_at);
        snapshot.active = pg_atomic_read_u32(&slot.active);
 
        pg_memory_barrier();
 
        const uint64 end_seq = pg_atomic_read_u64(&slot.publish_seq);
        if (begin_seq != end_seq || (end_seq & 1U) != 0)
            continue;
 
        if (snapshot.active == 0)
            return SlotReadResult::Inactive;
        if (snapshot.proc_number < 0 ||
            static_cast<uint32>(snapshot.proc_number) >= g_shared->activity_slot_count ||
            ProcGlobal == nullptr ||
            static_cast<uint32>(snapshot.proc_number) >= ProcGlobal->allProcCount ||
            snapshot.pid <= 0)
            return SlotReadResult::InvalidProcNumber;
        if (snapshot.database_id == InvalidOid)
            return SlotReadResult::InvalidDatabase;
 
        PGPROC* proc = GetPGProcByNumber(snapshot.proc_number);
        if (proc == nullptr)
            return SlotReadResult::MissingProc;
        if (proc->pid != snapshot.pid)
            return SlotReadResult::PidMismatch;
        if (snapshot.pid == MyProcPid)
            return SlotReadResult::SelfPid;
 
        std::memset(sample, 0, sizeof(*sample));
        sample->activity_generation = snapshot.generation;
        sample->sample_time = sample_time;
        sample->dbid = local_dbid_impl(snapshot.database_id);
        sample->instance_number = 1;
        sample->session_id = snapshot.pid;
        sample->session_serial = 0;
        sample->session_generation = snapshot.session_generation;
        sample->started_at = static_cast<TimestampTz>(snapshot.started_at);
        sample->backend_type = snapshot.backend_type;
        sample->user_id = snapshot.user_id;
        const uint32 wait_event_info = proc->wait_event_info;
        if (proc->pid != snapshot.pid)
            return SlotReadResult::PidMismatch;
        sample->wait_event_info = wait_event_info;
        sample->is_awr_sample = false;
        sample->sql_text_complete = false;
        sample->sql_cache_slot = snapshot.sql_cache_slot;
        sample->sql_cache_generation = snapshot.sql_cache_generation;
        copy_cstring_field(sample->sql_id, sizeof(sample->sql_id), snapshot.sql_id);
        copy_cstring_field(sample->module_name, sizeof(sample->module_name), snapshot.module_name);
        copy_cstring_field(sample->application_name, sizeof(sample->application_name), snapshot.application_name);
        copy_cstring_field(sample->state, sizeof(sample->state), snapshot.state);
        if (snapshot.sql_cache_generation != 0 && snapshot.sql_cache_slot < g_shared->sql_cache_capacity)
        {
            const AshSharedSqlTextEntry& entry = sql_cache()[snapshot.sql_cache_slot];
            if (entry.generation == snapshot.sql_cache_generation)
            {
                copy_cstring_field(sample->command_type, sizeof(sample->command_type),
                    entry.command_type);
            }
            else
            {
                sample->command_type[0] = '\0';
                ++g_shared->reject_sql_cache_reference;
            }
        }
        if (sample->sql_cache_generation != 0 && !populate_sample_sql_reference_locked(sample))
        {
            sample->sql_cache_slot = kSqlCacheCapacity;
            sample->sql_cache_generation = 0;
            sample->sql_text_complete = false;
            ++g_shared->reject_sql_cache_reference;
        }
        return SlotReadResult::SampleReady;
    }
 
    return SlotReadResult::UnstablePublication;
}
 
bool
sample_is_retained(const AshSharedSample& sample, TimestampTz sample_time)
{
    if (sample.sample_sequence == 0)
        return false;
 
    const TimestampTz cutoff = sample_time - static_cast<TimestampTz>(g_shared->retention_seconds) * USECS_PER_SEC;
    return sample.sample_time >= cutoff;
}
 
void
release_sample_sql_reference_locked(AshSharedSample& sample)
{
    if (sample.sql_cache_generation != 0)
        release_sql_text_reference_locked(sample.sql_cache_slot, sample.sql_cache_generation);
 
    sample.sql_cache_slot = kSqlCacheCapacity;
    sample.sql_cache_generation = 0;
    sample.sql_text_complete = false;
}
 
void
clear_expired_samples_locked(TimestampTz sample_time)
{
    AshSharedSample* samples = sample_ring();
 
    for (uint32 idx = 0; idx < g_shared->sample_capacity; ++idx)
    {
        AshSharedSample& sample = samples[idx];
        if (sample.sample_sequence == 0 || sample_is_retained(sample, sample_time))
            continue;
 
        release_sample_sql_reference_locked(sample);
        std::memset(&sample, 0, sizeof(sample));
        sample.sql_cache_slot = kSqlCacheCapacity;
    }
}
 
void
capture_sample_locked(AshActivitySlot& slot, TimestampTz sample_time)
{
    AshSharedSample* samples = sample_ring();
    AshSharedSample candidate{};
    const SlotReadResult read_result = read_published_slot(slot, &candidate, sample_time);
    switch (read_result)
    {
        case SlotReadResult::SampleReady:
            ++g_shared->active_slots_seen;
            break;
        case SlotReadResult::Inactive:
            ++g_shared->reject_inactive_slot;
            return;
        case SlotReadResult::UnstablePublication:
            ++g_shared->reject_unstable_publication;
            return;
        case SlotReadResult::InvalidProcNumber:
            ++g_shared->reject_invalid_proc_number;
            return;
        case SlotReadResult::MissingProc:
            ++g_shared->reject_missing_pgproc;
            clear_stale_activity_locked(slot);
            return;
        case SlotReadResult::PidMismatch:
            ++g_shared->reject_pid_mismatch;
            clear_stale_activity_locked(slot);
            return;
        case SlotReadResult::SelfPid:
            ++g_shared->reject_self_pid;
            return;
        case SlotReadResult::InvalidDatabase:
            ++g_shared->reject_invalid_database;
        return;
    }
 
    uint64 epoch_milliseconds = static_cast<uint64>(sample_time / INT64CONST(1000));
    if (epoch_milliseconds < g_shared->sample_sequence_epoch_milliseconds)
        epoch_milliseconds = g_shared->sample_sequence_epoch_milliseconds;
    if (epoch_milliseconds != g_shared->sample_sequence_epoch_milliseconds ||
        g_shared->next_local_sample_sequence >= kSampleSequenceCounterLimit)
    {
        g_shared->sample_sequence_epoch_milliseconds = std::max(
            epoch_milliseconds,
            g_shared->sample_sequence_epoch_milliseconds + 1);
        g_shared->next_local_sample_sequence = 0;
    }
    if (g_shared->sample_sequence_epoch_milliseconds >
        static_cast<uint64>(PG_INT64_MAX) / kSampleSequenceCounterLimit)
    {
        ereport(ERROR,
                (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                 errmsg("переполнен идентификатор RUDB ASH sample")));
    }
    const uint64 sequence_base =
        g_shared->sample_sequence_epoch_milliseconds * kSampleSequenceCounterLimit;
    const uint64 local_counter = g_shared->next_local_sample_sequence++;
    if (local_counter > static_cast<uint64>(PG_INT64_MAX) - sequence_base)
        ereport(ERROR,
                (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                 errmsg("недопустимый идентификатор RUDB ASH sample")));
    const uint64 next_sample_sequence = sequence_base + local_counter;
    if (next_sample_sequence == 0 || next_sample_sequence > static_cast<uint64>(PG_INT64_MAX))
        ereport(ERROR,
                (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                 errmsg("недопустимый идентификатор RUDB ASH sample")));
 
    if (g_shared->next_ring_position == std::numeric_limits<uint64>::max())
        g_shared->next_ring_position = 0;
    const uint64 ring_position = g_shared->next_ring_position++;
    AshSharedSample& sample = samples[ring_position % g_shared->sample_capacity];
    const bool overwritten_retained = sample_is_retained(sample, sample_time);
    release_sample_sql_reference_locked(sample);
    if (overwritten_retained)
        ++g_shared->dropped_samples;
 
    std::memset(&sample, 0, sizeof(sample));
    sample = candidate;
    sample.sample_sequence = next_sample_sequence;
    if (g_shared->next_sample_generation == std::numeric_limits<uint64>::max())
        ereport(ERROR,
                (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                 errmsg("переполнен счётчик поколений RUDB ASH sample")));
    sample.sample_generation = g_shared->next_sample_generation++;
    g_shared->last_sample_time = static_cast<uint64>(sample_time);
    ++g_shared->samples_written;
}
 
void
sample_active_slots(void)
{
    // Фоновый процесс фиксирует устойчивые слоты активности и сохраняет
    // записи ASH под одной блокировкой со ссылками кольцевого буфера и кэша.
    ensure_shared_state_attached();
 
    const TimestampTz now = GetCurrentTimestamp();
    LWLockAcquire(g_ash_lock, LW_EXCLUSIVE);
    g_shared->sample_interval_ms = static_cast<uint32>(g_sample_interval_ms);
    g_shared->retention_seconds = static_cast<uint32>(g_retention_seconds);
    ++g_shared->worker_cycles;
    clear_expired_samples_locked(now);
 
    for (uint32 idx = 0; idx < g_shared->activity_slot_count; ++idx)
        capture_sample_locked(activity_slots()[idx], now);
 
    LWLockRelease(g_ash_lock);
}
 
void
executor_start_hook(QueryDesc* queryDesc, int eflags)
{
    bool frame_pushed = false;
    if (g_capture_enabled && queryDesc != nullptr && queryDesc->sourceText != nullptr)
    {
        ActivityFrame frame = build_activity_frame(queryDesc->sourceText,
                                                 std::string(command_type_for_operation(queryDesc->operation)),
                                                 "ACTIVE");
        if (!frame.normalized_sql.empty())
        {
            frame.owner = queryDesc;
            activity_stack().push_back(std::move(frame));
            publish_frame(activity_stack().back());
            frame_pushed = true;
        }
    }
 
    PG_TRY();
    {
        if (g_prev_executor_start_hook != nullptr)
            g_prev_executor_start_hook(queryDesc, eflags);
        else
            standard_ExecutorStart(queryDesc, eflags);
    }
    PG_CATCH();
    {
        if (frame_pushed && !activity_stack().empty() &&
            activity_stack().back().owner == queryDesc)
        {
            activity_stack().pop_back();
            if (activity_stack().empty())
                clear_activity();
            else
                restore_outer_activity();
        }
        PG_RE_THROW();
    }
    PG_END_TRY();
}
 
void
executor_end_hook(QueryDesc* queryDesc)
{
    // Очистка выполняется и после ERROR, чтобы слот активности не пережил
    // владельца SQL-оператора.
    PG_TRY();
    {
        if (g_prev_executor_end_hook != nullptr)
            g_prev_executor_end_hook(queryDesc);
        else
            standard_ExecutorEnd(queryDesc);
    }
    PG_CATCH();
    {
        finish_current_activity_frame(queryDesc);
        PG_RE_THROW();
    }
    PG_END_TRY();
 
    finish_current_activity_frame(queryDesc);
}
 
void
process_utility_hook(PlannedStmt* pstmt,
                     const char* queryString,
                     bool readOnlyTree,
                     ProcessUtilityContext context,
                     ParamListInfo params,
                     QueryEnvironment* queryEnv,
                     DestReceiver* dest,
                     QueryCompletion* qc)
{
    // Служебный SQL-оператор использует тот же срок жизни слота, что и обычный.
    bool frame_pushed = false;
    if (g_capture_enabled && queryString != nullptr && queryString[0] != '\0')
    {
        ActivityFrame frame = build_activity_frame(queryString, "UTILITY", "ACTIVE");
        if (!frame.normalized_sql.empty())
        {
            frame.owner = queryString;
            activity_stack().push_back(std::move(frame));
            publish_frame(activity_stack().back());
            frame_pushed = true;
        }
    }
 
    PG_TRY();
    {
        if (g_prev_process_utility_hook != nullptr)
        {
            g_prev_process_utility_hook(pstmt, queryString, readOnlyTree, context,
                                        params, queryEnv, dest, qc);
        }
        else
        {
            standard_ProcessUtility(pstmt, queryString, readOnlyTree, context,
                                    params, queryEnv, dest, qc);
        }
    }
    PG_CATCH();
    {
        if (frame_pushed)
            finish_current_activity_frame(queryString);
        PG_RE_THROW();
    }
    PG_END_TRY();
 
    if (frame_pushed)
        finish_current_activity_frame(queryString);
}
 
void
install_backend_hooks(void)
{
    if (g_hooks_installed)
        return;
 
    g_prev_executor_start_hook = ExecutorStart_hook;
    ExecutorStart_hook = executor_start_hook;
    g_prev_executor_end_hook = ExecutorEnd_hook;
    ExecutorEnd_hook = executor_end_hook;
    g_prev_process_utility_hook = ProcessUtility_hook;
    ProcessUtility_hook = process_utility_hook;
    g_hooks_installed = true;
}
 
void
xact_callback(XactEvent event, void*)
{
    // Вставка в постоянное историческое хранилище ещё не создаёт снимок AWR:
    // `snap_id` публикуется только после фиксации внешней транзакции.
    if (event == XACT_EVENT_ABORT || event == XACT_EVENT_PREPARE)
    {
        pending_archive_marks().clear();
        pending_snapshot_clear_marks().clear();
        activity_stack().clear();
        clear_activity();
        return;
    }
 
    if (event != XACT_EVENT_COMMIT)
        return;
 
    ensure_shared_state_attached();
    LWLockAcquire(g_ash_lock, LW_EXCLUSIVE);
    for (const PendingArchiveMark& mark : pending_archive_marks())
    {
        for (uint32 idx = 0; idx < g_shared->sample_capacity; ++idx)
        {
            AshSharedSample& sample = sample_ring()[idx];
            if (sample.sample_sequence != mark.sample_sequence ||
                sample.sample_generation != mark.sample_generation ||
                sample.activity_generation != mark.activity_generation)
                continue;
 
            sample.is_awr_sample = true;
            sample.snap_id = mark.snap_id;
            break;
        }
    }
    for (const PendingSnapshotClearMark& mark : pending_snapshot_clear_marks())
    {
        for (uint32 idx = 0; idx < g_shared->sample_capacity; ++idx)
        {
            AshSharedSample& sample = sample_ring()[idx];
            if (sample.sample_sequence == 0 ||
                sample.dbid != mark.dbid ||
                sample.snap_id < mark.low_snap_id ||
                sample.snap_id > mark.high_snap_id)
            {
                continue;
            }
 
            sample.is_awr_sample = false;
            sample.snap_id = 0;
        }
    }
    LWLockRelease(g_ash_lock);
    pending_archive_marks().clear();
    pending_snapshot_clear_marks().clear();
}
 
bool
subxid_is_descendant_or_same(SubTransactionId candidate, SubTransactionId target)
{
    if (candidate == InvalidSubTransactionId || target == InvalidSubTransactionId)
        return false;
 
    for (SubTransactionId current = candidate;
         current != InvalidSubTransactionId;
         current = SubTransGetParent(current))
    {
        if (current == target)
            return true;
    }
 
    return false;
}
 
void
subxact_callback(SubXactEvent event,
                 SubTransactionId my_subid,
                 SubTransactionId parent_subid,
                 void*)
{
    if (event == SUBXACT_EVENT_ABORT_SUB)
    {
        auto& marks = pending_archive_marks();
        marks.erase(std::remove_if(marks.begin(),
                                   marks.end(),
                                   [my_subid](const PendingArchiveMark& mark)
                                   {
                                       return subxid_is_descendant_or_same(mark.subxid, my_subid);
                                   }),
                    marks.end());
        auto& clear_marks = pending_snapshot_clear_marks();
        clear_marks.erase(std::remove_if(clear_marks.begin(),
                                         clear_marks.end(),
                                         [my_subid](const PendingSnapshotClearMark& mark)
                                         {
                                             return subxid_is_descendant_or_same(mark.subxid, my_subid);
                                         }),
                      clear_marks.end());
 
        auto& frames = activity_stack();
        frames.erase(std::remove_if(frames.begin(),
                                    frames.end(),
                                    [my_subid](const ActivityFrame& frame)
                                    {
                                        return subxid_is_descendant_or_same(frame.subxid, my_subid);
                                    }),
                     frames.end());
    }
    else if (event == SUBXACT_EVENT_COMMIT_SUB)
    {
        for (PendingArchiveMark& mark : pending_archive_marks())
        {
            if (mark.subxid == my_subid)
                mark.subxid = parent_subid;
        }
        for (PendingSnapshotClearMark& mark : pending_snapshot_clear_marks())
        {
            if (mark.subxid == my_subid)
                mark.subxid = parent_subid;
        }
 
        for (ActivityFrame& frame : activity_stack())
        {
            if (frame.subxid == my_subid)
                frame.subxid = parent_subid;
        }
    }
    else
    {
        return;
    }
 
    if (activity_stack().empty())
        clear_activity();
    else
        restore_outer_activity();
}
 
void
install_xact_callbacks(void)
{
    if (g_xact_callbacks_installed)
        return;
 
    RegisterXactCallback(xact_callback, nullptr);
    g_xact_callbacks_installed = true;
    if (!g_subxact_callbacks_installed)
    {
        RegisterSubXactCallback(subxact_callback, nullptr);
        g_subxact_callbacks_installed = true;
    }
}
 
std::optional<TimestampTz>
parse_timestamp_tz(const std::optional<std::string>& value)
{
    if (!value.has_value())
        return std::nullopt;
 
    const std::string trimmed = trim_ascii_copy(*value);
    if (trimmed.empty())
        return std::nullopt;
 
    Datum parsed = DirectFunctionCall3(timestamptz_in,
                                       CStringGetDatum(trimmed.c_str()),
                                       ObjectIdGetDatum(InvalidOid),
                                       Int32GetDatum(-1));
    return DatumGetTimestampTz(parsed);
}
 
TimestampTz
compute_begin_time(const std::optional<TimestampTz>& parsed_begin_time,
                   const TimestampTz end_time,
                   int64 time_since_sec)
{
    if (parsed_begin_time.has_value() && *parsed_begin_time < end_time)
        return *parsed_begin_time;
 
    return end_time - static_cast<TimestampTz>(time_since_sec) * USECS_PER_SEC;
}
 
bool
matches_instance_filter(const rudb::ash::SampleRow& entry, const rudb::ash::HistoryFilter& filter)
{
    if (filter.instance_list_is_empty)
        return false;
 
    if (!filter.instance_filter_enabled)
        return true;
 
    if (filter.global_scope)
    {
        return std::find(filter.instance_numbers.begin(),
                         filter.instance_numbers.end(),
                         entry.instance_number) != filter.instance_numbers.end();
    }
 
    return filter.instance_number.has_value() && *filter.instance_number == entry.instance_number;
}
 
bool
matches_sample(const rudb::ash::SampleRow& entry, const rudb::ash::HistoryFilter& filter)
{
    if (filter.begin_time.has_value())
    {
        if (filter.begin_time_exclusive ? entry.sample_time <= *filter.begin_time
                                        : entry.sample_time < *filter.begin_time)
            return false;
    }
 
    if (filter.end_time.has_value())
    {
        if (filter.end_time_exclusive ? entry.sample_time >= *filter.end_time
                                      : entry.sample_time > *filter.end_time)
            return false;
    }
 
    if (filter.dbid.has_value() && entry.dbid != *filter.dbid)
        return false;
 
    if (!matches_instance_filter(entry, filter))
        return false;
 
    if (filter.sql_id.has_value() && entry.sql_id != *filter.sql_id)
        return false;
 
    if (filter.wait_class.has_value() &&
        pg_strcasecmp(entry.wait_class.c_str(), filter.wait_class->c_str()) != 0)
    {
        return false;
    }
    if (filter.session_id.has_value() && entry.session_id != *filter.session_id)
        return false;
    if (filter.module_name.has_value() && entry.module_name != *filter.module_name)
        return false;
 
    if (filter.begin_snap_id.has_value() && entry.snap_id <= *filter.begin_snap_id)
        return false;
 
    if (filter.end_snap_id.has_value() && entry.snap_id > *filter.end_snap_id)
        return false;
 
    if (filter.awr_only && !entry.is_awr_sample)
        return false;
 
    return true;
}
 
std::string
format_timestamp(const std::optional<TimestampTz>& value)
{
    if (!value.has_value())
        return "NULL";
 
    char* rendered = DatumGetCString(
        DirectFunctionCall1(timestamptz_out, TimestampTzGetDatum(*value)));
    std::string result(rendered);
    pfree(rendered);
    return result;
}
 
std::string
format_optional_int64(const std::optional<int64>& value)
{
    return value.has_value() ? std::to_string(*value) : "NULL";
}
 
std::string
format_optional_text(const std::optional<std::string>& value)
{
    return value.has_value() ? *value : "NULL";
}
 
std::string
normalize_options_text(const std::optional<int64>& options)
{
    return options.has_value() ? std::to_string(*options) : "NULL";
}
 
std::string
normalize_slot_width_text(const std::optional<int64>& slot_width)
{
    if (!slot_width.has_value() || *slot_width == 0)
        return "auto";
 
    return std::to_string(*slot_width);
}
 
std::string
slot_width_effect(const std::optional<int64>& slot_width)
{
    return (!slot_width.has_value() || *slot_width == 0) ? "auto" : "minimal-report-only";
}
 
std::string
normalize_data_src_text(const std::optional<int64>& data_src)
{
    if (!data_src.has_value())
        return "auto";
 
    switch (*data_src)
    {
        case 0:
            return "all";
        case 1:
            return "memory";
        case 2:
            return "historical";
        case 3:
            return "global";
        default:
            return std::to_string(*data_src);
    }
}
 
ReportStats
collect_report_stats(const std::vector<rudb::ash::SampleRow>& samples,
                     const rudb::ash::HistoryFilter& filter)
{
    ReportStats stats;
    std::map<std::string, std::size_t> sql_id_counts;
    std::map<std::string, std::size_t> wait_class_counts;
    std::set<std::string> distinct_sql_ids;
 
    stats.sample_count_total = samples.size();
    stats.sql_text_entry_count = rudb::ash::sql_text_count();
 
    for (const rudb::ash::SampleRow& entry : samples)
    {
        if (!matches_sample(entry, filter))
            continue;
 
        ++stats.sample_count_matched;
 
        if (!entry.sql_id.empty())
        {
            distinct_sql_ids.insert(entry.sql_id);
            ++sql_id_counts[entry.sql_id];
        }
 
        if (!entry.wait_class.empty())
            ++wait_class_counts[entry.wait_class];
    }
 
    stats.distinct_sql_id_count_matched = distinct_sql_ids.size();
 
    for (const auto& entry : sql_id_counts)
    {
        if (!stats.top_sql_id.has_value() || entry.second > sql_id_counts[*stats.top_sql_id] ||
            (entry.second == sql_id_counts[*stats.top_sql_id] && entry.first < *stats.top_sql_id))
        {
            stats.top_sql_id = entry.first;
        }
    }
 
    for (const auto& entry : wait_class_counts)
    {
        if (!stats.top_wait_class.has_value() || entry.second > wait_class_counts[*stats.top_wait_class] ||
            (entry.second == wait_class_counts[*stats.top_wait_class] && entry.first < *stats.top_wait_class))
        {
            stats.top_wait_class = entry.first;
        }
    }
 
    return stats;
}
 
void
append_filter_summary_rows(std::vector<std::string>& rows,
                           const rudb::ash::LayerReportRequest& request,
                           const ReportStats& stats)
{
    rows.push_back("dbid=" + std::to_string(request.dbid));
    rows.push_back(request.global_scope
                       ? "instance_list=" + request.normalized_instance_list
                       : "inst_num=" + std::to_string(request.inst_num.value_or(1)));
    rows.push_back("begin_time=" + format_timestamp(request.begin_time));
    rows.push_back("end_time=" + format_timestamp(request.end_time));
    rows.push_back("options=" + normalize_options_text(request.options));
    rows.push_back("options_effect=minimal-report-format");
    rows.push_back("slot_width=" + normalize_slot_width_text(request.slot_width));
    rows.push_back("slot_width_effect=" + slot_width_effect(request.slot_width));
    rows.push_back("data_src=" + normalize_data_src_text(request.data_src));
    rows.push_back("filter_sid=" + format_optional_int64(request.sid));
    rows.push_back("filter_sql_id=" + format_optional_text(request.sql_id));
    rows.push_back("filter_wait_class=" + format_optional_text(request.wait_class));
    rows.push_back("filter_service_hash=" + format_optional_int64(request.service_hash));
    rows.push_back("filter_module=" + format_optional_text(request.module));
    rows.push_back("filter_action=" + format_optional_text(request.action));
    rows.push_back("filter_client_id=" + format_optional_text(request.client_id));
    rows.push_back("filter_plsql_entry=" + format_optional_text(request.plsql_entry));
    rows.push_back("filter_container=" + format_optional_text(request.container));
    rows.push_back(std::string("sql_id_filter_applied=") +
               (request.sql_id.has_value() ? "true" : "false"));
    rows.push_back(std::string("wait_class_filter_applied=") +
               (request.wait_class.has_value() ? "true" : "false"));
    rows.push_back("service_hash_filter_applied=false");
    rows.push_back(std::string("module_filter_applied=") +
               (request.module.has_value() ? "true" : "false"));
    rows.push_back("action_filter_applied=false");
    rows.push_back("client_id_filter_applied=false");
    rows.push_back("plsql_entry_filter_applied=false");
    rows.push_back("container_filter_applied=false");
    rows.push_back("sample_count_total=" + std::to_string(stats.sample_count_total));
    rows.push_back("sample_count_matched=" + std::to_string(stats.sample_count_matched));
    rows.push_back("sql_text_entry_count=" + std::to_string(stats.sql_text_entry_count));
    rows.push_back("distinct_sql_id_count_matched=" +
                   std::to_string(stats.distinct_sql_id_count_matched));
    rows.push_back("top_sql_id=" + stats.top_sql_id.value_or("NULL"));
    rows.push_back("top_wait_class=" + stats.top_wait_class.value_or("NULL"));
}
 
std::string
join_text_rows(const std::vector<std::string>& rows)
{
    std::string result;
 
    for (std::size_t idx = 0; idx < rows.size(); ++idx)
    {
        if (idx != 0)
            result += "\n";
 
        result += rows[idx];
    }
 
    return result;
}
 
std::vector<std::string>
build_report_rows(const char* title, const rudb::ash::LayerReportRequest& request)
{
    rudb::ash::HistoryFilter filter;
    filter.dbid = request.dbid;
    filter.instance_number = request.inst_num;
    filter.instance_numbers = request.instance_numbers;
    filter.global_scope = request.global_scope;
    filter.begin_time = request.begin_time;
    filter.end_time = request.end_time;
    filter.sql_id = request.sql_id;
    filter.wait_class = request.wait_class;
    filter.session_id = request.sid;
    filter.module_name = request.module;
 
    std::vector<rudb::ash::SampleRow> samples;
    const int64 data_src = request.data_src.value_or(0);
    if (data_src == 0 || data_src == 1 || data_src == 3)
        samples = rudb::ash::collect_memory_samples(filter);
 
    if (data_src == 0 || data_src == 2 || data_src == 3)
    {
        std::vector<rudb::ash::SampleRow> history = rudb::ash::collect_history_samples(filter);
        if (history.size() > samples.max_size() - samples.size())
            ereport(ERROR,
                (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                 errmsg("слишком много ASH samples для формирования отчёта")));
        samples.insert(samples.end(),
                       std::make_move_iterator(history.begin()),
                       std::make_move_iterator(history.end()));
    }
    std::sort(samples.begin(), samples.end(),
              [](const rudb::ash::SampleRow& left, const rudb::ash::SampleRow& right)
              {
                  return left.sample_sequence < right.sample_sequence;
              });
    samples.erase(std::unique(samples.begin(), samples.end(),
                          [](const rudb::ash::SampleRow& left,
                             const rudb::ash::SampleRow& right)
                          {
                              return left.sample_sequence == right.sample_sequence;
                          }),
              samples.end());
 
    const ReportStats stats = collect_report_stats(samples, filter);
    std::vector<std::string> rows = {title};
    append_filter_summary_rows(rows, request, stats);
    return rows;
}
 
std::string
build_timepicker_buckets_xml(const TimestampTz begin_time,
                             const TimestampTz end_time,
                             int bucket_count,
                             int64 bucket_interval_sec)
{
    struct BucketEntry
    {
        int64 cpu_count = 0;
        int64 io_count = 0;
        int64 other_count = 0;
    };
 
    rudb::ash::HistoryFilter filter;
    filter.begin_time = begin_time;
    filter.end_time = end_time;
    std::vector<rudb::ash::SampleRow> samples = rudb::ash::collect_memory_samples(filter);
    std::vector<BucketEntry> buckets(static_cast<std::size_t>(bucket_count));
    const TimestampTz bucket_interval = static_cast<TimestampTz>(bucket_interval_sec) * USECS_PER_SEC;
 
    for (const rudb::ash::SampleRow& entry : samples)
    {
        if (entry.sample_time < begin_time || entry.sample_time > end_time)
            continue;
 
        int64 bucket_index = bucket_interval > 0 ? (entry.sample_time - begin_time) / bucket_interval : 0;
 
        if (bucket_index < 0)
            bucket_index = 0;
        else if (bucket_index >= bucket_count)
            bucket_index = bucket_count - 1;
 
        BucketEntry& bucket = buckets[static_cast<std::size_t>(bucket_index)];
 
        if (pg_strcasecmp(entry.wait_class.c_str(), "CPU") == 0)
            ++bucket.cpu_count;
        else if (pg_strcasecmp(entry.wait_class.c_str(), "USER I/O") == 0 ||
                 pg_strcasecmp(entry.wait_class.c_str(), "IO") == 0)
            ++bucket.io_count;
        else
            ++bucket.other_count;
    }
 
    std::string xml;
 
    for (int bucket_index = 0; bucket_index < bucket_count; ++bucket_index)
    {
        const BucketEntry& bucket = buckets[static_cast<std::size_t>(bucket_index)];
 
        if (bucket.cpu_count == 0 && bucket.io_count == 0 && bucket.other_count == 0)
            continue;
 
        xml += "<b n=\"";
        xml += std::to_string(bucket_index);
        xml += "\" c=\"";
        xml += std::to_string(static_cast<long long>(bucket.cpu_count));
        xml += "\" i=\"";
        xml += std::to_string(static_cast<long long>(bucket.io_count));
        xml += "\" o=\"";
        xml += std::to_string(static_cast<long long>(bucket.other_count));
        xml += "\"></b>";
    }
 
    return xml;
}
 
void
reserve_pending_archive_marks(std::size_t additional)
{
    auto& marks = pending_archive_marks();
    if (additional > marks.max_size() - marks.size())
        throw std::length_error("pending archive marks capacity overflow");
 
    marks.reserve(marks.size() + additional);
}
 
void
reserve_pending_snapshot_clear_marks(std::size_t additional)
{
    auto& marks = pending_snapshot_clear_marks();
    if (additional > marks.max_size() - marks.size())
        throw std::length_error("pending snapshot clear marks capacity overflow");
 
    marks.reserve(marks.size() + additional);
}
 
struct AshSpiScope
{
    bool connected = false;
 
    AshSpiScope()
    {
        if (SPI_connect() != SPI_OK_CONNECT)
            ereport(ERROR,
                    (errcode(ERRCODE_INTERNAL_ERROR),
                     errmsg("не удалось открыть SPI для работы с RUDB ASH history")));
        connected = true;
    }
 
    ~AshSpiScope()
    {
        close_noexcept();
    }
 
    void close_noexcept() noexcept
    {
        if (!connected)
            return;
 
        connected = false;
        (void) SPI_finish();
    }
 
    void finish()
    {
        if (!connected)
            return;
 
        connected = false;
        if (SPI_finish() != SPI_OK_FINISH)
            ereport(ERROR,
                    (errcode(ERRCODE_INTERNAL_ERROR),
                     errmsg("не удалось завершить SPI для работы с RUDB ASH history")));
    }
};
 
template <typename Callback>
auto
with_ash_spi(Callback&& callback) -> decltype(callback())
{
    AshSpiScope spi;
 
    try
    {
        auto result = callback();
        spi.finish();
        return result;
    }
    catch (...)
    {
        spi.close_noexcept();
        throw;
    }
}
 
std::string
datum_text_to_string(Datum datum)
{
    char* value = TextDatumGetCString(datum);
    std::string result(value);
    pfree(value);
    return result;
}
 
rudb::ash::SampleRow
sample_from_shared(const AshSharedSample& sample)
{
    rudb::ash::SampleRow row;
    row.sample_sequence = sample.sample_sequence;
    row.sample_time = sample.sample_time;
    row.dbid = sample.dbid;
    row.instance_number = sample.instance_number;
    row.session_id = sample.session_id;
    row.session_serial = sample.session_serial;
    row.session_generation = sample.session_generation;
    row.started_at = sample.started_at;
    row.command_type = cstring_field_to_string(sample.command_type);
    const char* backend_type = GetBackendTypeDesc(static_cast<BackendType>(sample.backend_type));
    row.backend_type = backend_type != nullptr ? backend_type : "";
    row.user_id = sample.user_id;
    row.sql_id = cstring_field_to_string(sample.sql_id);
    if (sample.sql_text_complete &&
        sample.sql_cache_generation != 0 &&
        sample.sql_cache_slot < g_shared->sql_cache_capacity)
    {
        const AshSharedSqlTextEntry& entry = sql_cache()[sample.sql_cache_slot];
        if (sql_cache_reference_matches(sample, entry))
        {
            std::string sql_text;
            if (read_sql_text_from_entry(entry, &sql_text))
                row.sql_text = std::move(sql_text);
        }
    }
    row.module_name = cstring_field_to_string(sample.module_name);
    row.application_name = cstring_field_to_string(sample.application_name);
    row.state = cstring_field_to_string(sample.state);
    row.wait_class = wait_class_for_info(sample.wait_event_info);
    row.event_name = wait_event_for_info(sample.wait_event_info);
    row.is_awr_sample = sample.is_awr_sample;
    row.snap_id = sample.snap_id;
    return row;
}
 
MemoryArchiveCandidate
archive_candidate_from_shared(const AshSharedSample& sample)
{
    MemoryArchiveCandidate candidate;
    candidate.row = sample_from_shared(sample);
    candidate.sample_generation = sample.sample_generation;
    candidate.activity_generation = sample.activity_generation;
    candidate.sql_cache_slot = sample.sql_cache_slot;
    candidate.sql_cache_generation = sample.sql_cache_generation;
    return candidate;
}
 
std::vector<SharedSampleSnapshot>
snapshot_memory_samples(void)
{
    /*
     * Под блокировкой копируются только простые поля и временно
     * удерживаются ссылки на текст SQL. Строки создаются уже после
     * освобождения блокировки.
     */
    std::vector<SharedSampleSnapshot> snapshots(kSampleCapacity);
    std::size_t snapshot_count = 0;
 
    LWLockAcquire(g_ash_lock, LW_EXCLUSIVE);
    const TimestampTz retention_cutoff = GetCurrentTimestamp() -
        static_cast<TimestampTz>(g_shared->retention_seconds) * USECS_PER_SEC;
    for (uint32 idx = 0; idx < g_shared->sample_capacity; ++idx)
    {
        const AshSharedSample& sample = sample_ring()[idx];
        if (sample.sample_sequence == 0 || sample.sample_time < retention_cutoff)
            continue;
 
        SharedSampleSnapshot snapshot;
        snapshot.sample = sample;
        if (snapshot.sample.sql_text_complete &&
            snapshot.sample.sql_cache_generation != 0 &&
            snapshot.sample.sql_cache_slot < g_shared->sql_cache_capacity)
        {
            snapshot.sql_reference_retained = retain_sql_text_reference_locked(
                snapshot.sample.sql_cache_slot, snapshot.sample.sql_cache_generation);
            if (!snapshot.sql_reference_retained)
                snapshot.sample.sql_text_complete = false;
        }
        snapshots[snapshot_count++] = snapshot;
    }
    LWLockRelease(g_ash_lock);
    snapshots.resize(snapshot_count);
    return snapshots;
}
 
void
release_snapshot_sql_references(const std::vector<SharedSampleSnapshot>& snapshots)
{
    // Временные ссылки отчёта и архива освобождаются после построения строк
    // за пределами блокировки.
    LWLockAcquire(g_ash_lock, LW_EXCLUSIVE);
    for (const SharedSampleSnapshot& snapshot : snapshots)
    {
        if (snapshot.sql_reference_retained)
        {
            release_sql_text_reference_locked(snapshot.sample.sql_cache_slot,
                                  snapshot.sample.sql_cache_generation);
        }
    }
    LWLockRelease(g_ash_lock);
}
} // namespace
 
extern "C" void
rudb_ash_postmaster_init(void)
{
    if (g_postmaster_initialized)
        return;
 
    define_gucs();
    g_prev_shmem_request_hook = shmem_request_hook;
    shmem_request_hook = request_shared_resources;
    g_prev_shmem_startup_hook = shmem_startup_hook;
    shmem_startup_hook = startup_shared_state;
    register_worker();
    g_postmaster_initialized = true;
}
 
extern "C" void
rudb_ash_backend_init(void)
{
    if (g_backend_initialized)
        return;
 
    define_gucs();
    ensure_shared_state_attached();
    install_backend_hooks();
    install_xact_callbacks();
    before_shmem_exit(backend_shutdown, 0);
    g_backend_initialized = true;
}
 
extern "C" void
rudb_ash_archive_backend_init(void)
{
    if (g_archive_backend_initialized)
        return;
 
    define_gucs();
    ensure_shared_state_attached();
    install_xact_callbacks();
    before_shmem_exit(backend_shutdown, 0);
    g_archive_backend_initialized = true;
}
 
extern "C" PGDLLEXPORT void
rudb_ash_worker_main(Datum)
{
    pqsignal(SIGTERM, ash_worker_die);
    pqsignal(SIGHUP, SignalHandlerForConfigReload);
    pqsignal(SIGUSR1, procsignal_sigusr1_handler);
    pqsignal(SIGPIPE, SIG_IGN);
    BackgroundWorkerUnblockSignals();
 
    ensure_shared_state_attached();
    LWLockAcquire(g_ash_lock, LW_EXCLUSIVE);
    g_shared->worker_pid = MyProcPid;
    LWLockRelease(g_ash_lock);
 
    instr_time next_deadline;
    instr_time interval;
    interval.ticks = static_cast<decltype(interval.ticks)>(g_sample_interval_ms) * NS_PER_MS;
    INSTR_TIME_SET_CURRENT(next_deadline);
    INSTR_TIME_ADD(next_deadline, interval);
    while (!g_worker_shutdown_requested)
    {
        instr_time current_time;
        INSTR_TIME_SET_CURRENT(current_time);
        instr_time remaining = next_deadline;
        INSTR_TIME_SUBTRACT(remaining, current_time);
        long timeout_ms = INSTR_TIME_GET_MILLISEC(remaining);
        if (timeout_ms < 0)
            timeout_ms = 0;
        int rc = WaitLatch(MyLatch,
                               WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH,
                               timeout_ms,
                               0);
        ResetLatch(MyLatch);
 
        if ((rc & WL_POSTMASTER_DEATH) != 0)
            proc_exit(1);
 
        if (ConfigReloadPending)
        {
            ConfigReloadPending = false;
            ProcessConfigFile(PGC_SIGHUP);
        }
 
        INSTR_TIME_SET_CURRENT(current_time);
        if (current_time.ticks >= next_deadline.ticks)
        {
            sample_active_slots();
            interval.ticks = static_cast<decltype(interval.ticks)>(g_sample_interval_ms) * NS_PER_MS;
            INSTR_TIME_ADD(next_deadline, interval);
            if (current_time.ticks >= next_deadline.ticks)
            {
                next_deadline = current_time;
                INSTR_TIME_ADD(next_deadline, interval);
            }
        }
    }
 
    proc_exit(0);
}
 
void
rudb::ash::initialize(void)
{
    rudb_ash_backend_init();
}
 
bool
rudb::ash::is_initialized(void)
{
    return g_backend_initialized && g_shared != nullptr && g_ash_lock != nullptr;
}
 
std::string
rudb::ash::compute_sql_id(const std::string& sql_text)
{
    char hexsum[MD5_DIGEST_LENGTH * 2 + 1];
    const char* errstr = nullptr;
 
    if (!pg_md5_hash(sql_text.data(), sql_text.size(), hexsum, &errstr))
    {
        ereport(ERROR,
                (errcode(ERRCODE_INTERNAL_ERROR),
                 errmsg("не удалось вычислить RUDB ASH SQL_ID: %s",
                        errstr != nullptr ? errstr : "unknown error")));
    }
 
    return std::string(hexsum);
}
 
std::optional<std::string>
rudb::ash::lookup_sql_text(const std::string& sql_id, bool local_path, bool historical_path)
{
    const std::optional<std::string> plain = find_sql_text(
        sql_id, historical_path, local_dbid_impl(MyDatabaseId), !historical_path);
 
    if (!plain.has_value())
        return std::nullopt;
 
    if (!local_path && !historical_path)
        return std::nullopt;
 
    return "<a><c>SQL</c><s><![CDATA[" + *plain + "]]></s></a>";
}
 
std::optional<std::string>
rudb::ash::find_sql_text(const std::string& sql_id,
                         bool include_historical,
                         const std::optional<int64_t>& dbid)
{
    return find_sql_text(sql_id, include_historical, dbid, true);
}
 
std::optional<std::string>
rudb::ash::find_sql_text(const std::string& sql_id,
                         bool include_historical,
                         const std::optional<int64_t>& dbid,
                         bool include_memory)
{
    ensure_shared_state_attached();
    std::optional<std::string> memory_result;
 
    if (include_memory)
    {
        uint32 retained_slot = kSqlCacheCapacity;
        uint64 retained_generation = 0;
        LWLockAcquire(g_ash_lock, LW_EXCLUSIVE);
        for (uint32 idx = 0; idx < g_shared->sql_cache_capacity; ++idx)
        {
            AshSharedSqlTextEntry& entry = sql_cache()[idx];
            if (entry.generation != 0 &&
                std::strcmp(entry.sql_id, sql_id.c_str()) == 0 &&
                (!dbid.has_value() || entry.dbid == *dbid))
            {
                if (entry.complete &&
                    retain_sql_text_reference_locked(idx, entry.generation))
                {
                    retained_slot = idx;
                    retained_generation = entry.generation;
                }
                break;
            }
        }
        LWLockRelease(g_ash_lock);
        if (retained_generation != 0)
        {
            try
            {
                const AshSharedSqlTextEntry& entry = sql_cache()[retained_slot];
                std::string rendered;
                if (entry.generation == retained_generation &&
                    read_sql_text_from_entry(entry, &rendered))
                {
                    memory_result = std::move(rendered);
                }
            }
            catch (...)
            {
                LWLockAcquire(g_ash_lock, LW_EXCLUSIVE);
                release_sql_text_reference_locked(retained_slot, retained_generation);
                LWLockRelease(g_ash_lock);
                throw;
            }
 
            LWLockAcquire(g_ash_lock, LW_EXCLUSIVE);
            release_sql_text_reference_locked(retained_slot, retained_generation);
            LWLockRelease(g_ash_lock);
        }
        if (memory_result.has_value())
            return memory_result;
    }
 
    if (!include_historical)
        return std::nullopt;
    if (!dbid.has_value())
        return std::nullopt;
 
    Oid argtypes[2] = {TEXTOID, INT8OID};
    Datum values[2] = {
        CStringGetTextDatum(sql_id.c_str()),
        Int64GetDatum(*dbid)};
    const char nulls[2] = {' ', ' '};
 
    return with_ash_spi([&]() {
        const int rc = SPI_execute_with_args(
            "SELECT sql_text FROM pg_catalog.rudb_ash_history_sqltext "
            "WHERE dbid = $2 AND sql_id = $1 ORDER BY last_seen DESC LIMIT 1",
            2, argtypes, values, nulls, true, 1);
 
        if (rc != SPI_OK_SELECT)
            ereport(ERROR,
                    (errcode(ERRCODE_INTERNAL_ERROR),
                     errmsg("не удалось получить historical SQL text")));
 
        std::optional<std::string> result = std::nullopt;
        if (SPI_processed == 1)
        {
            bool isnull = false;
            Datum datum = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull);
            if (!isnull)
            {
                char* text_value = TextDatumGetCString(datum);
                result = std::string(text_value);
                pfree(text_value);
            }
        }
        return result;
    });
}
 
std::string
rudb::ash::capture_sql_text(const std::string& sql_text,
                            const std::optional<std::string>& command_type,
                            Oid user_id)
{
    const std::string normalized_sql = trim_ascii_copy(sql_text);
    if (normalized_sql.empty())
        return "";
 
    const std::string sql_id = compute_sql_id(normalized_sql);
    const std::string normalized_command_type = normalize_command_type(command_type);
    ensure_shared_state_attached();
    LWLockAcquire(g_ash_lock, LW_EXCLUSIVE);
    (void) update_sql_cache_locked(sql_id,
                                   normalized_sql,
                                   normalized_command_type,
                                   user_id,
                                   local_dbid_impl(MyDatabaseId),
                                   GetCurrentTimestamp());
    LWLockRelease(g_ash_lock);
    return sql_id;
}
 
std::string
rudb::ash::build_timepicker_core_xml(const TimepickerRequest& request)
{
    const TimestampTz now = GetCurrentTimestamp();
    const std::optional<TimestampTz> parsed_end_time = parse_timestamp_tz(request.end_time_utc);
    const TimestampTz end_time = parsed_end_time.value_or(now);
    const TimestampTz begin_time =
        compute_begin_time(parse_timestamp_tz(request.begin_time_utc), end_time, request.time_since_sec);
    const ResolutionInfo resolution = normalize_resolution(request.resolution);
    const int64 effective_time_since_sec = std::max<int64>(1, ceil_div(end_time - begin_time, USECS_PER_SEC));
    const int64 bucket_interval = std::max<int64>(
        1, ceil_div(effective_time_since_sec, static_cast<int64>(resolution.bucket_count)));
 
    std::string xml = "<report xml_version=\"61\">";
    xml += "<sys_info data_source=\"LOCAL\"></sys_info>";
    xml += "<timing time_since_sec=\"" + std::to_string(request.time_since_sec) +
           "\" bucket_interval=\"" + std::to_string(bucket_interval) + "\"></timing>";
    xml += "<context begin_time_utc=\"" + xml_escape(request.begin_time_utc.value_or("")) +
           "\" end_time_utc=\"" + xml_escape(request.end_time_utc.value_or("")) +
           "\" instance_number=\"" + std::to_string(request.instance_number.value_or(1)) +
           "\"></context>";
    xml += "<report_parameters show_sql=\"";
    xml += request.show_sql ? "Y" : "N";
    xml += "\" verbose_xml=\"";
    xml += request.verbose_xml ? "Y" : "N";
    xml += "\" awr_info=\"";
    xml += request.awr_info ? "Y" : "N";
    xml += "\" ignore_cpu_history=\"";
    xml += request.ignore_cpu_history ? "Y" : "N";
    xml += "\" resolution=\"";
    xml += resolution.name;
    xml += "\" include_bg=\"";
    xml += request.include_bg ? "Y" : "N";
    xml += "\" memory_only=\"";
    xml += request.memory_only ? "Y" : "N";
    xml += "\"></report_parameters>";
    xml += "<cpuinfo ignore_cpu_history=\"";
    xml += request.ignore_cpu_history ? "Y" : "N";
    xml += "\"></cpuinfo>";
    xml += "<timepicker bucket_count=\"" + std::to_string(resolution.bucket_count) +
           "\" bucket_interval=\"" + std::to_string(bucket_interval) +
           "\" last_bucket_interval=\"0\">";
    xml += build_timepicker_buckets_xml(begin_time, end_time, resolution.bucket_count, bucket_interval);
    xml += "</timepicker></report>";
    return xml;
}
 
std::vector<std::string>
rudb::ash::report_text(const LayerReportRequest& request)
{
    return build_report_rows("ASH Report", request);
}
 
std::vector<std::string>
rudb::ash::report_html(const LayerReportRequest& request)
{
    return {
        "<html><head><title>ASH Report</title></head><body><pre>" +
        xml_escape(join_text_rows(report_text(request))) +
        "</pre></body></html>"
    };
}
 
std::vector<std::string>
rudb::ash::global_report_text(const LayerReportRequest& request)
{
    return build_report_rows("ASH RAC Report", request);
}
 
std::vector<std::string>
rudb::ash::global_report_html(const LayerReportRequest& request)
{
    return {
        "<html><head><title>ASH RAC Report</title></head><body><pre>" +
        xml_escape(join_text_rows(global_report_text(request))) +
        "</pre></body></html>"
    };
}
 
std::vector<rudb::ash::SampleRow>
rudb::ash::collect_memory_samples(const HistoryFilter& filter)
{
    ensure_shared_state_attached();
    std::vector<SampleRow> rows;
    const std::vector<SharedSampleSnapshot> snapshots = snapshot_memory_samples();
 
    try
    {
        for (const SharedSampleSnapshot& snapshot : snapshots)
        {
            SampleRow row = sample_from_shared(snapshot.sample);
            if (matches_sample(row, filter))
                rows.push_back(std::move(row));
        }
    }
    catch (...)
    {
        release_snapshot_sql_references(snapshots);
        throw;
    }
    release_snapshot_sql_references(snapshots);
 
    std::sort(rows.begin(), rows.end(),
              [](const SampleRow& left, const SampleRow& right)
              {
                  return left.sample_sequence < right.sample_sequence;
              });
    return rows;
}
 
std::vector<MemoryArchiveCandidate>
collect_memory_archive_candidates(const rudb::ash::HistoryFilter& filter)
{
    ensure_shared_state_attached();
    std::vector<MemoryArchiveCandidate> rows;
    const std::vector<SharedSampleSnapshot> snapshots = snapshot_memory_samples();
 
    try
    {
        for (const SharedSampleSnapshot& snapshot : snapshots)
        {
            MemoryArchiveCandidate candidate = archive_candidate_from_shared(snapshot.sample);
            if (matches_sample(candidate.row, filter))
                rows.push_back(std::move(candidate));
        }
    }
    catch (...)
    {
        release_snapshot_sql_references(snapshots);
        throw;
    }
    release_snapshot_sql_references(snapshots);
 
    std::sort(rows.begin(), rows.end(),
              [](const MemoryArchiveCandidate& left, const MemoryArchiveCandidate& right)
              {
                  return left.row.sample_sequence < right.row.sample_sequence;
              });
    return rows;
}
 
std::vector<rudb::ash::SampleRow>
rudb::ash::collect_history_samples(const HistoryFilter& filter)
{
    std::string sql =
        "SELECT s.sample_sequence, s.sample_time, s.dbid::bigint, s.instance_number::bigint,"
        " s.session_id::bigint, s.session_serial::bigint, s.session_generation::bigint,"
        " s.started_at, COALESCE(s.command_type, ''), COALESCE(s.backend_type, ''),"
        " s.user_id, COALESCE(s.sql_id, ''), COALESCE(t.sql_text, ''),"
        " COALESCE(s.module_name, ''), COALESCE(s.application_name, ''), COALESCE(s.state, ''),"
        " COALESCE(s.wait_class, ''), COALESCE(s.event_name, ''), s.snap_id, s.is_awr_sample"
        " FROM pg_catalog.rudb_ash_history_samples s"
        " LEFT JOIN pg_catalog.rudb_ash_history_sqltext t"
        "   ON t.dbid = s.dbid AND t.sql_id = s.sql_id"
        " WHERE TRUE";
 
    std::vector<Oid> argtypes;
    std::vector<Datum> values;
    std::vector<char> nulls;
    int argno = 1;
    auto append_arg = [&](Oid type, Datum value, char null_mark) -> std::string
    {
        argtypes.push_back(type);
        values.push_back(value);
        nulls.push_back(null_mark);
        return "$" + std::to_string(argno++);
    };
 
    if (filter.dbid.has_value())
        sql += " AND s.dbid = " + append_arg(INT8OID, Int64GetDatum(*filter.dbid), ' ');
    if (filter.instance_number.has_value())
        sql += " AND s.instance_number = " + append_arg(INT8OID, Int64GetDatum(*filter.instance_number), ' ');
    if (filter.begin_time.has_value())
        sql += " AND s.sample_time >= " + append_arg(TIMESTAMPTZOID, TimestampTzGetDatum(*filter.begin_time), ' ');
    if (filter.end_time.has_value())
        sql += std::string(" AND s.sample_time ") +
            (filter.end_time_exclusive ? "< " : "<= ") +
            append_arg(TIMESTAMPTZOID, TimestampTzGetDatum(*filter.end_time), ' ');
    if (filter.begin_snap_id.has_value())
        sql += " AND s.snap_id > " + append_arg(INT8OID, Int64GetDatum(*filter.begin_snap_id), ' ');
    if (filter.end_snap_id.has_value())
        sql += " AND s.snap_id <= " + append_arg(INT8OID, Int64GetDatum(*filter.end_snap_id), ' ');
    if (filter.sql_id.has_value())
        sql += " AND s.sql_id = " + append_arg(TEXTOID, CStringGetTextDatum(filter.sql_id->c_str()), ' ');
    if (filter.wait_class.has_value())
        sql += " AND lower(s.wait_class) = lower(" +
            append_arg(TEXTOID, CStringGetTextDatum(filter.wait_class->c_str()), ' ') + ")";
    if (filter.session_id.has_value())
        sql += " AND s.session_id = " + append_arg(INT8OID, Int64GetDatum(*filter.session_id), ' ');
    if (filter.module_name.has_value())
        sql += " AND s.module_name = " +
            append_arg(TEXTOID, CStringGetTextDatum(filter.module_name->c_str()), ' ');
    if (filter.awr_only)
        sql += " AND s.is_awr_sample";
 
    sql += " ORDER BY s.sample_sequence";
 
    std::vector<SampleRow> rows = with_ash_spi([&]() {
        const int rc = SPI_execute_with_args(sql.c_str(),
                                             argno - 1,
                                             argtypes.empty() ? nullptr : argtypes.data(),
                                             values.empty() ? nullptr : values.data(),
                                             nulls.empty() ? nullptr : nulls.data(),
                                             true,
                                             0);
 
        if (rc != SPI_OK_SELECT)
            ereport(ERROR,
                    (errcode(ERRCODE_INTERNAL_ERROR),
                     errmsg("не удалось получить historical ASH samples")));
 
        const uint64 processed = SPI_processed;
        std::vector<SampleRow> result;
        if (processed > result.max_size() ||
            processed > std::numeric_limits<std::size_t>::max() / sizeof(SampleRow))
        {
            ereport(ERROR,
                    (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                     errmsg("слишком много historical ASH samples для формирования отчёта")));
        }
        result.reserve(static_cast<std::size_t>(processed));
 
        for (uint64 idx = 0; idx < processed; ++idx)
        {
            HeapTuple tuple = SPI_tuptable->vals[idx];
            TupleDesc tupdesc = SPI_tuptable->tupdesc;
            bool isnull = false;
            SampleRow row;
            row.sample_sequence = DatumGetInt64(SPI_getbinval(tuple, tupdesc, 1, &isnull));
            row.sample_time = DatumGetTimestampTz(SPI_getbinval(tuple, tupdesc, 2, &isnull));
            row.dbid = DatumGetInt64(SPI_getbinval(tuple, tupdesc, 3, &isnull));
            row.instance_number = DatumGetInt64(SPI_getbinval(tuple, tupdesc, 4, &isnull));
            row.session_id = DatumGetInt64(SPI_getbinval(tuple, tupdesc, 5, &isnull));
            row.session_serial = DatumGetInt64(SPI_getbinval(tuple, tupdesc, 6, &isnull));
            row.session_generation = DatumGetInt64(SPI_getbinval(tuple, tupdesc, 7, &isnull));
            Datum started_at = SPI_getbinval(tuple, tupdesc, 8, &isnull);
            if (!isnull)
                row.started_at = DatumGetTimestampTz(started_at);
            row.command_type = datum_text_to_string(SPI_getbinval(tuple, tupdesc, 9, &isnull));
            row.backend_type = datum_text_to_string(SPI_getbinval(tuple, tupdesc, 10, &isnull));
            row.user_id = DatumGetObjectId(SPI_getbinval(tuple, tupdesc, 11, &isnull));
            row.sql_id = datum_text_to_string(SPI_getbinval(tuple, tupdesc, 12, &isnull));
            row.sql_text = datum_text_to_string(SPI_getbinval(tuple, tupdesc, 13, &isnull));
            row.module_name = datum_text_to_string(SPI_getbinval(tuple, tupdesc, 14, &isnull));
            row.application_name = datum_text_to_string(SPI_getbinval(tuple, tupdesc, 15, &isnull));
            row.state = datum_text_to_string(SPI_getbinval(tuple, tupdesc, 16, &isnull));
            row.wait_class = datum_text_to_string(SPI_getbinval(tuple, tupdesc, 17, &isnull));
            row.event_name = datum_text_to_string(SPI_getbinval(tuple, tupdesc, 18, &isnull));
            row.snap_id = DatumGetInt64(SPI_getbinval(tuple, tupdesc, 19, &isnull));
            row.is_awr_sample = DatumGetBool(SPI_getbinval(tuple, tupdesc, 20, &isnull));
 
            if (matches_sample(row, filter))
                result.push_back(std::move(row));
        }
 
        return result;
    });
 
    std::sort(rows.begin(), rows.end(),
              [](const SampleRow& left, const SampleRow& right)
              {
                  return left.sample_sequence < right.sample_sequence;
              });
    return rows;
}
 
bool
rudb::ash::archive_snapshot(int64_t dbid,
                              int64_t instance_number,
                              int64_t snap_id,
                              TimestampTz begin_time,
                              TimestampTz end_time)
{
    // Интервал архива использует (начало, конец]; метки публикует
    // обратный вызов транзакции.
    HistoryFilter filter;
    filter.dbid = dbid;
    filter.instance_number = instance_number;
    filter.begin_time = begin_time;
    filter.end_time = end_time;
    filter.begin_time_exclusive = true;
    filter.end_time_exclusive = false;
    std::vector<MemoryArchiveCandidate> rows = collect_memory_archive_candidates(filter);
    reserve_pending_archive_marks(rows.size());
 
    with_ash_spi([&]() {
        for (const MemoryArchiveCandidate& candidate : rows)
        {
            const SampleRow& row = candidate.row;
            constexpr int kArchiveSampleArgCount = 18;
 
            Oid sample_argtypes[] = {
                INT8OID, TIMESTAMPTZOID, INT8OID, INT8OID, INT8OID, INT8OID, INT8OID, TIMESTAMPTZOID,
                TEXTOID, TEXTOID, OIDOID, TEXTOID, TEXTOID, TEXTOID, TEXTOID, TEXTOID, TEXTOID, INT8OID
            };
            Datum sample_values[] = {
                Int64GetDatum(static_cast<int64>(row.sample_sequence)),
                TimestampTzGetDatum(row.sample_time),
                Int64GetDatum(row.dbid),
                Int64GetDatum(row.instance_number),
                Int64GetDatum(row.session_id),
                Int64GetDatum(row.session_serial),
                Int64GetDatum(row.session_generation),
                TimestampTzGetDatum(row.started_at),
                row.command_type.empty() ? (Datum) 0 : CStringGetTextDatum(row.command_type.c_str()),
                row.backend_type.empty() ? (Datum) 0 : CStringGetTextDatum(row.backend_type.c_str()),
                ObjectIdGetDatum(row.user_id),
                row.sql_id.empty() ? (Datum) 0 : CStringGetTextDatum(row.sql_id.c_str()),
                row.module_name.empty() ? (Datum) 0 : CStringGetTextDatum(row.module_name.c_str()),
                row.application_name.empty() ? (Datum) 0 : CStringGetTextDatum(row.application_name.c_str()),
                row.state.empty() ? (Datum) 0 : CStringGetTextDatum(row.state.c_str()),
                row.wait_class.empty() ? (Datum) 0 : CStringGetTextDatum(row.wait_class.c_str()),
                row.event_name.empty() ? (Datum) 0 : CStringGetTextDatum(row.event_name.c_str()),
                Int64GetDatum(snap_id)
            };
            StaticAssertDecl(lengthof(sample_argtypes) == kArchiveSampleArgCount,
                             "archive sample argtypes count must stay synchronized");
            StaticAssertDecl(lengthof(sample_values) == kArchiveSampleArgCount,
                             "archive sample values count must stay synchronized");
            const char sample_nulls[] = {
                ' ', ' ', ' ', ' ', ' ', ' ', ' ', row.started_at == 0 ? 'n' : ' ',
                row.command_type.empty() ? 'n' : ' ', row.backend_type.empty() ? 'n' : ' ',
                row.user_id == InvalidOid ? 'n' : ' ',
                row.sql_id.empty() ? 'n' : ' ',
                row.module_name.empty() ? 'n' : ' ',
                row.application_name.empty() ? 'n' : ' ',
                row.state.empty() ? 'n' : ' ',
                row.wait_class.empty() ? 'n' : ' ',
                row.event_name.empty() ? 'n' : ' ',
                ' '
            };
            StaticAssertDecl(lengthof(sample_nulls) == kArchiveSampleArgCount,
                             "archive sample null flags count must stay synchronized");
            const int sample_rc = SPI_execute_with_args(
                "INSERT INTO pg_catalog.rudb_ash_history_samples("
                " sample_sequence, sample_time, dbid, instance_number, session_id,"
                " session_serial, session_generation, started_at, command_type, backend_type, user_id, sql_id, module_name, application_name,"
                " state, wait_class, event_name, snap_id, is_awr_sample)"
                " VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, true)"
                " ON CONFLICT (sample_sequence) DO NOTHING",
                kArchiveSampleArgCount, sample_argtypes, sample_values, sample_nulls, false, 0);
            if (sample_rc != SPI_OK_INSERT && sample_rc != SPI_OK_INSERT_RETURNING)
                ereport(ERROR,
                        (errcode(ERRCODE_INTERNAL_ERROR),
                         errmsg("не удалось архивировать RUDB ASH sample")));
 
            const bool sample_inserted = SPI_processed == 1;
            if (!row.sql_id.empty() && !row.sql_text.empty())
            {
                Oid sqltext_argtypes[] = {INT8OID, TEXTOID, TEXTOID, TIMESTAMPTZOID, TIMESTAMPTZOID};
                Datum sqltext_values[] = {
                    Int64GetDatum(row.dbid),
                    CStringGetTextDatum(row.sql_id.c_str()),
                    CStringGetTextDatum(row.sql_text.c_str()),
                    TimestampTzGetDatum(row.sample_time),
                    TimestampTzGetDatum(row.sample_time)
                };
                const char sqltext_nulls[] = {' ', ' ', ' ', ' ', ' '};
                const int sqltext_rc = SPI_execute_with_args(
                    "INSERT INTO pg_catalog.rudb_ash_history_sqltext(dbid, sql_id, sql_text, first_seen, last_seen)"
                    " VALUES ($1, $2, $3, $4, $5)"
                    " ON CONFLICT (dbid, sql_id)"
                    " DO UPDATE SET sql_text = EXCLUDED.sql_text, last_seen = EXCLUDED.last_seen",
                    5, sqltext_argtypes, sqltext_values, sqltext_nulls, false, 0);
                if (sqltext_rc != SPI_OK_INSERT && sqltext_rc != SPI_OK_UPDATE)
                    ereport(ERROR,
                            (errcode(ERRCODE_INTERNAL_ERROR),
                             errmsg("не удалось архивировать RUDB ASH SQL text")));
            }
            if (sample_inserted)
            {
                pending_archive_marks().push_back(
                    {row.sample_sequence,
                     candidate.sample_generation,
                     candidate.activity_generation,
                     snap_id,
                     GetCurrentSubTransactionId()});
            }
        }
 
        return 0;
    });
    return true;
}
 
void
rudb::ash::mark_snapshot_range_pending_clear(int64_t dbid,
                                             int64_t low_snap_id,
                                             int64_t high_snap_id)
{
    reserve_pending_snapshot_clear_marks(1);
    pending_snapshot_clear_marks().push_back(
        {dbid, low_snap_id, high_snap_id, GetCurrentSubTransactionId()});
}
 
void
rudb::ash::drop_snapshot_range(int64_t dbid, int64_t low_snap_id, int64_t high_snap_id)
{
    // Метаданные снимков AWR и связанные записи ASH удаляются
    // согласованно для одного диапазона.
    Oid argtypes[] = {INT8OID, INT8OID, INT8OID};
    Datum values[] = {Int64GetDatum(dbid), Int64GetDatum(low_snap_id), Int64GetDatum(high_snap_id)};
    const char nulls[] = {' ', ' ', ' '};
    with_ash_spi([&]() {
        int rc = SPI_execute_with_args(
            "DELETE FROM pg_catalog.rudb_ash_history_samples"
            " WHERE dbid = $1 AND snap_id >= $2 AND snap_id <= $3",
            3, argtypes, values, nulls, false, 0);
        if (rc != SPI_OK_DELETE)
            ereport(ERROR,
                    (errcode(ERRCODE_INTERNAL_ERROR),
                     errmsg("не удалось удалить RUDB ASH history samples")));
 
        mark_snapshot_range_pending_clear(dbid, low_snap_id, high_snap_id);
 
        rc = SPI_execute(
            "DELETE FROM pg_catalog.rudb_ash_history_sqltext t "
            "WHERE NOT EXISTS ("
            "  SELECT 1 FROM pg_catalog.rudb_ash_history_samples s"
            "  WHERE s.dbid = t.dbid AND s.sql_id = t.sql_id)",
            false, 0);
        if (rc != SPI_OK_DELETE)
            ereport(ERROR,
                    (errcode(ERRCODE_INTERNAL_ERROR),
                     errmsg("не удалось удалить orphan RUDB ASH SQL texts")));
        return 0;
    });
}
 
void
rudb::ash::purge_history(int retention_seconds)
{
    // Очистка удаляет постоянное историческое хранилище; кольцевой буфер
    // в памяти ограничен независимо.
    char* sql = psprintf(
        "DELETE FROM %s WHERE sample_time < clock_timestamp() - make_interval(secs => %d)",
        kHistorySampleTable,
        retention_seconds);
    try
    {
        with_ash_spi([&]() {
            int rc = SPI_execute(sql, false, 0);
            if (rc != SPI_OK_DELETE)
                ereport(ERROR,
                        (errcode(ERRCODE_INTERNAL_ERROR),
                         errmsg("не удалось очистить RUDB ASH history")));
 
            rc = SPI_execute(
                "DELETE FROM pg_catalog.rudb_ash_history_sqltext t "
                "WHERE NOT EXISTS ("
                "  SELECT 1 FROM pg_catalog.rudb_ash_history_samples s"
                "  WHERE s.dbid = t.dbid AND s.sql_id = t.sql_id)",
                false, 0);
            if (rc != SPI_OK_DELETE)
                ereport(ERROR,
                        (errcode(ERRCODE_INTERNAL_ERROR),
                         errmsg("не удалось очистить orphan RUDB ASH SQL texts")));
            return 0;
        });
    }
    catch (...)
    {
        pfree(sql);
        throw;
    }
    pfree(sql);
}
 
std::size_t
rudb::ash::sql_text_count(void)
{
    ensure_shared_state_attached();
    std::size_t count = 0;
 
    LWLockAcquire(g_ash_lock, LW_SHARED);
    for (uint32 idx = 0; idx < g_shared->sql_cache_capacity; ++idx)
    {
        if (sql_cache()[idx].generation != 0)
            ++count;
    }
    LWLockRelease(g_ash_lock);
    return count;
}
 
std::size_t
rudb::ash::sample_count(void)
{
    ensure_shared_state_attached();
    std::size_t count = 0;
 
    LWLockAcquire(g_ash_lock, LW_SHARED);
    for (uint32 idx = 0; idx < g_shared->sample_capacity; ++idx)
    {
        if (sample_ring()[idx].sample_sequence != 0)
            ++count;
    }
    LWLockRelease(g_ash_lock);
    return count;
}
 
std::string
rudb::ash::service_state(void)
{
    ensure_shared_state_attached();
    std::size_t sql_cache_count = 0;
    std::size_t memory_sample_count = 0;
    std::size_t retained_memory_sample_count = 0;
    std::size_t current_db_memory_sample_count = 0;
    AshSharedHeader header_snapshot{};
    const TimestampTz retention_cutoff =
        GetCurrentTimestamp() -
        static_cast<TimestampTz>(g_retention_seconds) * USECS_PER_SEC;
    const int64 current_dbid = MyDatabaseId == InvalidOid ? 0 : local_dbid_impl(MyDatabaseId);
 
    LWLockAcquire(g_ash_lock, LW_SHARED);
    header_snapshot = *g_shared;
    for (uint32 idx = 0; idx < g_shared->sql_cache_capacity; ++idx)
    {
        if (sql_cache()[idx].generation != 0)
            ++sql_cache_count;
    }
    for (uint32 idx = 0; idx < g_shared->sample_capacity; ++idx)
    {
        const AshSharedSample& sample = sample_ring()[idx];
 
        if (sample.sample_sequence == 0)
            continue;
 
        ++memory_sample_count;
        if (sample.sample_time < retention_cutoff)
            continue;
 
        ++retained_memory_sample_count;
        if (current_dbid != 0 && sample.dbid == current_dbid)
            ++current_db_memory_sample_count;
    }
    LWLockRelease(g_ash_lock);
    return "ash_worker_pid=" + std::to_string(header_snapshot.worker_pid) +
        "; ash_sample_interval_ms=" + std::to_string(header_snapshot.sample_interval_ms) +
        "; ash_retention_seconds=" + std::to_string(header_snapshot.retention_seconds) +
        "; ash_sql_cache=" + std::to_string(sql_cache_count) +
        "; ash_dropped_samples=" + std::to_string(header_snapshot.dropped_samples) +
        "; ash_memory_samples=" + std::to_string(memory_sample_count) +
        "; ash_memory_slots_used=" + std::to_string(memory_sample_count) +
        "; ash_memory_samples_retained=" + std::to_string(retained_memory_sample_count) +
        "; ash_memory_samples_current_db=" + std::to_string(current_db_memory_sample_count) +
        "; ash_worker_cycles=" + std::to_string(header_snapshot.worker_cycles) +
        "; ash_next_ring_position=" + std::to_string(header_snapshot.next_ring_position) +
        "; ash_active_slots_seen=" + std::to_string(header_snapshot.active_slots_seen) +
        "; ash_samples_written=" + std::to_string(header_snapshot.samples_written) +
        "; ash_reject_unstable_publication=" + std::to_string(header_snapshot.reject_unstable_publication) +
        "; ash_reject_inactive_slot=" + std::to_string(header_snapshot.reject_inactive_slot) +
        "; ash_reject_invalid_proc_number=" + std::to_string(header_snapshot.reject_invalid_proc_number) +
        "; ash_reject_missing_pgproc=" + std::to_string(header_snapshot.reject_missing_pgproc) +
        "; ash_reject_pid_mismatch=" + std::to_string(header_snapshot.reject_pid_mismatch) +
        "; ash_reject_self_pid=" + std::to_string(header_snapshot.reject_self_pid) +
        "; ash_reject_invalid_database=" + std::to_string(header_snapshot.reject_invalid_database) +
        "; ash_reject_sql_cache_reference=" + std::to_string(header_snapshot.reject_sql_cache_reference);
}
 
int
rudb::ash::retention_seconds(void)
{
    return g_retention_seconds;
}
 
int
rudb::ash::sample_interval_ms(void)
{
    return g_sample_interval_ms;
}
 
int64_t
rudb::ash::local_dbid(void)
{
    return local_dbid_impl(MyDatabaseId);
}