summaryrefslogtreecommitdiffstats
path: root/wsrep-lib/src/transaction.cpp
blob: 2738271ad85022160f0cf79c4aae0682d1f4be46 (plain)
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
/*
 * Copyright (C) 2018 Codership Oy <info@codership.com>
 *
 * This file is part of wsrep-lib.
 *
 * Wsrep-lib is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * Wsrep-lib is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with wsrep-lib.  If not, see <https://www.gnu.org/licenses/>.
 */

#include "wsrep/transaction.hpp"
#include "wsrep/client_state.hpp"
#include "wsrep/server_state.hpp"
#include "wsrep/storage_service.hpp"
#include "wsrep/high_priority_service.hpp"
#include "wsrep/key.hpp"
#include "wsrep/logger.hpp"
#include "wsrep/compiler.hpp"

#include <sstream>
#include <memory>

namespace
{
    class storage_service_deleter
    {
    public:
        storage_service_deleter(wsrep::server_service& server_service)
            : server_service_(server_service)
        { }
        void operator()(wsrep::storage_service* storage_service)
        {
            server_service_.release_storage_service(storage_service);
        }
    private:
        wsrep::server_service& server_service_;
    };

    template <class D>
    class scoped_storage_service
    {
    public:
        scoped_storage_service(wsrep::client_service& client_service,
                               wsrep::storage_service* storage_service,
                               D deleter)
            : client_service_(client_service)
            , storage_service_(storage_service)
            , deleter_(deleter)
        {
            if (storage_service_ == 0)
            {
                throw wsrep::runtime_error("Null client_state provided");
            }
            client_service_.reset_globals();
            storage_service_->store_globals();
        }

        wsrep::storage_service& storage_service()
        {
            return *storage_service_;
        }

        ~scoped_storage_service()
        {
            deleter_(storage_service_);
            client_service_.store_globals();
        }
    private:
        scoped_storage_service(const scoped_storage_service&);
        scoped_storage_service& operator=(const scoped_storage_service&);
        wsrep::client_service& client_service_;
        wsrep::storage_service* storage_service_;
        D deleter_;
    };
}

// Public

wsrep::transaction::transaction(
    wsrep::client_state& client_state)
    : server_service_(client_state.server_state().server_service())
    , client_service_(client_state.client_service())
    , client_state_(client_state)
    , server_id_()
    , id_(transaction_id::undefined())
    , state_(s_executing)
    , state_hist_()
    , bf_abort_state_(s_executing)
    , bf_abort_provider_status_()
    , bf_abort_client_state_()
    , bf_aborted_in_total_order_()
    , ws_handle_()
    , ws_meta_()
    , flags_()
    , implicit_deps_(false)
    , certified_(false)
    , fragments_certified_for_statement_()
    , streaming_context_()
    , sr_keys_()
    , apply_error_buf_()
    , xid_()
{ }


wsrep::transaction::~transaction()
{
}

int wsrep::transaction::start_transaction(
    const wsrep::transaction_id& id)
{
    debug_log_state("start_transaction enter");
    assert(active() == false);
    assert(is_xa() == false);
    assert(flags() == 0);
    server_id_ = client_state_.server_state().id();
    id_ = id;
    state_ = s_executing;
    state_hist_.clear();
    ws_handle_ = wsrep::ws_handle(id);
    flags(wsrep::provider::flag::start_transaction);
    switch (client_state_.mode())
    {
    case wsrep::client_state::m_high_priority:
        debug_log_state("start_transaction success");
        return 0;
    case wsrep::client_state::m_local:
        debug_log_state("start_transaction success");
        return provider().start_transaction(ws_handle_);
    default:
        debug_log_state("start_transaction error");
        assert(0);
        return 1;
    }
}

int wsrep::transaction::start_transaction(
    const wsrep::ws_handle& ws_handle,
    const wsrep::ws_meta& ws_meta)
{
    debug_log_state("start_transaction enter");
    if (state() != s_replaying)
    {
        // assert(ws_meta.flags());
        assert(active() == false);
        assert(flags() == 0);
        server_id_ = ws_meta.server_id();
        id_ = ws_meta.transaction_id();
        assert(client_state_.mode() == wsrep::client_state::m_high_priority);
        state_ = s_executing;
        state_hist_.clear();
        ws_handle_ = ws_handle;
        ws_meta_ = ws_meta;
        flags(wsrep::provider::flag::start_transaction);
        certified_ = true;
    }
    else
    {
        ws_meta_ = ws_meta;
        assert(ws_meta_.flags() & wsrep::provider::flag::commit);
        assert(active());
        assert(client_state_.mode() == wsrep::client_state::m_high_priority);
        assert(state() == s_replaying);
        assert(ws_meta_.seqno().is_undefined() == false);
        certified_ = true;
    }
    debug_log_state("start_transaction leave");
    return 0;
}

int wsrep::transaction::next_fragment(
    const wsrep::ws_meta& ws_meta)
{
    debug_log_state("next_fragment enter");
    ws_meta_ = ws_meta;
    debug_log_state("next_fragment leave");
    return 0;
}

void wsrep::transaction::adopt(const wsrep::transaction& transaction)
{
    debug_log_state("adopt enter");
    assert(transaction.is_streaming());
    start_transaction(transaction.id());
    server_id_ = transaction.server_id_;
    flags_  = transaction.flags();
    streaming_context_ = transaction.streaming_context();
    debug_log_state("adopt leave");
}

void wsrep::transaction::fragment_applied(wsrep::seqno seqno)
{
    assert(active());
    streaming_context_.applied(seqno);
}

int wsrep::transaction::prepare_for_ordering(
    const wsrep::ws_handle& ws_handle,
    const wsrep::ws_meta& ws_meta,
    bool is_commit)
{
    assert(active());

    if (state_ != s_replaying)
    {
        ws_handle_ = ws_handle;
        ws_meta_ = ws_meta;
        certified_ = is_commit;
    }
    return 0;
}

int wsrep::transaction::assign_read_view(const wsrep::gtid* const gtid)
{
    try
    {
        return provider().assign_read_view(ws_handle_, gtid);
    }
    catch (...)
    {
        wsrep::log_error() << "Failed to assign read view";
        return 1;
    }
}

int wsrep::transaction::append_key(const wsrep::key& key)
{
    try
    {
        debug_log_key_append(key);
        sr_keys_.insert(key);
        return provider().append_key(ws_handle_, key);
    }
    catch (...)
    {
        wsrep::log_error() << "Failed to append key";
        return 1;
    }
}

int wsrep::transaction::append_data(const wsrep::const_buffer& data)
{

    return provider().append_data(ws_handle_, data);
}

int wsrep::transaction::after_row()
{
    wsrep::unique_lock<wsrep::mutex> lock(client_state_.mutex());
    debug_log_state("after_row_enter");
    int ret(0);
    if (streaming_context_.fragment_size() &&
        streaming_context_.fragment_unit() != streaming_context::statement)
    {
        ret = streaming_step(lock);
    }
    debug_log_state("after_row_leave");
    return ret;
}

