aboutsummaryrefslogtreecommitdiffstats
path: root/yt/yt/client/table_client/schema.cpp
blob: 25a5c29ed94ad19c43e7ec89be273554777c62a9 (plain) (blame)
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
#include "schema.h"

#include "column_sort_schema.h"
#include "comparator.h"
#include "logical_type.h"
#include "unversioned_row.h"
#include "versioned_io_options.h"

#include <yt/yt/client/tablet_client/public.h>

#include <yt/yt/core/yson/public.h>
#include <yt/yt/core/yson/pull_parser_deserialize.h>

#include <yt/yt/core/ytree/serialize.h>
#include <yt/yt/core/ytree/convert.h>
#include <yt/yt/core/ytree/fluent.h>
#include <yt/yt/core/ytree/yson_struct.h>

#include <yt/yt_proto/yt/client/table_chunk_format/proto/chunk_meta.pb.h>
#include <yt/yt_proto/yt/client/table_chunk_format/proto/wire_protocol.pb.h>

#include <yt/yt_proto/yt/client/tablet_client/proto/lock_mask.pb.h>

#include <optional>

namespace NYT::NTableClient {

using namespace NChunkClient;
using namespace NObjectClient;
using namespace NTabletClient;
using namespace NYson;
using namespace NYTree;

using NYT::ToProto;
using NYT::FromProto;

////////////////////////////////////////////////////////////////////////////////

namespace {

int GetLockPriority(ELockType lockType)
{
    switch (lockType) {
        case ELockType::None:
            return 0;
        case ELockType::SharedWeak:
            return 1;
        case ELockType::SharedStrong:
            return 2;
        case ELockType::SharedWrite:
            return 3;
        case ELockType::Exclusive:
            return 4;
        default:
            YT_ABORT();
    }
}

} // namespace

////////////////////////////////////////////////////////////////////////////////

bool IsReadLock(ELockType lock)
{
    return lock == ELockType::SharedWeak || lock == ELockType::SharedStrong;
}

bool IsWriteLock(ELockType lock)
{
    return lock == ELockType::Exclusive || lock == ELockType::SharedWrite;
}

ELockType GetStrongestLock(ELockType lhs, ELockType rhs)
{
    if (lhs == ELockType::None) {
        return rhs;
    }

    if (rhs == ELockType::None) {
        return lhs;
    }

    if (IsReadLock(lhs) && IsWriteLock(rhs) ||
        IsReadLock(rhs) && IsWriteLock(lhs))
    {
        return ELockType::Exclusive;
    }

    return GetLockPriority(lhs) > GetLockPriority(rhs) ? lhs : rhs;
}

////////////////////////////////////////////////////////////////////////////////

bool operator == (const TLockMask& lhs, const TLockMask& rhs)
{
    int lockCount = std::max(lhs.GetSize(), rhs.GetSize());
    for (int index = 0; index < lockCount; ++index) {
        if (lhs.Get(index) != rhs.Get(index)) {
            return false;
        }
    }

    return true;
}

TLockMask MaxMask(TLockMask lhs, TLockMask rhs)
{
    int size = std::max<int>(lhs.GetSize(), rhs.GetSize());
    for (int index = 0; index < size; ++index) {
        lhs.Set(index, GetStrongestLock(lhs.Get(index), rhs.Get(index)));
    }

    return lhs;
}

void ToProto(NTabletClient::NProto::TLockMask* protoLockMask, const TLockMask& lockMask)
{
    auto size = lockMask.GetSize();
    YT_VERIFY(size <= TLockMask::MaxSize);

    protoLockMask->set_size(size);

    const auto& bitmap = lockMask.GetBitmap();
    auto wordCount = DivCeil(size, TLockMask::LocksPerWord);
    YT_VERIFY(std::ssize(bitmap) >= wordCount);

    protoLockMask->clear_bitmap();
    for (int index = 0; index < wordCount; ++index) {
        protoLockMask->add_bitmap(bitmap[index]);
    }
}

void FromProto(TLockMask* lockMask, const NTabletClient::NProto::TLockMask& protoLockMask)
{
    auto size = protoLockMask.size();
    auto wordCount = DivCeil<int>(size, TLockMask::LocksPerWord);

    TLockBitmap bitmap;
    bitmap.reserve(wordCount);
    for (int index = 0; index < wordCount; ++index) {
        bitmap.push_back(protoLockMask.bitmap(index));
    }

    *lockMask = TLockMask(bitmap, size);
}

////////////////////////////////////////////////////////////////////////////////

TColumnSchema::TColumnSchema()
    : TColumnSchema(
        std::string(),
        NullLogicalType(),
        std::nullopt)
{ }

TColumnSchema::TColumnSchema(
    const std::string& name,
    EValueType type,
    std::optional<ESortOrder> sortOrder)
    : TColumnSchema(
        name,
        MakeLogicalType(GetLogicalType(type), /*required*/ false),
        sortOrder)
{ }

TColumnSchema::TColumnSchema(
    const std::string& name,
    ESimpleLogicalValueType type,
    std::optional<ESortOrder> sortOrder)
    : TColumnSchema(
        name,
        MakeLogicalType(type, /*required*/ false),
        sortOrder)
{ }

TColumnSchema::TColumnSchema(
    const std::string& name,
    TLogicalTypePtr type,
    std::optional<ESortOrder> sortOrder)
    : StableName_(name)
    , Name_(name)
    , SortOrder_(sortOrder)
{
    SetLogicalType(std::move(type));
}

TColumnSchema& TColumnSchema::SetStableName(const TColumnStableName& value)
{
    StableName_ = value;
    return *this;
}

TColumnSchema& TColumnSchema::SetName(const std::string& value)
{
    Name_ = value;
    return *this;
}

TColumnSchema& TColumnSchema::SetSortOrder(std::optional<ESortOrder> value)
{
    SortOrder_ = value;
    return *this;
}

TColumnSchema& TColumnSchema::SetLock(const std::optional<std::string>& value)
{
    Lock_ = value;
    return *this;
}

TColumnSchema& TColumnSchema::SetGroup(const std::optional<std::string>& value)
{
    Group_ = value;
    return *this;
}

TColumnSchema& TColumnSchema::SetExpression(const std::optional<TString>& value)
{
    Expression_ = value;
    return *this;
}

TColumnSchema& TColumnSchema::SetMaterialized(std::optional<bool> value)
{
    Materialized_ = std::move(value);
    return *this;
}

TColumnSchema& TColumnSchema::SetAggregate(const std::optional<std::string>& value)
{
    Aggregate_ = value;
    return *this;
}

TColumnSchema& TColumnSchema::SetRequired(bool value)
{
    if (!IsOfV1Type_) {
        THROW_ERROR_EXCEPTION("Cannot set required flag for non-v1 typed column");
    }
    SetLogicalType(MakeLogicalType(V1Type_, value));
    return *this;
}

TColumnSchema& TColumnSchema::SetMaxInlineHunkSize(std::optional<i64> value)
{
    MaxInlineHunkSize_ = value;
    return *this;
}

TColumnSchema& TColumnSchema::SetLogicalType(TLogicalTypePtr type)
{
    LogicalType_ = std::move(type);
    WireType_ = NTableClient::GetWireType(LogicalType_);
    IsOfV1Type_ = IsV1Type(LogicalType_);
    std::tie(V1Type_, Required_) = NTableClient::CastToV1Type(LogicalType_);
    return *this;
}

TColumnSchema& TColumnSchema::SetSimpleLogicalType(ESimpleLogicalValueType type)
{
    SetLogicalType(MakeLogicalType(type, /*required*/ false));
    return *this;
}

EValueType TColumnSchema::GetWireType() const
{
    return WireType_;
}

i64 TColumnSchema::GetMemoryUsage() const
{
    return
        sizeof(TColumnSchema) +
        StableName_.Underlying().size() +
        Name_.size() +
        (LogicalType_ ? LogicalType_->GetMemoryUsage() : 0) +
        (Lock_ ? Lock_->size() : 0) +
        (Expression_ ? Expression_->size() : 0) +
        (Aggregate_ ? Aggregate_->size() : 0) +
        (Group_ ? Group_->size() : 0);
}

bool TColumnSchema::IsOfV1Type() const
{
    return IsOfV1Type_;
}

bool TColumnSchema::IsOfV1Type(ESimpleLogicalValueType type) const
{
    return IsOfV1Type_ && V1Type_ == type;
}

ESimpleLogicalValueType TColumnSchema::CastToV1Type() const
{
    return V1Type_;
}

bool TColumnSchema::IsRenamed() const
{
    return Name() != StableName().Underlying();
}

std::string TColumnSchema::GetDiagnosticNameString() const
{
    if (IsRenamed()) {
        return Format("%Qv (stable name %Qv)", Name(), StableName().Underlying());
    } else {
        return Format("%Qv", Name());
    }
}

////////////////////////////////////////////////////////////////////////////////

TDeletedColumn::TDeletedColumn()
{
}

TDeletedColumn::TDeletedColumn(TColumnStableName stableName)
    : StableName_(stableName)
{
}

TDeletedColumn& TDeletedColumn::SetStableName(TColumnStableName value)
{
    StableName_ = std::move(value);
    return *this;
}

////////////////////////////////////////////////////////////////////////////////

void FormatValue(TStringBuilderBase* builder, const TColumnSchema& schema, TStringBuf /*spec*/)
{
    builder->AppendChar('{');

    builder->AppendFormat("name=%Qv", schema.Name());

    if (schema.IsRenamed()) {
        builder->AppendFormat("; stable_name=%Qv", schema.StableName());
    }

    if (const auto& logicalType = schema.LogicalType()) {
        builder->AppendFormat("; type=%v", *logicalType);
    }

    if (const auto& sortOrder = schema.SortOrder()) {
        builder->AppendFormat("; sort_order=%v", *sortOrder);
    }

    if (const auto& lock = schema.Lock()) {
        builder->AppendFormat("; lock=%v", *lock);
    }

    if (const auto& expression = schema.Expression()) {
        builder->AppendFormat("; expression=%Qv", *expression);
    }

    if (const auto& materialized = schema.Materialized()) {
        builder->AppendFormat("; materialized=%v", *materialized);
    }

    if (const auto& aggregate = schema.Aggregate()) {
        builder->AppendFormat("; aggregate=%v", *aggregate);
    }

    if (const auto& group = schema.Group()) {
        builder->AppendFormat("; group=%v", *group);
    }

    builder->AppendFormat("; physical_type=%v", CamelCaseToUnderscoreCase(ToString(schema.CastToV1Type())));

    builder->AppendFormat("; required=%v", schema.Required());

    if (auto maxInlineHunkSize = schema.MaxInlineHunkSize()) {
        builder->AppendFormat("; max_inline_hunk_size=%v", *maxInlineHunkSize);
    }

    builder->AppendChar('}');
}

void FormatValue(TStringBuilderBase* builder, const TDeletedColumn& schema, TStringBuf spec)
{
    builder->AppendChar('{');

    FormatValue(builder, schema.StableName(), spec);
    builder->AppendFormat("; deleted=true");

    builder->AppendChar('}');
}

void ToProto(NProto::TColumnSchema* protoSchema, const TColumnSchema& schema)
{
    protoSchema->set_name(ToProto(schema.Name()));
    if (schema.IsRenamed()) {
        protoSchema->set_stable_name(ToProto(schema.StableName()));
    }

    protoSchema->set_type(ToProto(GetPhysicalType(schema.CastToV1Type())));

    if (schema.IsOfV1Type()) {
        protoSchema->set_simple_logical_type(ToProto(schema.CastToV1Type()));
    } else {
        protoSchema->clear_simple_logical_type();
    }
    if (schema.Required()) {
        protoSchema->set_required(true);
    } else {
        protoSchema->clear_required();
    }
    ToProto(protoSchema->mutable_logical_type(), schema.LogicalType());
    if (schema.Lock()) {
        protoSchema->set_lock(ToProto(*schema.Lock()));
    } else {
        protoSchema->clear_lock();
    }
    if (schema.Expression()) {
        protoSchema->set_expression(*schema.Expression());
    } else {
        protoSchema->clear_expression();
    }
    if (schema.Materialized()) {
        protoSchema->set_materialized(*schema.Materialized());
    } else {
        protoSchema->clear_materialized();
    }
    if (schema.Aggregate()) {
        protoSchema->set_aggregate(ToProto(*schema.Aggregate()));
    } else {
        protoSchema->clear_aggregate();
    }
    if (schema.SortOrder()) {
        protoSchema->set_sort_order(ToProto(*schema.SortOrder()));
    } else {
        protoSchema->clear_sort_order();
    }
    if (schema.Group()) {
        protoSchema->set_group(ToProto(*schema.Group()));
    } else {
        protoSchema->clear_group();
    }
    if (schema.MaxInlineHunkSize()) {
        protoSchema->set_max_inline_hunk_size(*schema.MaxInlineHunkSize());
    } else {
        protoSchema->clear_max_inline_hunk_size();
    }
}

void ToProto(NProto::TDeletedColumn* protoSchema, const TDeletedColumn& schema)
{
    protoSchema->set_stable_name(ToProto(schema.StableName()));
}

void FromProto(TColumnSchema* schema, const NProto::TColumnSchema& protoSchema)
{
    schema->SetName(protoSchema.name());
    schema->SetStableName(protoSchema.has_stable_name()
        ? TColumnStableName(protoSchema.stable_name())
        : TColumnStableName(protoSchema.name()));

    if (protoSchema.has_logical_type()) {
        TLogicalTypePtr logicalType;
        FromProto(&logicalType, protoSchema.logical_type());
        schema->SetLogicalType(logicalType);
    } else if (protoSchema.has_simple_logical_type()) {
        schema->SetLogicalType(
            MakeLogicalType(
                CheckedEnumCast<ESimpleLogicalValueType>(protoSchema.simple_logical_type()),
                protoSchema.required()));
    } else {
        auto physicalType = CheckedEnumCast<EValueType>(protoSchema.type());
        schema->SetLogicalType(MakeLogicalType(GetLogicalType(physicalType), protoSchema.required()));
    }

    schema->SetLock(YT_PROTO_OPTIONAL(protoSchema, lock));
    schema->SetExpression(YT_PROTO_OPTIONAL(protoSchema, expression));
    schema->SetMaterialized(YT_PROTO_OPTIONAL(protoSchema, materialized));
    schema->SetAggregate(YT_PROTO_OPTIONAL(protoSchema, aggregate));
    schema->SetSortOrder(YT_APPLY_PROTO_OPTIONAL(protoSchema, sort_order, CheckedEnumCast<ESortOrder>));
    schema->SetGroup(YT_PROTO_OPTIONAL(protoSchema, group));
    schema->SetMaxInlineHunkSize(YT_PROTO_OPTIONAL(protoSchema, max_inline_hunk_size));
}

void FromProto(TDeletedColumn* schema, const NProto::TDeletedColumn& protoSchema)
{
    schema->SetStableName(TColumnStableName{protoSchema.stable_name()});
}

void PrintTo(const TColumnSchema& columnSchema, std::ostream* os)
{
    *os << Format("%v", columnSchema);
}

////////////////////////////////////////////////////////////////////////////////

TTableSchema::TNameMapping::TNameMapping(const TTableSchema& schema)
    : Schema_(schema)
{ }

bool TTableSchema::TNameMapping::IsDeleted(const TColumnStableName& stableName) const
{
    return Schema_.FindDeletedColumn(stableName) != nullptr;
}

std::string TTableSchema::TNameMapping::StableNameToName(const TColumnStableName& stableName) const
{
    auto* column = Schema_.FindColumnByStableName(stableName);
    if (!column) {
        if (Schema_.GetStrict()) {
            THROW_ERROR_EXCEPTION("No column with stable name %Qv in strict schema", stableName);
        }
        return stableName.Underlying();
    }
    return column->Name();
}

TColumnStableName TTableSchema::TNameMapping::NameToStableName(TStringBuf name) const
{
    auto* column = Schema_.FindColumn(name);
    if (!column) {
        if (Schema_.GetStrict()) {
            if (auto originalColumnName = GetTimestampColumnOriginalNameOrNull(name);
                !originalColumnName || !Schema_.FindColumn(*originalColumnName))
            {
                THROW_ERROR_EXCEPTION("No column with name %Qv in strict schema", name);
            }
        }
        return TColumnStableName(std::string(name));
    }
    return column->StableName();
}

////////////////////////////////////////////////////////////////////////////////

const std::vector<TColumnSchema>& TTableSchema::Columns() const
{
    if (ColumnInfo_) [[likely]] {
        return ColumnInfo_->Columns;
    } else {
        static const std::vector<TColumnSchema> empty;
        return empty;
    }
}

const std::vector<TDeletedColumn>& TTableSchema::DeletedColumns() const
{
    if (ColumnInfo_) [[likely]] {
        return ColumnInfo_->DeletedColumns;
    } else {
        static std::vector<TDeletedColumn> empty;
        return empty;
    }
}

TTableSchema::TTableSchema(
    std::vector<TColumnSchema> columns,
    bool strict,
    bool uniqueKeys,
    ETableSchemaModification schemaModification,
    std::vector<TDeletedColumn> deletedColumns)
    : Strict_(strict)
    , UniqueKeys_(uniqueKeys)
    , SchemaModification_(schemaModification)
    , ColumnInfo_(std::make_shared<const TColumnInfo>(std::move(columns), std::move(deletedColumns)))
{
    const auto& info = *ColumnInfo_;
    for (int index = 0; index < std::ssize(Columns()); ++index) {
        const auto& column = info.Columns[index];
        if (column.SortOrder()) {
            ++KeyColumnCount_;
        }
        if (column.Expression()) {
            if (column.Materialized().value_or(true)) {
                HasMaterializedComputedColumns_ = true;
            } else {
                HasNonMaterializedComputedColumns_ = true;
            }
        }
        if (column.Aggregate()) {
            HasAggregateColumns_ = true;
        }
        if (column.MaxInlineHunkSize()) {
            HunkColumnsIds_.push_back(index);
        }
        // NB(levysotsky): We ignore duplicates in both maps, they will be
        // accounted for in consequent validation.
        NameToColumnIndex_.emplace(column.Name(), index);
        StableNameToColumnIndex_.emplace(column.StableName().Underlying(), index);
    }
    for (int index = 0; index < std::ssize(DeletedColumns()); ++index) {
        const auto& deletedColumn = info.DeletedColumns[index];
        StableNameToDeletedColumnIndex_.emplace(deletedColumn.StableName().Underlying(), index);
    }
}

const TColumnSchema* TTableSchema::FindColumnByStableName(const TColumnStableName& stableName) const
{
    auto it = StableNameToColumnIndex_.find(stableName.Underlying());
    if (it == StableNameToColumnIndex_.end()) {
        return nullptr;
    }
    return &Columns()[it->second];
}

const TDeletedColumn* TTableSchema::FindDeletedColumn(const TColumnStableName& stableName) const
{
    auto it = StableNameToDeletedColumnIndex_.find(stableName.Underlying());
    if (it == StableNameToDeletedColumnIndex_.end()) {
        return nullptr;
    }
    return &DeletedColumns()[it->second];
}

const TColumnSchema* TTableSchema::FindColumn(TStringBuf name) const
{
    auto it = NameToColumnIndex_.find(name);
    if (it == NameToColumnIndex_.end()) {
        return nullptr;
    }
    return &Columns()[it->second];
}

const TColumnSchema& TTableSchema::GetColumn(TStringBuf name) const
{
    auto* column = FindColumn(name);
    YT_VERIFY(column);
    return *column;
}

const TColumnSchema& TTableSchema::GetColumnOrThrow(TStringBuf name) const
{
    auto* column = FindColumn(name);
    if (!column) {
        THROW_ERROR_EXCEPTION("Missing schema column with name %Qv", name);
    }
    return *column;
}

int TTableSchema::GetColumnIndex(const TColumnSchema& column) const
{
    auto begin = Columns().data();
    auto end = begin + Columns().size();
    YT_VERIFY(begin <= &column && &column < end);

    return &column - begin;
}

int TTableSchema::GetColumnIndex(TStringBuf name) const
{
    return GetColumnIndex(GetColumn(name));
}

int TTableSchema::GetColumnIndexOrThrow(TStringBuf name) const
{
    return GetColumnIndex(GetColumnOrThrow(name));
}

TTableSchema::TNameMapping TTableSchema::GetNameMapping() const
{
    return TNameMapping(*this);
}

TTableSchemaPtr TTableSchema::Filter(const TColumnFilter& columnFilter, bool discardSortOrder) const
{
    int newKeyColumnCount = 0;
    std::vector<TColumnSchema> columns;
    if (columnFilter.IsUniversal()) {
        if (!discardSortOrder) {
            return New<TTableSchema>(*this);
        } else {
            columns = Columns();
            for (auto& column : columns) {
                column.SetSortOrder(std::nullopt);
            }
        }
    } else {
        bool inKeyColumns = !discardSortOrder;
        const auto& schemaColumns = Columns();
        for (int id : columnFilter.GetIndexes()) {
            if (id < 0 || id >= std::ssize(schemaColumns)) {
                THROW_ERROR_EXCEPTION("Invalid column during schema filtering: expected in range [0, %v), got %v",
                    schemaColumns.size(),
                    id);
            }

            if (id != std::ssize(columns) || !schemaColumns[id].SortOrder()) {
                inKeyColumns = false;
            }

            columns.push_back(schemaColumns[id]);

            if (!inKeyColumns) {
                columns.back().SetSortOrder(std::nullopt);
            }

            if (columns.back().SortOrder()) {
                ++newKeyColumnCount;
            }
        }
    }

    return New<TTableSchema>(
        std::move(columns),
        Strict_,
        UniqueKeys_ && (newKeyColumnCount == GetKeyColumnCount()),
        ETableSchemaModification::None,
        DeletedColumns());
}

TTableSchemaPtr TTableSchema::Filter(const THashSet<std::string>& columnNames, bool discardSortOrder) const
{
    TColumnFilter::TIndexes indexes;
    for (const auto& column : Columns()) {
        if (columnNames.find(column.Name()) != columnNames.end()) {
            indexes.push_back(GetColumnIndex(column));
        }
    }
    return Filter(TColumnFilter(std::move(indexes)), discardSortOrder);
}

TTableSchemaPtr TTableSchema::Filter(const std::optional<std::vector<std::string>>& columnNames, bool discardSortOrder) const
{
    if (!columnNames) {
        return Filter(TColumnFilter(), discardSortOrder);
    }

    return Filter(THashSet<std::string>(columnNames->begin(), columnNames->end()), discardSortOrder);
}

bool TTableSchema::HasMaterializedComputedColumns() const
{
    return HasMaterializedComputedColumns_;
}

bool TTableSchema::HasNonMaterializedComputedColumns() const
{
    return HasNonMaterializedComputedColumns_;
}

bool TTableSchema::HasComputedColumns() const
{
    return HasMaterializedComputedColumns() || HasNonMaterializedComputedColumns();
}

bool TTableSchema::HasAggregateColumns() const
{
    return HasAggregateColumns_;
}

bool TTableSchema::HasHunkColumns() const
{
    return !HunkColumnsIds_.empty();
}

bool TTableSchema::HasTimestampColumn() const
{
    return FindColumn(TimestampColumnName);
}

bool TTableSchema::HasTtlColumn() const
{
    return FindColumn(TtlColumnName);
}

bool TTableSchema::IsSorted() const
{
    return KeyColumnCount_ > 0;
}

bool TTableSchema::IsUniqueKeys() const
{
    return UniqueKeys_;
}

bool TTableSchema::HasRenamedColumns() const
{
    return std::any_of(Columns().begin(), Columns().end(), [] (const TColumnSchema& column) {
        return column.IsRenamed();
    });
}

bool TTableSchema::IsEmpty() const
{
    return Columns().empty();
}

bool TTableSchema::IsCGComparatorApplicable() const
{
    if (GetKeyColumnCount() > MaxKeyColumnCountInDynamicTable) {
        return false;
    }

    auto keyTypes = GetKeyColumnTypes();
    return std::none_of(keyTypes.begin(), keyTypes.end(), [] (auto type) {
        return type == EValueType::Any;
    });
}

std::optional<int> TTableSchema::GetTtlColumnIndex() const
{
    auto* column = FindColumn(TtlColumnName);
    if (!column) {
        return std::nullopt;
    }
    return GetColumnIndex(*column);
}

TKeyColumns TTableSchema::GetKeyColumnNames() const
{
    TKeyColumns keyColumns;
    for (const auto& column : Columns()) {
        if (column.SortOrder()) {
            keyColumns.push_back(column.Name());
        }
    }
    return keyColumns;
}

std::vector<TColumnStableName> TTableSchema::GetKeyColumnStableNames() const
{
    std::vector<TColumnStableName> keyColumns;
    for (const auto& column : Columns()) {
        if (column.SortOrder()) {
            keyColumns.push_back(column.StableName());
        }
    }
    return keyColumns;
}

TKeyColumns TTableSchema::GetKeyColumns() const
{
    return GetKeyColumnNames();
}

int TTableSchema::GetColumnCount() const
{
    return ssize(Columns());
}

std::vector<std::string> TTableSchema::GetColumnNames() const
{
    if (!ColumnInfo_) {
        return std::vector<std::string>();
    }
    std::vector<std::string> result;
    const auto& info = *ColumnInfo_;
    result.reserve(info.Columns.size());
    for (const auto& column : info.Columns) {
        result.push_back(column.Name());
    }
    return result;
}

std::vector<TColumnStableName> TTableSchema::GetColumnStableNames() const
{
    if (!ColumnInfo_) {
        return std::vector<TColumnStableName>();
    }
    std::vector<TColumnStableName> result;
    const auto& info = *ColumnInfo_;
    result.reserve(info.Columns.size());
    for (const auto& column : info.Columns) {
        result.push_back(column.StableName());
    }
    return result;
}

const THunkColumnIds& TTableSchema::GetHunkColumnIds() const
{
    return HunkColumnsIds_;
}

std::vector<TColumnStableName> MapNamesToStableNames(
    const TTableSchema& schema,
    const std::vector<std::string>& names,
    std::optional<TStringBuf> missingColumnReplacement)
{
    std::vector<TColumnStableName> stableNames;
    stableNames.reserve(names.size());
    for (const auto& name : names) {
        const auto* column = schema.FindColumn(name);
        if (column) {
            stableNames.push_back(column->StableName());
        } else if (!schema.GetStrict()) {
            stableNames.push_back(TColumnStableName(name));
        } else if (missingColumnReplacement) {
            stableNames.push_back(TColumnStableName(std::string(*missingColumnReplacement)));
        } else {
            THROW_ERROR_EXCEPTION("Column %Qv is missing in strict schema",
                name);
        }
    }
    return stableNames;
}

int TTableSchema::GetKeyColumnCount() const
{
    return KeyColumnCount_;
}

int TTableSchema::GetValueColumnCount() const
{
    return GetColumnCount() - GetKeyColumnCount();
}

TSortColumns TTableSchema::GetSortColumns(const std::optional<TNameMapping>& nameMapping) const
{
    auto actualNameMapping = nameMapping
        ? *nameMapping
        : GetNameMapping();

    TSortColumns sortColumns;
    sortColumns.reserve(GetKeyColumnCount());

    for (const auto& column : Columns()) {
        if (column.SortOrder()) {
            const auto& name = actualNameMapping.StableNameToName(column.StableName());
            sortColumns.push_back(TColumnSortSchema{
                .Name = std::string(name),
                .SortOrder = *column.SortOrder(),
            });
        }
    }

    return sortColumns;
}

TTableSchemaPtr TTableSchema::SetUniqueKeys(bool uniqueKeys) const
{
    auto schema = *this;
    schema.UniqueKeys_ = uniqueKeys;
    return New<TTableSchema>(std::move(schema));
}

TTableSchemaPtr TTableSchema::SetSchemaModification(ETableSchemaModification schemaModification) const
{
    auto schema = *this;
    schema.SchemaModification_ = schemaModification;
    return New<TTableSchema>(std::move(schema));
}

bool TTableSchema::HasNontrivialSchemaModification() const
{
    return GetSchemaModification() != ETableSchemaModification::None;
}

TTableSchemaPtr TTableSchema::FromKeyColumns(const TKeyColumns& keyColumns)
{
    TTableSchema schema;
    std::vector<TColumnSchema> columns;
    for (const auto& columnName : keyColumns) {
        columns.push_back(
            TColumnSchema(columnName, ESimpleLogicalValueType::Any)
                .SetSortOrder(ESortOrder::Ascending));
    }
    schema.ColumnInfo_ = std::make_shared<const TColumnInfo>(
        std::move(columns),
        std::vector<TDeletedColumn>{});
    schema.KeyColumnCount_ = keyColumns.size();
    ValidateTableSchema(schema);
    return New<TTableSchema>(std::move(schema));
}

TTableSchemaPtr TTableSchema::FromSortColumns(const TSortColumns& sortColumns)
{
    std::vector<TColumnSchema> columns;
    for (const auto& sortColumn : sortColumns) {
        columns.push_back(
            TColumnSchema(sortColumn.Name, ESimpleLogicalValueType::Any)
                .SetSortOrder(sortColumn.SortOrder));
    }

    auto schema = New<TTableSchema>(std::move(columns), /*strict*/ false);
    ValidateTableSchema(*schema);
    return schema;
}

TTableSchemaPtr TTableSchema::ToQuery() const
{
    if (!ColumnInfo_) {
        return New<TTableSchema>(
            std::vector<TColumnSchema>(),
            true,  /*strict*/
            false,  /*uniqueKeys*/
            ETableSchemaModification::None,
            std::vector<TDeletedColumn>());
    }
    const auto& info = *ColumnInfo_;
    if (IsSorted()) {
        return New<TTableSchema>(*this);
    } else {
        std::vector<TColumnSchema> columns {
            TColumnSchema(TabletIndexColumnName, ESimpleLogicalValueType::Int64)
                .SetSortOrder(ESortOrder::Ascending),
            TColumnSchema(RowIndexColumnName, ESimpleLogicalValueType::Int64)
                .SetSortOrder(ESortOrder::Ascending)
        };
        columns.insert(columns.end(), info.Columns.begin(), info.Columns.end());
        return New<TTableSchema>(std::move(columns), true, false,
            ETableSchemaModification::None, DeletedColumns());
    }
}

TTableSchemaPtr TTableSchema::ToWriteViaQueueProducer() const
{
    std::vector<TColumnSchema> columns;
    if (IsSorted()) {
        for (const auto& column : Columns()) {
            if (!column.Expression()) {
                columns.push_back(column);
            }
        }
    } else {
        columns.push_back(TColumnSchema(TabletIndexColumnName, ESimpleLogicalValueType::Int64)
            .SetSortOrder(ESortOrder::Ascending));
        columns.push_back(TColumnSchema(SequenceNumberColumnName, ESimpleLogicalValueType::Int64));
        for (const auto& column : Columns()) {
            if (column.StableName().Underlying() != TimestampColumnName &&
                column.StableName().Underlying() != CumulativeDataWeightColumnName)
            {
                columns.push_back(column);
            }
        }
    }
    return New<TTableSchema>(
        std::move(columns),
        Strict_,
        UniqueKeys_,
        ETableSchemaModification::None,
        DeletedColumns());
}

TTableSchemaPtr TTableSchema::ToWrite() const
{
    std::vector<TColumnSchema> columns;
    if (IsSorted()) {
        for (const auto& column : Columns()) {
            if (!column.Expression()) {
                columns.push_back(column);
            }
        }
    } else {
        columns.push_back(TColumnSchema(TabletIndexColumnName, ESimpleLogicalValueType::Int64)
            .SetSortOrder(ESortOrder::Ascending));
        for (const auto& column : Columns()) {
            if (column.StableName().Underlying() != TimestampColumnName &&
                column.StableName().Underlying() != CumulativeDataWeightColumnName)
            {
                columns.push_back(column);
            }
        }
    }
    return New<TTableSchema>(
        std::move(columns),
        Strict_,
        UniqueKeys_,
        ETableSchemaModification::None,
        DeletedColumns());
}

TTableSchemaPtr TTableSchema::WithTabletIndex() const
{
    if (IsSorted()) {
        return New<TTableSchema>(*this);
    } else {
        auto columns = Columns();
        // XXX: Is it ok? $tablet_index is usually a key column.
        columns.push_back(TColumnSchema(TabletIndexColumnName, ESimpleLogicalValueType::Int64));
        return New<TTableSchema>(
            std::move(columns),
            Strict_,
            UniqueKeys_,
            ETableSchemaModification::None,
            DeletedColumns());
    }
}

TTableSchemaPtr TTableSchema::ToVersionedWrite() const
{
    if (IsSorted()) {
        return New<TTableSchema>(*this);
    } else {
        auto columns = Columns();
        columns.insert(columns.begin(), TColumnSchema(TabletIndexColumnName, ESimpleLogicalValueType::Int64)
            .SetSortOrder(ESortOrder::Ascending));
        return New<TTableSchema>(
            std::move(columns),
            Strict_,
            UniqueKeys_,
            ETableSchemaModification::None,
            DeletedColumns());
    }
}

TTableSchemaPtr TTableSchema::ToLookup() const
{
    std::vector<TColumnSchema> columns;
    for (const auto& column : Columns()) {
        if (column.SortOrder() && !column.Expression()) {
            columns.push_back(column);
        }
    }
    return New<TTableSchema>(
        std::move(columns),
        Strict_,
        UniqueKeys_,
        ETableSchemaModification::None,
        DeletedColumns());
}

TTableSchemaPtr TTableSchema::ToDelete() const
{
    return ToLookup();
}

TTableSchemaPtr TTableSchema::ToLock() const
{
    return ToLookup();
}

TTableSchemaPtr TTableSchema::ToKeys() const
{
    if (!ColumnInfo_) {
        return New<TTableSchema>(
            std::vector<TColumnSchema>(),
            Strict_,
            UniqueKeys_,
            ETableSchemaModification::None,
            std::vector<TDeletedColumn>());
    }
    const auto& info = *ColumnInfo_;
    std::vector<TColumnSchema> columns(info.Columns.begin(), info.Columns.begin() + KeyColumnCount_);
    return New<TTableSchema>(
        std::move(columns),
        Strict_,
        UniqueKeys_,
        ETableSchemaModification::None,
        info.DeletedColumns);
}

TTableSchemaPtr TTableSchema::ToUniqueKeys() const
{
    if (!ColumnInfo_) {
        return New<TTableSchema>(
            std::vector<TColumnSchema>(),
            Strict_,
            true,  /*uniqueKeys*/
            ETableSchemaModification::None,
            std::vector<TDeletedColumn>());
    }
    const auto& info = *ColumnInfo_;
    return New<TTableSchema>(
        info.Columns,
        Strict_,
        /*uniqueKeys*/ true,
        ETableSchemaModification::None,
        info.DeletedColumns);
}

TTableSchemaPtr TTableSchema::ToStrippedColumnAttributes() const
{
    if (!ColumnInfo_) {
        return New<TTableSchema>(
            std::vector<TColumnSchema>(),
            Strict_,
            false,  /*uniqueKeys*/
            ETableSchemaModification::None,
            std::vector<TDeletedColumn>());
    }
    const auto& info = *ColumnInfo_;
    std::vector<TColumnSchema> strippedColumns;
    for (const auto& column : info.Columns) {
        auto& strippedColumn = strippedColumns.emplace_back(column.Name(), column.LogicalType());
        strippedColumn.SetStableName(column.StableName());
    }
    return New<TTableSchema>(
        std::move(strippedColumns),
        Strict_,
        /*uniqueKeys*/ false,
        ETableSchemaModification::None,
        info.DeletedColumns);
}

TTableSchemaPtr TTableSchema::ToSortedStrippedColumnAttributes() const
{
    if (!ColumnInfo_) {
        return New<TTableSchema>(
            std::vector<TColumnSchema>(),
            Strict_,
            UniqueKeys_,  /*uniqueKeys*/
            ETableSchemaModification::None,
            std::vector<TDeletedColumn>());
    }
    const auto& info = *ColumnInfo_;
    std::vector<TColumnSchema> strippedColumns;
    for (const auto& column : info.Columns) {
        auto& strippedColumn = strippedColumns.emplace_back(column.Name(), column.LogicalType(), column.SortOrder());
        strippedColumn.SetStableName(column.StableName());
    }
    return New<TTableSchema>(
        std::move(strippedColumns),
        Strict_,
        UniqueKeys_,
        ETableSchemaModification::None,
        info.DeletedColumns);
}

TTableSchemaPtr TTableSchema::ToCanonical() const
{
    if (!ColumnInfo_) {
        return New<TTableSchema>(
            std::vector<TColumnSchema>(),
            Strict_,
            UniqueKeys_,  /*uniqueKeys*/
            ETableSchemaModification::None,
            std::vector<TDeletedColumn>());
    }
    const auto& info = *ColumnInfo_;
    auto columns = info.Columns;
    std::sort(
        columns.begin() + KeyColumnCount_,
        columns.end(),
        [] (const TColumnSchema& lhs, const TColumnSchema& rhs) {
            return lhs.Name() < rhs.Name();
        });
    return New<TTableSchema>(
        columns,
        Strict_,
        UniqueKeys_,
        ETableSchemaModification::None,
        info.DeletedColumns);
}

TTableSchemaPtr TTableSchema::ToSorted(const TKeyColumns& keyColumns) const
{
    TSortColumns sortColumns;
    sortColumns.reserve(keyColumns.size());
    for (const auto& keyColumn : keyColumns) {
        sortColumns.push_back(TColumnSortSchema{
            .Name = keyColumn,
            .SortOrder = ESortOrder::Ascending
        });
    }

    return TTableSchema::ToSorted(sortColumns);
}

TTableSchemaPtr TTableSchema::ToSorted(const TSortColumns& sortColumns) const
{
    int oldKeyColumnCount = 0;
    auto columns = Columns();
    for (int index = 0; index < std::ssize(sortColumns); ++index) {
        auto it = std::find_if(
            columns.begin() + index,
            columns.end(),
            [&] (const TColumnSchema& column) {
                return column.Name() == sortColumns[index].Name;
            });

        if (it == columns.end()) {
            if (Strict_) {
                THROW_ERROR_EXCEPTION(
                    EErrorCode::IncompatibleKeyColumns,
                    "Column %Qv is not found in strict schema",
                    sortColumns[index].Name)
                    << TErrorAttribute("schema", *this)
                    << TErrorAttribute("sort_columns", sortColumns);
            } else {
                columns.push_back(TColumnSchema(sortColumns[index].Name, EValueType::Any));
                it = columns.end();
                --it;
            }
        }

        if (it->SortOrder()) {
            ++oldKeyColumnCount;
        }

        std::swap(columns[index], *it);
        columns[index].SetSortOrder(sortColumns[index].SortOrder);
    }

    auto uniqueKeys = UniqueKeys_ && oldKeyColumnCount == GetKeyColumnCount();

    for (auto it = columns.begin() + sortColumns.size(); it != columns.end(); ++it) {
        it->SetSortOrder(std::nullopt);
    }

    return New<TTableSchema>(
        std::move(columns),
        Strict_,
        uniqueKeys,
        GetSchemaModification(),
        DeletedColumns());
}

TTableSchemaPtr TTableSchema::ToReplicationLog() const
{
    const auto& schemaColumns = Columns();
    std::vector<TColumnSchema> columns;
    columns.push_back(TColumnSchema(TimestampColumnName, ESimpleLogicalValueType::Uint64));
    if (IsSorted()) {
        columns.push_back(TColumnSchema(TReplicationLogTable::ChangeTypeColumnName, ESimpleLogicalValueType::Int64));
        for (const auto& column : schemaColumns) {
            if (column.SortOrder()) {
                columns.push_back(
                    TColumnSchema(
                        TReplicationLogTable::KeyColumnNamePrefix + column.Name(),
                        column.LogicalType()));
            } else {
                columns.push_back(
                    TColumnSchema(
                        TReplicationLogTable::ValueColumnNamePrefix + column.Name(),
                        MakeOptionalIfNot(column.LogicalType())));
                columns.push_back(
                    TColumnSchema(TReplicationLogTable::FlagsColumnNamePrefix + column.Name(), ESimpleLogicalValueType::Uint64));
            }
        }
    } else {
        for (const auto& column : schemaColumns) {
            columns.push_back(
                TColumnSchema(
                    TReplicationLogTable::ValueColumnNamePrefix + column.Name(),
                    MakeOptionalIfNot(column.LogicalType()))
                .SetMaxInlineHunkSize(column.MaxInlineHunkSize()));
        }
        columns.push_back(TColumnSchema(TReplicationLogTable::ValueColumnNamePrefix + TabletIndexColumnName, ESimpleLogicalValueType::Int64));
    }
    return New<TTableSchema>(
        std::move(columns),
        /* strict */ true,
        /* uniqueKeys */ false,
        ETableSchemaModification::None,
        DeletedColumns());
}

TTableSchemaPtr TTableSchema::ToUnversionedUpdate(bool sorted) const
{
    YT_VERIFY(IsSorted());
    const auto& info = *ColumnInfo_;

    std::vector<TColumnSchema> columns;
    columns.reserve(GetKeyColumnCount() + 1 + GetValueColumnCount() * 2);

    // Keys.
    for (int columnIndex = 0; columnIndex < GetKeyColumnCount(); ++columnIndex) {
        auto column = Columns()[columnIndex];
        if (!sorted) {
            column.SetSortOrder(std::nullopt);
        }
        columns.push_back(column);
    }

    // Modification type.
    columns.emplace_back(
        TUnversionedUpdateSchema::ChangeTypeColumnName,
        MakeLogicalType(ESimpleLogicalValueType::Uint64, /*required*/ true));

    // Values.
    for (int columnIndex = GetKeyColumnCount(); columnIndex < GetColumnCount(); ++columnIndex) {
        const auto& column = info.Columns[columnIndex];
        YT_VERIFY(!column.SortOrder());
        columns.emplace_back(
            TUnversionedUpdateSchema::ValueColumnNamePrefix + column.Name(),
            MakeOptionalIfNot(column.LogicalType()));
        columns.emplace_back(
            TUnversionedUpdateSchema::FlagsColumnNamePrefix + column.Name(),
            MakeLogicalType(ESimpleLogicalValueType::Uint64, /*required*/ false));
    }

    return New<TTableSchema>(
        std::move(columns),
        /*strict*/ true,
        /*uniqueKeys*/ sorted,
        ETableSchemaModification::None,
        info.DeletedColumns);
}

TTableSchemaPtr TTableSchema::ToModifiedSchema(ETableSchemaModification schemaModification) const
{
    if (HasNontrivialSchemaModification()) {
        THROW_ERROR_EXCEPTION("Cannot apply schema modification because schema is already modified")
            << TErrorAttribute("existing_modification", GetSchemaModification())
            << TErrorAttribute("requested_modification", schemaModification);
    }
    YT_VERIFY(GetSchemaModification() == ETableSchemaModification::None);

    switch (schemaModification) {
        case ETableSchemaModification::None:
            return New<TTableSchema>(*this);

        case ETableSchemaModification::UnversionedUpdate:
            return ToUnversionedUpdate(/*sorted*/ true)
                ->SetSchemaModification(schemaModification);

        case ETableSchemaModification::UnversionedUpdateUnsorted:
            return ToUnversionedUpdate(/*sorted*/ false)
                ->SetSchemaModification(schemaModification);

        default:
            YT_ABORT();
    }
}

TComparator TTableSchema::ToComparator(TCallback<TUUComparerSignature> cgComparator) const
{
    std::vector<ESortOrder> sortOrders;
    if (ColumnInfo_) {
        const auto& info = *ColumnInfo_;
        sortOrders.resize(KeyColumnCount_);
        for (int index = 0; index < KeyColumnCount_; ++index) {
            YT_VERIFY(info.Columns[index].SortOrder());
            sortOrders[index] = *info.Columns[index].SortOrder();
        }
    }

    return TComparator(std::move(sortOrders), std::move(cgComparator));
}

void TTableSchema::Save(TStreamSaveContext& context) const
{
    using NYT::Save;
    Save(context, ToProto<NTableClient::NProto::TTableSchemaExt>(*this));
}

void TTableSchema::Load(TStreamLoadContext& context)
{
    using NYT::Load;
    auto protoSchema = NYT::Load<NTableClient::NProto::TTableSchemaExt>(context);
    *this = FromProto<TTableSchema>(protoSchema);
}

i64 TTableSchema::GetMemoryUsage() const
{
    i64 usage = sizeof(TTableSchema);
    for (const auto& column : Columns()) {
        usage += column.GetMemoryUsage();
    }
    return usage;
}

TKeyColumnTypes TTableSchema::GetKeyColumnTypes() const
{
    TKeyColumnTypes result(KeyColumnCount_);
    for (int index = 0; index < KeyColumnCount_; ++index) {
        result[index] = Columns()[index].GetWireType();
    }
    return result;
}

////////////////////////////////////////////////////////////////////////////////

void FormatValue(TStringBuilderBase* builder, const TTableSchema& schema, TStringBuf /*spec*/)
{
    builder->AppendFormat("<strict=%v;unique_keys=%v", schema.GetStrict(), schema.GetUniqueKeys());
    if (schema.HasNontrivialSchemaModification()) {
        builder->AppendFormat(";schema_modification=%v", schema.GetSchemaModification());
    }
    builder->AppendChar('>');
    builder->AppendChar('[');
    bool first = true;
    for (const auto& column : schema.Columns()) {
        if (!first) {
            builder->AppendString(TStringBuf("; "));
        }
        builder->AppendFormat("%v", column);
        first = false;
    }
    for (const auto& deletedColumn : schema.DeletedColumns()) {
        if (!first) {
            builder->AppendString(TStringBuf("; "));
        }
        builder->AppendFormat("%v", deletedColumn);
        first = false;
    }
    builder->AppendChar(']');
}

void FormatValue(TStringBuilderBase* builder, const TTableSchemaPtr& schema, TStringBuf spec)
{
    if (schema) {
        FormatValue(builder, *schema, spec);
    } else {
        builder->AppendString(TStringBuf("<null>"));
    }
}

std::string SerializeToWireProto(const TTableSchemaPtr& schema)
{
    NTableClient::NProto::TTableSchemaExt protoSchema;
    ToProto(&protoSchema, schema);
    return protoSchema.SerializeAsString();
}

void DeserializeFromWireProto(TTableSchemaPtr* schema, const std::string& serializedProto)
{
    NTableClient::NProto::TTableSchemaExt protoSchema;
    if (!protoSchema.ParseFromString(serializedProto)) {
        THROW_ERROR_EXCEPTION("Failed to deserialize table schema from wire proto");
    }
    FromProto(schema, protoSchema);
}

void ToProto(NProto::TTableSchemaExt* protoSchema, const TTableSchema& schema)
{
    ToProto(protoSchema->mutable_columns(), schema.Columns());
    ToProto(protoSchema->mutable_deleted_columns(), schema.DeletedColumns());
    protoSchema->set_strict(schema.GetStrict());
    protoSchema->set_unique_keys(schema.GetUniqueKeys());
    protoSchema->set_schema_modification(ToProto(schema.GetSchemaModification()));
}

void FromProto(TTableSchema* schema, const NProto::TTableSchemaExt& protoSchema)
{
    *schema = TTableSchema(
        FromProto<std::vector<TColumnSchema>>(protoSchema.columns()),
        protoSchema.strict(),
        protoSchema.unique_keys(),
        CheckedEnumCast<ETableSchemaModification>(protoSchema.schema_modification()),
        FromProto<std::vector<TDeletedColumn>>(protoSchema.deleted_columns()));
}

void FromProto(
    TTableSchema* schema,
    const NProto::TTableSchemaExt& protoSchema,
    const NProto::TKeyColumnsExt& protoKeyColumns)
{
    auto columns = FromProto<std::vector<TColumnSchema>>(protoSchema.columns());
    for (int columnIndex = 0; columnIndex < protoKeyColumns.names_size(); ++columnIndex) {
        auto& columnSchema = columns[columnIndex];
        YT_VERIFY(columnSchema.Name() == protoKeyColumns.names(columnIndex));
        // TODO(gritukan): YT-14155
        if (!columnSchema.SortOrder()) {
            columnSchema.SetSortOrder(ESortOrder::Ascending);
        }
    }
    for (int columnIndex = protoKeyColumns.names_size(); columnIndex < std::ssize(columns); ++columnIndex) {
        auto& columnSchema = columns[columnIndex];
        YT_VERIFY(!columnSchema.SortOrder());
    }

    auto deletedColumns = FromProto<std::vector<TDeletedColumn>>(protoSchema.deleted_columns());

    *schema = TTableSchema(
        std::move(columns),
        protoSchema.strict(),
        protoSchema.unique_keys(),
        ETableSchemaModification::None,
        deletedColumns);
}

void ToProto(NProto::TTableSchemaExt* protoSchema, const TTableSchemaPtr& schema)
{
    ToProto(protoSchema, *schema);
}

void FromProto(TTableSchemaPtr* schema, const NProto::TTableSchemaExt& protoSchema)
{
    *schema = New<TTableSchema>();
    FromProto(schema->Get(), protoSchema);
}

void FromProto(
    TTableSchemaPtr* schema,
    const NProto::TTableSchemaExt& protoSchema,
    const NProto::TKeyColumnsExt& keyColumnsExt)
{
    *schema = New<TTableSchema>();
    FromProto(schema->Get(), protoSchema, keyColumnsExt);
}

void PrintTo(const TTableSchema& tableSchema, std::ostream* os)
{
    *os << Format("%v", tableSchema);
}

////////////////////////////////////////////////////////////////////////////////

bool operator==(const TColumnSchema& lhs, const TColumnSchema& rhs)
{
    return
        lhs.StableName() == rhs.StableName() &&
        lhs.Name() == rhs.Name() &&
        *lhs.LogicalType() == *rhs.LogicalType() &&
        lhs.Required() == rhs.Required() &&
        lhs.SortOrder() == rhs.SortOrder() &&
        lhs.Lock() == rhs.Lock() &&
        lhs.Expression() == rhs.Expression() &&
        lhs.Materialized() == rhs.Materialized() &&
        lhs.Aggregate() == rhs.Aggregate() &&
        lhs.Group() == rhs.Group() &&
        lhs.MaxInlineHunkSize() == rhs.MaxInlineHunkSize();
}

bool operator==(const TDeletedColumn& lhs, const TDeletedColumn& rhs)
{
    return lhs.StableName() == rhs.StableName();
}

bool operator==(const TTableSchema& lhs, const TTableSchema& rhs)
{
    return
        lhs.Columns() == rhs.Columns() &&
        lhs.GetStrict() == rhs.GetStrict() &&
        lhs.GetUniqueKeys() == rhs.GetUniqueKeys() &&
        lhs.GetSchemaModification() == rhs.GetSchemaModification() &&
        lhs.DeletedColumns() == rhs.DeletedColumns();
}

// Compat code for https://st.yandex-team.ru/YT-10668 workaround.
bool IsEqualIgnoringRequiredness(const TTableSchema& lhs, const TTableSchema& rhs)
{
    auto dropRequiredness = [] (const TTableSchema& schema) {
        std::vector<TColumnSchema> resultColumns;
        for (auto column : schema.Columns()) {
            if (column.LogicalType()->GetMetatype() == ELogicalMetatype::Optional) {
                column.SetLogicalType(column.LogicalType()->AsOptionalTypeRef().GetElement());
            }
            resultColumns.emplace_back(column);
        }
        return TTableSchema(resultColumns, schema.GetStrict(), schema.GetUniqueKeys());
    };
    return dropRequiredness(lhs) == dropRequiredness(rhs);
}

////////////////////////////////////////////////////////////////////////////////

// Parses description of the following form nested_key.name or nested_value.name or nested_value.name.sum
std::optional<TNestedColumn> TryParseNestedAggregate(TStringBuf description)
{
    if (!description.starts_with("nested")) {
        return std::nullopt;
    }

    const char* ptr = description.data();
    const char* ptrEnd = ptr + description.size();

    auto skipSpace = [&] () {
        while (ptr != ptrEnd) {
            if (!IsSpace(*ptr)) {
                break;
            }

            ++ptr;
        }
    };

    auto parseName = [&] () {
        auto start = ptr;
        while (ptr != ptrEnd) {
            auto ch = *ptr;
            if (!isalpha(ch) && !isdigit(ch) && ch != '_' && ch != '-' && ch != '%' && ch != '.') {
                break;
            }

            ++ptr;
        }

        return TStringBuf(start, ptr);
    };

    auto parseToken = [&] (TStringBuf token) {
        if (TStringBuf(ptr, ptrEnd).starts_with(token)) {
            ptr += token.size();
            return true;
        }

        return false;
    };

    auto throwError = [&] (TStringBuf message) {
        int location = ptr - description.data();

        THROW_ERROR_EXCEPTION("Error while parsing nested aggregate description: %v", message)
            << TErrorAttribute("position", Format("%v", location))
            << TErrorAttribute("description", description);
    };

    auto nestedFunction = parseName();

    skipSpace();

    if (!parseToken("(")) {
        throwError("expected \"(\"");
    }

    if (nestedFunction == "nested_key") {
        skipSpace();
        auto nestedTableName = parseName();
        skipSpace();

        if (parseToken(")")) {
            return TNestedColumn{
                .NestedTableName = nestedTableName,
                .IsKey = true
            };
        }

        throwError("expected \")\"");
    } else if (nestedFunction == "nested_value") {
        skipSpace();
        auto nestedTableName = parseName();
        skipSpace();

        if (parseToken(")")) {
            return TNestedColumn{
                .NestedTableName = nestedTableName,
                .IsKey = false
            };
        }

        if (parseToken(",")) {
            skipSpace();
            auto aggregateFunction = parseName();
            skipSpace();

            if (parseToken(")")) {
                return TNestedColumn{
                    .NestedTableName = nestedTableName,
                    .IsKey = false,
                    .Aggregate = aggregateFunction
                };
            }

            throwError("expected \")\"");
        }

        throwError("expected \")\" or \",\" ");
    }

    THROW_ERROR_EXCEPTION("Error while parsing nested aggregate description. Expected nested_key or nested_value");
}

EValueType GetNestedColumnElementType(const TLogicalType* logicalType)
{
    if (logicalType->GetMetatype() == ELogicalMetatype::Optional) {
        logicalType = logicalType->GetElement().Get();
    }

    if (logicalType->GetMetatype() != ELogicalMetatype::List) {
        THROW_ERROR_EXCEPTION("Invalid nested column type %Qv",
            *logicalType);
    }

    return GetWireType(logicalType->GetElement());
}

////////////////////////////////////////////////////////////////////////////////

void ValidateKeyColumns(const TKeyColumns& keyColumns)
{
    ValidateKeyColumnCount(keyColumns.size());

    THashSet<std::string> names;
    for (const auto& name : keyColumns) {
        if (!names.insert(name).second) {
            THROW_ERROR_EXCEPTION("Duplicate key column name %Qv",
                name);
        }
    }
}

////////////////////////////////////////////////////////////////////////////////

void ValidateDynamicTableKeyColumnCount(int count)
{
    THROW_ERROR_EXCEPTION_IF(count > MaxKeyColumnCountInDynamicTable,
        "Too many key columns: expected <= %v, got %v",
        MaxKeyColumnCountInDynamicTable,
        count);
}

////////////////////////////////////////////////////////////////////////////////

void ValidateSystemColumnSchema(
    const TColumnSchema& columnSchema,
    bool isTableSorted,
    bool allowUnversionedUpdateColumns,
    bool allowTimestampColumns)
{
    static const auto allowedSortedTablesSystemColumns = THashMap<std::string, ESimpleLogicalValueType>{
        {EmptyValueColumnName, ESimpleLogicalValueType::Int64},
        {TtlColumnName, ESimpleLogicalValueType::Uint64},
    };

    static const auto allowedOrderedTablesSystemColumns = THashMap<std::string, ESimpleLogicalValueType>{
        {TimestampColumnName, ESimpleLogicalValueType::Uint64},
        {CumulativeDataWeightColumnName, ESimpleLogicalValueType::Int64},
    };

    auto validateType = [&] (ESimpleLogicalValueType expected) {
        if (!columnSchema.IsOfV1Type(expected)) {
            THROW_ERROR_EXCEPTION("Invalid type of column %Qv: expected %Qlv, got %Qlv",
                columnSchema.GetDiagnosticNameString(),
                expected,
                *columnSchema.LogicalType());
        }
    };

    const auto& name = columnSchema.Name();

    if (columnSchema.IsRenamed()) {
        THROW_ERROR_EXCEPTION("System column schema must have equal name and stable name")
            << TErrorAttribute("name", name)
            << TErrorAttribute("stable_name", columnSchema.StableName().Underlying());
    }

    const auto& allowedSystemColumns = isTableSorted
        ? allowedSortedTablesSystemColumns
        : allowedOrderedTablesSystemColumns;
    auto it = allowedSystemColumns.find(name);

    // Ordinary system column.
    if (it != allowedSystemColumns.end()) {
        validateType(it->second);
        return;
    }

    if (allowUnversionedUpdateColumns) {
        // Unversioned update schema system column.
        if (name == TUnversionedUpdateSchema::ChangeTypeColumnName) {
            validateType(ESimpleLogicalValueType::Uint64);
            return;
        } else if (name.starts_with(TUnversionedUpdateSchema::FlagsColumnNamePrefix)) {
            validateType(ESimpleLogicalValueType::Uint64);
            return;
        } else if (name.starts_with(TUnversionedUpdateSchema::ValueColumnNamePrefix)) {
            // Value can have any type.
            return;
        }
    }

    if (allowTimestampColumns) {
        if (name.starts_with(TimestampColumnPrefix)) {
            validateType(ESimpleLogicalValueType::Uint64);
            return;
        }
    }

    // Unexpected system column.
    THROW_ERROR_EXCEPTION("System column name %Qv is not allowed here",
        name);
}

void ValidateColumnName(const std::string& name)
{
    if (name.empty()) {
        THROW_ERROR_EXCEPTION("Column name cannot be empty");
    }

    if (name.size() > MaxColumnNameLength) {
        THROW_ERROR_EXCEPTION("Column name %Qv is longer than maximum allowed: %v > %v",
            name,
            name.size(),
            MaxColumnNameLength);
    }
}

void ValidateColumnSchema(
    const TColumnSchema& columnSchema,
    bool isTableSorted,
    bool isTableDynamic,
    bool allowUnversionedUpdateColumns,
    bool allowTimestampColumns)
{
    static const auto allowedAggregates = THashSet<std::string, THash<TStringBuf>, TEqualTo<>>{
        "sum",
        "min",
        "max",
        "first",
        "xdelta",
        "_yt_stored_replica_set",
        "_yt_last_seen_replica_set",
        "dict_sum",
    };

    static const auto allowedNestedAggregates = THashSet<std::string, THash<TStringBuf>, TEqualTo<>>{
        "sum",
        "max"
    };

    try {
        const auto& stableName = columnSchema.StableName();
        ValidateColumnName(stableName.Underlying());

        const auto& name = columnSchema.Name();
        ValidateColumnName(name);

        if (stableName.Underlying().starts_with(SystemColumnNamePrefix) || name.starts_with(SystemColumnNamePrefix)) {
            ValidateSystemColumnSchema(
                columnSchema,
                isTableSorted,
                allowUnversionedUpdateColumns,
                allowTimestampColumns);
        }

        {
            TComplexTypeFieldDescriptor descriptor(name, columnSchema.LogicalType());
            ValidateLogicalType(descriptor, MaxSchemaDepth);
        }

        if (!IsComparable(columnSchema.LogicalType()) &&
            columnSchema.SortOrder() &&
            !columnSchema.IsOfV1Type(ESimpleLogicalValueType::Any))
        {
            THROW_ERROR_EXCEPTION("Key column cannot be of %Qv type",
                *columnSchema.LogicalType());
        }

        if (*DetagLogicalType(columnSchema.LogicalType()) == *SimpleLogicalType(ESimpleLogicalValueType::Any)) {
            THROW_ERROR_EXCEPTION("Column of type %Qlv cannot be required",
                ESimpleLogicalValueType::Any);
        }

        if (columnSchema.Lock()) {
            if (columnSchema.Lock()->empty()) {
                THROW_ERROR_EXCEPTION("Column lock name cannot be empty");
            }
            if (columnSchema.Lock()->size() > MaxColumnLockLength) {
                THROW_ERROR_EXCEPTION("Column lock name is longer than maximum allowed: %v > %v",
                    columnSchema.Lock()->size(),
                    MaxColumnLockLength);
            }
            if (columnSchema.SortOrder()) {
                THROW_ERROR_EXCEPTION("Column lock cannot be set on a key column");
            }
        }

        if (columnSchema.Group()) {
            if (columnSchema.Group()->empty()) {
                THROW_ERROR_EXCEPTION("Column group should either be unset or be non-empty");
            }
            if (columnSchema.Group()->size() > MaxColumnGroupLength) {
                THROW_ERROR_EXCEPTION("Column group name is longer than maximum allowed: %v > %v",
                    columnSchema.Group()->size(),
                    MaxColumnGroupLength);
            }
        }

        ValidateSchemaValueType(columnSchema.GetWireType());
        if (columnSchema.Expression()) {
            auto materialized = columnSchema.Materialized().value_or(true);
            if (materialized && !columnSchema.SortOrder() && isTableDynamic) {
                THROW_ERROR_EXCEPTION("Non-key column cannot be computed in materializable way");
            } else if (!materialized && columnSchema.SortOrder()) {
                THROW_ERROR_EXCEPTION("Key column cannot be computed in non-materializable way");
            }
        }

        if (columnSchema.Aggregate() && columnSchema.SortOrder()) {
            THROW_ERROR_EXCEPTION("Key column cannot be aggregated");
        }

        if (columnSchema.Aggregate()) {
            auto aggregateName = *columnSchema.Aggregate();

            if (auto nested = TryParseNestedAggregate(aggregateName)) {
                if (nested->NestedTableName.empty()) {
                    THROW_ERROR_EXCEPTION("Invalid nested table name for aggregate %Qv",
                        aggregateName);
                }

                GetNestedColumnElementType(columnSchema.LogicalType().Get());

                if (!nested->IsKey) {
                    auto aggregateName = nested->Aggregate;
                    if (!aggregateName.empty() && allowedNestedAggregates.find(aggregateName) == allowedNestedAggregates.end()) {
                        THROW_ERROR_EXCEPTION("Invalid aggregate function %Qv",
                            aggregateName);
                    }
                }
            } else if (allowedAggregates.find(aggregateName) == allowedAggregates.end()) {
                THROW_ERROR_EXCEPTION("Invalid aggregate function %Qv",
                    aggregateName);
            }
        }

        if (columnSchema.Expression() && columnSchema.Required()) {
            THROW_ERROR_EXCEPTION("Computed column cannot be required");
        }

        if (columnSchema.MaxInlineHunkSize()) {
            if (columnSchema.MaxInlineHunkSize() <= 0) {
                THROW_ERROR_EXCEPTION("Max inline hunk size must be positive");
            }
            if (!IsStringLikeType(columnSchema.GetWireType())) {
                THROW_ERROR_EXCEPTION("Max inline hunk size can only be set for string-like columns, not %Qlv",
                    columnSchema.GetWireType());
            }
            if (columnSchema.SortOrder()) {
                THROW_ERROR_EXCEPTION("Max inline hunk size cannot be set for key column");
            }
            if (columnSchema.Aggregate()) {
                THROW_ERROR_EXCEPTION("Max inline hunk size cannot be set for aggregate column");
            }
        }
    } catch (const std::exception& ex) {
        THROW_ERROR_EXCEPTION("Error validating schema of column %v",
            columnSchema.GetDiagnosticNameString())
            << ex;
    }
}

void ValidateDynamicTableConstraints(const TTableSchema& schema)
{
    if (!schema.GetStrict()) {
        THROW_ERROR_EXCEPTION("\"strict\" cannot be \"false\" for a dynamic table");
    }

    if (schema.IsSorted() && !schema.GetUniqueKeys()) {
        THROW_ERROR_EXCEPTION("\"unique_keys\" cannot be \"false\" for a sorted dynamic table");
    }

    if (schema.GetKeyColumnCount() == std::ssize(schema.Columns())) {
        THROW_ERROR_EXCEPTION("There must be at least one non-key column");
    }

    ValidateDynamicTableKeyColumnCount(schema.GetKeyColumnCount());

    for (const auto& column : schema.Columns()) {
        try {
            auto logicalType = column.LogicalType();
            if (!IsComparable(logicalType) &&
                column.SortOrder() &&
                !column.IsOfV1Type(ESimpleLogicalValueType::Any))
            {
                THROW_ERROR_EXCEPTION("Dynamic table cannot have key column of type %Qv",
                    *logicalType);
            }
        } catch (const std::exception& ex) {
            THROW_ERROR_EXCEPTION("Error validating column %v in dynamic table schema",
                column.GetDiagnosticNameString())
                << ex;
        }
    }
}

//! Validates that there are no duplicates among the column names.
void ValidateColumnUniqueness(const TTableSchema& schema)
{
    THashSet<TStringBuf> columnNames;
    THashSet<TStringBuf> columnStableNames;
    for (const auto& column : schema.Columns()) {
        if (!columnStableNames.insert(column.StableName().Underlying()).second) {
            THROW_ERROR_EXCEPTION("Duplicate column stable name %Qv in table schema",
                column.StableName());
        }
        if (!columnNames.insert(column.Name()).second) {
            THROW_ERROR_EXCEPTION("Duplicate column name %Qv in table schema",
                column.Name());
        }
    }
    for (const auto& deletedColumn : schema.DeletedColumns()) {
        if (!columnStableNames.insert(deletedColumn.StableName().Underlying()).second) {
            THROW_ERROR_EXCEPTION("Duplicate column stable name %Qv in table schema",
                deletedColumn.StableName());
        }
    }
}

void ValidatePivotKey(
    TUnversionedRow pivotKey,
    const TTableSchema& schema,
    TStringBuf keyType,
    bool validateRequired)
{
    if (static_cast<int>(pivotKey.GetCount()) > schema.GetKeyColumnCount()) {
        auto titleKeyType = TString(keyType);
        titleKeyType.to_title();
        THROW_ERROR_EXCEPTION(NTableClient::EErrorCode::SchemaViolation, "%v key must form a prefix of key", titleKeyType);
    }

    for (int index = 0; index < static_cast<int>(pivotKey.GetCount()); ++index) {
        if (pivotKey[index].Type != EValueType::Null && pivotKey[index].Type != schema.Columns()[index].GetWireType()) {
            THROW_ERROR_EXCEPTION(
                NTableClient::EErrorCode::SchemaViolation,
                "Mismatched type of column %v in %v key: expected %Qlv, found %Qlv",
                schema.Columns()[index].GetDiagnosticNameString(),
                keyType,
                schema.Columns()[index].GetWireType(),
                pivotKey[index].Type);
        }
        if (validateRequired && pivotKey[index].Type == EValueType::Null && !schema.Columns()[index].LogicalType()->IsNullable()) {
            THROW_ERROR_EXCEPTION(
                NTableClient::EErrorCode::SchemaViolation,
                "Unexpected null for required column %v in %v key",
                schema.Columns()[index].GetDiagnosticNameString(),
                keyType);
        }
    }
}

////////////////////////////////////////////////////////////////////////////////

//! Validates that number of locks doesn't exceed #MaxColumnLockCount.
void ValidateLocks(const TTableSchema& schema)
{
    THashSet<std::string> lockNames;
    YT_VERIFY(lockNames.insert(PrimaryLockName).second);
    for (const auto& column : schema.Columns()) {
        if (column.Lock()) {
            lockNames.insert(*column.Lock());
        }
    }

    if (lockNames.size() > MaxColumnLockCount) {
        THROW_ERROR_EXCEPTION("Too many column locks in table schema: actual %v, limit %v",
            lockNames.size(),
            MaxColumnLockCount);
    }
}

//! Validates that key columns form a prefix of a table schema.
void ValidateKeyColumnsFormPrefix(const TTableSchema& schema)
{
    for (int index = 0; index < schema.GetKeyColumnCount(); ++index) {
        if (!schema.Columns()[index].SortOrder()) {
            THROW_ERROR_EXCEPTION("Key columns must form a prefix of schema");
        }
    }
    // The fact that first GetKeyColumnCount() columns have SortOrder automatically
    // implies that the rest of columns don't have SortOrder, so we don't need to check it.
}

//! Validates |$timestamp| column, if any.
/*!
 *  Validate that:
 *  - |$timestamp| column cannot be a part of key.
 *  - |$timestamp| column can only be present in ordered tables.
 *  - |$timestamp| column has type |uint64|.
 */
void ValidateTimestampColumn(const TTableSchema& schema)
{
    auto* column = schema.FindColumn(TimestampColumnName);
    if (!column) {
        return;
    }

    if (column->SortOrder()) {
        THROW_ERROR_EXCEPTION("Column %Qv cannot be a part of key",
            TimestampColumnName);
    }

    if (!column->IsOfV1Type(ESimpleLogicalValueType::Uint64)) {
        THROW_ERROR_EXCEPTION("Column %Qv must have %Qlv type",
            TimestampColumnName,
            EValueType::Uint64);
    }

    if (schema.IsSorted()) {
        THROW_ERROR_EXCEPTION("Column %Qv cannot appear in a sorted table",
            TimestampColumnName);
    }
}

//! Validates |$ttl| column, if any.
/*!
 *  Validate that:
 *  - |$ttl| column cannot be a part of key.
 *  - |$ttl| column can only be present in sorted tables.
 *  - |$ttl| column has type |uint64|.
 */
void ValidateTtlColumn(const TTableSchema& schema)
{
    auto* column = schema.FindColumn(TtlColumnName);
    if (!column) {
        return;
    }

    if (column->SortOrder()) {
        THROW_ERROR_EXCEPTION("Column %Qv cannot be a part of key",
            TtlColumnName);
    }

    if (!column->IsOfV1Type(ESimpleLogicalValueType::Uint64)) {
        THROW_ERROR_EXCEPTION("Column %Qv must have %Qlv type",
            TtlColumnName,
            EValueType::Uint64);
    }

    if (!schema.IsSorted()) {
        THROW_ERROR_EXCEPTION("Column %Qv cannot appear in an ordered table",
            TtlColumnName);
    }
}

//! Validates |$cumulative_data_weight| column, if any.
/*!
 *  Validate that:
 *  - |$cumulative_data_weight| column cannot be a part of key.
 *  - |$cumulative_data_weight| column can only be present in ordered tables.
 *  - |$cumulative_data_weight| column has type |int64|.
 */
void ValidateCumulativeDataWeightColumn(const TTableSchema& schema)
{
    auto* column = schema.FindColumn(CumulativeDataWeightColumnName);
    if (!column) {
        return;
    }

    if (column->SortOrder()) {
        THROW_ERROR_EXCEPTION(
            "Column %Qv cannot be a part of key",
            CumulativeDataWeightColumnName);
    }

    if (!column->IsOfV1Type(ESimpleLogicalValueType::Int64)) {
        THROW_ERROR_EXCEPTION(
            "Column %Qv must have %Qlv type",
            CumulativeDataWeightColumnName,
            EValueType::Int64);
    }

    if (schema.IsSorted()) {
        THROW_ERROR_EXCEPTION(
            "Column %Qv cannot appear in a sorted table",
            CumulativeDataWeightColumnName);
    }
}

// Validate schema attributes.
void ValidateSchemaAttributes(const TTableSchema& schema)
{
    if (schema.GetUniqueKeys() && schema.GetKeyColumnCount() == 0) {
        THROW_ERROR_EXCEPTION("\"unique_keys\" can only be true if key columns are present");
    }
}

void ValidateTableSchema(
    const TTableSchema& schema,
    bool isTableDynamic,
    bool allowUnversionedUpdateColumns,
    bool allowTimestampColumns)
{
    int totalTypeComplexity = 0;
    for (const auto& column : schema.Columns()) {
        ValidateColumnSchema(
            column,
            schema.IsSorted(),
            isTableDynamic,
            allowUnversionedUpdateColumns,
            allowTimestampColumns);
        if (!schema.GetStrict() && column.IsRenamed()) {
            THROW_ERROR_EXCEPTION("Renamed column %v in non-strict schema",
                column.GetDiagnosticNameString());
        }
        totalTypeComplexity += column.LogicalType()->GetTypeComplexity();
    }
    if (totalTypeComplexity >= MaxSchemaTotalTypeComplexity) {
        THROW_ERROR_EXCEPTION("Table schema is too complex, reduce number of columns or simplify their types");
    }
    ValidateColumnUniqueness(schema);
    ValidateLocks(schema);
    ValidateKeyColumnsFormPrefix(schema);
    ValidateTimestampColumn(schema);
    ValidateTtlColumn(schema);
    ValidateCumulativeDataWeightColumn(schema);
    ValidateSchemaAttributes(schema);
    if (isTableDynamic) {
        ValidateDynamicTableConstraints(schema);
    }

    // Validate nested table names.
    std::vector<TStringBuf> definedNestedTableNames;
    std::vector<TStringBuf> usedNestedTableNames;

    for (const auto& columnSchema : schema.Columns()) {
        if (columnSchema.Aggregate()) {
            const auto& aggregateName = *columnSchema.Aggregate();

            if (auto nested = TryParseNestedAggregate(aggregateName)) {
                // Already validated.
                YT_VERIFY(!nested->NestedTableName.empty());

                if (nested->IsKey) {
                    definedNestedTableNames.push_back(nested->NestedTableName);
                } else {
                    usedNestedTableNames.push_back(nested->NestedTableName);
                }
            }
        }
    }

    std::sort(definedNestedTableNames.begin(), definedNestedTableNames.end());
    definedNestedTableNames.erase(
        std::unique(definedNestedTableNames.begin(), definedNestedTableNames.end()),
        definedNestedTableNames.end());

    std::sort(usedNestedTableNames.begin(), usedNestedTableNames.end());
    usedNestedTableNames.erase(
        std::unique(usedNestedTableNames.begin(), usedNestedTableNames.end()),
        usedNestedTableNames.end());

    for (auto nestedName : usedNestedTableNames) {
        if (!std::binary_search(definedNestedTableNames.begin(), definedNestedTableNames.end(), nestedName)) {
            THROW_ERROR_EXCEPTION("No key columns for nested table %Qv",
                nestedName);
        }
    }
}

void ValidateNoDescendingSortOrder(const TTableSchema& schema)
{
    for (const auto& column : schema.Columns()) {
        if (column.SortOrder() == ESortOrder::Descending) {
            THROW_ERROR_EXCEPTION(
                NTableClient::EErrorCode::InvalidSchemaValue,
                "Descending sort order is not available in this context yet")
                << TErrorAttribute("column_name", column.Name());
        }
    }
}

void ValidateNoRenamedColumns(const TTableSchema& schema)
{
    for (const auto& column : schema.Columns()) {
        if (column.IsRenamed()) {
            THROW_ERROR_EXCEPTION(
                NTableClient::EErrorCode::InvalidSchemaValue,
                "Table column renaming is not available yet")
                << TErrorAttribute("renamed_column", column.GetDiagnosticNameString());
        }
    }
}

////////////////////////////////////////////////////////////////////////////////

THashMap<std::string, int> GetLocksMapping(
    const NTableClient::TTableSchema& schema,
    bool fullAtomicity,
    std::vector<int>* columnIndexToLockIndex,
    std::vector<std::string>* lockIndexToName)
{
    if (columnIndexToLockIndex) {
        // Assign dummy lock indexes to key components.
        columnIndexToLockIndex->assign(schema.Columns().size(), -1);
    }

    if (lockIndexToName) {
        lockIndexToName->push_back(PrimaryLockName);
    }

    THashMap<std::string, int> groupToIndex;
    if (fullAtomicity) {
        // Assign lock indexes to data components.
        for (int index = schema.GetKeyColumnCount(); index < std::ssize(schema.Columns()); ++index) {
            const auto& columnSchema = schema.Columns()[index];
            int lockIndex = PrimaryLockIndex;

            if (columnSchema.Lock()) {
                auto emplaced = groupToIndex.emplace(*columnSchema.Lock(), groupToIndex.size() + 1);
                if (emplaced.second && lockIndexToName) {
                    lockIndexToName->push_back(*columnSchema.Lock());
                }
                lockIndex = emplaced.first->second;
            }

            if (columnIndexToLockIndex) {
                (*columnIndexToLockIndex)[index] = lockIndex;
            }
        }
    } else if (columnIndexToLockIndex) {
        // No locking supported for non-atomic tablets, however we still need the primary
        // lock descriptor to maintain last commit timestamps.
        for (int index = schema.GetKeyColumnCount(); index < std::ssize(schema.Columns()); ++index) {
            (*columnIndexToLockIndex)[index] = PrimaryLockIndex;
        }
    }
    return groupToIndex;
}

TLockMask GetLockMask(
    const NTableClient::TTableSchema& schema,
    bool fullAtomicity,
    const std::vector<std::string>& locks,
    ELockType lockType)
{
    auto groupToIndex = GetLocksMapping(schema, fullAtomicity);

    TLockMask lockMask;
    for (const auto& lock : locks) {
        auto it = groupToIndex.find(lock);
        if (it != groupToIndex.end()) {
            lockMask.Set(it->second, lockType);
        } else {
            THROW_ERROR_EXCEPTION("Lock group %Qv not found in schema", lock);
        }
    }
    return lockMask;
}

////////////////////////////////////////////////////////////////////////////////

namespace NProto {

using NYT::ToProto;
using NYT::FromProto;

void ToProto(TKeyColumnsExt* protoKeyColumns, const TKeyColumns& keyColumns)
{
    ToProto(protoKeyColumns->mutable_names(), keyColumns);
}

void FromProto(TKeyColumns* keyColumns, const TKeyColumnsExt& protoKeyColumns)
{
    *keyColumns = FromProto<TKeyColumns>(protoKeyColumns.names());
}

void ToProto(TColumnFilter* protoColumnFilter, const NTableClient::TColumnFilter& columnFilter)
{
    if (!columnFilter.IsUniversal()) {
        for (auto index : columnFilter.GetIndexes()) {
            protoColumnFilter->add_indexes(index);
        }
    }
}

void FromProto(NTableClient::TColumnFilter* columnFilter, const TColumnFilter& protoColumnFilter)
{
    *columnFilter = protoColumnFilter.indexes().empty()
        ? NTableClient::TColumnFilter()
        : NTableClient::TColumnFilter(FromProto<NTableClient::TColumnFilter::TIndexes>(protoColumnFilter.indexes()));
}

} // namespace NProto

////////////////////////////////////////////////////////////////////////////////

TCellTaggedTableSchema::TCellTaggedTableSchema(TTableSchema tableSchema, TCellTag cellTag)
    : TableSchema(std::move(tableSchema))
    , CellTag(cellTag)
{ }

////////////////////////////////////////////////////////////////////////////////

TCellTaggedTableSchemaPtr::TCellTaggedTableSchemaPtr(TTableSchemaPtr tableSchema, TCellTag cellTag)
    : TableSchema(std::move(tableSchema))
    , CellTag(cellTag)
{
    YT_VERIFY(TableSchema);
}

////////////////////////////////////////////////////////////////////////////////

} // namespace NYT::NTableClient