int wsrep::transaction::before_prepare(
    wsrep::unique_lock<wsrep::mutex>& lock)
{
    assert(lock.owns_lock());
    int ret(0);
    debug_log_state("before_prepare_enter");
    assert(state() == s_executing || state() == s_must_abort ||
           state() == s_replaying);

    if (state() == s_must_abort)
    {
        assert(client_state_.mode() == wsrep::client_state::m_local);
        client_state_.override_error(wsrep::e_deadlock_error);
        return 1;
    }

    switch (client_state_.mode())
    {
    case wsrep::client_state::m_local:
        if (is_streaming())
        {
            client_service_.debug_crash(
                "crash_last_fragment_commit_before_fragment_removal");
            lock.unlock();
            if (client_service_.statement_allowed_for_streaming() == false)
            {
                client_state_.override_error(
                    wsrep::e_error_during_commit,
                    wsrep::provider::error_not_allowed);
                ret = 1;
            }
            else if (!is_xa())
            {
                // Note: we can't remove fragments here for XA,
                // the transaction has already issued XA END and
                // is in IDLE state, no more changes allowed!
                ret = client_service_.remove_fragments();
                if (ret)
                {
                    client_state_.override_error(wsrep::e_deadlock_error);
                }
            }
            lock.lock();
            client_service_.debug_crash(
                "crash_last_fragment_commit_after_fragment_removal");
            if (state() == s_must_abort)
            {
                client_state_.override_error(wsrep::e_deadlock_error);
                ret = 1;
            }
        }

        if (ret == 0)
        {
            if (is_xa())
            {
                // Force fragment replication on XA prepare
                flags(flags() | wsrep::provider::flag::prepare);
                pa_unsafe(true);
                append_sr_keys_for_commit();
                const bool force_streaming_step = true;
                ret = streaming_step(lock, force_streaming_step);
                if (ret == 0)
                {
                    assert(state() == s_executing);
                    state(lock, s_preparing);
                }
            }
            else
            {
                ret = certify_commit(lock);
            }

            assert((ret == 0 && state() == s_preparing) ||
                   (state() == s_must_abort ||
                    state() == s_must_replay ||
                    state() == s_cert_failed));

            if (ret)
            {
                assert(state() == s_must_replay ||
                       client_state_.current_error());
                ret = 1;
            }
        }

        break;
    case wsrep::client_state::m_high_priority:
        // Note: fragment removal is done from applying
        // context for high priority mode.
        if (is_xa())
        {
            assert(state() == s_executing ||
                   state() == s_replaying);
            if (state() == s_replaying)
            {
                break;
            }
        }
        state(lock, s_preparing);
        break;
    default:
        assert(0);
        break;
    }

    assert(state() == s_preparing ||
           (is_xa() && state() == s_replaying) ||
           (ret && (state() == s_must_abort ||
                    state() == s_must_replay ||
                    state() == s_cert_failed ||
                    state() == s_aborted)));
    debug_log_state("before_prepare_leave");
    return ret;
}

int wsrep::transaction::after_prepare(
    wsrep::unique_lock<wsrep::mutex>& lock)
{
    assert(lock.owns_lock());

    int ret = 0;
    debug_log_state("after_prepare_enter");
    if (is_xa())
    {
        switch (state())
        {
        case s_preparing:
            assert(client_state_.mode() == wsrep::client_state::m_local ||
                   (certified() && ordered()));
            state(lock, s_prepared);
            break;
        case s_must_abort:
            // prepared locally, but client has not received
            // a result yet. We can still abort.
            assert(client_state_.mode() == wsrep::client_state::m_local);
            client_state_.override_error(wsrep::e_deadlock_error);
            ret = 1;
            break;
        case s_replaying:
            assert(client_state_.mode() == wsrep::client_state::m_high_priority);
            break;
        default:
            assert(0);
        }
    }
    else
    {
        assert(certified() && ordered());
        assert(state() == s_preparing || state() == s_must_abort);

        if (state() == s_must_abort)
        {
            assert(client_state_.mode() == wsrep::client_state::m_local);
            state(lock, s_must_replay);
            ret = 1;
        }
        else
        {
            state(lock, s_committing);
        }
    }
    debug_log_state("after_prepare_leave");
    return ret;
}

int wsrep::transaction::before_commit()
{
    int ret(1);

    wsrep::unique_lock<wsrep::mutex> lock(client_state_.mutex());
    debug_log_state("before_commit_enter");
    assert(client_state_.mode() != wsrep::client_state::m_toi);
    assert(state() == s_executing ||
           state() == s_prepared ||
           state() == s_committing ||
           state() == s_must_abort ||
           state() == s_replaying);
    assert((state() != s_committing && state() != s_replaying) ||
           certified());

    switch (client_state_.mode())
    {
    case wsrep::client_state::m_local:
        if (state() == s_executing)
        {
            ret = before_prepare(lock) || after_prepare(lock);
            assert((ret == 0 &&
                    (state() == s_committing || state() == s_prepared))
                   ||
                   (state() == s_must_abort ||
                    state() == s_must_replay ||
                    state() == s_cert_failed ||
                    state() == s_aborted));
        }
        else if (state() != s_committing && state() != s_prepared)
        {
            assert(state() == s_must_abort);
            if (certified() ||
                (is_xa() && is_streaming()))
            {
                state(lock, s_must_replay);
            }
            else
            {
                client_state_.override_error(wsrep::e_deadlock_error);
            }
        }
        else
        {
            // 2PC commit, prepare was done before
            ret = 0;
        }

        if (ret == 0 && state() == s_prepared)
        {
            ret = certify_commit(lock);
            assert((ret == 0 && state() == s_committing) ||
                   (state() == s_must_abort ||
                    state() == s_must_replay ||
                    state() == s_cert_failed ||
                    state() == s_prepared));
        }

        if (ret == 0)
        {
            assert(certified());
            assert(ordered());
            lock.unlock();
            client_service_.debug_sync("wsrep_before_commit_order_enter");
            enum wsrep::provider::status
                status(provider().commit_order_enter(ws_handle_, ws_meta_));
            lock.lock();
            switch (status)
            {
            case wsrep::provider::success:
                break;
            case wsrep::provider::error_bf_abort:
                if (state() != s_must_abort)
                {
                    state(lock, s_must_abort);
                }
                state(lock, s_must_replay);
                ret = 1;
                break;
            default:
                ret = 1;
                assert(0);
                break;
            }
        }
        break;
    case wsrep::client_state::m_high_priority:
        assert(certified());
        assert(ordered());
        if (is_xa())
        {
            assert(state() == s_prepared ||
                   state() == s_replaying);
            state(lock, s_committing);
            ret = 0;
        }
        else if (state() == s_executing || state() == s_replaying)
        {
            ret = before_prepare(lock) || after_prepare(lock);
        }
        else
        {
            ret = 0;
        }
        lock.unlock();
        ret = ret || provider().commit_order_enter(ws_handle_, ws_meta_);
        lock.lock();
        if (ret)
        {
            state(lock, s_must_abort);
            state(lock, s_aborting);
        }
        break;
    default:
        assert(0);
        break;
    }
    debug_log_state("before_commit_leave");
    return ret;
}

int wsrep::transaction::ordered_commit()
{
    wsrep::unique_lock<wsrep::mutex> lock(client_state_.mutex());
    debug_log_state("ordered_commit_enter");
    assert(state() == s_committing);
    assert(ordered());
    client_service_.debug_sync("wsrep_before_commit_order_leave");
    int ret(provider().commit_order_leave(ws_handle_, ws_meta_,
                                          apply_error_buf_));
    client_service_.debug_sync("wsrep_after_commit_order_leave");
    // Should always succeed:
    // 1) If before commit before succeeds, the transaction handle
    //    in the provider is guaranteed to exist and the commit
    //    has been ordered
    // 2) The transaction which has been ordered for commit cannot be BF
    //    aborted anymore
    // 3) The provider should always guarantee that the transactions which
    //    have been ordered for commit can finish committing.
    //
    // The exception here is a storage service transaction which is running
    // in high priority mode. The fragment storage commit may get BF
    // aborted in the provider after commit ordering has been
    // established since the transaction is operating in streaming
    // mode.
    if (ret)
    {
        assert(client_state_.mode() == wsrep::client_state::m_high_priority);
        state(lock, s_must_abort);
        state(lock, s_aborting);
    }
    else
    {
        state(lock, s_ordered_commit);
    }
    debug_log_state("ordered_commit_leave");
    return ret;
}

int wsrep::transaction::after_commit()
{
    int ret(0);

    wsrep::unique_lock<wsrep::mutex> lock(client_state_.mutex());
    debug_log_state("after_commit_enter");
    assert(state() == s_ordered_commit);

    if (is_streaming())
    {
        assert(client_state_.mode() == wsrep::client_state::m_local ||
               client_state_.mode() == wsrep::client_state::m_high_priority);

        if (is_xa())
        {
            // XA fragment removal happens here,
            // see comment in before_prepare
            lock.unlock();
            scoped_storage_service<storage_service_deleter>
                sr_scope(
                    client_service_,
                    server_service_.storage_service(client_service_),
                    storage_service_deleter(server_service_));
            wsrep::storage_service& storage_service(
                sr_scope.storage_service());
            storage_service.adopt_transaction(*this);
            storage_service.remove_fragments();
            storage_service.commit(wsrep::ws_handle(), wsrep::ws_meta());
            lock.lock();
        }

        if (client_state_.mode() == wsrep::client_state::m_local)
        {
            lock.unlock();
            client_state_.server_state_.stop_streaming_client(&client_state_);
            lock.lock();
        }
        streaming_context_.cleanup();
    }

    switch (client_state_.mode())
    {
    case wsrep::client_state::m_local:
        ret = provider().release(ws_handle_);
        break;
    case wsrep::client_state::m_high_priority:
        break;
    default:
        assert(0);
        break;
    }
    assert(ret == 0);
    state(lock, s_committed);

    // client_state_.server_state().last_committed_gtid(ws_meta.gitd());
    debug_log_state("after_commit_leave");
    return ret;
}

int wsrep::transaction::before_rollback()
{
    wsrep::unique_lock<wsrep::mutex> lock(client_state_.mutex());
    debug_log_state("before_rollback_enter");
    assert(state() == s_executing ||
           state() == s_preparing ||
           state() == s_prepared ||
           state() == s_must_abort ||
           // Background rollbacker or rollback initiated from SE
           state() == s_aborting ||
           state() == s_cert_failed ||
           state() == s_must_replay);

    switch (client_state_.mode())
    {
    case wsrep::client_state::m_local:
        if (is_streaming())
        {
            client_service_.debug_sync("wsrep_before_SR_rollback");
        }
        switch (state())
        {
        case s_preparing:
            // Error detected during prepare phase
            state(lock, s_must_abort);
            // fall through
        case s_prepared:
            // fall through
        case s_executing:
            // Voluntary rollback
            if (is_streaming())
            {
                streaming_rollback(lock);
            }
            state(lock, s_aborting);
            break;
        case s_must_abort:
            if (certified())
            {
                state(lock, s_must_replay);
            }
            else
            {
                if (is_streaming())
                {
                    streaming_rollback(lock);
                }
                state(lock, s_aborting);
            }
            break;
        case s_cert_failed:
            if (is_streaming())
            {
                streaming_rollback(lock);
            }
            state(lock, s_aborting);
            break;
        case s_aborting:
            if (is_streaming())
            {
                streaming_rollback(lock);
            }
            break;
        case s_must_replay:
            break;
        default:
            assert(0);
            break;
        }
        break;
    case wsrep::client_state::m_high_priority:
        // Rollback by rollback write set or BF abort
        assert(state_ == s_executing || state_ == s_prepared || state_ == s_aborting);
        if (state_ != s_aborting)
        {
            state(lock, s_aborting);
        }
        break;
    default:
        assert(0);
        break;
    }

    debug_log_state("before_rollback_leave");
    return 0;
}

int wsrep::transaction::after_rollback()
{
    wsrep::unique_lock<wsrep::mutex> lock(client_state_.mutex());
    debug_log_state("after_rollback_enter");
    assert(state() == s_aborting ||
           state() == s_must_replay);

    if (is_streaming() && bf_aborted_in_total_order_)
    {
        lock.unlock();
        // Storage service scope
        {
            scoped_storage_service<storage_service_deleter>
                sr_scope(
                    client_service_,
                    server_service_.storage_service(client_service_),
                    storage_service_deleter(server_service_));
            wsrep::storage_service& storage_service(
                sr_scope.storage_service());
            storage_service.adopt_transaction(*this);
            storage_service.remove_fragments();
            storage_service.commit(wsrep::ws_handle(), wsrep::ws_meta());
        }
        lock.lock();
        streaming_context_.cleanup();
    }

    if (is_streaming() && state() != s_must_replay)
    {
        streaming_context_.cleanup();
    }

    if (state() == s_aborting)
    {
        state(lock, s_aborted);
    }

    // Releasing the transaction from provider is postponed into
    // after_statement() hook. Depending on DBMS system all the
    // resources acquired by transaction may or may not be released
    // during actual rollback. If the transaction has been ordered,
    // releasing the commit ordering critical section should be
    // also postponed until all resources have been released.
    debug_log_state("after_rollback_leave");
    return 0;
}

int wsrep::transaction::release_commit_order(
    wsrep::unique_lock<wsrep::mutex>& lock)
{
    lock.unlock();
    int ret(provider().commit_order_enter(ws_handle_, ws_meta_));
    lock.lock();
    if (!ret)
    {
        server_service_.set_position(client_service_, ws_meta_.gtid());
        ret = provider().commit_order_leave(ws_handle_, ws_meta_,
                                            apply_error_buf_);
    }
    return ret;
}