size_t THash<NYT::NTableClient::TColumnStableName>::operator()(const NYT::NTableClient::TColumnStableName& stableName) const
{
    return THash<std::string>()(stableName.Underlying());
}

size_t THash<NYT::NTableClient::TColumnSchema>::operator()(const NYT::NTableClient::TColumnSchema& columnSchema) const
{
    return MultiHash(
        columnSchema.StableName(),
        columnSchema.Name(),
        *columnSchema.LogicalType(),
        columnSchema.SortOrder(),
        columnSchema.Lock(),
        columnSchema.Expression(),
        columnSchema.Materialized(),
        columnSchema.Aggregate(),
        columnSchema.Group(),
        columnSchema.MaxInlineHunkSize());
}

size_t THash<NYT::NTableClient::TDeletedColumn>::operator()(const NYT::NTableClient::TDeletedColumn& columnSchema) const
{
    return THash<NYT::NTableClient::TColumnStableName>()(columnSchema.StableName());
}

size_t THash<NYT::NTableClient::TTableSchema>::operator()(const NYT::NTableClient::TTableSchema& tableSchema) const
{
    size_t result = CombineHashes(THash<bool>()(tableSchema.GetUniqueKeys()), THash<bool>()(tableSchema.GetStrict()));
    if (tableSchema.HasNontrivialSchemaModification()) {
        result = CombineHashes(
            result,
            THash<NYT::NTableClient::ETableSchemaModification>()(tableSchema.GetSchemaModification()));
    }
    for (const auto& columnSchema : tableSchema.Columns()) {
        result = CombineHashes(result, THash<NYT::NTableClient::TColumnSchema>()(columnSchema));
    }
    for (const auto& deletedColumnSchema : tableSchema.DeletedColumns()) {
        result = CombineHashes(result, THash<NYT::NTableClient::TDeletedColumn>()(
            deletedColumnSchema));
    }
    return result;
}