int wsrep::transaction::after_statement()
{
    int ret(0);
    wsrep::unique_lock<wsrep::mutex> lock(client_state_.mutex());
    debug_log_state("after_statement_enter");
    assert(client_state_.mode() == wsrep::client_state::m_local);
    assert(state() == s_executing ||
           state() == s_prepared ||
           state() == s_committed ||
           state() == s_aborted ||
           state() == s_must_abort ||
           state() == s_cert_failed ||
           state() == s_must_replay);

    if (state() == s_executing &&
        streaming_context_.fragment_size() &&
        streaming_context_.fragment_unit() == streaming_context::statement)
    {
        ret = streaming_step(lock);
    }

    switch (state())
    {
    case s_executing:
        // ?
        break;
    case s_prepared:
        assert(is_xa());
        break;
    case s_committed:
        assert(is_streaming() == false);
        break;
    case s_must_abort:
    case s_cert_failed:
        client_state_.override_error(wsrep::e_deadlock_error);
        lock.unlock();
        ret = client_service_.bf_rollback();
        lock.lock();
        if (state() != s_must_replay)
        {
            break;
        }
        // Continue to replay if rollback() changed the state to s_must_replay
        // Fall through
    case s_must_replay:
    {
        if (is_xa() && !ordered())
        {
            ret = xa_replay(lock);
        }
        else
        {
            ret = replay(lock);
        }
        break;
    }
    case s_aborted:
        // Raise a deadlock error if the transaction was BF aborted and
        // rolled back by client outside of transaction hooks.
        if (bf_aborted() && client_state_.current_error() == wsrep::e_success &&
            !client_service_.is_xa_rollback())
        {
            client_state_.override_error(wsrep::e_deadlock_error);
        }
        break;
    default:
        assert(0);
        break;
    }

    assert(state() == s_executing ||
           state() == s_prepared ||
           state() == s_committed ||
           state() == s_aborted   ||
           state() == s_must_replay);

    if (state() == s_aborted)
    {
        if (ordered())
        {
            ret = release_commit_order(lock);
        }
        lock.unlock();
        provider().release(ws_handle_);
        lock.lock();
    }

    if (state() != s_executing &&
        (!client_service_.is_explicit_xa() ||
         client_state_.state() == wsrep::client_state::s_quitting))
    {
        cleanup();
    }
    fragments_certified_for_statement_ = 0;
    debug_log_state("after_statement_leave");
    assert(ret == 0 || state() == s_aborted);
    return ret;
}

void wsrep::transaction::after_applying()
{
    wsrep::unique_lock<wsrep::mutex> lock(client_state_.mutex_);
    debug_log_state("after_applying enter");
    assert(state_ == s_executing ||
           state_ == s_prepared ||
           state_ == s_committed ||
           state_ == s_aborted ||
           state_ == s_replaying);

    if (state_ != s_executing && state_ != s_prepared)
    {
        if (state_ == s_replaying) state(lock, s_aborted);
        cleanup();
    }
    else
    {
        // State remains executing or prepared, so this is a streaming applier.
        // Reset the meta data to avoid releasing commit order
        // critical section above if the next fragment is rollback
        // fragment. Rollback fragment ordering will be handled by
        // another instance while removing the fragments from
        // storage.
        ws_meta_ = wsrep::ws_meta();
    }
    debug_log_state("after_applying leave");
}

bool wsrep::transaction::bf_abort(
    wsrep::unique_lock<wsrep::mutex>& lock,
    wsrep::seqno bf_seqno)
{
    bool ret(false);
    const enum wsrep::transaction::state state_at_enter(state());
    assert(lock.owns_lock());

    if (active() == false)
    {
         WSREP_LOG_DEBUG(client_state_.debug_log_level(),
                         wsrep::log::debug_level_transaction,
                         "Transaction not active, skipping bf abort");
    }
    else
    {
        switch (state_at_enter)
        {
        case s_executing:
        case s_preparing:
        case s_prepared:
        case s_certifying:
        case s_committing:
        {
            wsrep::seqno victim_seqno;
            enum wsrep::provider::status
                status(client_state_.provider().bf_abort(
                           bf_seqno, id_, victim_seqno));
            switch (status)
            {
            case wsrep::provider::success:
                WSREP_LOG_DEBUG(client_state_.debug_log_level(),
                                wsrep::log::debug_level_transaction,
                                "Seqno " << bf_seqno
                                << " successfully BF aborted " << id_
                                << " victim_seqno " << victim_seqno);
                bf_abort_state_ = state_at_enter;
                state(lock, s_must_abort);
                ret = true;
                break;
            default:
                WSREP_LOG_DEBUG(client_state_.debug_log_level(),
                                wsrep::log::debug_level_transaction,
                                "Seqno " << bf_seqno
                                << " failed to BF abort " << id_
                                << " with status " << status
                                << " victim_seqno " << victim_seqno);
                break;
            }
            break;
        }
        default:
                WSREP_LOG_DEBUG(client_state_.debug_log_level(),
                                wsrep::log::debug_level_transaction,
                                "BF abort not allowed in state "
                                << wsrep::to_string(state_at_enter));
            break;
        }
    }

    if (ret)
    {
        bf_abort_client_state_ = client_state_.state();
        // If the transaction is in executing state, we must initiate
        // streaming rollback to ensure that the rollback fragment gets
        // replicated before the victim starts to roll back and release locks.
        // In other states the BF abort will be detected outside of
        // storage engine operations and streaming rollback will be
        // handled from before_rollback() call.
        if (client_state_.mode() == wsrep::client_state::m_local &&
            is_streaming() && state_at_enter == s_executing)
        {
            streaming_rollback(lock);
        }

        if ((client_state_.state() == wsrep::client_state::s_idle &&
             client_state_.server_state().rollback_mode() ==
             wsrep::server_state::rm_sync) // locally processing idle
            ||
            // high priority streaming
            (client_state_.mode() == wsrep::client_state::m_high_priority &&
             is_streaming()))
        {
            // We need to change the state to aborting under the
            // lock protection to avoid a race between client thread,
            // otherwise it could happen that the client gains control
            // between releasing the lock and before background
            // rollbacker gets control.
            if (is_xa() && state_at_enter == s_prepared)
            {
                state(lock, s_must_replay);
                client_state_.set_rollbacker_active(true);
            }
            else
            {
                state(lock, s_aborting);
                client_state_.set_rollbacker_active(true);
                if (client_state_.mode() == wsrep::client_state::m_high_priority)
                {
                    lock.unlock();
                    client_state_.server_state().stop_streaming_applier(
                        server_id_, id_);
                    lock.lock();
                }
            }

            lock.unlock();
            server_service_.background_rollback(client_state_);
        }
    }
    return ret;
}

bool wsrep::transaction::total_order_bf_abort(
    wsrep::unique_lock<wsrep::mutex>& lock WSREP_UNUSED,
    wsrep::seqno bf_seqno)
{
    bool ret(bf_abort(lock, bf_seqno));
    if (ret)
    {
        bf_aborted_in_total_order_ = true;
    }
    return ret;
}

void wsrep::transaction::clone_for_replay(const wsrep::transaction& other)
{
    assert(other.state() == s_replaying);
    id_ = other.id_;
    xid_ = other.xid_;
    server_id_ = other.server_id_;
    ws_handle_ = other.ws_handle_;
    ws_meta_ = other.ws_meta_;
    streaming_context_ = other.streaming_context_;
    state_ = s_replaying;
}

void wsrep::transaction::assign_xid(const wsrep::xid& xid)
{
    assert(active());
    assert(!is_xa());
    xid_ = xid;
}

int wsrep::transaction::restore_to_prepared_state(const wsrep::xid& xid)
{
    wsrep::unique_lock<wsrep::mutex> lock(client_state_.mutex_);
    assert(active());
    assert(is_empty());
    assert(state() == s_executing || state() == s_replaying);
    flags(flags() & ~wsrep::provider::flag::start_transaction);
    if (state() == s_executing)
    {
        state(lock, s_certifying);
    }
    else
    {
        state(lock, s_preparing);
    }
    state(lock, s_prepared);
    xid_ = xid;
    return 0;
}

int wsrep::transaction::commit_or_rollback_by_xid(const wsrep::xid& xid,
                                                  bool commit)
{
    debug_log_state("commit_or_rollback_by_xid enter");
    wsrep::unique_lock<wsrep::mutex> lock(client_state_.mutex_);
    wsrep::server_state& server_state(client_state_.server_state());
    wsrep::high_priority_service* sa(server_state.find_streaming_applier(xid));

    if (!sa)
    {
        assert(sa);
        client_state_.override_error(wsrep::e_error_during_commit);
        return 1;
    }

    if (commit)
    {
        flags(wsrep::provider::flag::commit);
    }
    else
    {
        flags(wsrep::provider::flag::rollback);
    }
    pa_unsafe(true);
    wsrep::stid stid(sa->transaction().server_id(),
                     sa->transaction().id(),
                     client_state_.id());
    wsrep::ws_meta meta(stid);

    const enum wsrep::provider::status cert_ret(
        provider().certify(client_state_.id(),
                           ws_handle_,
                           flags(),
                           meta));

    int ret;
    if (cert_ret == wsrep::provider::success)
    {
        if (commit)
        {
            state(lock, s_certifying);
            state(lock, s_committing);
            state(lock, s_committed);
        }
        else
        {
            state(lock, s_aborting);
            state(lock, s_aborted);
        }
        ret = 0;
    }
    else
    {
        client_state_.override_error(wsrep::e_error_during_commit,
                                     cert_ret);
        wsrep::log_error() << "Failed to commit_or_rollback_by_xid,"
                           << " xid: " << xid
                           << " error: " << cert_ret;
        ret = 1;
    }
    debug_log_state("commit_or_rollback_by_xid leave");
    return ret;
}

void wsrep::transaction::xa_detach()
{
    debug_log_state("xa_detach enter");
    assert(state() == s_prepared);
    wsrep::server_state& server_state(client_state_.server_state());
    server_state.convert_streaming_client_to_applier(&client_state_);
    client_service_.store_globals();
    client_service_.cleanup_transaction();
    wsrep::unique_lock<wsrep::mutex> lock(client_state_.mutex_);
    streaming_context_.cleanup();
    state(lock, s_aborting);
    state(lock, s_aborted);
    provider().release(ws_handle_);
    cleanup();
    debug_log_state("xa_detach leave");
}

int wsrep::transaction::xa_replay(wsrep::unique_lock<wsrep::mutex>& lock)
{
    debug_log_state("xa_replay enter");
    assert(lock.owns_lock());
    assert(is_xa());
    assert(is_streaming());
    assert(state() == s_must_replay);
    assert(bf_aborted());

    state(lock, s_replaying);

    enum wsrep::provider::status status;
    wsrep::server_state& server_state(client_state_.server_state());

    lock.unlock();
    server_state.convert_streaming_client_to_applier(&client_state_);
    status = client_service_.replay_unordered();
    client_service_.store_globals();
    lock.lock();

    if (status != wsrep::provider::success)
    {
        client_service_.emergency_shutdown();
    }

    int ret(1);
    if (bf_abort_client_state_ == wsrep::client_state::s_idle)
    {
        state(lock, s_aborted);
        streaming_context_.cleanup();
        provider().release(ws_handle_);
        cleanup();
        ret = 0;
    }
    else
    {
        lock.unlock();
        enum wsrep::provider::status status(client_service_.commit_by_xid());
        lock.lock();
        switch (status)
        {
        case wsrep::provider::success:
            state(lock, s_committed);
            streaming_context_.cleanup();
            provider().release(ws_handle_);
            cleanup();
            ret = 0;
            break;
        default:
            log_warning() << "Failed to commit by xid during replay";
            // Commit by xid failed, return a commit
            // error and let the client retry
            state(lock, s_preparing);
            state(lock, s_prepared);
            client_state_.override_error(wsrep::e_error_during_commit, status);
        }
    }

    client_service_.signal_replayed();
    debug_log_state("xa_replay leave");
    return ret;
}

////////////////////////////////////////////////////////////////////////////////
//                                 Private                                    //
////////////////////////////////////////////////////////////////////////////////

inline wsrep::provider& wsrep::transaction::provider()
{
    return client_state_.server_state().provider();
}

void wsrep::transaction::state(
    wsrep::unique_lock<wsrep::mutex>& lock __attribute__((unused)),
    enum wsrep::transaction::state next_state)
{
    WSREP_LOG_DEBUG(client_state_.debug_log_level(),
                    wsrep::log::debug_level_transaction,
                    "client: " << client_state_.id().get()
                    << " txc: " << id().get()
                    << " state: " << to_string(state_)
                    << " -> " << to_string(next_state));

    assert(lock.owns_lock());
    // BF aborter is allowed to change the state without gaining control
    // to the state if the next state is s_must_abort, s_aborting or
    // s_must_replay (for xa idle replay).
    assert(client_state_.owning_thread_id_ == wsrep::this_thread::get_id() ||
           next_state == s_must_abort ||
           next_state == s_must_replay ||
           next_state == s_aborting);

    static const char allowed[n_states][n_states] =
        { /*  ex pg pd ce co oc ct cf ma ab ad mr re */
            { 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0}, /* ex */
            { 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0}, /* pg */
            { 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0}, /* pd */
            { 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0}, /* ce */
            { 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0}, /* co */
            { 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0}, /* oc */
            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, /* ct */
            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0}, /* cf */
            { 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0}, /* ma */
            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0}, /* ab */
            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, /* ad */
            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, /* mr */
            { 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0}  /* re */
        };

    if (!allowed[state_][next_state])
    {
        wsrep::log_debug() << "unallowed state transition for transaction "
                           << id_ << ": " << wsrep::to_string(state_)
                           << " -> " << wsrep::to_string(next_state);
        assert(0);
    }

    state_hist_.push_back(state_);
    if (state_hist_.size() == 12)
    {
        state_hist_.erase(state_hist_.begin());
    }
    state_ = next_state;

    if (state_ == s_must_replay)
    {
        client_service_.will_replay();
    }
}

bool wsrep::transaction::abort_or_interrupt(
    wsrep::unique_lock<wsrep::mutex>& lock)
{
    assert(lock.owns_lock());
    if (state() == s_must_abort)
    {
        client_state_.override_error(wsrep::e_deadlock_error);
        return true;
    }
    else if (state() == s_aborting || state() == s_aborted)
    {
        // Somehow we got there after BF abort without setting error
        // status. This may happen if the DBMS side aborts the transaction
        // but still tries to continue processing rows. Raise the error here
        // and assert so that the error will be caught in debug builds.
        if (bf_abort_client_state_ &&
            client_state_.current_error() == wsrep::e_success)
        {
            client_state_.override_error(wsrep::e_deadlock_error);
            assert(0);
        }
        return true;
    }
    else if (client_service_.interrupted(lock))
    {
        client_state_.override_error(wsrep::e_interrupted_error);
        if (state() != s_must_abort)
        {
            state(lock, s_must_abort);
        }
        return true;
    }
    return false;
}

int wsrep::transaction::streaming_step(wsrep::unique_lock<wsrep::mutex>& lock,
                                       bool force)
{
    assert(lock.owns_lock());
    assert(streaming_context_.fragment_size() || is_xa());

    if (client_service_.bytes_generated() <
        streaming_context_.log_position())
    {
        /* Something went wrong on DBMS side in keeping track of
           generated bytes. Return an error to abort the transaction. */
        wsrep::log_warning() << "Bytes generated "
                             << client_service_.bytes_generated()
                             << " less than bytes certified "
                             << streaming_context_.log_position()
                             << ", aborting streaming transaction";
        return 1;
    }
    int ret(0);

    const size_t bytes_to_replicate(client_service_.bytes_generated() -
                                    streaming_context_.log_position());

    switch (streaming_context_.fragment_unit())
    {
    case streaming_context::row:
        // fall through
    case streaming_context::statement:
        streaming_context_.increment_unit_counter(1);
        break;
    case streaming_context::bytes:
        streaming_context_.set_unit_counter(bytes_to_replicate);
        break;
    }

    // Some statements have no effect. Do not atttempt to
    // replicate a fragment if no data has been generated since
    // last fragment replication.
    // We use `force = true` on XA prepare: a fragment will be
    // generated even if no data is pending replication.
    if (bytes_to_replicate <= 0 && !force)
    {
        assert(bytes_to_replicate == 0);
        return ret;
    }

    if (streaming_context_.fragment_size_exceeded() || force)
    {
        streaming_context_.reset_unit_counter();
        ret = certify_fragment(lock);
    }

    return ret;
}

int wsrep::transaction::certify_fragment(
    wsrep::unique_lock<wsrep::mutex>& lock)
{
    assert(lock.owns_lock());

    assert(client_state_.mode() == wsrep::client_state::m_local);
    assert(streaming_context_.rolled_back() == false ||
           state() == s_must_abort);

    client_service_.wait_for_replayers(lock);
    if (abort_or_interrupt(lock))
    {
        return 1;
    }

    state(lock, s_certifying);
    lock.unlock();
    client_service_.debug_sync("wsrep_before_fragment_certification");

    wsrep::mutable_buffer data;
    size_t log_position(0);
    if (client_service_.prepare_fragment_for_replication(data, log_position))
    {
        lock.lock();
        state(lock, s_must_abort);
        client_state_.override_error(wsrep::e_error_during_commit);
        return 1;
    }
    streaming_context_.set_log_position(log_position);

    if (data.size() == 0)
    {
        wsrep::log_warning() << "Attempt to replicate empty data buffer";
        lock.lock();
        state(lock, s_executing);
        return 0;
    }

    if (provider().append_data(ws_handle_,
                               wsrep::const_buffer(data.data(), data.size())))
    {
        lock.lock();
        state(lock, s_must_abort);
        client_state_.override_error(wsrep::e_error_during_commit);
        return 1;
    }

    if (is_xa())
    {
        // One more check to see if the transaction
        // has been aborted. This is necessary because
        // until the append_data above will make sure
        // that the transaction exists in provider.
        lock.lock();
        if (abort_or_interrupt(lock))
        {
            return 1;
        }
        lock.unlock();
    }

    if (is_streaming() == false)
    {
        client_state_.server_state_.start_streaming_client(&client_state_);
    }

    if (implicit_deps())
    {
        flags(flags() | wsrep::provider::flag::implicit_deps);
    }

    int ret(0);
    enum wsrep::client_error error(wsrep::e_success);
    enum wsrep::provider::status cert_ret(wsrep::provider::success);
    // Storage service scope
    {
        scoped_storage_service<storage_service_deleter>
            sr_scope(
                client_service_,
                server_service_.storage_service(client_service_),
                storage_service_deleter(server_service_));
        wsrep::storage_service& storage_service(
            sr_scope.storage_service());

        // First the fragment is appended to the stable storage.
        // This is done to ensure that there is enough capacity
        // available to store the fragment. The fragment meta data
        // is updated after certification.
        wsrep::id server_id(client_state_.server_state().id());
        assert(server_id.is_undefined() == false);
        if (storage_service.start_transaction(ws_handle_) ||
            storage_service.append_fragment(
                server_id,
                id(),
                flags(),
                wsrep::const_buffer(data.data(), data.size()),
                xid()))
        {
            ret = 1;
            error = wsrep::e_append_fragment_error;
        }

        if (ret == 0)
        {
            client_service_.debug_crash(
                "crash_replicate_fragment_before_certify");

            wsrep::ws_meta sr_ws_meta;
            cert_ret = provider().certify(client_state_.id(),
                                          ws_handle_,
                                          flags(),
                                          sr_ws_meta);
            client_service_.debug_crash(
                "crash_replicate_fragment_after_certify");

            switch (cert_ret)
            {
            case wsrep::provider::success:
                ++fragments_certified_for_statement_;
                assert(sr_ws_meta.seqno().is_undefined() == false);
                streaming_context_.certified();
                if (storage_service.update_fragment_meta(sr_ws_meta))
                {
                    storage_service.rollback(wsrep::ws_handle(),
                                             wsrep::ws_meta());
                    ret = 1;
                    error = wsrep::e_deadlock_error;
                    break;
                }
                if (storage_service.commit(ws_handle_, sr_ws_meta))
                {
                    ret = 1;
                    error = wsrep::e_deadlock_error;
                }
                else
                {
                    streaming_context_.stored(sr_ws_meta.seqno());
                }
                client_service_.debug_crash(
                    "crash_replicate_fragment_success");
                break;
            case wsrep::provider::error_bf_abort:
            case wsrep::provider::error_certification_failed:
                // Streaming transcation got BF aborted, so it must roll
                // back. Roll back the fragment storage operation out of
                // order as the commit order will be grabbed later on
                // during rollback process. Mark the fragment as certified
                // though in streaming context in order to enter streaming
                // rollback codepath.
                //
                // Note that despite we handle error_certification_failed
                // here, we mark the transaction as streaming. Apparently
                // the provider may return status corresponding to certification
                // failure even if the fragment has passed certification.
                // This may be a bug in provider implementation or a limitation
                // of error codes defined in wsrep-API. In order to make
                // sure that the transaction will be cleaned on other servers,
                // we take a risk of sending one rollback fragment for nothing.
                storage_service.rollback(wsrep::ws_handle(),
                                         wsrep::ws_meta());
                streaming_context_.certified();
                ret = 1;
                error = wsrep::e_deadlock_error;
                break;
            default:
                // Storage service rollback must be done out of order,
                // otherwise there may be a deadlock between BF aborter
                // and the rollback process.
                storage_service.rollback(wsrep::ws_handle(), wsrep::ws_meta());
                ret = 1;
                error = wsrep::e_deadlock_error;
                break;
            }
        }
    }

    // Note: This does not release the handle in the provider
    // since streaming is still on. However it is needed to
    // make provider internal state to transition for the
    // next fragment. If any of the operations above failed,
    // the handle needs to be left unreleased for the following
    // rollback process.
    if (ret == 0)
    {
        assert(error == wsrep::e_success);
        ret = provider().release(ws_handle_);
        if (ret)
        {
            error = wsrep::e_deadlock_error;
        }
    }
    lock.lock();
    if (ret)
    {
        assert(error != wsrep::e_success);
        if (is_streaming() == false)
        {
            lock.unlock();
            client_state_.server_state_.stop_streaming_client(&client_state_);
            lock.lock();
        }
        else
        {
            streaming_rollback(lock);
        }
        if (state_ != s_must_abort)
        {
            state(lock, s_must_abort);
        }
        client_state_.override_error(error, cert_ret);
    }
    else if (state_ == s_must_abort)
    {
        if (is_streaming())
        {
            streaming_rollback(lock);
        }
        client_state_.override_error(wsrep::e_deadlock_error, cert_ret);
        ret = 1;
    }
    else
    {
        assert(state_ == s_certifying);
        state(lock, s_executing);
        flags(flags() & ~wsrep::provider::flag::start_transaction);
        flags(flags() & ~wsrep::provider::flag::pa_unsafe);
    }
    return ret;
}

int wsrep::transaction::certify_commit(
    wsrep::unique_lock<wsrep::mutex>& lock)
{
    assert(lock.owns_lock());
    assert(active());
    client_service_.wait_for_replayers(lock);

    assert(lock.owns_lock());

    if (abort_or_interrupt(lock))
    {
        if (is_xa() && state() == s_must_abort)
        {
            state(lock, s_must_replay);
        }
        return 1;
    }

    state(lock, s_certifying);
    lock.unlock();

    if (is_streaming())
    {
        if (!is_xa())
        {
            append_sr_keys_for_commit();
        }
        pa_unsafe(true);
    }

    if (implicit_deps())
    {
        flags(flags() | wsrep::provider::flag::implicit_deps);
    }

    flags(flags() | wsrep::provider::flag::commit);
    flags(flags() & ~wsrep::provider::flag::prepare);

    if (client_service_.prepare_data_for_replication())
    {
        lock.lock();
        // Here we fake that the size exceeded error came from provider,
        // even though it came from the client service. This requires
        // some consideration how to get meaningful error codes from
        // the client service.
        client_state_.override_error(wsrep::e_size_exceeded_error,
                                     wsrep::provider::error_size_exceeded);
        if (state_ != s_must_abort)
        {
            state(lock, s_must_abort);
        }
        return 1;
    }

    client_service_.debug_sync("wsrep_before_certification");
    enum wsrep::provider::status
        cert_ret(provider().certify(client_state_.id(),
                                   ws_handle_,
                                   flags(),
                                   ws_meta_));
    client_service_.debug_sync("wsrep_after_certification");

    lock.lock();

    assert(state() == s_certifying || state() == s_must_abort);

    int ret(1);
    switch (cert_ret)
    {
    case wsrep::provider::success:
        assert(ordered());
        certified_ = true;
        ++fragments_certified_for_statement_;
        switch (state())
        {
        case s_certifying:
            if (is_xa())
            {
                state(lock, s_committing);
            }
            else
            {
                state(lock, s_preparing);
            }
            ret = 0;
            break;
        case s_must_abort:
            // We got BF aborted after succesful certification
            // and before acquiring client state lock. The trasaction
            // must be replayed.
            state(lock, s_must_replay);
            break;
        default:
            assert(0);
            break;
        }
        break;
    case wsrep::provider::error_warning:
        assert(ordered() == false);
        state(lock, s_must_abort);
        client_state_.override_error(wsrep::e_error_during_commit, cert_ret);
        break;
    case wsrep::provider::error_transaction_missing:
        state(lock, s_must_abort);
        // The execution should never reach this point if the
        // transaction has not generated any keys or data.
        wsrep::log_warning() << "Transaction was missing in provider";
        client_state_.override_error(wsrep::e_error_during_commit, cert_ret);
        break;
    case wsrep::provider::error_bf_abort:
        // Transaction was replicated successfully and it was either
        // certified successfully or the result of certifying is not
        // yet known. Therefore the transaction must roll back
        // and go through replay either to replay and commit the whole
        // transaction or to determine failed certification status.
        if (state() != s_must_abort)
        {
            state(lock, s_must_abort);
        }
        state(lock, s_must_replay);
        break;
    case wsrep::provider::error_certification_failed:
        state(lock, s_cert_failed);
        client_state_.override_error(wsrep::e_deadlock_error);
        break;
    case wsrep::provider::error_size_exceeded:
        state(lock, s_must_abort);
        client_state_.override_error(wsrep::e_error_during_commit, cert_ret);
        break;
    case wsrep::provider::error_connection_failed:
        // Galera provider may return CONN_FAIL if the trx is
        // BF aborted O_o. If we see here that the trx was BF aborted,
        // return deadlock error instead of error during commit
        // to reduce number of error state combinations elsewhere.
        if (state() == s_must_abort)
        {
            if (is_xa())
            {
                state(lock, s_must_replay);
            }
            client_state_.override_error(wsrep::e_deadlock_error);
        }
        else
        {
            client_state_.override_error(wsrep::e_error_during_commit,
                                         cert_ret);
            if (is_xa())
            {
                state(lock, s_prepared);
            }
            else
            {
                state(lock, s_must_abort);
            }
        }
        break;
    case wsrep::provider::error_provider_failed:
        if (state() != s_must_abort)
        {
            state(lock, s_must_abort);
        }
        client_state_.override_error(wsrep::e_error_during_commit, cert_ret);
        break;
    case wsrep::provider::error_fatal:
        client_state_.override_error(wsrep::e_error_during_commit, cert_ret);
        state(lock, s_must_abort);
        client_service_.emergency_shutdown();
        break;
    case wsrep::provider::error_not_implemented:
    case wsrep::provider::error_not_allowed:
        client_state_.override_error(wsrep::e_error_during_commit, cert_ret);
        state(lock, s_must_abort);
        wsrep::log_warning() << "Certification operation was not allowed: "
                             << "id: " << id().get()
                             << " flags: " << std::hex << flags() << std::dec;
        break;
    default:
        state(lock, s_must_abort);
        client_state_.override_error(wsrep::e_error_during_commit, cert_ret);
        break;
    }

    return ret;
}

int wsrep::transaction::append_sr_keys_for_commit()
{
    int ret(0);
    assert(client_state_.mode() == wsrep::client_state::m_local);
    for (wsrep::sr_key_set::branch_type::const_iterator
             i(sr_keys_.root().begin());
         ret == 0 && i != sr_keys_.root().end(); ++i)
    {
        for (wsrep::sr_key_set::leaf_type::const_iterator
                 j(i->second.begin());
             ret == 0 && j != i->second.end(); ++j)
        {
            wsrep::key key(wsrep::key::shared);
            key.append_key_part(i->first.data(), i->first.size());
            key.append_key_part(j->data(), j->size());
            ret = provider().append_key(ws_handle_, key);
        }
    }
    return ret;
}

void wsrep::transaction::streaming_rollback(wsrep::unique_lock<wsrep::mutex>& lock)
{
    debug_log_state("streaming_rollback enter");
    assert(state_ != s_must_replay);
    assert(is_streaming());
    if (streaming_context_.rolled_back() == false)
    {
        // We must set rolled_back id before stopping streaming client
        // or converting to applier. Accessing server_state requires
        // releasing the client_state lock in order to avoid violating
        // locking order, and this will open up a possibility for two
        // threads accessing this block simultaneously.
        streaming_context_.rolled_back(id_);
        if (bf_aborted_in_total_order_)
        {
            lock.unlock();
            client_state_.server_state_.stop_streaming_client(&client_state_);
            lock.lock();
        }
        else
        {
            // Create a high priority applier which will handle the
            // rollback fragment or clean up on configuration change.
            // Adopt transaction will copy fragment set and appropriate
            // meta data. Mark current transaction streaming context
            // rolled back.
            lock.unlock();
            client_state_.server_state_.convert_streaming_client_to_applier(
                &client_state_);
            lock.lock();
            streaming_context_.cleanup();
            // Cleanup cleans rolled_back_for from streaming context, but
            // we want to preserve it to avoid executing this block
            // more than once.
            streaming_context_.rolled_back(id_);
            enum wsrep::provider::status ret;
            if ((ret = provider().rollback(id_)))
            {
                wsrep::log_debug()
                    << "Failed to replicate rollback fragment for "
                    << id_ << ": " << ret;
            }
        }
    }
    debug_log_state("streaming_rollback leave");
}

int wsrep::transaction::replay(wsrep::unique_lock<wsrep::mutex>& lock)
{
    int ret(0);
    state(lock, s_replaying);
    // Need to remember streaming state before replay, entering
    // after_commit() after succesful replay will clear
    // fragments.
    const bool was_streaming(is_streaming());
    lock.unlock();
    client_service_.debug_sync("wsrep_before_replay");
    enum wsrep::provider::status replay_ret(client_service_.replay());
    client_service_.signal_replayed();
    if (was_streaming)
    {
        client_state_.server_state_.stop_streaming_client(&client_state_);
    }
    lock.lock();
    switch (replay_ret)
    {
    case wsrep::provider::success:
        if (state() == s_replaying)
        {
            // Replay was done by using different client state, adjust state
            // to committed.
            state(lock, s_committed);
        }
        if (is_streaming())
        {
            streaming_context_.cleanup();
        }
        provider().release(ws_handle_);
        break;
    case wsrep::provider::error_certification_failed:
        client_state_.override_error(
            wsrep::e_deadlock_error);
        if (is_streaming())
        {
            client_service_.remove_fragments();
            streaming_context_.cleanup();
        }
        state(lock, s_aborted);
        ret = 1;
        break;
    default:
        client_service_.emergency_shutdown();
        break;
    }

    WSREP_LOG_DEBUG(client_state_.debug_log_level(),
                    wsrep::log::debug_level_transaction,
                    "replay returned" << replay_ret);
    return ret;
}

void wsrep::transaction::cleanup()
{
    debug_log_state("cleanup_enter");
    assert(is_streaming() == false);
    assert(state() == s_committed || state() == s_aborted);
    id_ = wsrep::transaction_id::undefined();
    ws_handle_ = wsrep::ws_handle();
    // Keep the state history for troubleshooting. Reset
    // at start_transaction().
    // state_hist_.clear();
    if (ordered())
    {
        client_state_.update_last_written_gtid(ws_meta_.gtid());
    }
    bf_abort_state_ = s_executing;
    bf_abort_provider_status_ = wsrep::provider::success;
    bf_abort_client_state_ = 0;
    bf_aborted_in_total_order_ = false;
    ws_meta_ = wsrep::ws_meta();
    flags_ = 0;
    certified_ = false;
    implicit_deps_ = false;
    sr_keys_.clear();
    streaming_context_.cleanup();
    client_service_.cleanup_transaction();
    apply_error_buf_.clear();
    xid_.clear();
    debug_log_state("cleanup_leave");
}

void wsrep::transaction::debug_log_state(
    const char* context) const
{
    WSREP_LOG_DEBUG(
        client_state_.debug_log_level(),
        wsrep::log::debug_level_transaction,
        context
        << "\n    server: " << server_id_
        << ", client: " << int64_t(client_state_.id().get())
        << ", state: " << wsrep::to_c_string(client_state_.state())
        << ", mode: " << wsrep::to_c_string(client_state_.mode())
        << "\n    trx_id: " << int64_t(id_.get())
        << ", seqno: " << ws_meta_.seqno().get()
        << ", flags: " << flags()
        << "\n"
        << "    state: " << wsrep::to_c_string(state_)
        << ", bfa_state: " << wsrep::to_c_string(bf_abort_state_)
        << ", error: " << wsrep::to_c_string(client_state_.current_error())
        << ", status: " << client_state_.current_error_status()
        << "\n"
        << "    is_sr: " << is_streaming()
        << ", frags: " << streaming_context_.fragments_certified()
        << ", frags size: " << streaming_context_.fragments().size()
        << ", unit: " << streaming_context_.fragment_unit()
        << ", size: " << streaming_context_.fragment_size()
        << ", counter: " << streaming_context_.unit_counter()
        << ", log_pos: " << streaming_context_.log_position()
        << ", sr_rb: " << streaming_context_.rolled_back()
        << "\n    own: " << (client_state_.owning_thread_id_ == wsrep::this_thread::get_id())
        << " thread_id: " << client_state_.owning_thread_id_
        << "");
}

void wsrep::transaction::debug_log_key_append(const wsrep::key& key) const
{
    WSREP_LOG_DEBUG(client_state_.debug_log_level(),
                    wsrep::log::debug_level_transaction,
                    "key_append: "
                    << "trx_id: "
                    << int64_t(id().get())
                    << " append key:\n" << key);
}