summaryrefslogtreecommitdiffstats
path: root/fluent-bit/lib/librdkafka-2.1.0/src/rdkafka_partition.c
blob: 46d2fb3ed8f934a885a6ef2bb4d204d7b6ea932e (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
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
/*
 * librdkafka - The Apache Kafka C/C++ library
 *
 * Copyright (c) 2015 Magnus Edenhill
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
#include "rdkafka_int.h"
#include "rdkafka_topic.h"
#include "rdkafka_broker.h"
#include "rdkafka_request.h"
#include "rdkafka_offset.h"
#include "rdkafka_partition.h"
#include "rdkafka_fetcher.h"
#include "rdregex.h"
#include "rdports.h" /* rd_qsort_r() */

#include "rdunittest.h"

const char *rd_kafka_fetch_states[] = {"none",        "stopping",
                                       "stopped",     "offset-query",
                                       "offset-wait", "validate-epoch-wait",
                                       "active"};


static rd_kafka_op_res_t rd_kafka_toppar_op_serve(rd_kafka_t *rk,
                                                  rd_kafka_q_t *rkq,
                                                  rd_kafka_op_t *rko,
                                                  rd_kafka_q_cb_type_t cb_type,
                                                  void *opaque);

static void rd_kafka_toppar_offset_retry(rd_kafka_toppar_t *rktp,
                                         int backoff_ms,
                                         const char *reason);


static RD_INLINE int32_t
rd_kafka_toppar_version_new_barrier0(rd_kafka_toppar_t *rktp,
                                     const char *func,
                                     int line) {
        int32_t version = rd_atomic32_add(&rktp->rktp_version, 1);
        rd_kafka_dbg(rktp->rktp_rkt->rkt_rk, TOPIC, "BARRIER",
                     "%s [%" PRId32 "]: %s:%d: new version barrier v%" PRId32,
                     rktp->rktp_rkt->rkt_topic->str, rktp->rktp_partition, func,
                     line, version);
        return version;
}

#define rd_kafka_toppar_version_new_barrier(rktp)                              \
        rd_kafka_toppar_version_new_barrier0(rktp, __FUNCTION__, __LINE__)


/**
 * Toppar based OffsetResponse handling.
 * This is used for updating the low water mark for consumer lag.
 */
static void rd_kafka_toppar_lag_handle_Offset(rd_kafka_t *rk,
                                              rd_kafka_broker_t *rkb,
                                              rd_kafka_resp_err_t err,
                                              rd_kafka_buf_t *rkbuf,
                                              rd_kafka_buf_t *request,
                                              void *opaque) {
        rd_kafka_toppar_t *rktp = opaque;
        rd_kafka_topic_partition_list_t *offsets;
        rd_kafka_topic_partition_t *rktpar;

        offsets = rd_kafka_topic_partition_list_new(1);

        /* Parse and return Offset */
        err = rd_kafka_handle_ListOffsets(rk, rkb, err, rkbuf, request, offsets,
                                          NULL);

        if (err == RD_KAFKA_RESP_ERR__IN_PROGRESS) {
                rd_kafka_topic_partition_list_destroy(offsets);
                return; /* Retrying */
        }

        if (!err && !(rktpar = rd_kafka_topic_partition_list_find(
                          offsets, rktp->rktp_rkt->rkt_topic->str,
                          rktp->rktp_partition)))
                err = RD_KAFKA_RESP_ERR__UNKNOWN_PARTITION;

        if (!err && !rktpar->err) {
                rd_kafka_toppar_lock(rktp);
                rktp->rktp_lo_offset = rktpar->offset;
                rd_kafka_toppar_unlock(rktp);
        }

        rd_kafka_topic_partition_list_destroy(offsets);

        rktp->rktp_wait_consumer_lag_resp = 0;

        rd_kafka_toppar_destroy(rktp); /* from request.opaque */
}



/**
 * Request information from broker to keep track of consumer lag.
 *
 * @locality toppar handle thread
 * @locks none
 */
static void rd_kafka_toppar_consumer_lag_req(rd_kafka_toppar_t *rktp) {
        rd_kafka_topic_partition_list_t *partitions;
        rd_kafka_topic_partition_t *rktpar;

        if (rktp->rktp_wait_consumer_lag_resp)
                return; /* Previous request not finished yet */

        rd_kafka_toppar_lock(rktp);

        /* Offset requests can only be sent to the leader replica.
         *
         * Note: If rktp is delegated to a preferred replica, it is
         * certain that FETCH >= v5 and so rktp_lo_offset will be
         * updated via LogStartOffset in the FETCH response.
         */
        if (!rktp->rktp_leader || (rktp->rktp_leader != rktp->rktp_broker)) {
                rd_kafka_toppar_unlock(rktp);
                return;
        }

        /* Also don't send a timed log start offset request if leader
         * broker supports FETCH >= v5, since this will be set when
         * doing fetch requests.
         */
        if (rd_kafka_broker_ApiVersion_supported(
                rktp->rktp_broker, RD_KAFKAP_Fetch, 0, 5, NULL) == 5) {
                rd_kafka_toppar_unlock(rktp);
                return;
        }

        rktp->rktp_wait_consumer_lag_resp = 1;

        partitions = rd_kafka_topic_partition_list_new(1);
        rktpar     = rd_kafka_topic_partition_list_add(
            partitions, rktp->rktp_rkt->rkt_topic->str, rktp->rktp_partition);
        rktpar->offset = RD_KAFKA_OFFSET_BEGINNING;
        rd_kafka_topic_partition_set_current_leader_epoch(
            rktpar, rktp->rktp_leader_epoch);

        /* Ask for oldest offset. The newest offset is automatically
         * propagated in FetchResponse.HighwaterMark. */
        rd_kafka_ListOffsetsRequest(
            rktp->rktp_broker, partitions, RD_KAFKA_REPLYQ(rktp->rktp_ops, 0),
            rd_kafka_toppar_lag_handle_Offset, rd_kafka_toppar_keep(rktp));

        rd_kafka_toppar_unlock(rktp);

        rd_kafka_topic_partition_list_destroy(partitions);
}



/**
 * Request earliest offset for a partition
 *
 * Locality: toppar handler thread
 */
static void rd_kafka_toppar_consumer_lag_tmr_cb(rd_kafka_timers_t *rkts,
                                                void *arg) {
        rd_kafka_toppar_t *rktp = arg;
        rd_kafka_toppar_consumer_lag_req(rktp);
}

/**
 * @brief Update rktp_op_version.
 *        Enqueue an RD_KAFKA_OP_BARRIER type of operation
 *        when the op_version is updated.
 *
 * @locks_required rd_kafka_toppar_lock() must be held.
 * @locality Toppar handler thread
 */
void rd_kafka_toppar_op_version_bump(rd_kafka_toppar_t *rktp, int32_t version) {
        rd_kafka_op_t *rko;

        rktp->rktp_op_version = version;
        rko                   = rd_kafka_op_new(RD_KAFKA_OP_BARRIER);
        rko->rko_version      = version;
        rko->rko_prio         = RD_KAFKA_PRIO_FLASH;
        rko->rko_rktp         = rd_kafka_toppar_keep(rktp);
        rd_kafka_q_enq(rktp->rktp_fetchq, rko);
}


/**
 * Add new partition to topic.
 *
 * Locks: rd_kafka_topic_wrlock() must be held.
 * Locks: rd_kafka_wrlock() must be held.
 */
rd_kafka_toppar_t *rd_kafka_toppar_new0(rd_kafka_topic_t *rkt,
                                        int32_t partition,
                                        const char *func,
                                        int line) {
        rd_kafka_toppar_t *rktp;

        rktp = rd_calloc(1, sizeof(*rktp));

        rktp->rktp_partition    = partition;
        rktp->rktp_rkt          = rkt;
        rktp->rktp_leader_id    = -1;
        rktp->rktp_broker_id    = -1;
        rktp->rktp_leader_epoch = -1;
        rd_interval_init(&rktp->rktp_lease_intvl);
        rd_interval_init(&rktp->rktp_new_lease_intvl);
        rd_interval_init(&rktp->rktp_new_lease_log_intvl);
        rd_interval_init(&rktp->rktp_metadata_intvl);
        /* Mark partition as unknown (does not exist) until we see the
         * partition in topic metadata. */
        if (partition != RD_KAFKA_PARTITION_UA)
                rktp->rktp_flags |= RD_KAFKA_TOPPAR_F_UNKNOWN;
        rktp->rktp_fetch_state = RD_KAFKA_TOPPAR_FETCH_NONE;
        rktp->rktp_fetch_msg_max_bytes =
            rkt->rkt_rk->rk_conf.fetch_msg_max_bytes;
        rktp->rktp_offset_fp = NULL;
        rd_kafka_offset_stats_reset(&rktp->rktp_offsets);
        rd_kafka_offset_stats_reset(&rktp->rktp_offsets_fin);
        rktp->rktp_ls_offset = RD_KAFKA_OFFSET_INVALID;
        rktp->rktp_hi_offset = RD_KAFKA_OFFSET_INVALID;
        rktp->rktp_lo_offset = RD_KAFKA_OFFSET_INVALID;
        rd_kafka_fetch_pos_init(&rktp->rktp_query_pos);
        rd_kafka_fetch_pos_init(&rktp->rktp_next_fetch_start);
        rd_kafka_fetch_pos_init(&rktp->rktp_last_next_fetch_start);
        rd_kafka_fetch_pos_init(&rktp->rktp_app_pos);
        rd_kafka_fetch_pos_init(&rktp->rktp_stored_pos);
        rd_kafka_fetch_pos_init(&rktp->rktp_committing_pos);
        rd_kafka_fetch_pos_init(&rktp->rktp_committed_pos);
        rd_kafka_msgq_init(&rktp->rktp_msgq);
        rd_kafka_msgq_init(&rktp->rktp_xmit_msgq);
        mtx_init(&rktp->rktp_lock, mtx_plain);

        rd_refcnt_init(&rktp->rktp_refcnt, 0);
        rktp->rktp_fetchq          = rd_kafka_q_new(rkt->rkt_rk);
        rktp->rktp_ops             = rd_kafka_q_new(rkt->rkt_rk);
        rktp->rktp_ops->rkq_serve  = rd_kafka_toppar_op_serve;
        rktp->rktp_ops->rkq_opaque = rktp;
        rd_atomic32_init(&rktp->rktp_version, 1);
        rktp->rktp_op_version = rd_atomic32_get(&rktp->rktp_version);

        rd_atomic32_init(&rktp->rktp_msgs_inflight, 0);
        rd_kafka_pid_reset(&rktp->rktp_eos.pid);

        /* Consumer: If statistics is available we query the log start offset
         * of each partition.
         * Since the oldest offset only moves on log retention, we cap this
         * value on the low end to a reasonable value to avoid flooding
         * the brokers with OffsetRequests when our statistics interval is low.
         * FIXME: Use a global timer to collect offsets for all partitions
         * FIXME: This timer is superfulous for FETCH >= v5 because the log
         *        start offset is included in fetch responses.
         * */
        if (rktp->rktp_rkt->rkt_rk->rk_conf.stats_interval_ms > 0 &&
            rkt->rkt_rk->rk_type == RD_KAFKA_CONSUMER &&
            rktp->rktp_partition != RD_KAFKA_PARTITION_UA) {
                int intvl = rkt->rkt_rk->rk_conf.stats_interval_ms;
                if (intvl < 10 * 1000 /* 10s */)
                        intvl = 10 * 1000;
                rd_kafka_timer_start(
                    &rkt->rkt_rk->rk_timers, &rktp->rktp_consumer_lag_tmr,
                    intvl * 1000ll, rd_kafka_toppar_consumer_lag_tmr_cb, rktp);
        }

        rktp->rktp_rkt = rd_kafka_topic_keep(rkt);

        rd_kafka_q_fwd_set(rktp->rktp_ops, rkt->rkt_rk->rk_ops);
        rd_kafka_dbg(rkt->rkt_rk, TOPIC, "TOPPARNEW",
                     "NEW %s [%" PRId32 "] %p refcnt %p (at %s:%d)",
                     rkt->rkt_topic->str, rktp->rktp_partition, rktp,
                     &rktp->rktp_refcnt, func, line);

        return rd_kafka_toppar_keep(rktp);
}



/**
 * Removes a toppar from its duties, global lists, etc.
 *
 * Locks: rd_kafka_toppar_lock() MUST be held
 */
static void rd_kafka_toppar_remove(rd_kafka_toppar_t *rktp) {
        rd_kafka_dbg(rktp->rktp_rkt->rkt_rk, TOPIC, "TOPPARREMOVE",
                     "Removing toppar %s [%" PRId32 "] %p",
                     rktp->rktp_rkt->rkt_topic->str, rktp->rktp_partition,
                     rktp);

        rd_kafka_timer_stop(&rktp->rktp_rkt->rkt_rk->rk_timers,
                            &rktp->rktp_validate_tmr, 1 /*lock*/);
        rd_kafka_timer_stop(&rktp->rktp_rkt->rkt_rk->rk_timers,
                            &rktp->rktp_offset_query_tmr, 1 /*lock*/);
        rd_kafka_timer_stop(&rktp->rktp_rkt->rkt_rk->rk_timers,
                            &rktp->rktp_consumer_lag_tmr, 1 /*lock*/);

        rd_kafka_q_fwd_set(rktp->rktp_ops, NULL);
}


/**
 * Final destructor for partition.
 */
void rd_kafka_toppar_destroy_final(rd_kafka_toppar_t *rktp) {

        rd_kafka_toppar_remove(rktp);

        rd_kafka_dbg(rktp->rktp_rkt->rkt_rk, TOPIC, "DESTROY",
                     "%s [%" PRId32 "]: %p DESTROY_FINAL",
                     rktp->rktp_rkt->rkt_topic->str, rktp->rktp_partition,
                     rktp);

        /* Clear queues */
        rd_kafka_assert(rktp->rktp_rkt->rkt_rk,
                        rd_kafka_msgq_len(&rktp->rktp_xmit_msgq) == 0);
        rd_kafka_dr_msgq(rktp->rktp_rkt, &rktp->rktp_msgq,
                         RD_KAFKA_RESP_ERR__DESTROY);
        rd_kafka_q_destroy_owner(rktp->rktp_fetchq);
        rd_kafka_q_destroy_owner(rktp->rktp_ops);

        rd_kafka_replyq_destroy(&rktp->rktp_replyq);

        rd_kafka_topic_destroy0(rktp->rktp_rkt);

        mtx_destroy(&rktp->rktp_lock);

        if (rktp->rktp_leader)
                rd_kafka_broker_destroy(rktp->rktp_leader);

        rd_refcnt_destroy(&rktp->rktp_refcnt);

        rd_free(rktp);
}


/**
 * Set toppar fetching state.
 *
 * @locality any
 * @locks_required rd_kafka_toppar_lock() MUST be held.
 */
void rd_kafka_toppar_set_fetch_state(rd_kafka_toppar_t *rktp, int fetch_state) {
        rd_kafka_assert(NULL,
                        thrd_is_current(rktp->rktp_rkt->rkt_rk->rk_thread));

        if ((int)rktp->rktp_fetch_state == fetch_state)
                return;

        rd_kafka_dbg(
            rktp->rktp_rkt->rkt_rk, TOPIC, "PARTSTATE",
            "Partition %.*s [%" PRId32 "] changed fetch state %s -> %s",
            RD_KAFKAP_STR_PR(rktp->rktp_rkt->rkt_topic), rktp->rktp_partition,
            rd_kafka_fetch_states[rktp->rktp_fetch_state],
            rd_kafka_fetch_states[fetch_state]);

        rktp->rktp_fetch_state = fetch_state;

        if (fetch_state == RD_KAFKA_TOPPAR_FETCH_ACTIVE)
                rd_kafka_dbg(
                    rktp->rktp_rkt->rkt_rk, CONSUMER | RD_KAFKA_DBG_TOPIC,
                    "FETCH",
                    "Partition %.*s [%" PRId32 "] start fetching at %s",
                    RD_KAFKAP_STR_PR(rktp->rktp_rkt->rkt_topic),
                    rktp->rktp_partition,
                    rd_kafka_fetch_pos2str(rktp->rktp_next_fetch_start));
}


/**
 * Returns the appropriate toppar for a given rkt and partition.
 * The returned toppar has increased refcnt and must be unreffed by calling
 *  rd_kafka_toppar_destroy().
 * May return NULL.
 *
 * If 'ua_on_miss' is true the UA (unassigned) toppar is returned if
 * 'partition' was not known locally, else NULL is returned.
 *
 * Locks: Caller must hold rd_kafka_topic_*lock()
 */
rd_kafka_toppar_t *rd_kafka_toppar_get0(const char *func,
                                        int line,
                                        const rd_kafka_topic_t *rkt,
                                        int32_t partition,
                                        int ua_on_miss) {
        rd_kafka_toppar_t *rktp;

        if (partition >= 0 && partition < rkt->rkt_partition_cnt)
                rktp = rkt->rkt_p[partition];
        else if (partition == RD_KAFKA_PARTITION_UA || ua_on_miss)
                rktp = rkt->rkt_ua;
        else
                return NULL;

        if (rktp)
                return rd_kafka_toppar_keep_fl(func, line, rktp);

        return NULL;
}


/**
 * Same as rd_kafka_toppar_get() but no need for locking and
 * looks up the topic first.
 *
 * Locality: any
 * Locks: none
 */
rd_kafka_toppar_t *rd_kafka_toppar_get2(rd_kafka_t *rk,
                                        const char *topic,
                                        int32_t partition,
                                        int ua_on_miss,
                                        int create_on_miss) {
        rd_kafka_topic_t *rkt;
        rd_kafka_toppar_t *rktp;

        rd_kafka_wrlock(rk);

        /* Find or create topic */
        if (unlikely(!(rkt = rd_kafka_topic_find(rk, topic, 0 /*no-lock*/)))) {
                if (!create_on_miss) {
                        rd_kafka_wrunlock(rk);
                        return NULL;
                }
                rkt = rd_kafka_topic_new0(rk, topic, NULL, NULL, 0 /*no-lock*/);
                if (!rkt) {
                        rd_kafka_wrunlock(rk);
                        rd_kafka_log(rk, LOG_ERR, "TOPIC",
                                     "Failed to create local topic \"%s\": %s",
                                     topic, rd_strerror(errno));
                        return NULL;
                }
        }

        rd_kafka_wrunlock(rk);

        rd_kafka_topic_wrlock(rkt);
        rktp = rd_kafka_toppar_desired_add(rkt, partition);
        rd_kafka_topic_wrunlock(rkt);

        rd_kafka_topic_destroy0(rkt);

        return rktp;
}


/**
 * Returns a toppar if it is available in the cluster.
 * '*errp' is set to the error-code if lookup fails.
 *
 * Locks: topic_*lock() MUST be held
 */
rd_kafka_toppar_t *rd_kafka_toppar_get_avail(const rd_kafka_topic_t *rkt,
                                             int32_t partition,
                                             int ua_on_miss,
                                             rd_kafka_resp_err_t *errp) {
        rd_kafka_toppar_t *rktp;

        switch (rkt->rkt_state) {
        case RD_KAFKA_TOPIC_S_UNKNOWN:
                /* No metadata received from cluster yet.
                 * Put message in UA partition and re-run partitioner when
                 * cluster comes up. */
                partition = RD_KAFKA_PARTITION_UA;
                break;

        case RD_KAFKA_TOPIC_S_NOTEXISTS:
                /* Topic not found in cluster.
                 * Fail message immediately. */
                *errp = RD_KAFKA_RESP_ERR__UNKNOWN_TOPIC;
                return NULL;

        case RD_KAFKA_TOPIC_S_ERROR:
                /* Permanent topic error. */
                *errp = rkt->rkt_err;
                return NULL;

        case RD_KAFKA_TOPIC_S_EXISTS:
                /* Topic exists in cluster. */

                /* Topic exists but has no partitions.
                 * This is usually an transient state following the
                 * auto-creation of a topic. */
                if (unlikely(rkt->rkt_partition_cnt == 0)) {
                        partition = RD_KAFKA_PARTITION_UA;
                        break;
                }

                /* Check that partition exists. */
                if (partition >= rkt->rkt_partition_cnt) {
                        *errp = RD_KAFKA_RESP_ERR__UNKNOWN_PARTITION;
                        return NULL;
                }
                break;

        default:
                rd_kafka_assert(rkt->rkt_rk, !*"NOTREACHED");
                break;
        }

        /* Get new partition */
        rktp = rd_kafka_toppar_get(rkt, partition, 0);

        if (unlikely(!rktp)) {
                /* Unknown topic or partition */
                if (rkt->rkt_state == RD_KAFKA_TOPIC_S_NOTEXISTS)
                        *errp = RD_KAFKA_RESP_ERR__UNKNOWN_TOPIC;
                else
                        *errp = RD_KAFKA_RESP_ERR__UNKNOWN_PARTITION;

                return NULL;
        }

        return rktp;
}


/**
 * Looks for partition 'i' in topic 'rkt's desired list.
 *
 * The desired partition list is the list of partitions that are desired
 * (e.g., by the consumer) but not yet seen on a broker.
 * As soon as the partition is seen on a broker the toppar is moved from
 * the desired list and onto the normal rkt_p array.
 * When the partition on the broker goes away a desired partition is put
 * back on the desired list.
 *
 * Locks: rd_kafka_topic_*lock() must be held.
 * Note: 'rktp' refcount is increased.
 */

rd_kafka_toppar_t *rd_kafka_toppar_desired_get(rd_kafka_topic_t *rkt,
                                               int32_t partition) {
        rd_kafka_toppar_t *rktp;
        int i;

        RD_LIST_FOREACH(rktp, &rkt->rkt_desp, i) {
                if (rktp->rktp_partition == partition)
                        return rd_kafka_toppar_keep(rktp);
        }

        return NULL;
}


/**
 * Link toppar on desired list.
 *
 * Locks: rd_kafka_topic_wrlock() and toppar_lock() must be held.
 */
void rd_kafka_toppar_desired_link(rd_kafka_toppar_t *rktp) {

        if (rktp->rktp_flags & RD_KAFKA_TOPPAR_F_ON_DESP)
                return; /* Already linked */

        rd_kafka_toppar_keep(rktp);
        rd_list_add(&rktp->rktp_rkt->rkt_desp, rktp);
        rd_interval_reset(&rktp->rktp_rkt->rkt_desp_refresh_intvl);
        rktp->rktp_flags |= RD_KAFKA_TOPPAR_F_ON_DESP;
}

/**
 * Unlink toppar from desired list.
 *
 * Locks: rd_kafka_topic_wrlock() and toppar_lock() must be held.
 */
void rd_kafka_toppar_desired_unlink(rd_kafka_toppar_t *rktp) {
        if (!(rktp->rktp_flags & RD_KAFKA_TOPPAR_F_ON_DESP))
                return; /* Not linked */

        rktp->rktp_flags &= ~RD_KAFKA_TOPPAR_F_ON_DESP;
        rd_list_remove(&rktp->rktp_rkt->rkt_desp, rktp);
        rd_interval_reset(&rktp->rktp_rkt->rkt_desp_refresh_intvl);
        rd_kafka_toppar_destroy(rktp);
}


/**
 * @brief If rktp is not already desired:
 *  - mark as DESIRED|~REMOVE
 *  - add to desired list if unknown
 *
 * @remark toppar_lock() MUST be held
 */
void rd_kafka_toppar_desired_add0(rd_kafka_toppar_t *rktp) {
        if ((rktp->rktp_flags & RD_KAFKA_TOPPAR_F_DESIRED))
                return;

        rd_kafka_dbg(rktp->rktp_rkt->rkt_rk, TOPIC, "DESIRED",
                     "%s [%" PRId32 "]: marking as DESIRED",
                     rktp->rktp_rkt->rkt_topic->str, rktp->rktp_partition);

        /* If toppar was marked for removal this is no longer
         * the case since the partition is now desired. */
        rktp->rktp_flags &= ~RD_KAFKA_TOPPAR_F_REMOVE;

        rktp->rktp_flags |= RD_KAFKA_TOPPAR_F_DESIRED;

        if (rktp->rktp_flags & RD_KAFKA_TOPPAR_F_UNKNOWN) {
                rd_kafka_dbg(rktp->rktp_rkt->rkt_rk, TOPIC, "DESIRED",
                             "%s [%" PRId32 "]: adding to DESIRED list",
                             rktp->rktp_rkt->rkt_topic->str,
                             rktp->rktp_partition);
                rd_kafka_toppar_desired_link(rktp);
        }
}


/**
 * Adds 'partition' as a desired partition to topic 'rkt', or updates
 * an existing partition to be desired.
 *
 * Locks: rd_kafka_topic_wrlock() must be held.
 */
rd_kafka_toppar_t *rd_kafka_toppar_desired_add(rd_kafka_topic_t *rkt,
                                               int32_t partition) {
        rd_kafka_toppar_t *rktp;

        rktp = rd_kafka_toppar_get(rkt, partition, 0 /*no_ua_on_miss*/);

        if (!rktp)
                rktp = rd_kafka_toppar_desired_get(rkt, partition);

        if (!rktp)
                rktp = rd_kafka_toppar_new(rkt, partition);

        rd_kafka_toppar_lock(rktp);
        rd_kafka_toppar_desired_add0(rktp);
        rd_kafka_toppar_unlock(rktp);

        return rktp; /* Callers refcount */
}



/**
 * Unmarks an 'rktp' as desired.
 *
 * Locks: rd_kafka_topic_wrlock() and rd_kafka_toppar_lock() MUST be held.
 */
void rd_kafka_toppar_desired_del(rd_kafka_toppar_t *rktp) {

        if (!(rktp->rktp_flags & RD_KAFKA_TOPPAR_F_DESIRED))
                return;

        rktp->rktp_flags &= ~RD_KAFKA_TOPPAR_F_DESIRED;
        rd_kafka_toppar_desired_unlink(rktp);

        rd_kafka_dbg(rktp->rktp_rkt->rkt_rk, TOPIC, "DESP",
                     "Removing (un)desired topic %s [%" PRId32 "]",
                     rktp->rktp_rkt->rkt_topic->str, rktp->rktp_partition);

        if (rktp->rktp_flags & RD_KAFKA_TOPPAR_F_UNKNOWN) {
                /* If this partition does not exist in the cluster
                 * and is no longer desired, remove it. */
                rd_kafka_toppar_broker_leave_for_remove(rktp);
        }
}



/**
 * Append message at tail of 'rktp' message queue.
 */
void rd_kafka_toppar_enq_msg(rd_kafka_toppar_t *rktp,
                             rd_kafka_msg_t *rkm,
                             rd_ts_t now) {
        rd_kafka_q_t *wakeup_q = NULL;

        rd_kafka_toppar_lock(rktp);

        if (!rkm->rkm_u.producer.msgid &&
            rktp->rktp_partition != RD_KAFKA_PARTITION_UA)
                rkm->rkm_u.producer.msgid = ++rktp->rktp_msgid;

        if (rktp->rktp_partition == RD_KAFKA_PARTITION_UA ||
            rktp->rktp_rkt->rkt_conf.queuing_strategy == RD_KAFKA_QUEUE_FIFO) {
                /* No need for enq_sorted(), this is the oldest message. */
                rd_kafka_msgq_enq(&rktp->rktp_msgq, rkm);
        } else {
                rd_kafka_msgq_enq_sorted(rktp->rktp_rkt, &rktp->rktp_msgq, rkm);
        }

        if (unlikely(rktp->rktp_partition != RD_KAFKA_PARTITION_UA &&
                     rd_kafka_msgq_may_wakeup(&rktp->rktp_msgq, now) &&
                     (wakeup_q = rktp->rktp_msgq_wakeup_q))) {
                /* Wake-up broker thread */
                rktp->rktp_msgq.rkmq_wakeup.signalled = rd_true;
                rd_kafka_q_keep(wakeup_q);
        }

        rd_kafka_toppar_unlock(rktp);

        if (unlikely(wakeup_q != NULL)) {
                rd_kafka_q_yield(wakeup_q);
                rd_kafka_q_destroy(wakeup_q);
        }
}


/**
 * @brief Insert \p srcq before \p insert_before in \p destq.
 *
 * If \p srcq and \p destq overlaps only part of the \p srcq will be inserted.
 *
 * Upon return \p srcq will contain any remaining messages that require
 * another insert position in \p destq.
 */
static void rd_kafka_msgq_insert_msgq_before(rd_kafka_msgq_t *destq,
                                             rd_kafka_msg_t *insert_before,
                                             rd_kafka_msgq_t *srcq,
                                             int (*cmp)(const void *a,
                                                        const void *b)) {
        rd_kafka_msg_t *slast;
        rd_kafka_msgq_t tmpq;

        if (!insert_before) {
                /* Append all of srcq to destq */
                rd_kafka_msgq_concat(destq, srcq);
                rd_kafka_msgq_verify_order(NULL, destq, 0, rd_false);
                return;
        }

        slast = rd_kafka_msgq_last(srcq);
        rd_dassert(slast);

        if (cmp(slast, insert_before) > 0) {
                rd_kafka_msg_t *new_sfirst;
                int cnt;
                int64_t bytes;

                /* destq insert_before resides somewhere between
                 * srcq.first and srcq.last, find the first message in
                 * srcq that is > insert_before and split srcq into
                 * a left part that contains the messages to insert before
                 * insert_before, and a right part that will need another
                 * insert position. */

                new_sfirst = rd_kafka_msgq_find_pos(srcq, NULL, insert_before,
                                                    cmp, &cnt, &bytes);
                rd_assert(new_sfirst);

                /* split srcq into two parts using the divider message */
                rd_kafka_msgq_split(srcq, &tmpq, new_sfirst, cnt, bytes);

                rd_kafka_msgq_verify_order(NULL, srcq, 0, rd_false);
                rd_kafka_msgq_verify_order(NULL, &tmpq, 0, rd_false);
        } else {
                rd_kafka_msgq_init(&tmpq);
        }

        /* srcq now contains messages up to the first message in destq,
         * insert srcq at insert_before in destq. */
        rd_dassert(!TAILQ_EMPTY(&destq->rkmq_msgs));
        rd_dassert(!TAILQ_EMPTY(&srcq->rkmq_msgs));
        TAILQ_INSERT_LIST_BEFORE(&destq->rkmq_msgs, insert_before,
                                 &srcq->rkmq_msgs, rd_kafka_msgs_head_s,
                                 rd_kafka_msg_t *, rkm_link);
        destq->rkmq_msg_cnt += srcq->rkmq_msg_cnt;
        destq->rkmq_msg_bytes += srcq->rkmq_msg_bytes;
        srcq->rkmq_msg_cnt   = 0;
        srcq->rkmq_msg_bytes = 0;

        rd_kafka_msgq_verify_order(NULL, destq, 0, rd_false);
        rd_kafka_msgq_verify_order(NULL, srcq, 0, rd_false);

        /* tmpq contains the remaining messages in srcq, move it over. */
        rd_kafka_msgq_move(srcq, &tmpq);

        rd_kafka_msgq_verify_order(NULL, srcq, 0, rd_false);
}


/**
 * @brief Insert all messages from \p srcq into \p destq in their sorted
 *        position (using \p cmp)
 */
void rd_kafka_msgq_insert_msgq(rd_kafka_msgq_t *destq,
                               rd_kafka_msgq_t *srcq,
                               int (*cmp)(const void *a, const void *b)) {
        rd_kafka_msg_t *sfirst, *dlast, *start_pos = NULL;

        if (unlikely(RD_KAFKA_MSGQ_EMPTY(srcq))) {
                /* srcq is empty */
                return;
        }

        if (unlikely(RD_KAFKA_MSGQ_EMPTY(destq))) {
                /* destq is empty, simply move the srcq. */
                rd_kafka_msgq_move(destq, srcq);
                rd_kafka_msgq_verify_order(NULL, destq, 0, rd_false);
                return;
        }

        /* Optimize insertion by bulk-moving messages in place.
         * We know that:
         *  - destq is sorted but might not be continous (1,2,3,7)
         *  - srcq is sorted but might not be continous (4,5,6,8)
         *  - there migt be (multiple) overlaps between the two, e.g:
         *     destq = (1,2,3,7), srcq = (4,5,6,8)
         *  - there may be millions of messages.
         */

        rd_kafka_msgq_verify_order(NULL, destq, 0, rd_false);
        rd_kafka_msgq_verify_order(NULL, srcq, 0, rd_false);

        dlast  = rd_kafka_msgq_last(destq);
        sfirst = rd_kafka_msgq_first(srcq);

        /* Most common case, all of srcq goes after destq */
        if (likely(cmp(dlast, sfirst) < 0)) {
                rd_kafka_msgq_concat(destq, srcq);

                rd_kafka_msgq_verify_order(NULL, destq, 0, rd_false);

                rd_assert(RD_KAFKA_MSGQ_EMPTY(srcq));
                return;
        }

        /* Insert messages from srcq into destq in non-overlapping
         * chunks until srcq is exhausted. */
        while (likely(sfirst != NULL)) {
                rd_kafka_msg_t *insert_before;

                /* Get insert position in destq of first element in srcq */
                insert_before = rd_kafka_msgq_find_pos(destq, start_pos, sfirst,
                                                       cmp, NULL, NULL);

                /* Insert as much of srcq as possible at insert_before */
                rd_kafka_msgq_insert_msgq_before(destq, insert_before, srcq,
                                                 cmp);

                /* Remember the current destq position so the next find_pos()
                 * does not have to re-scan destq and what was
                 * added from srcq. */
                start_pos = insert_before;

                /* For next iteration */
                sfirst = rd_kafka_msgq_first(srcq);

                rd_kafka_msgq_verify_order(NULL, destq, 0, rd_false);
                rd_kafka_msgq_verify_order(NULL, srcq, 0, rd_false);
        }

        rd_kafka_msgq_verify_order(NULL, destq, 0, rd_false);

        rd_assert(RD_KAFKA_MSGQ_EMPTY(srcq));
}


/**
 * @brief Inserts messages from \p srcq according to their sorted position
 *        into \p destq, filtering out messages that can not be retried.
 *
 * @param incr_retry Increment retry count for messages.
 * @param max_retries Maximum retries allowed per message.
 * @param backoff Absolute retry backoff for retried messages.
 *
 * @returns 0 if all messages were retried, or 1 if some messages
 *          could not be retried.
 */
int rd_kafka_retry_msgq(rd_kafka_msgq_t *destq,
                        rd_kafka_msgq_t *srcq,
                        int incr_retry,
                        int max_retries,
                        rd_ts_t backoff,
                        rd_kafka_msg_status_t status,
                        int (*cmp)(const void *a, const void *b)) {
        rd_kafka_msgq_t retryable = RD_KAFKA_MSGQ_INITIALIZER(retryable);
        rd_kafka_msg_t *rkm, *tmp;

        /* Scan through messages to see which ones are eligible for retry,
         * move the retryable ones to temporary queue and
         * set backoff time for first message and optionally
         * increase retry count for each message.
         * Sorted insert is not necessary since the original order
         * srcq order is maintained. */
        TAILQ_FOREACH_SAFE(rkm, &srcq->rkmq_msgs, rkm_link, tmp) {
                if (rkm->rkm_u.producer.retries + incr_retry > max_retries)
                        continue;

                rd_kafka_msgq_deq(srcq, rkm, 1);
                rd_kafka_msgq_enq(&retryable, rkm);

                rkm->rkm_u.producer.ts_backoff = backoff;
                rkm->rkm_u.producer.retries += incr_retry;

                /* Don't downgrade a message from any form of PERSISTED
                 * to NOT_PERSISTED, since the original cause of indicating
                 * PERSISTED can't be changed.
                 * E.g., a previous ack or in-flight timeout. */
                if (likely(!(status == RD_KAFKA_MSG_STATUS_NOT_PERSISTED &&
                             rkm->rkm_status !=
                                 RD_KAFKA_MSG_STATUS_NOT_PERSISTED)))
                        rkm->rkm_status = status;
        }

        /* No messages are retryable */
        if (RD_KAFKA_MSGQ_EMPTY(&retryable))
                return 0;

        /* Insert retryable list at sorted position */
        rd_kafka_msgq_insert_msgq(destq, &retryable, cmp);

        return 1;
}

/**
 * @brief Inserts messages from \p rkmq according to their sorted position
 *        into the partition's message queue.
 *
 * @param incr_retry Increment retry count for messages.
 * @param status Set status on each message.
 *
 * @returns 0 if all messages were retried, or 1 if some messages
 *          could not be retried.
 *
 * @locality Broker thread (but not necessarily the leader broker thread)
 */

int rd_kafka_toppar_retry_msgq(rd_kafka_toppar_t *rktp,
                               rd_kafka_msgq_t *rkmq,
                               int incr_retry,
                               rd_kafka_msg_status_t status) {
        rd_kafka_t *rk  = rktp->rktp_rkt->rkt_rk;
        rd_ts_t backoff = rd_clock() + (rk->rk_conf.retry_backoff_ms * 1000);
        int r;

        if (rd_kafka_terminating(rk))
                return 1;

        rd_kafka_toppar_lock(rktp);
        r = rd_kafka_retry_msgq(&rktp->rktp_msgq, rkmq, incr_retry,
                                rk->rk_conf.max_retries, backoff, status,
                                rktp->rktp_rkt->rkt_conf.msg_order_cmp);
        rd_kafka_toppar_unlock(rktp);

        return r;
}

/**
 * @brief Insert sorted message list \p rkmq at sorted position in \p rktp 's
 *        message queue. The queues must not overlap.
 * @remark \p rkmq will be cleared.
 */
void rd_kafka_toppar_insert_msgq(rd_kafka_toppar_t *rktp,
                                 rd_kafka_msgq_t *rkmq) {
        rd_kafka_toppar_lock(rktp);
        rd_kafka_msgq_insert_msgq(&rktp->rktp_msgq, rkmq,
                                  rktp->rktp_rkt->rkt_conf.msg_order_cmp);
        rd_kafka_toppar_unlock(rktp);
}



/**
 * Helper method for purging queues when removing a toppar.
 * Locks: rd_kafka_toppar_lock() MUST be held
 */
void rd_kafka_toppar_purge_and_disable_queues(rd_kafka_toppar_t *rktp) {
        rd_kafka_q_disable(rktp->rktp_fetchq);
        rd_kafka_q_purge(rktp->rktp_fetchq);
        rd_kafka_q_disable(rktp->rktp_ops);
        rd_kafka_q_purge(rktp->rktp_ops);
}


/**
 * @brief Migrate rktp from (optional) \p old_rkb to (optional) \p new_rkb,
 *        but at least one is required to be non-NULL.
 *
 * This is an async operation.
 *
 * @locks rd_kafka_toppar_lock() MUST be held
 */
static void rd_kafka_toppar_broker_migrate(rd_kafka_toppar_t *rktp,
                                           rd_kafka_broker_t *old_rkb,
                                           rd_kafka_broker_t *new_rkb) {
        rd_kafka_op_t *rko;
        rd_kafka_broker_t *dest_rkb;
        int had_next_broker = rktp->rktp_next_broker ? 1 : 0;

        rd_assert(old_rkb || new_rkb);

        /* Update next broker */
        if (new_rkb)
                rd_kafka_broker_keep(new_rkb);
        if (rktp->rktp_next_broker)
                rd_kafka_broker_destroy(rktp->rktp_next_broker);
        rktp->rktp_next_broker = new_rkb;

        /* If next_broker is set it means there is already an async
         * migration op going on and we should not send a new one
         * but simply change the next_broker (which we did above). */
        if (had_next_broker)
                return;

        /* Revert from offset-wait state back to offset-query
         * prior to leaving the broker to avoid stalling
         * on the new broker waiting for a offset reply from
         * this old broker (that might not come and thus need
         * to time out..slowly) */
        if (rktp->rktp_fetch_state == RD_KAFKA_TOPPAR_FETCH_OFFSET_WAIT)
                rd_kafka_toppar_offset_retry(rktp, 500,
                                             "migrating to new broker");

        if (old_rkb) {
                /* If there is an existing broker for this toppar we let it
                 * first handle its own leave and then trigger the join for
                 * the next broker, if any. */
                rko      = rd_kafka_op_new(RD_KAFKA_OP_PARTITION_LEAVE);
                dest_rkb = old_rkb;
        } else {
                /* No existing broker, send join op directly to new broker. */
                rko      = rd_kafka_op_new(RD_KAFKA_OP_PARTITION_JOIN);
                dest_rkb = new_rkb;
        }

        rko->rko_rktp = rd_kafka_toppar_keep(rktp);

        rd_kafka_dbg(
            rktp->rktp_rkt->rkt_rk, TOPIC, "BRKMIGR",
            "Migrating topic %.*s [%" PRId32
            "] %p from %s to %s "
            "(sending %s to %s)",
            RD_KAFKAP_STR_PR(rktp->rktp_rkt->rkt_topic), rktp->rktp_partition,
            rktp, old_rkb ? rd_kafka_broker_name(old_rkb) : "(none)",
            new_rkb ? rd_kafka_broker_name(new_rkb) : "(none)",
            rd_kafka_op2str(rko->rko_type), rd_kafka_broker_name(dest_rkb));

        rd_kafka_q_enq(dest_rkb->rkb_ops, rko);
}


/**
 * Async toppar leave from broker.
 * Only use this when partitions are to be removed.
 *
 * Locks: rd_kafka_toppar_lock() MUST be held
 */
void rd_kafka_toppar_broker_leave_for_remove(rd_kafka_toppar_t *rktp) {
        rd_kafka_op_t *rko;
        rd_kafka_broker_t *dest_rkb;

        rktp->rktp_flags |= RD_KAFKA_TOPPAR_F_REMOVE;

        if (rktp->rktp_next_broker)
                dest_rkb = rktp->rktp_next_broker;
        else if (rktp->rktp_broker)
                dest_rkb = rktp->rktp_broker;
        else {
                rd_kafka_dbg(rktp->rktp_rkt->rkt_rk, TOPIC, "TOPPARDEL",
                             "%.*s [%" PRId32
                             "] %p not handled by any broker: "
                             "not sending LEAVE for remove",
                             RD_KAFKAP_STR_PR(rktp->rktp_rkt->rkt_topic),
                             rktp->rktp_partition, rktp);
                return;
        }


        /* Revert from offset-wait state back to offset-query
         * prior to leaving the broker to avoid stalling
         * on the new broker waiting for a offset reply from
         * this old broker (that might not come and thus need
         * to time out..slowly) */
        if (rktp->rktp_fetch_state == RD_KAFKA_TOPPAR_FETCH_OFFSET_WAIT)
                rd_kafka_toppar_set_fetch_state(
                    rktp, RD_KAFKA_TOPPAR_FETCH_OFFSET_QUERY);

        rko           = rd_kafka_op_new(RD_KAFKA_OP_PARTITION_LEAVE);
        rko->rko_rktp = rd_kafka_toppar_keep(rktp);

        rd_kafka_dbg(
            rktp->rktp_rkt->rkt_rk, TOPIC, "BRKMIGR",
            "%.*s [%" PRId32 "] %p sending final LEAVE for removal by %s",
            RD_KAFKAP_STR_PR(rktp->rktp_rkt->rkt_topic), rktp->rktp_partition,
            rktp, rd_kafka_broker_name(dest_rkb));

        rd_kafka_q_enq(dest_rkb->rkb_ops, rko);
}


/**
 * @brief Delegates toppar 'rktp' to broker 'rkb'. 'rkb' may be NULL to
 *        undelegate broker.
 *
 * @locks Caller must have rd_kafka_toppar_lock(rktp) held.
 */
void rd_kafka_toppar_broker_delegate(rd_kafka_toppar_t *rktp,
                                     rd_kafka_broker_t *rkb) {
        rd_kafka_t *rk        = rktp->rktp_rkt->rkt_rk;
        int internal_fallback = 0;

        rd_kafka_dbg(rktp->rktp_rkt->rkt_rk, TOPIC, "BRKDELGT",
                     "%s [%" PRId32
                     "]: delegate to broker %s "
                     "(rktp %p, term %d, ref %d)",
                     rktp->rktp_rkt->rkt_topic->str, rktp->rktp_partition,
                     rkb ? rkb->rkb_name : "(none)", rktp,
                     rd_kafka_terminating(rk),
                     rd_refcnt_get(&rktp->rktp_refcnt));

        /* Undelegated toppars are delgated to the internal
         * broker for bookkeeping. */
        if (!rkb && !rd_kafka_terminating(rk)) {
                rkb               = rd_kafka_broker_internal(rk);
                internal_fallback = 1;
        }

        if (rktp->rktp_broker == rkb && !rktp->rktp_next_broker) {
                rd_kafka_dbg(rktp->rktp_rkt->rkt_rk, TOPIC, "BRKDELGT",
                             "%.*s [%" PRId32
                             "]: not updating broker: "
                             "already on correct broker %s",
                             RD_KAFKAP_STR_PR(rktp->rktp_rkt->rkt_topic),
                             rktp->rktp_partition,
                             rkb ? rd_kafka_broker_name(rkb) : "(none)");

                if (internal_fallback)
                        rd_kafka_broker_destroy(rkb);
                return;
        }

        if (rktp->rktp_broker)
                rd_kafka_dbg(rktp->rktp_rkt->rkt_rk, TOPIC, "BRKDELGT",
                             "%.*s [%" PRId32
                             "]: no longer delegated to "
                             "broker %s",
                             RD_KAFKAP_STR_PR(rktp->rktp_rkt->rkt_topic),
                             rktp->rktp_partition,
                             rd_kafka_broker_name(rktp->rktp_broker));


        if (rkb) {
                rd_kafka_dbg(rktp->rktp_rkt->rkt_rk, TOPIC, "BRKDELGT",
                             "%.*s [%" PRId32
                             "]: delegating to broker %s "
                             "for partition with %i messages "
                             "(%" PRIu64 " bytes) queued",
                             RD_KAFKAP_STR_PR(rktp->rktp_rkt->rkt_topic),
                             rktp->rktp_partition, rd_kafka_broker_name(rkb),
                             rktp->rktp_msgq.rkmq_msg_cnt,
                             rktp->rktp_msgq.rkmq_msg_bytes);


        } else {
                rd_kafka_dbg(rktp->rktp_rkt->rkt_rk, TOPIC, "BRKDELGT",
                             "%.*s [%" PRId32 "]: no broker delegated",
                             RD_KAFKAP_STR_PR(rktp->rktp_rkt->rkt_topic),
                             rktp->rktp_partition);
        }

        if (rktp->rktp_broker || rkb)
                rd_kafka_toppar_broker_migrate(rktp, rktp->rktp_broker, rkb);

        if (internal_fallback)
                rd_kafka_broker_destroy(rkb);
}



void rd_kafka_toppar_offset_commit_result(
    rd_kafka_toppar_t *rktp,
    rd_kafka_resp_err_t err,
    rd_kafka_topic_partition_list_t *offsets) {
        if (err)
                rd_kafka_consumer_err(
                    rktp->rktp_fetchq,
                    /* FIXME: propagate broker_id */
                    RD_KAFKA_NODEID_UA, err, 0 /* FIXME:VERSION*/, NULL, rktp,
                    RD_KAFKA_OFFSET_INVALID, "Offset commit failed: %s",
                    rd_kafka_err2str(err));

        rd_kafka_toppar_lock(rktp);
        if (!err)
                rktp->rktp_committed_pos =
                    rd_kafka_topic_partition_get_fetch_pos(&offsets->elems[0]);

        /* When stopping toppars:
         * Final commit is now done (or failed), propagate. */
        if (rktp->rktp_fetch_state == RD_KAFKA_TOPPAR_FETCH_STOPPING)
                rd_kafka_toppar_fetch_stopped(rktp, err);

        rd_kafka_toppar_unlock(rktp);
}



/**
 * Handle the next offset to consume for a toppar.
 * This is used during initial setup when trying to figure out what
 * offset to start consuming from.
 *
 * Locality: toppar handler thread.
 * Locks: toppar_lock(rktp) must be held
 */
void rd_kafka_toppar_next_offset_handle(rd_kafka_toppar_t *rktp,
                                        rd_kafka_fetch_pos_t next_pos) {

        if (RD_KAFKA_OFFSET_IS_LOGICAL(next_pos.offset)) {
                /* Offset storage returned logical offset (e.g. "end"),
                 * look it up. */

                /* Save next offset, even if logical, so that e.g.,
                 * assign(BEGINNING) survives a pause+resume, etc.
                 * See issue #2105. */
                rd_kafka_toppar_set_next_fetch_position(rktp, next_pos);

                rd_kafka_offset_reset(rktp, RD_KAFKA_NODEID_UA, next_pos,
                                      RD_KAFKA_RESP_ERR_NO_ERROR, "update");
                return;
        }

        /* Adjust by TAIL count if, if wanted */
        if (rktp->rktp_query_pos.offset <= RD_KAFKA_OFFSET_TAIL_BASE) {
                int64_t orig_offset = next_pos.offset;
                int64_t tail_cnt    = llabs(rktp->rktp_query_pos.offset -
                                         RD_KAFKA_OFFSET_TAIL_BASE);

                if (tail_cnt > next_pos.offset)
                        next_pos.offset = 0;
                else
                        next_pos.offset -= tail_cnt;

                rd_kafka_dbg(rktp->rktp_rkt->rkt_rk, TOPIC, "OFFSET",
                             "OffsetReply for topic %s [%" PRId32
                             "]: "
                             "offset %" PRId64
                             ": adjusting for "
                             "OFFSET_TAIL(%" PRId64 "): effective %s",
                             rktp->rktp_rkt->rkt_topic->str,
                             rktp->rktp_partition, orig_offset, tail_cnt,
                             rd_kafka_fetch_pos2str(next_pos));
        }

        rd_kafka_toppar_set_next_fetch_position(rktp, next_pos);

        rd_kafka_toppar_set_fetch_state(rktp, RD_KAFKA_TOPPAR_FETCH_ACTIVE);

        /* Wake-up broker thread which might be idling on IO */
        if (rktp->rktp_broker)
                rd_kafka_broker_wakeup(rktp->rktp_broker, "ready to fetch");
}



/**
 * Fetch committed offset for a single partition. (simple consumer)
 *
 * Locality: toppar thread
 */
void rd_kafka_toppar_offset_fetch(rd_kafka_toppar_t *rktp,
                                  rd_kafka_replyq_t replyq) {
        rd_kafka_t *rk = rktp->rktp_rkt->rkt_rk;
        rd_kafka_topic_partition_list_t *part;
        rd_kafka_op_t *rko;

        rd_kafka_dbg(rk, TOPIC, "OFFSETREQ",
                     "Partition %.*s [%" PRId32
                     "]: querying cgrp for "
                     "committed offset (opv %d)",
                     RD_KAFKAP_STR_PR(rktp->rktp_rkt->rkt_topic),
                     rktp->rktp_partition, replyq.version);

        part = rd_kafka_topic_partition_list_new(1);
        rd_kafka_topic_partition_list_add0(__FUNCTION__, __LINE__, part,
                                           rktp->rktp_rkt->rkt_topic->str,
                                           rktp->rktp_partition, rktp, NULL);

        rko             = rd_kafka_op_new(RD_KAFKA_OP_OFFSET_FETCH);
        rko->rko_rktp   = rd_kafka_toppar_keep(rktp);
        rko->rko_replyq = replyq;

        rko->rko_u.offset_fetch.partitions = part;
        rko->rko_u.offset_fetch.require_stable_offsets =
            rk->rk_conf.isolation_level == RD_KAFKA_READ_COMMITTED;
        rko->rko_u.offset_fetch.do_free = 1;

        rd_kafka_q_enq(rktp->rktp_cgrp->rkcg_ops, rko);
}



/**
 * Toppar based OffsetResponse handling.
 * This is used for finding the next offset to Fetch.
 *
 * Locality: toppar handler thread
 */
static void rd_kafka_toppar_handle_Offset(rd_kafka_t *rk,
                                          rd_kafka_broker_t *rkb,
                                          rd_kafka_resp_err_t err,
                                          rd_kafka_buf_t *rkbuf,
                                          rd_kafka_buf_t *request,
                                          void *opaque) {
        rd_kafka_toppar_t *rktp = opaque;
        rd_kafka_topic_partition_list_t *offsets;
        rd_kafka_topic_partition_t *rktpar;
        int actions = 0;

        rd_kafka_toppar_lock(rktp);
        /* Drop reply from previous partition leader */
        if (err != RD_KAFKA_RESP_ERR__DESTROY && rktp->rktp_broker != rkb)
                err = RD_KAFKA_RESP_ERR__OUTDATED;
        rd_kafka_toppar_unlock(rktp);

        offsets = rd_kafka_topic_partition_list_new(1);

        rd_rkb_dbg(rkb, TOPIC, "OFFSET",
                   "Offset reply for "
                   "topic %.*s [%" PRId32 "] (v%d vs v%d)",
                   RD_KAFKAP_STR_PR(rktp->rktp_rkt->rkt_topic),
                   rktp->rktp_partition, request->rkbuf_replyq.version,
                   rktp->rktp_op_version);

        rd_dassert(request->rkbuf_replyq.version > 0);
        if (err != RD_KAFKA_RESP_ERR__DESTROY &&
            rd_kafka_buf_version_outdated(request, rktp->rktp_op_version)) {
                /* Outdated request response, ignore. */
                err = RD_KAFKA_RESP_ERR__OUTDATED;
        }

        /* Parse and return Offset */
        if (err != RD_KAFKA_RESP_ERR__OUTDATED)
                err = rd_kafka_handle_ListOffsets(rk, rkb, err, rkbuf, request,
                                                  offsets, &actions);

        if (!err && !(rktpar = rd_kafka_topic_partition_list_find(
                          offsets, rktp->rktp_rkt->rkt_topic->str,
                          rktp->rktp_partition))) {
                /* Requested partition not found in response */
                err = RD_KAFKA_RESP_ERR__UNKNOWN_PARTITION;
                actions |= RD_KAFKA_ERR_ACTION_PERMANENT;
        }

        if (err) {
                rd_rkb_dbg(rkb, TOPIC, "OFFSET",
                           "Offset reply error for "
                           "topic %.*s [%" PRId32 "] (v%d, %s): %s",
                           RD_KAFKAP_STR_PR(rktp->rktp_rkt->rkt_topic),
                           rktp->rktp_partition, request->rkbuf_replyq.version,
                           rd_kafka_err2str(err),
                           rd_kafka_actions2str(actions));

                rd_kafka_topic_partition_list_destroy(offsets);

                if (err == RD_KAFKA_RESP_ERR__DESTROY ||
                    err == RD_KAFKA_RESP_ERR__OUTDATED) {
                        /* Termination or outdated, quick cleanup. */

                        if (err == RD_KAFKA_RESP_ERR__OUTDATED) {
                                rd_kafka_toppar_lock(rktp);
                                rd_kafka_toppar_offset_retry(
                                    rktp, 500, "outdated offset response");
                                rd_kafka_toppar_unlock(rktp);
                        }

                        /* from request.opaque */
                        rd_kafka_toppar_destroy(rktp);
                        return;

                } else if (err == RD_KAFKA_RESP_ERR__IN_PROGRESS)
                        return; /* Retry in progress */


                rd_kafka_toppar_lock(rktp);

                if (!(actions & (RD_KAFKA_ERR_ACTION_RETRY |
                                 RD_KAFKA_ERR_ACTION_REFRESH))) {
                        /* Permanent error. Trigger auto.offset.reset policy
                         * and signal error back to application. */

                        rd_kafka_offset_reset(rktp, rkb->rkb_nodeid,
                                              rktp->rktp_query_pos, err,
                                              "failed to query logical offset");

                        rd_kafka_consumer_err(
                            rktp->rktp_fetchq, rkb->rkb_nodeid, err, 0, NULL,
                            rktp,
                            (rktp->rktp_query_pos.offset <=
                                     RD_KAFKA_OFFSET_TAIL_BASE
                                 ? rktp->rktp_query_pos.offset -
                                       RD_KAFKA_OFFSET_TAIL_BASE
                                 : rktp->rktp_query_pos.offset),
                            "Failed to query logical offset %s: %s",
                            rd_kafka_offset2str(rktp->rktp_query_pos.offset),
                            rd_kafka_err2str(err));

                } else {
                        /* Temporary error. Schedule retry. */
                        char tmp[256];

                        rd_snprintf(
                            tmp, sizeof(tmp),
                            "failed to query logical offset %s: %s",
                            rd_kafka_offset2str(rktp->rktp_query_pos.offset),
                            rd_kafka_err2str(err));

                        rd_kafka_toppar_offset_retry(rktp, 500, tmp);
                }

                rd_kafka_toppar_unlock(rktp);

                rd_kafka_toppar_destroy(rktp); /* from request.opaque */
                return;
        }


        rd_kafka_toppar_lock(rktp);
        rd_kafka_dbg(rktp->rktp_rkt->rkt_rk, TOPIC, "OFFSET",
                     "Offset %s request for %.*s [%" PRId32
                     "] "
                     "returned offset %s (%" PRId64 ") leader epoch %" PRId32,
                     rd_kafka_offset2str(rktp->rktp_query_pos.offset),
                     RD_KAFKAP_STR_PR(rktp->rktp_rkt->rkt_topic),
                     rktp->rktp_partition, rd_kafka_offset2str(rktpar->offset),
                     rktpar->offset,
                     rd_kafka_topic_partition_get_leader_epoch(rktpar));


        rd_kafka_toppar_next_offset_handle(
            rktp, RD_KAFKA_FETCH_POS(
                      rktpar->offset,
                      rd_kafka_topic_partition_get_leader_epoch(rktpar)));
        rd_kafka_toppar_unlock(rktp);

        rd_kafka_topic_partition_list_destroy(offsets);

        rd_kafka_toppar_destroy(rktp); /* from request.opaque */
}


/**
 * @brief An Offset fetch failed (for whatever reason) in
 *        the RD_KAFKA_TOPPAR_FETCH_OFFSET_WAIT state:
 *        set the state back to FETCH_OFFSET_QUERY and start the
 *        offset_query_tmr to trigger a new request eventually.
 *
 * @locality toppar handler thread
 * @locks toppar_lock() MUST be held
 */
static void rd_kafka_toppar_offset_retry(rd_kafka_toppar_t *rktp,
                                         int backoff_ms,
                                         const char *reason) {
        rd_ts_t tmr_next;
        int restart_tmr;

        /* (Re)start timer if not started or the current timeout
         * is larger than \p backoff_ms. */
        tmr_next = rd_kafka_timer_next(&rktp->rktp_rkt->rkt_rk->rk_timers,
                                       &rktp->rktp_offset_query_tmr, 1);

        restart_tmr =
            (tmr_next == -1 || tmr_next > rd_clock() + (backoff_ms * 1000ll));

        rd_kafka_dbg(rktp->rktp_rkt->rkt_rk, TOPIC, "OFFSET",
                     "%s [%" PRId32 "]: %s: %s for %s",
                     rktp->rktp_rkt->rkt_topic->str, rktp->rktp_partition,
                     reason,
                     restart_tmr ? "(re)starting offset query timer"
                                 : "offset query timer already scheduled",
                     rd_kafka_fetch_pos2str(rktp->rktp_query_pos));

        rd_kafka_toppar_set_fetch_state(rktp,
                                        RD_KAFKA_TOPPAR_FETCH_OFFSET_QUERY);

        if (restart_tmr)
                rd_kafka_timer_start(&rktp->rktp_rkt->rkt_rk->rk_timers,
                                     &rktp->rktp_offset_query_tmr,
                                     backoff_ms * 1000ll,
                                     rd_kafka_offset_query_tmr_cb, rktp);
}



/**
 * Send OffsetRequest for toppar.
 *
 * If \p backoff_ms is non-zero only the query timer is started,
 * otherwise a query is triggered directly.
 *
 * Locality: toppar handler thread
 * Locks: toppar_lock() must be held
 */
void rd_kafka_toppar_offset_request(rd_kafka_toppar_t *rktp,
                                    rd_kafka_fetch_pos_t query_pos,
                                    int backoff_ms) {
        rd_kafka_broker_t *rkb;

        rd_kafka_assert(NULL,
                        thrd_is_current(rktp->rktp_rkt->rkt_rk->rk_thread));

        rkb = rktp->rktp_broker;

        if (!backoff_ms && (!rkb || rkb->rkb_source == RD_KAFKA_INTERNAL))
                backoff_ms = 500;

        if (backoff_ms) {
                rd_kafka_toppar_offset_retry(
                    rktp, backoff_ms,
                    !rkb ? "no current leader for partition" : "backoff");
                return;
        }


        rd_kafka_timer_stop(&rktp->rktp_rkt->rkt_rk->rk_timers,
                            &rktp->rktp_offset_query_tmr, 1 /*lock*/);


        if (query_pos.offset == RD_KAFKA_OFFSET_STORED &&
            rktp->rktp_rkt->rkt_conf.offset_store_method ==
                RD_KAFKA_OFFSET_METHOD_BROKER) {
                /*
                 * Get stored offset from broker based storage:
                 * ask cgrp manager for offsets
                 */
                rd_kafka_toppar_offset_fetch(
                    rktp,
                    RD_KAFKA_REPLYQ(rktp->rktp_ops, rktp->rktp_op_version));

        } else {
                rd_kafka_topic_partition_list_t *offsets;
                rd_kafka_topic_partition_t *rktpar;

                /*
                 * Look up logical offset (end,beginning,tail,..)
                 */

                rd_rkb_dbg(rkb, TOPIC, "OFFREQ",
                           "Partition %.*s [%" PRId32
                           "]: querying for logical "
                           "offset %s (opv %d)",
                           RD_KAFKAP_STR_PR(rktp->rktp_rkt->rkt_topic),
                           rktp->rktp_partition,
                           rd_kafka_offset2str(query_pos.offset),
                           rktp->rktp_op_version);

                rd_kafka_toppar_keep(rktp); /* refcnt for OffsetRequest opaque*/

                if (query_pos.offset <= RD_KAFKA_OFFSET_TAIL_BASE)
                        query_pos.offset = RD_KAFKA_OFFSET_END;

                offsets = rd_kafka_topic_partition_list_new(1);
                rktpar  = rd_kafka_topic_partition_list_add(
                    offsets, rktp->rktp_rkt->rkt_topic->str,
                    rktp->rktp_partition);
                rd_kafka_topic_partition_set_from_fetch_pos(rktpar, query_pos);
                rd_kafka_topic_partition_set_current_leader_epoch(
                    rktpar, rktp->rktp_leader_epoch);

                rd_kafka_ListOffsetsRequest(
                    rkb, offsets,
                    RD_KAFKA_REPLYQ(rktp->rktp_ops, rktp->rktp_op_version),
                    rd_kafka_toppar_handle_Offset, rktp);

                rd_kafka_topic_partition_list_destroy(offsets);
        }

        rd_kafka_toppar_set_fetch_state(rktp,
                                        RD_KAFKA_TOPPAR_FETCH_OFFSET_WAIT);
}


/**
 * Start fetching toppar.
 *
 * Locality: toppar handler thread
 * Locks: none
 */
static void rd_kafka_toppar_fetch_start(rd_kafka_toppar_t *rktp,
                                        rd_kafka_fetch_pos_t pos,
                                        rd_kafka_op_t *rko_orig) {
        rd_kafka_cgrp_t *rkcg   = rko_orig->rko_u.fetch_start.rkcg;
        rd_kafka_resp_err_t err = 0;
        int32_t version         = rko_orig->rko_version;

        rd_kafka_toppar_lock(rktp);

        rd_kafka_dbg(rktp->rktp_rkt->rkt_rk, TOPIC, "FETCH",
                     "Start fetch for %.*s [%" PRId32
                     "] in "
                     "state %s at %s (v%" PRId32 ")",
                     RD_KAFKAP_STR_PR(rktp->rktp_rkt->rkt_topic),
                     rktp->rktp_partition,
                     rd_kafka_fetch_states[rktp->rktp_fetch_state],
                     rd_kafka_fetch_pos2str(pos), version);

        if (rktp->rktp_fetch_state == RD_KAFKA_TOPPAR_FETCH_STOPPING) {
                err = RD_KAFKA_RESP_ERR__PREV_IN_PROGRESS;
                rd_kafka_toppar_unlock(rktp);
                goto err_reply;
        }

        rd_kafka_toppar_op_version_bump(rktp, version);

        if (rkcg) {
                rd_kafka_assert(rktp->rktp_rkt->rkt_rk, !rktp->rktp_cgrp);
                /* Attach toppar to cgrp */
                rktp->rktp_cgrp = rkcg;
                rd_kafka_cgrp_op(rkcg, rktp, RD_KAFKA_NO_REPLYQ,
                                 RD_KAFKA_OP_PARTITION_JOIN, 0);
        }


        if (pos.offset == RD_KAFKA_OFFSET_BEGINNING ||
            pos.offset == RD_KAFKA_OFFSET_END ||
            pos.offset <= RD_KAFKA_OFFSET_TAIL_BASE) {
                rd_kafka_toppar_next_offset_handle(rktp, pos);

        } else if (pos.offset == RD_KAFKA_OFFSET_STORED) {
                rd_kafka_offset_store_init(rktp);

        } else if (pos.offset == RD_KAFKA_OFFSET_INVALID) {
                rd_kafka_offset_reset(rktp, RD_KAFKA_NODEID_UA, pos,
                                      RD_KAFKA_RESP_ERR__NO_OFFSET,
                                      "no previously committed offset "
                                      "available");

        } else {
                rd_kafka_toppar_set_next_fetch_position(rktp, pos);

                rd_kafka_toppar_set_fetch_state(rktp,
                                                RD_KAFKA_TOPPAR_FETCH_ACTIVE);

                /* Wake-up broker thread which might be idling on IO */
                if (rktp->rktp_broker)
                        rd_kafka_broker_wakeup(rktp->rktp_broker,
                                               "fetch start");
        }

        rktp->rktp_offsets_fin.eof_offset = RD_KAFKA_OFFSET_INVALID;

        rd_kafka_toppar_unlock(rktp);

        /* Signal back to caller thread that start has commenced, or err */
err_reply:
        if (rko_orig->rko_replyq.q) {
                rd_kafka_op_t *rko;

                rko = rd_kafka_op_new(RD_KAFKA_OP_FETCH_START);

                rko->rko_err  = err;
                rko->rko_rktp = rd_kafka_toppar_keep(rktp);

                rd_kafka_replyq_enq(&rko_orig->rko_replyq, rko, 0);
        }
}



/**
 * Mark toppar's fetch state as stopped (all decommissioning is done,
 * offsets are stored, etc).
 *
 * Locality: toppar handler thread
 * Locks: toppar_lock(rktp) MUST be held
 */
void rd_kafka_toppar_fetch_stopped(rd_kafka_toppar_t *rktp,
                                   rd_kafka_resp_err_t err) {


        rd_kafka_toppar_set_fetch_state(rktp, RD_KAFKA_TOPPAR_FETCH_STOPPED);

        rktp->rktp_app_pos.offset       = RD_KAFKA_OFFSET_INVALID;
        rktp->rktp_app_pos.leader_epoch = -1;

        if (rktp->rktp_cgrp) {
                /* Detach toppar from cgrp */
                rd_kafka_cgrp_op(rktp->rktp_cgrp, rktp, RD_KAFKA_NO_REPLYQ,
                                 RD_KAFKA_OP_PARTITION_LEAVE, 0);
                rktp->rktp_cgrp = NULL;
        }

        /* Signal back to application thread that stop is done. */
        if (rktp->rktp_replyq.q) {
                rd_kafka_op_t *rko;
                rko =
                    rd_kafka_op_new(RD_KAFKA_OP_FETCH_STOP | RD_KAFKA_OP_REPLY);
                rko->rko_err  = err;
                rko->rko_rktp = rd_kafka_toppar_keep(rktp);

                rd_kafka_replyq_enq(&rktp->rktp_replyq, rko, 0);
        }
}


/**
 * Stop toppar fetcher.
 * This is usually an async operation.
 *
 * Locality: toppar handler thread
 */
void rd_kafka_toppar_fetch_stop(rd_kafka_toppar_t *rktp,
                                rd_kafka_op_t *rko_orig) {
        int32_t version = rko_orig->rko_version;

        rd_kafka_toppar_lock(rktp);

        rd_kafka_dbg(rktp->rktp_rkt->rkt_rk, TOPIC, "FETCH",
                     "Stopping fetch for %.*s [%" PRId32 "] in state %s (v%d)",
                     RD_KAFKAP_STR_PR(rktp->rktp_rkt->rkt_topic),
                     rktp->rktp_partition,
                     rd_kafka_fetch_states[rktp->rktp_fetch_state], version);

        rd_kafka_toppar_op_version_bump(rktp, version);

        /* Abort pending offset lookups. */
        if (rktp->rktp_fetch_state == RD_KAFKA_TOPPAR_FETCH_OFFSET_QUERY)
                rd_kafka_timer_stop(&rktp->rktp_rkt->rkt_rk->rk_timers,
                                    &rktp->rktp_offset_query_tmr, 1 /*lock*/);

        /* Clear out the forwarding queue. */
        rd_kafka_q_fwd_set(rktp->rktp_fetchq, NULL);

        /* Assign the future replyq to propagate stop results. */
        rd_kafka_assert(rktp->rktp_rkt->rkt_rk, rktp->rktp_replyq.q == NULL);
        rktp->rktp_replyq = rko_orig->rko_replyq;
        rd_kafka_replyq_clear(&rko_orig->rko_replyq);

        rd_kafka_toppar_set_fetch_state(rktp, RD_KAFKA_TOPPAR_FETCH_STOPPING);

        /* Stop offset store (possibly async).
         * NOTE: will call .._stopped() if store finishes immediately,
         *       so no more operations after this call! */
        rd_kafka_offset_store_stop(rktp);

        rd_kafka_toppar_unlock(rktp);
}


/**
 * Update a toppars offset.
 * The toppar must have been previously FETCH_START:ed
 *
 * Locality: toppar handler thread
 */
void rd_kafka_toppar_seek(rd_kafka_toppar_t *rktp,
                          rd_kafka_fetch_pos_t pos,
                          rd_kafka_op_t *rko_orig) {
        rd_kafka_resp_err_t err = 0;
        int32_t version         = rko_orig->rko_version;

        rd_kafka_toppar_lock(rktp);

        rd_kafka_dbg(rktp->rktp_rkt->rkt_rk, TOPIC, "FETCH",
                     "Seek %.*s [%" PRId32 "] to %s in state %s (v%" PRId32 ")",
                     RD_KAFKAP_STR_PR(rktp->rktp_rkt->rkt_topic),
                     rktp->rktp_partition, rd_kafka_fetch_pos2str(pos),
                     rd_kafka_fetch_states[rktp->rktp_fetch_state], version);


        if (rktp->rktp_fetch_state == RD_KAFKA_TOPPAR_FETCH_STOPPING) {
                err = RD_KAFKA_RESP_ERR__PREV_IN_PROGRESS;
                goto err_reply;
        } else if (!RD_KAFKA_TOPPAR_FETCH_IS_STARTED(rktp->rktp_fetch_state)) {
                err = RD_KAFKA_RESP_ERR__STATE;
                goto err_reply;
        } else if (pos.offset == RD_KAFKA_OFFSET_STORED) {
                err = RD_KAFKA_RESP_ERR__INVALID_ARG;
                goto err_reply;
        }

        rd_kafka_toppar_op_version_bump(rktp, version);

        /* Reset app offsets since seek()ing is analogue to a (re)assign(),
         * and we want to avoid using the current app offset on resume()
         * following a seek (#3567). */
        rktp->rktp_app_pos.offset       = RD_KAFKA_OFFSET_INVALID;
        rktp->rktp_app_pos.leader_epoch = -1;

        /* Abort pending offset lookups. */
        if (rktp->rktp_fetch_state == RD_KAFKA_TOPPAR_FETCH_OFFSET_QUERY)
                rd_kafka_timer_stop(&rktp->rktp_rkt->rkt_rk->rk_timers,
                                    &rktp->rktp_offset_query_tmr, 1 /*lock*/);

        if (pos.offset <= 0 || pos.validated) {
                rd_kafka_toppar_next_offset_handle(rktp, pos);
        } else {
                rd_kafka_toppar_set_fetch_state(
                    rktp, RD_KAFKA_TOPPAR_FETCH_VALIDATE_EPOCH_WAIT);
                rd_kafka_toppar_set_next_fetch_position(rktp, pos);
                rd_kafka_offset_validate(rktp, "seek");
        }

        /* Signal back to caller thread that seek has commenced, or err */
err_reply:
        rd_kafka_toppar_unlock(rktp);

        if (rko_orig->rko_replyq.q) {
                rd_kafka_op_t *rko;

                rko = rd_kafka_op_new(RD_KAFKA_OP_SEEK | RD_KAFKA_OP_REPLY);

                rko->rko_err               = err;
                rko->rko_u.fetch_start.pos = rko_orig->rko_u.fetch_start.pos;
                rko->rko_rktp              = rd_kafka_toppar_keep(rktp);

                rd_kafka_replyq_enq(&rko_orig->rko_replyq, rko, 0);
        }
}


/**
 * @brief Pause/resume toppar.
 *
 * This is the internal handler of the pause/resume op.
 *
 * @locality toppar's handler thread
 */
static void rd_kafka_toppar_pause_resume(rd_kafka_toppar_t *rktp,
                                         rd_kafka_op_t *rko_orig) {
        rd_kafka_t *rk  = rktp->rktp_rkt->rkt_rk;
        int pause       = rko_orig->rko_u.pause.pause;
        int flag        = rko_orig->rko_u.pause.flag;
        int32_t version = rko_orig->rko_version;

        rd_kafka_toppar_lock(rktp);

        rd_kafka_toppar_op_version_bump(rktp, version);

        if (!pause && (rktp->rktp_flags & flag) != flag) {
                rd_kafka_dbg(rk, TOPIC, "RESUME",
                             "Not resuming %s [%" PRId32
                             "]: "
                             "partition is not paused by %s",
                             rktp->rktp_rkt->rkt_topic->str,
                             rktp->rktp_partition,
                             (flag & RD_KAFKA_TOPPAR_F_APP_PAUSE ? "application"
                                                                 : "library"));
                rd_kafka_toppar_unlock(rktp);
                return;
        }

        if (pause) {
                /* Pause partition by setting either
                 * RD_KAFKA_TOPPAR_F_APP_PAUSE or
                 * RD_KAFKA_TOPPAR_F_LIB_PAUSE */
                rktp->rktp_flags |= flag;

                if (rk->rk_type == RD_KAFKA_CONSUMER) {
                        /* Save offset of last consumed message+1 as the
                         * next message to fetch on resume. */
                        if (rktp->rktp_app_pos.offset !=
                            RD_KAFKA_OFFSET_INVALID)
                                rd_kafka_toppar_set_next_fetch_position(
                                    rktp, rktp->rktp_app_pos);

                        rd_kafka_dbg(
                            rk, TOPIC, pause ? "PAUSE" : "RESUME",
                            "%s %s [%" PRId32 "]: at %s (state %s, v%d)",
                            pause ? "Pause" : "Resume",
                            rktp->rktp_rkt->rkt_topic->str,
                            rktp->rktp_partition,
                            rd_kafka_fetch_pos2str(rktp->rktp_next_fetch_start),
                            rd_kafka_fetch_states[rktp->rktp_fetch_state],
                            version);
                } else {
                        rd_kafka_dbg(
                            rk, TOPIC, pause ? "PAUSE" : "RESUME",
                            "%s %s [%" PRId32 "] (state %s, v%d)",
                            pause ? "Pause" : "Resume",
                            rktp->rktp_rkt->rkt_topic->str,
                            rktp->rktp_partition,
                            rd_kafka_fetch_states[rktp->rktp_fetch_state],
                            version);
                }

        } else {
                /* Unset the RD_KAFKA_TOPPAR_F_APP_PAUSE or
                 * RD_KAFKA_TOPPAR_F_LIB_PAUSE flag */
                rktp->rktp_flags &= ~flag;

                if (rk->rk_type == RD_KAFKA_CONSUMER) {
                        rd_kafka_dbg(
                            rk, TOPIC, pause ? "PAUSE" : "RESUME",
                            "%s %s [%" PRId32 "]: at %s (state %s, v%d)",
                            rktp->rktp_fetch_state ==
                                    RD_KAFKA_TOPPAR_FETCH_ACTIVE
                                ? "Resuming"
                                : "Not resuming stopped",
                            rktp->rktp_rkt->rkt_topic->str,
                            rktp->rktp_partition,
                            rd_kafka_fetch_pos2str(rktp->rktp_next_fetch_start),
                            rd_kafka_fetch_states[rktp->rktp_fetch_state],
                            version);

                        /* If the resuming offset is logical we
                         * need to trigger a seek (that performs the
                         * logical->absolute lookup logic) to get
                         * things going.
                         * Typical case is when a partition is paused
                         * before anything has been consumed by app
                         * yet thus having rktp_app_offset=INVALID. */
                        if (!RD_KAFKA_TOPPAR_IS_PAUSED(rktp) &&
                            (rktp->rktp_fetch_state ==
                                 RD_KAFKA_TOPPAR_FETCH_ACTIVE ||
                             rktp->rktp_fetch_state ==
                                 RD_KAFKA_TOPPAR_FETCH_OFFSET_WAIT) &&
                            rktp->rktp_next_fetch_start.offset ==
                                RD_KAFKA_OFFSET_INVALID)
                                rd_kafka_toppar_next_offset_handle(
                                    rktp, rktp->rktp_next_fetch_start);

                } else
                        rd_kafka_dbg(
                            rk, TOPIC, pause ? "PAUSE" : "RESUME",
                            "%s %s [%" PRId32 "] (state %s, v%d)",
                            pause ? "Pause" : "Resume",
                            rktp->rktp_rkt->rkt_topic->str,
                            rktp->rktp_partition,
                            rd_kafka_fetch_states[rktp->rktp_fetch_state],
                            version);
        }
        rd_kafka_toppar_unlock(rktp);

        if (pause && rk->rk_type == RD_KAFKA_CONSUMER) {
                /* Flush partition's fetch queue */
                rd_kafka_q_purge_toppar_version(rktp->rktp_fetchq, rktp,
                                                rko_orig->rko_version);
        }
}



/**
 * @brief Serve a toppar in a consumer broker thread.
 *        This is considered the fast path and should be minimal,
 *        mostly focusing on fetch related mechanisms.
 *
 * @returns the partition's Fetch backoff timestamp, or 0 if no backoff.
 *
 * @locality broker thread
 * @locks none
 */
rd_ts_t rd_kafka_broker_consumer_toppar_serve(rd_kafka_broker_t *rkb,
                                              rd_kafka_toppar_t *rktp) {
        return rd_kafka_toppar_fetch_decide(rktp, rkb, 0);
}



/**
 * @brief Serve a toppar op
 *
 * @param rktp may be NULL for certain ops (OP_RECV_BUF)
 *
 * Will send an empty reply op if the request rko has a replyq set,
 * providing synchronous operation.
 *
 * @locality toppar handler thread
 */
static rd_kafka_op_res_t rd_kafka_toppar_op_serve(rd_kafka_t *rk,
                                                  rd_kafka_q_t *rkq,
                                                  rd_kafka_op_t *rko,
                                                  rd_kafka_q_cb_type_t cb_type,
                                                  void *opaque) {
        rd_kafka_toppar_t *rktp = NULL;
        int outdated            = 0;

        if (rko->rko_rktp)
                rktp = rko->rko_rktp;

        if (rktp) {
                outdated =
                    rd_kafka_op_version_outdated(rko, rktp->rktp_op_version);

                rd_kafka_dbg(rktp->rktp_rkt->rkt_rk, TOPIC, "OP",
                             "%.*s [%" PRId32
                             "] received %sop %s "
                             "(v%" PRId32 ") in fetch-state %s (opv%d)",
                             RD_KAFKAP_STR_PR(rktp->rktp_rkt->rkt_topic),
                             rktp->rktp_partition, outdated ? "outdated " : "",
                             rd_kafka_op2str(rko->rko_type), rko->rko_version,
                             rd_kafka_fetch_states[rktp->rktp_fetch_state],
                             rktp->rktp_op_version);

                if (outdated) {
#if ENABLE_DEVEL
                        rd_kafka_op_print(stdout, "PART_OUTDATED", rko);
#endif
                        rd_kafka_op_reply(rko, RD_KAFKA_RESP_ERR__OUTDATED);
                        return RD_KAFKA_OP_RES_HANDLED;
                }
        }

        switch ((int)rko->rko_type) {
        case RD_KAFKA_OP_FETCH_START:
                rd_kafka_toppar_fetch_start(rktp, rko->rko_u.fetch_start.pos,
                                            rko);
                break;

        case RD_KAFKA_OP_FETCH_STOP:
                rd_kafka_toppar_fetch_stop(rktp, rko);
                break;

        case RD_KAFKA_OP_SEEK:
                rd_kafka_toppar_seek(rktp, rko->rko_u.fetch_start.pos, rko);
                break;

        case RD_KAFKA_OP_PAUSE:
                rd_kafka_toppar_pause_resume(rktp, rko);
                break;

        case RD_KAFKA_OP_OFFSET_COMMIT | RD_KAFKA_OP_REPLY:
                rd_kafka_assert(NULL, rko->rko_u.offset_commit.cb);
                rko->rko_u.offset_commit.cb(rk, rko->rko_err,
                                            rko->rko_u.offset_commit.partitions,
                                            rko->rko_u.offset_commit.opaque);
                break;

        case RD_KAFKA_OP_OFFSET_FETCH | RD_KAFKA_OP_REPLY: {
                /* OffsetFetch reply */
                rd_kafka_topic_partition_list_t *offsets =
                    rko->rko_u.offset_fetch.partitions;
                rd_kafka_fetch_pos_t pos = {RD_KAFKA_OFFSET_INVALID, -1};

                rktp = rd_kafka_topic_partition_get_toppar(
                    rk, &offsets->elems[0], rd_true /*create-on-miss*/);

                if (!rko->rko_err) {
                        /* Request succeeded but per-partition might have failed
                         */
                        rko->rko_err = offsets->elems[0].err;
                        pos          = rd_kafka_topic_partition_get_fetch_pos(
                            &offsets->elems[0]);
                }

                rd_kafka_topic_partition_list_destroy(offsets);
                rko->rko_u.offset_fetch.partitions = NULL;

                rd_kafka_timer_stop(&rktp->rktp_rkt->rkt_rk->rk_timers,
                                    &rktp->rktp_offset_query_tmr, 1 /*lock*/);

                rd_kafka_toppar_lock(rktp);

                if (rko->rko_err) {
                        rd_kafka_dbg(
                            rktp->rktp_rkt->rkt_rk, TOPIC, "OFFSET",
                            "Failed to fetch offset for "
                            "%.*s [%" PRId32 "]: %s",
                            RD_KAFKAP_STR_PR(rktp->rktp_rkt->rkt_topic),
                            rktp->rktp_partition,
                            rd_kafka_err2str(rko->rko_err));

                        /* Keep on querying until we succeed. */
                        rd_kafka_toppar_offset_retry(rktp, 500,
                                                     "failed to fetch offsets");
                        rd_kafka_toppar_unlock(rktp);


                        /* Propagate error to application */
                        if (rko->rko_err != RD_KAFKA_RESP_ERR__WAIT_COORD &&
                            rko->rko_err !=
                                RD_KAFKA_RESP_ERR_UNSTABLE_OFFSET_COMMIT)
                                rd_kafka_consumer_err(
                                    rktp->rktp_fetchq, RD_KAFKA_NODEID_UA,
                                    rko->rko_err, 0, NULL, rktp,
                                    RD_KAFKA_OFFSET_INVALID,
                                    "Failed to fetch "
                                    "offsets from brokers: %s",
                                    rd_kafka_err2str(rko->rko_err));

                        /* Refcount from get_toppar() */
                        rd_kafka_toppar_destroy(rktp);

                        break;
                }

                rd_kafka_dbg(rktp->rktp_rkt->rkt_rk, TOPIC, "OFFSET",
                             "%.*s [%" PRId32 "]: OffsetFetch returned %s",
                             RD_KAFKAP_STR_PR(rktp->rktp_rkt->rkt_topic),
                             rktp->rktp_partition, rd_kafka_fetch_pos2str(pos));

                if (pos.offset > 0)
                        rktp->rktp_committed_pos = pos;

                if (pos.offset >= 0)
                        rd_kafka_toppar_next_offset_handle(rktp, pos);
                else
                        rd_kafka_offset_reset(rktp, RD_KAFKA_NODEID_UA, pos,
                                              RD_KAFKA_RESP_ERR__NO_OFFSET,
                                              "no previously committed offset "
                                              "available");
                rd_kafka_toppar_unlock(rktp);

                /* Refcount from get_toppar() */
                rd_kafka_toppar_destroy(rktp);
        } break;

        default:
                rd_kafka_assert(NULL, !*"unknown type");
                break;
        }

        rd_kafka_op_reply(rko, RD_KAFKA_RESP_ERR_NO_ERROR);

        return RD_KAFKA_OP_RES_HANDLED;
}



/**
 * Send command op to toppar (handled by toppar's thread).
 *
 * Locality: any thread
 */
static void rd_kafka_toppar_op0(rd_kafka_toppar_t *rktp,
                                rd_kafka_op_t *rko,
                                rd_kafka_replyq_t replyq) {
        rko->rko_rktp   = rd_kafka_toppar_keep(rktp);
        rko->rko_replyq = replyq;

        rd_kafka_q_enq(rktp->rktp_ops, rko);
}


/**
 * Send command op to toppar (handled by toppar's thread).
 *
 * Locality: any thread
 */
static void rd_kafka_toppar_op(rd_kafka_toppar_t *rktp,
                               rd_kafka_op_type_t type,
                               int32_t version,
                               rd_kafka_fetch_pos_t pos,
                               rd_kafka_cgrp_t *rkcg,
                               rd_kafka_replyq_t replyq) {
        rd_kafka_op_t *rko;

        rko              = rd_kafka_op_new(type);
        rko->rko_version = version;
        if (type == RD_KAFKA_OP_FETCH_START || type == RD_KAFKA_OP_SEEK) {
                if (rkcg)
                        rko->rko_u.fetch_start.rkcg = rkcg;
                rko->rko_u.fetch_start.pos = pos;
        }

        rd_kafka_toppar_op0(rktp, rko, replyq);
}



/**
 * Start consuming partition (async operation).
 *  'offset' is the initial offset
 *  'fwdq' is an optional queue to forward messages to, if this is NULL
 *  then messages will be enqueued on rktp_fetchq.
 *  'replyq' is an optional queue for handling the consume_start ack.
 *
 * This is the thread-safe interface that can be called from any thread.
 */
rd_kafka_resp_err_t rd_kafka_toppar_op_fetch_start(rd_kafka_toppar_t *rktp,
                                                   rd_kafka_fetch_pos_t pos,
                                                   rd_kafka_q_t *fwdq,
                                                   rd_kafka_replyq_t replyq) {
        int32_t version;

        rd_kafka_q_lock(rktp->rktp_fetchq);
        if (fwdq && !(rktp->rktp_fetchq->rkq_flags & RD_KAFKA_Q_F_FWD_APP))
                rd_kafka_q_fwd_set0(rktp->rktp_fetchq, fwdq, 0, /* no do_lock */
                                    0 /* no fwd_app */);
        rd_kafka_q_unlock(rktp->rktp_fetchq);

        /* Bump version barrier. */
        version = rd_kafka_toppar_version_new_barrier(rktp);

        rd_kafka_dbg(rktp->rktp_rkt->rkt_rk, TOPIC, "CONSUMER",
                     "Start consuming %.*s [%" PRId32 "] at %s (v%" PRId32 ")",
                     RD_KAFKAP_STR_PR(rktp->rktp_rkt->rkt_topic),
                     rktp->rktp_partition, rd_kafka_fetch_pos2str(pos),
                     version);

        rd_kafka_toppar_op(rktp, RD_KAFKA_OP_FETCH_START, version, pos,
                           rktp->rktp_rkt->rkt_rk->rk_cgrp, replyq);

        return RD_KAFKA_RESP_ERR_NO_ERROR;
}


/**
 * Stop consuming partition (async operatoin)
 * This is thread-safe interface that can be called from any thread.
 *
 * Locality: any thread
 */
rd_kafka_resp_err_t rd_kafka_toppar_op_fetch_stop(rd_kafka_toppar_t *rktp,
                                                  rd_kafka_replyq_t replyq) {
        int32_t version;

        /* Bump version barrier. */
        version = rd_kafka_toppar_version_new_barrier(rktp);

        rd_kafka_dbg(rktp->rktp_rkt->rkt_rk, TOPIC, "CONSUMER",
                     "Stop consuming %.*s [%" PRId32 "] (v%" PRId32 ")",
                     RD_KAFKAP_STR_PR(rktp->rktp_rkt->rkt_topic),
                     rktp->rktp_partition, version);

        rd_kafka_toppar_op(rktp, RD_KAFKA_OP_FETCH_STOP, version,
                           RD_KAFKA_FETCH_POS(-1, -1), NULL, replyq);

        return RD_KAFKA_RESP_ERR_NO_ERROR;
}


/**
 * @brief Set/Seek offset of a consumed partition (async operation).
 *
 * @param offset is the target offset.
 * @param leader_epoch is the partition leader epoch, or -1.
 * @param replyq is an optional queue for handling the ack.
 *
 * This is the thread-safe interface that can be called from any thread.
 */
rd_kafka_resp_err_t rd_kafka_toppar_op_seek(rd_kafka_toppar_t *rktp,
                                            rd_kafka_fetch_pos_t pos,
                                            rd_kafka_replyq_t replyq) {
        int32_t version;

        /* Bump version barrier. */
        version = rd_kafka_toppar_version_new_barrier(rktp);

        rd_kafka_dbg(rktp->rktp_rkt->rkt_rk, TOPIC, "CONSUMER",
                     "Seek %.*s [%" PRId32 "] to %s (v%" PRId32 ")",
                     RD_KAFKAP_STR_PR(rktp->rktp_rkt->rkt_topic),
                     rktp->rktp_partition, rd_kafka_fetch_pos2str(pos),
                     version);

        rd_kafka_toppar_op(rktp, RD_KAFKA_OP_SEEK, version, pos, NULL, replyq);

        return RD_KAFKA_RESP_ERR_NO_ERROR;
}


/**
 * @brief Pause/resume partition (async operation).
 *
 * @param flag is either RD_KAFKA_TOPPAR_F_APP_PAUSE or .._F_LIB_PAUSE
 *             depending on if the app paused or librdkafka.
 * @param pause is 1 for pausing or 0 for resuming.
 *
 * @locality any
 */
rd_kafka_resp_err_t rd_kafka_toppar_op_pause_resume(rd_kafka_toppar_t *rktp,
                                                    int pause,
                                                    int flag,
                                                    rd_kafka_replyq_t replyq) {
        int32_t version;
        rd_kafka_op_t *rko;

        /* Bump version barrier. */
        version = rd_kafka_toppar_version_new_barrier(rktp);

        rd_kafka_dbg(rktp->rktp_rkt->rkt_rk, TOPIC, pause ? "PAUSE" : "RESUME",
                     "%s %.*s [%" PRId32 "] (v%" PRId32 ")",
                     pause ? "Pause" : "Resume",
                     RD_KAFKAP_STR_PR(rktp->rktp_rkt->rkt_topic),
                     rktp->rktp_partition, version);

        rko                    = rd_kafka_op_new(RD_KAFKA_OP_PAUSE);
        rko->rko_version       = version;
        rko->rko_u.pause.pause = pause;
        rko->rko_u.pause.flag  = flag;

        rd_kafka_toppar_op0(rktp, rko, replyq);

        return RD_KAFKA_RESP_ERR_NO_ERROR;
}


/**
 * @brief Pause a toppar (asynchronous).
 *
 * @param flag is either RD_KAFKA_TOPPAR_F_APP_PAUSE or .._F_LIB_PAUSE
 *             depending on if the app paused or librdkafka.
 *
 * @locality any
 * @locks none needed
 */
void rd_kafka_toppar_pause(rd_kafka_toppar_t *rktp, int flag) {
        rd_kafka_toppar_op_pause_resume(rktp, 1 /*pause*/, flag,
                                        RD_KAFKA_NO_REPLYQ);
}

/**
 * @brief Resume a toppar (asynchronous).
 *
 * @param flag is either RD_KAFKA_TOPPAR_F_APP_PAUSE or .._F_LIB_PAUSE
 *             depending on if the app paused or librdkafka.
 *
 * @locality any
 * @locks none needed
 */
void rd_kafka_toppar_resume(rd_kafka_toppar_t *rktp, int flag) {
        rd_kafka_toppar_op_pause_resume(rktp, 1 /*pause*/, flag,
                                        RD_KAFKA_NO_REPLYQ);
}



/**
 * @brief Pause or resume a list of partitions.
 *
 * @param flag is either RD_KAFKA_TOPPAR_F_APP_PAUSE or .._F_LIB_PAUSE
 *             depending on if the app paused or librdkafka.
 * @param pause true for pausing, false for resuming.
 * @param async RD_SYNC to wait for background thread to handle op,
 *              RD_ASYNC for asynchronous operation.
 *
 * @locality any
 *
 * @remark This is an asynchronous call, the actual pause/resume is performed
 *         by toppar_pause() in the toppar's handler thread.
 */
rd_kafka_resp_err_t
rd_kafka_toppars_pause_resume(rd_kafka_t *rk,
                              rd_bool_t pause,
                              rd_async_t async,
                              int flag,
                              rd_kafka_topic_partition_list_t *partitions) {
        int i;
        int waitcnt        = 0;
        rd_kafka_q_t *tmpq = NULL;

        if (!async)
                tmpq = rd_kafka_q_new(rk);

        rd_kafka_dbg(
            rk, TOPIC, pause ? "PAUSE" : "RESUME", "%s %s %d partition(s)",
            flag & RD_KAFKA_TOPPAR_F_APP_PAUSE ? "Application" : "Library",
            pause ? "pausing" : "resuming", partitions->cnt);

        for (i = 0; i < partitions->cnt; i++) {
                rd_kafka_topic_partition_t *rktpar = &partitions->elems[i];
                rd_kafka_toppar_t *rktp;

                rktp =
                    rd_kafka_topic_partition_get_toppar(rk, rktpar, rd_false);
                if (!rktp) {
                        rd_kafka_dbg(rk, TOPIC, pause ? "PAUSE" : "RESUME",
                                     "%s %s [%" PRId32
                                     "]: skipped: "
                                     "unknown partition",
                                     pause ? "Pause" : "Resume", rktpar->topic,
                                     rktpar->partition);

                        rktpar->err = RD_KAFKA_RESP_ERR__UNKNOWN_PARTITION;
                        continue;
                }

                rd_kafka_toppar_op_pause_resume(rktp, pause, flag,
                                                RD_KAFKA_REPLYQ(tmpq, 0));

                if (!async)
                        waitcnt++;

                rd_kafka_toppar_destroy(rktp);

                rktpar->err = RD_KAFKA_RESP_ERR_NO_ERROR;
        }

        if (!async) {
                while (waitcnt-- > 0)
                        rd_kafka_q_wait_result(tmpq, RD_POLL_INFINITE);

                rd_kafka_q_destroy_owner(tmpq);
        }

        return RD_KAFKA_RESP_ERR_NO_ERROR;
}



/**
 * Propagate error for toppar
 */
void rd_kafka_toppar_enq_error(rd_kafka_toppar_t *rktp,
                               rd_kafka_resp_err_t err,
                               const char *reason) {
        rd_kafka_op_t *rko;
        char buf[512];

        rko           = rd_kafka_op_new(RD_KAFKA_OP_ERR);
        rko->rko_err  = err;
        rko->rko_rktp = rd_kafka_toppar_keep(rktp);

        rd_snprintf(buf, sizeof(buf), "%.*s [%" PRId32 "]: %s (%s)",
                    RD_KAFKAP_STR_PR(rktp->rktp_rkt->rkt_topic),
                    rktp->rktp_partition, reason, rd_kafka_err2str(err));

        rko->rko_u.err.errstr = rd_strdup(buf);

        rd_kafka_q_enq(rktp->rktp_fetchq, rko);
}



/**
 * Returns the currently delegated broker for this toppar.
 * If \p proper_broker is set NULL will be returned if current handler
 * is not a proper broker (INTERNAL broker).
 *
 * The returned broker has an increased refcount.
 *
 * Locks: none
 */
rd_kafka_broker_t *rd_kafka_toppar_broker(rd_kafka_toppar_t *rktp,
                                          int proper_broker) {
        rd_kafka_broker_t *rkb;
        rd_kafka_toppar_lock(rktp);
        rkb = rktp->rktp_broker;
        if (rkb) {
                if (proper_broker && rkb->rkb_source == RD_KAFKA_INTERNAL)
                        rkb = NULL;
                else
                        rd_kafka_broker_keep(rkb);
        }
        rd_kafka_toppar_unlock(rktp);

        return rkb;
}


/**
 * @brief Take action when partition broker becomes unavailable.
 *        This should be called when requests fail with
 *        NOT_LEADER_FOR.. or similar error codes, e.g. ProduceRequest.
 *
 * @locks none
 * @locality any
 */
void rd_kafka_toppar_leader_unavailable(rd_kafka_toppar_t *rktp,
                                        const char *reason,
                                        rd_kafka_resp_err_t err) {
        rd_kafka_topic_t *rkt = rktp->rktp_rkt;

        rd_kafka_dbg(rkt->rkt_rk, TOPIC, "BROKERUA",
                     "%s [%" PRId32 "]: broker unavailable: %s: %s",
                     rkt->rkt_topic->str, rktp->rktp_partition, reason,
                     rd_kafka_err2str(err));

        rd_kafka_topic_wrlock(rkt);
        rkt->rkt_flags |= RD_KAFKA_TOPIC_F_LEADER_UNAVAIL;
        rd_kafka_topic_wrunlock(rkt);

        rd_kafka_topic_fast_leader_query(rkt->rkt_rk);
}


const char *
rd_kafka_topic_partition_topic(const rd_kafka_topic_partition_t *rktpar) {
        const rd_kafka_toppar_t *rktp = (const rd_kafka_toppar_t *)rktpar;
        return rktp->rktp_rkt->rkt_topic->str;
}

int32_t
rd_kafka_topic_partition_partition(const rd_kafka_topic_partition_t *rktpar) {
        const rd_kafka_toppar_t *rktp = (const rd_kafka_toppar_t *)rktpar;
        return rktp->rktp_partition;
}

void rd_kafka_topic_partition_get(const rd_kafka_topic_partition_t *rktpar,
                                  const char **name,
                                  int32_t *partition) {
        const rd_kafka_toppar_t *rktp = (const rd_kafka_toppar_t *)rktpar;
        *name                         = rktp->rktp_rkt->rkt_topic->str;
        *partition                    = rktp->rktp_partition;
}



/**
 *
 * rd_kafka_topic_partition_t lists
 * Fixed-size non-growable list of partitions for propagation to application.
 *
 */


static void
rd_kafka_topic_partition_list_grow(rd_kafka_topic_partition_list_t *rktparlist,
                                   int add_size) {
        if (add_size < rktparlist->size)
                add_size = RD_MAX(rktparlist->size, 32);

        rktparlist->size += add_size;
        rktparlist->elems = rd_realloc(
            rktparlist->elems, sizeof(*rktparlist->elems) * rktparlist->size);
}


/**
 * @brief Initialize a list for fitting \p size partitions.
 */
void rd_kafka_topic_partition_list_init(
    rd_kafka_topic_partition_list_t *rktparlist,
    int size) {
        memset(rktparlist, 0, sizeof(*rktparlist));

        if (size > 0)
                rd_kafka_topic_partition_list_grow(rktparlist, size);
}


/**
 * Create a list for fitting 'size' topic_partitions (rktp).
 */
rd_kafka_topic_partition_list_t *rd_kafka_topic_partition_list_new(int size) {
        rd_kafka_topic_partition_list_t *rktparlist;

        rktparlist = rd_calloc(1, sizeof(*rktparlist));

        if (size > 0)
                rd_kafka_topic_partition_list_grow(rktparlist, size);

        return rktparlist;
}



rd_kafka_topic_partition_t *rd_kafka_topic_partition_new(const char *topic,
                                                         int32_t partition) {
        rd_kafka_topic_partition_t *rktpar = rd_calloc(1, sizeof(*rktpar));

        rktpar->topic     = rd_strdup(topic);
        rktpar->partition = partition;

        return rktpar;
}

/**
 * @brief Update \p dst with info from \p src.
 */
static void
rd_kafka_topic_partition_update(rd_kafka_topic_partition_t *dst,
                                const rd_kafka_topic_partition_t *src) {
        const rd_kafka_topic_partition_private_t *srcpriv;
        rd_kafka_topic_partition_private_t *dstpriv;

        rd_dassert(!strcmp(dst->topic, src->topic));
        rd_dassert(dst->partition == src->partition);
        rd_dassert(dst != src);

        dst->offset = src->offset;
        dst->opaque = src->opaque;
        dst->err    = src->err;

        if (src->metadata_size > 0) {
                dst->metadata      = rd_malloc(src->metadata_size);
                dst->metadata_size = src->metadata_size;
                ;
                memcpy(dst->metadata, src->metadata, dst->metadata_size);
        }

        if ((srcpriv = src->_private)) {
                dstpriv = rd_kafka_topic_partition_get_private(dst);
                if (srcpriv->rktp && !dstpriv->rktp)
                        dstpriv->rktp = rd_kafka_toppar_keep(srcpriv->rktp);

                rd_assert(dstpriv->rktp == srcpriv->rktp);

                dstpriv->leader_epoch = srcpriv->leader_epoch;

        } else if ((dstpriv = dst->_private)) {
                /* No private object in source, reset the leader epoch. */
                dstpriv->leader_epoch = -1;
        }
}


rd_kafka_topic_partition_t *
rd_kafka_topic_partition_copy(const rd_kafka_topic_partition_t *src) {
        rd_kafka_topic_partition_t *dst =
            rd_kafka_topic_partition_new(src->topic, src->partition);

        rd_kafka_topic_partition_update(dst, src);

        return dst;
}


/** Same as above but with generic void* signature */
void *rd_kafka_topic_partition_copy_void(const void *src) {
        return rd_kafka_topic_partition_copy(src);
}


rd_kafka_topic_partition_t *
rd_kafka_topic_partition_new_from_rktp(rd_kafka_toppar_t *rktp) {
        rd_kafka_topic_partition_t *rktpar = rd_calloc(1, sizeof(*rktpar));

        rktpar->topic     = RD_KAFKAP_STR_DUP(rktp->rktp_rkt->rkt_topic);
        rktpar->partition = rktp->rktp_partition;

        return rktpar;
}

/**
 * @brief Destroy a partition private glue object.
 */
static void rd_kafka_topic_partition_private_destroy(
    rd_kafka_topic_partition_private_t *parpriv) {
        if (parpriv->rktp)
                rd_kafka_toppar_destroy(parpriv->rktp);
        rd_free(parpriv);
}

static void
rd_kafka_topic_partition_destroy0(rd_kafka_topic_partition_t *rktpar,
                                  int do_free) {
        if (rktpar->topic)
                rd_free(rktpar->topic);
        if (rktpar->metadata)
                rd_free(rktpar->metadata);
        if (rktpar->_private)
                rd_kafka_topic_partition_private_destroy(
                    (rd_kafka_topic_partition_private_t *)rktpar->_private);

        if (do_free)
                rd_free(rktpar);
}


int32_t rd_kafka_topic_partition_get_leader_epoch(
    const rd_kafka_topic_partition_t *rktpar) {
        const rd_kafka_topic_partition_private_t *parpriv;

        if (!(parpriv = rktpar->_private))
                return -1;

        return parpriv->leader_epoch;
}

void rd_kafka_topic_partition_set_leader_epoch(
    rd_kafka_topic_partition_t *rktpar,
    int32_t leader_epoch) {
        rd_kafka_topic_partition_private_t *parpriv;

        /* Avoid allocating private_t if clearing the epoch */
        if (leader_epoch == -1 && !rktpar->_private)
                return;

        parpriv = rd_kafka_topic_partition_get_private(rktpar);

        parpriv->leader_epoch = leader_epoch;
}

int32_t rd_kafka_topic_partition_get_current_leader_epoch(
    const rd_kafka_topic_partition_t *rktpar) {
        const rd_kafka_topic_partition_private_t *parpriv;

        if (!(parpriv = rktpar->_private))
                return -1;

        return parpriv->current_leader_epoch;
}

void rd_kafka_topic_partition_set_current_leader_epoch(
    rd_kafka_topic_partition_t *rktpar,
    int32_t current_leader_epoch) {
        rd_kafka_topic_partition_private_t *parpriv;

        /* Avoid allocating private_t if clearing the epoch */
        if (current_leader_epoch == -1 && !rktpar->_private)
                return;

        parpriv = rd_kafka_topic_partition_get_private(rktpar);

        parpriv->current_leader_epoch = current_leader_epoch;
}

/**
 * @brief Set offset and leader epoch from a fetchpos.
 */
void rd_kafka_topic_partition_set_from_fetch_pos(
    rd_kafka_topic_partition_t *rktpar,
    const rd_kafka_fetch_pos_t fetchpos) {
        rktpar->offset = fetchpos.offset;
        rd_kafka_topic_partition_set_leader_epoch(rktpar,
                                                  fetchpos.leader_epoch);
}

/**
 * @brief Destroy all partitions in list.
 *
 * @remark The allocated size of the list will not shrink.
 */
void rd_kafka_topic_partition_list_clear(
    rd_kafka_topic_partition_list_t *rktparlist) {
        int i;

        for (i = 0; i < rktparlist->cnt; i++)
                rd_kafka_topic_partition_destroy0(&rktparlist->elems[i], 0);

        rktparlist->cnt = 0;
}


void rd_kafka_topic_partition_destroy_free(void *ptr) {
        rd_kafka_topic_partition_destroy0(ptr, rd_true /*do_free*/);
}

void rd_kafka_topic_partition_destroy(rd_kafka_topic_partition_t *rktpar) {
        rd_kafka_topic_partition_destroy0(rktpar, 1);
}


/**
 * Destroys a list previously created with .._list_new() and drops
 * any references to contained toppars.
 */
void rd_kafka_topic_partition_list_destroy(
    rd_kafka_topic_partition_list_t *rktparlist) {
        int i;

        for (i = 0; i < rktparlist->cnt; i++)
                rd_kafka_topic_partition_destroy0(&rktparlist->elems[i], 0);

        if (rktparlist->elems)
                rd_free(rktparlist->elems);

        rd_free(rktparlist);
}


/**
 * @brief Wrapper for rd_kafka_topic_partition_list_destroy() that
 *        matches the standard free(void *) signature, for callback use.
 */
void rd_kafka_topic_partition_list_destroy_free(void *ptr) {
        rd_kafka_topic_partition_list_destroy(
            (rd_kafka_topic_partition_list_t *)ptr);
}


/**
 * @brief Add a partition to an rktpar list.
 * The list must have enough room to fit it.
 *
 * @param rktp Optional partition object that will be stored on the
 * ._private object (with refcount increased).
 *
 * @returns a pointer to the added element.
 */
rd_kafka_topic_partition_t *rd_kafka_topic_partition_list_add0(
    const char *func,
    int line,
    rd_kafka_topic_partition_list_t *rktparlist,
    const char *topic,
    int32_t partition,
    rd_kafka_toppar_t *rktp,
    const rd_kafka_topic_partition_private_t *parpriv) {
        rd_kafka_topic_partition_t *rktpar;
        if (rktparlist->cnt == rktparlist->size)
                rd_kafka_topic_partition_list_grow(rktparlist, 1);
        rd_kafka_assert(NULL, rktparlist->cnt < rktparlist->size);

        rktpar = &rktparlist->elems[rktparlist->cnt++];
        memset(rktpar, 0, sizeof(*rktpar));
        rktpar->topic     = rd_strdup(topic);
        rktpar->partition = partition;
        rktpar->offset    = RD_KAFKA_OFFSET_INVALID;

        if (parpriv) {
                rd_kafka_topic_partition_private_t *parpriv_copy =
                    rd_kafka_topic_partition_get_private(rktpar);
                if (parpriv->rktp) {
                        parpriv_copy->rktp =
                            rd_kafka_toppar_keep_fl(func, line, parpriv->rktp);
                }
                parpriv_copy->leader_epoch         = parpriv->leader_epoch;
                parpriv_copy->current_leader_epoch = parpriv->leader_epoch;
        } else if (rktp) {
                rd_kafka_topic_partition_private_t *parpriv_copy =
                    rd_kafka_topic_partition_get_private(rktpar);
                parpriv_copy->rktp = rd_kafka_toppar_keep_fl(func, line, rktp);
        }

        return rktpar;
}


rd_kafka_topic_partition_t *
rd_kafka_topic_partition_list_add(rd_kafka_topic_partition_list_t *rktparlist,
                                  const char *topic,
                                  int32_t partition) {
        return rd_kafka_topic_partition_list_add0(
            __FUNCTION__, __LINE__, rktparlist, topic, partition, NULL, NULL);
}


/**
 * Adds a consecutive list of partitions to a list
 */
void rd_kafka_topic_partition_list_add_range(
    rd_kafka_topic_partition_list_t *rktparlist,
    const char *topic,
    int32_t start,
    int32_t stop) {

        for (; start <= stop; start++)
                rd_kafka_topic_partition_list_add(rktparlist, topic, start);
}


rd_kafka_topic_partition_t *rd_kafka_topic_partition_list_upsert(
    rd_kafka_topic_partition_list_t *rktparlist,
    const char *topic,
    int32_t partition) {
        rd_kafka_topic_partition_t *rktpar;

        if ((rktpar = rd_kafka_topic_partition_list_find(rktparlist, topic,
                                                         partition)))
                return rktpar;

        return rd_kafka_topic_partition_list_add(rktparlist, topic, partition);
}



/**
 * @brief Creates a copy of \p rktpar and adds it to \p rktparlist
 */
void rd_kafka_topic_partition_list_add_copy(
    rd_kafka_topic_partition_list_t *rktparlist,
    const rd_kafka_topic_partition_t *rktpar) {
        rd_kafka_topic_partition_t *dst;

        dst = rd_kafka_topic_partition_list_add0(
            __FUNCTION__, __LINE__, rktparlist, rktpar->topic,
            rktpar->partition, NULL, rktpar->_private);
        rd_kafka_topic_partition_update(dst, rktpar);
}



/**
 * Create and return a copy of list 'src'
 */
rd_kafka_topic_partition_list_t *
rd_kafka_topic_partition_list_copy(const rd_kafka_topic_partition_list_t *src) {
        rd_kafka_topic_partition_list_t *dst;
        int i;

        dst = rd_kafka_topic_partition_list_new(src->size);

        for (i = 0; i < src->cnt; i++)
                rd_kafka_topic_partition_list_add_copy(dst, &src->elems[i]);
        return dst;
}

/**
 * @brief Same as rd_kafka_topic_partition_list_copy() but suitable for
 *        rd_list_copy(). The \p opaque is ignored.
 */
void *rd_kafka_topic_partition_list_copy_opaque(const void *src, void *opaque) {
        return rd_kafka_topic_partition_list_copy(src);
}

/**
 * @brief Append copies of all elements in \p src to \p dst.
 *        No duplicate-checks are performed.
 */
void rd_kafka_topic_partition_list_add_list(
    rd_kafka_topic_partition_list_t *dst,
    const rd_kafka_topic_partition_list_t *src) {
        int i;

        if (src->cnt == 0)
                return;

        if (dst->size < dst->cnt + src->cnt)
                rd_kafka_topic_partition_list_grow(dst, src->cnt);

        for (i = 0; i < src->cnt; i++)
                rd_kafka_topic_partition_list_add_copy(dst, &src->elems[i]);
}


/**
 * @brief Compare two partition lists using partition comparator \p cmp.
 *
 * @warning This is an O(Na*Nb) operation.
 */
int rd_kafka_topic_partition_list_cmp(const void *_a,
                                      const void *_b,
                                      int (*cmp)(const void *, const void *)) {
        const rd_kafka_topic_partition_list_t *a = _a, *b = _b;
        int r;
        int i;

        r = a->cnt - b->cnt;
        if (r || a->cnt == 0)
                return r;

        /* Since the lists may not be sorted we need to scan all of B
         * for each element in A.
         * FIXME: If the list sizes are larger than X we could create a
         *        temporary hash map instead. */
        for (i = 0; i < a->cnt; i++) {
                int j;

                for (j = 0; j < b->cnt; j++) {
                        r = cmp(&a->elems[i], &b->elems[j]);
                        if (!r)
                                break;
                }

                if (j == b->cnt)
                        return 1;
        }

        return 0;
}


/**
 * @brief Ensures the \p rktpar has a toppar set in _private.
 *
 * @returns the toppar object (or possibly NULL if \p create_on_miss is true)
 *          WITHOUT refcnt increased.
 */
rd_kafka_toppar_t *
rd_kafka_topic_partition_ensure_toppar(rd_kafka_t *rk,
                                       rd_kafka_topic_partition_t *rktpar,
                                       rd_bool_t create_on_miss) {
        rd_kafka_topic_partition_private_t *parpriv;

        parpriv = rd_kafka_topic_partition_get_private(rktpar);

        if (!parpriv->rktp)
                parpriv->rktp = rd_kafka_toppar_get2(
                    rk, rktpar->topic, rktpar->partition,
                    0 /* not ua on miss */, create_on_miss);

        return parpriv->rktp;
}


int rd_kafka_topic_partition_cmp(const void *_a, const void *_b) {
        const rd_kafka_topic_partition_t *a = _a;
        const rd_kafka_topic_partition_t *b = _b;
        int r                               = strcmp(a->topic, b->topic);
        if (r)
                return r;
        else
                return RD_CMP(a->partition, b->partition);
}

/** @brief Compare only the topic */
int rd_kafka_topic_partition_cmp_topic(const void *_a, const void *_b) {
        const rd_kafka_topic_partition_t *a = _a;
        const rd_kafka_topic_partition_t *b = _b;
        return strcmp(a->topic, b->topic);
}

static int rd_kafka_topic_partition_cmp_opaque(const void *_a,
                                               const void *_b,
                                               void *opaque) {
        return rd_kafka_topic_partition_cmp(_a, _b);
}

/** @returns a hash of the topic and partition */
unsigned int rd_kafka_topic_partition_hash(const void *_a) {
        const rd_kafka_topic_partition_t *a = _a;
        int r                               = 31 * 17 + a->partition;
        return 31 * r + rd_string_hash(a->topic, -1);
}



/**
 * @brief Search 'rktparlist' for 'topic' and 'partition'.
 * @returns the elems[] index or -1 on miss.
 */
static int rd_kafka_topic_partition_list_find0(
    const rd_kafka_topic_partition_list_t *rktparlist,
    const char *topic,
    int32_t partition,
    int (*cmp)(const void *, const void *)) {
        rd_kafka_topic_partition_t skel;
        int i;

        skel.topic     = (char *)topic;
        skel.partition = partition;

        for (i = 0; i < rktparlist->cnt; i++) {
                if (!cmp(&skel, &rktparlist->elems[i]))
                        return i;
        }

        return -1;
}

rd_kafka_topic_partition_t *rd_kafka_topic_partition_list_find(
    const rd_kafka_topic_partition_list_t *rktparlist,
    const char *topic,
    int32_t partition) {
        int i = rd_kafka_topic_partition_list_find0(
            rktparlist, topic, partition, rd_kafka_topic_partition_cmp);
        if (i == -1)
                return NULL;
        else
                return &rktparlist->elems[i];
}


int rd_kafka_topic_partition_list_find_idx(
    const rd_kafka_topic_partition_list_t *rktparlist,
    const char *topic,
    int32_t partition) {
        return rd_kafka_topic_partition_list_find0(
            rktparlist, topic, partition, rd_kafka_topic_partition_cmp);
}


/**
 * @returns the first element that matches \p topic, regardless of partition.
 */
rd_kafka_topic_partition_t *rd_kafka_topic_partition_list_find_topic(
    const rd_kafka_topic_partition_list_t *rktparlist,
    const char *topic) {
        int i = rd_kafka_topic_partition_list_find0(
            rktparlist, topic, RD_KAFKA_PARTITION_UA,
            rd_kafka_topic_partition_cmp_topic);
        if (i == -1)
                return NULL;
        else
                return &rktparlist->elems[i];
}


int rd_kafka_topic_partition_list_del_by_idx(
    rd_kafka_topic_partition_list_t *rktparlist,
    int idx) {
        if (unlikely(idx < 0 || idx >= rktparlist->cnt))
                return 0;

        rd_kafka_topic_partition_destroy0(&rktparlist->elems[idx], 0);
        memmove(&rktparlist->elems[idx], &rktparlist->elems[idx + 1],
                (rktparlist->cnt - idx - 1) * sizeof(rktparlist->elems[idx]));
        rktparlist->cnt--;

        return 1;
}


int rd_kafka_topic_partition_list_del(
    rd_kafka_topic_partition_list_t *rktparlist,
    const char *topic,
    int32_t partition) {
        int i = rd_kafka_topic_partition_list_find0(
            rktparlist, topic, partition, rd_kafka_topic_partition_cmp);
        if (i == -1)
                return 0;

        return rd_kafka_topic_partition_list_del_by_idx(rktparlist, i);
}



/**
 * Returns true if 'topic' matches the 'rktpar', else false.
 * On match, if rktpar is a regex pattern then 'matched_by_regex' is set to 1.
 */
int rd_kafka_topic_partition_match(rd_kafka_t *rk,
                                   const rd_kafka_group_member_t *rkgm,
                                   const rd_kafka_topic_partition_t *rktpar,
                                   const char *topic,
                                   int *matched_by_regex) {
        int ret = 0;

        if (*rktpar->topic == '^') {
                char errstr[128];

                ret = rd_regex_match(rktpar->topic, topic, errstr,
                                     sizeof(errstr));
                if (ret == -1) {
                        rd_kafka_dbg(rk, CGRP, "SUBMATCH",
                                     "Invalid regex for member "
                                     "\"%.*s\" subscription \"%s\": %s",
                                     RD_KAFKAP_STR_PR(rkgm->rkgm_member_id),
                                     rktpar->topic, errstr);
                        return 0;
                }

                if (ret && matched_by_regex)
                        *matched_by_regex = 1;

        } else if (!strcmp(rktpar->topic, topic)) {

                if (matched_by_regex)
                        *matched_by_regex = 0;

                ret = 1;
        }

        return ret;
}



void rd_kafka_topic_partition_list_sort(
    rd_kafka_topic_partition_list_t *rktparlist,
    int (*cmp)(const void *, const void *, void *),
    void *opaque) {

        if (!cmp)
                cmp = rd_kafka_topic_partition_cmp_opaque;

        rd_qsort_r(rktparlist->elems, rktparlist->cnt,
                   sizeof(*rktparlist->elems), cmp, opaque);
}


void rd_kafka_topic_partition_list_sort_by_topic(
    rd_kafka_topic_partition_list_t *rktparlist) {
        rd_kafka_topic_partition_list_sort(
            rktparlist, rd_kafka_topic_partition_cmp_opaque, NULL);
}

rd_kafka_resp_err_t rd_kafka_topic_partition_list_set_offset(
    rd_kafka_topic_partition_list_t *rktparlist,
    const char *topic,
    int32_t partition,
    int64_t offset) {
        rd_kafka_topic_partition_t *rktpar;

        if (!(rktpar = rd_kafka_topic_partition_list_find(rktparlist, topic,
                                                          partition)))
                return RD_KAFKA_RESP_ERR__UNKNOWN_PARTITION;

        rktpar->offset = offset;

        return RD_KAFKA_RESP_ERR_NO_ERROR;
}


/**
 * @brief Reset all offsets to the provided value.
 */
void rd_kafka_topic_partition_list_reset_offsets(
    rd_kafka_topic_partition_list_t *rktparlist,
    int64_t offset) {

        int i;
        for (i = 0; i < rktparlist->cnt; i++)
                rktparlist->elems[i].offset = offset;
}


/**
 * Set offset values in partition list based on toppar's last stored offset.
 *
 *  from_rktp - true: set rktp's last stored offset, false: set def_value
 *  unless a concrete offset is set.
 *  is_commit: indicates that set offset is to be committed (for debug log)
 *
 * Returns the number of valid non-logical offsets (>=0).
 */
int rd_kafka_topic_partition_list_set_offsets(
    rd_kafka_t *rk,
    rd_kafka_topic_partition_list_t *rktparlist,
    int from_rktp,
    int64_t def_value,
    int is_commit) {
        int i;
        int valid_cnt = 0;

        for (i = 0; i < rktparlist->cnt; i++) {
                rd_kafka_topic_partition_t *rktpar = &rktparlist->elems[i];
                const char *verb                   = "setting";
                char preamble[128];

                *preamble = '\0'; /* Avoid warning */

                if (from_rktp) {
                        rd_kafka_toppar_t *rktp =
                            rd_kafka_topic_partition_ensure_toppar(rk, rktpar,
                                                                   rd_true);
                        rd_kafka_toppar_lock(rktp);

                        if (rk->rk_conf.debug &
                            (RD_KAFKA_DBG_CGRP | RD_KAFKA_DBG_TOPIC))
                                rd_snprintf(preamble, sizeof(preamble),
                                            "stored %s, committed %s: ",
                                            rd_kafka_fetch_pos2str(
                                                rktp->rktp_stored_pos),
                                            rd_kafka_fetch_pos2str(
                                                rktp->rktp_committed_pos));

                        if (rd_kafka_fetch_pos_cmp(&rktp->rktp_stored_pos,
                                                   &rktp->rktp_committed_pos) >
                            0) {
                                verb = "setting stored";
                                rd_kafka_topic_partition_set_from_fetch_pos(
                                    rktpar, rktp->rktp_stored_pos);
                        } else {
                                rktpar->offset = RD_KAFKA_OFFSET_INVALID;
                        }
                        rd_kafka_toppar_unlock(rktp);
                } else {
                        if (RD_KAFKA_OFFSET_IS_LOGICAL(rktpar->offset)) {
                                verb           = "setting default";
                                rktpar->offset = def_value;
                                rd_kafka_topic_partition_set_leader_epoch(
                                    rktpar, -1);
                        } else
                                verb = "keeping";
                }

                if (is_commit && rktpar->offset == RD_KAFKA_OFFSET_INVALID)
                        rd_kafka_dbg(rk, CGRP | RD_KAFKA_DBG_TOPIC, "OFFSET",
                                     "Topic %s [%" PRId32
                                     "]: "
                                     "%snot including in commit",
                                     rktpar->topic, rktpar->partition,
                                     preamble);
                else
                        rd_kafka_dbg(
                            rk, CGRP | RD_KAFKA_DBG_TOPIC, "OFFSET",
                            "Topic %s [%" PRId32
                            "]: "
                            "%s%s offset %s (leader epoch %" PRId32 ") %s",
                            rktpar->topic, rktpar->partition, preamble, verb,
                            rd_kafka_offset2str(rktpar->offset),
                            rd_kafka_topic_partition_get_leader_epoch(rktpar),
                            is_commit ? " for commit" : "");

                if (!RD_KAFKA_OFFSET_IS_LOGICAL(rktpar->offset))
                        valid_cnt++;
        }

        return valid_cnt;
}


/**
 * @returns the number of partitions with absolute (non-logical) offsets set.
 */
int rd_kafka_topic_partition_list_count_abs_offsets(
    const rd_kafka_topic_partition_list_t *rktparlist) {
        int i;
        int valid_cnt = 0;

        for (i = 0; i < rktparlist->cnt; i++)
                if (!RD_KAFKA_OFFSET_IS_LOGICAL(rktparlist->elems[i].offset))
                        valid_cnt++;

        return valid_cnt;
}


/**
 * @brief Update _private (toppar) field to point to valid rktp
 *        for each parition.
 *
 * @param create_on_miss Create partition (and topic_t object) if necessary.
 */
void rd_kafka_topic_partition_list_update_toppars(
    rd_kafka_t *rk,
    rd_kafka_topic_partition_list_t *rktparlist,
    rd_bool_t create_on_miss) {
        int i;
        for (i = 0; i < rktparlist->cnt; i++) {
                rd_kafka_topic_partition_t *rktpar = &rktparlist->elems[i];

                rd_kafka_topic_partition_ensure_toppar(rk, rktpar,
                                                       create_on_miss);
        }
}


/**
 * @brief Populate \p leaders with the leaders+partitions for the partitions in
 *        \p rktparlist. Duplicates are suppressed.
 *
 *        If no leader is found for a partition that element's \c .err will
 *        be set to RD_KAFKA_RESP_ERR_LEADER_NOT_AVAILABLE.
 *
 *        If the partition does not exist \c .err will be set to
 *        RD_KAFKA_RESP_ERR__UNKNOWN_PARTITION.
 *
 * @param rktparlist The partitions to look up leaders for, the .err field
 *                   will be set according to outcome, e.g., ERR_NO_ERROR,
 *                   ERR_UNKNOWN_TOPIC_OR_PART, etc.
 * @param leaders rd_list_t of allocated (struct rd_kafka_partition_leader *)
 * @param query_topics (optional) rd_list of strdupped (char *)
 * @param query_unknown Add unknown topics to \p query_topics.
 * @param eonce (optional) For triggering asynchronously on cache change
 *              in case not all leaders are known now.
 *
 * @remark This is based on the current topic_t and partition state
 *         which may lag behind the last metadata update due to internal
 *         threading and also the fact that no topic_t may have been created.
 *
 * @param leaders rd_list_t of type (struct rd_kafka_partition_leader *)
 *
 * @returns true if all partitions have leaders, else false.
 *
 * @sa rd_kafka_topic_partition_list_get_leaders_by_metadata
 *
 * @locks rd_kafka_*lock() MUST NOT be held
 */
static rd_bool_t rd_kafka_topic_partition_list_get_leaders(
    rd_kafka_t *rk,
    rd_kafka_topic_partition_list_t *rktparlist,
    rd_list_t *leaders,
    rd_list_t *query_topics,
    rd_bool_t query_unknown,
    rd_kafka_enq_once_t *eonce) {
        rd_bool_t complete;
        int cnt = 0;
        int i;

        if (eonce)
                rd_kafka_wrlock(rk);
        else
                rd_kafka_rdlock(rk);

        for (i = 0; i < rktparlist->cnt; i++) {
                rd_kafka_topic_partition_t *rktpar = &rktparlist->elems[i];
                rd_kafka_topic_partition_t *rktpar2;
                rd_kafka_broker_t *rkb = NULL;
                struct rd_kafka_partition_leader leader_skel;
                struct rd_kafka_partition_leader *leader;
                const rd_kafka_metadata_topic_t *mtopic;
                const rd_kafka_metadata_partition_t *mpart;
                rd_bool_t topic_wait_cache;

                rd_kafka_metadata_cache_topic_partition_get(
                    rk, &mtopic, &mpart, rktpar->topic, rktpar->partition,
                    0 /*negative entries too*/);

                topic_wait_cache =
                    !mtopic ||
                    RD_KAFKA_METADATA_CACHE_ERR_IS_TEMPORARY(mtopic->err);

                if (!topic_wait_cache && mtopic &&
                    mtopic->err != RD_KAFKA_RESP_ERR_NO_ERROR &&
                    mtopic->err != RD_KAFKA_RESP_ERR_LEADER_NOT_AVAILABLE) {
                        /* Topic permanently errored */
                        rktpar->err = mtopic->err;
                        continue;
                }

                if (mtopic && !mpart && mtopic->partition_cnt > 0) {
                        /* Topic exists but partition doesnt.
                         * This is a permanent error. */
                        rktpar->err = RD_KAFKA_RESP_ERR__UNKNOWN_PARTITION;
                        continue;
                }

                if (mpart &&
                    (mpart->leader == -1 ||
                     !(rkb = rd_kafka_broker_find_by_nodeid0(
                           rk, mpart->leader, -1 /*any state*/, rd_false)))) {
                        /* Partition has no (valid) leader.
                         * This is a permanent error. */
                        rktpar->err =
                            mtopic->err
                                ? mtopic->err
                                : RD_KAFKA_RESP_ERR_LEADER_NOT_AVAILABLE;
                        continue;
                }

                if (topic_wait_cache || !rkb) {
                        /* Topic unknown or no current leader for partition,
                         * add topic to query list. */
                        rktpar->err = RD_KAFKA_RESP_ERR__IN_PROGRESS;
                        if (query_topics &&
                            !rd_list_find(query_topics, rktpar->topic,
                                          (void *)strcmp))
                                rd_list_add(query_topics,
                                            rd_strdup(rktpar->topic));
                        continue;
                }

                /* Leader exists, add to leader list. */

                rktpar->err = RD_KAFKA_RESP_ERR_NO_ERROR;

                memset(&leader_skel, 0, sizeof(leader_skel));
                leader_skel.rkb = rkb;

                leader = rd_list_find(leaders, &leader_skel,
                                      rd_kafka_partition_leader_cmp);

                if (!leader) {
                        leader = rd_kafka_partition_leader_new(rkb);
                        rd_list_add(leaders, leader);
                }

                rktpar2 = rd_kafka_topic_partition_list_find(
                    leader->partitions, rktpar->topic, rktpar->partition);
                if (rktpar2) {
                        /* Already exists in partitions list, just update. */
                        rd_kafka_topic_partition_update(rktpar2, rktpar);
                } else {
                        /* Make a copy of rktpar and add to partitions list */
                        rd_kafka_topic_partition_list_add_copy(
                            leader->partitions, rktpar);
                }

                rktpar->err = RD_KAFKA_RESP_ERR_NO_ERROR;

                rd_kafka_broker_destroy(rkb); /* loose refcount */
                cnt++;
        }

        complete = cnt == rktparlist->cnt;

        if (!complete && eonce)
                /* Add eonce to cache observers */
                rd_kafka_metadata_cache_wait_state_change_async(rk, eonce);

        if (eonce)
                rd_kafka_wrunlock(rk);
        else
                rd_kafka_rdunlock(rk);

        return complete;
}


/**
 * @brief Timer timeout callback for query_leaders_async rko's eonce object.
 */
static void
rd_kafka_partition_leader_query_eonce_timeout_cb(rd_kafka_timers_t *rkts,
                                                 void *arg) {
        rd_kafka_enq_once_t *eonce = arg;
        rd_kafka_enq_once_trigger(eonce, RD_KAFKA_RESP_ERR__TIMED_OUT,
                                  "timeout timer");
}


/**
 * @brief Query timer callback for query_leaders_async rko's eonce object.
 */
static void
rd_kafka_partition_leader_query_eonce_timer_cb(rd_kafka_timers_t *rkts,
                                               void *arg) {
        rd_kafka_enq_once_t *eonce = arg;
        rd_kafka_enq_once_trigger(eonce, RD_KAFKA_RESP_ERR_NO_ERROR,
                                  "query timer");
}


/**
 * @brief Query metadata cache for partition leaders, or trigger metadata
 *        refresh if leaders not known.
 *
 * @locks_required none
 * @locality any
 */
static rd_kafka_op_res_t
rd_kafka_topic_partition_list_query_leaders_async_worker(rd_kafka_op_t *rko) {
        rd_kafka_t *rk = rko->rko_rk;
        rd_list_t query_topics, *leaders = NULL;
        rd_kafka_op_t *reply;

        RD_KAFKA_OP_TYPE_ASSERT(rko, RD_KAFKA_OP_LEADERS);

        if (rko->rko_err)
                goto reply; /* Timeout or ERR__DESTROY */

        /* Since we're iterating over get_leaders() until all partition leaders
         * are known we need to re-enable the eonce to be triggered again (which
         * is not necessary the first time we get here, but there
         * is no harm doing it then either). */
        rd_kafka_enq_once_reenable(rko->rko_u.leaders.eonce, rko,
                                   RD_KAFKA_REPLYQ(rk->rk_ops, 0));

        /* Look up the leaders in the metadata cache, if not all leaders
         * are known the eonce is registered for metadata cache changes
         * which will cause our function to be called
         * again on (any) metadata cache change.
         *
         * When we are called again we perform the cache lookup again and
         * hopefully get all leaders, otherwise defer a new async wait.
         * Repeat until success or timeout. */

        rd_list_init(&query_topics, 4 + rko->rko_u.leaders.partitions->cnt / 2,
                     rd_free);

        leaders = rd_list_new(1 + rko->rko_u.leaders.partitions->cnt / 2,
                              rd_kafka_partition_leader_destroy_free);

        if (rd_kafka_topic_partition_list_get_leaders(
                rk, rko->rko_u.leaders.partitions, leaders, &query_topics,
                /* Add unknown topics to query_topics only on the
                 * first query, after that we consider them permanently
                 * non-existent */
                rko->rko_u.leaders.query_cnt == 0, rko->rko_u.leaders.eonce)) {
                /* All leaders now known (or failed), reply to caller */
                rd_list_destroy(&query_topics);
                goto reply;
        }

        if (rd_list_empty(&query_topics)) {
                /* Not all leaders known but no topics left to query,
                 * reply to caller. */
                rd_list_destroy(&query_topics);
                goto reply;
        }

        /* Need to refresh topic metadata, but at most every interval. */
        if (!rd_kafka_timer_is_started(&rk->rk_timers,
                                       &rko->rko_u.leaders.query_tmr)) {

                rko->rko_u.leaders.query_cnt++;

                /* Add query interval timer. */
                rd_kafka_enq_once_add_source(rko->rko_u.leaders.eonce,
                                             "query timer");
                rd_kafka_timer_start_oneshot(
                    &rk->rk_timers, &rko->rko_u.leaders.query_tmr, rd_true,
                    3 * 1000 * 1000 /* 3s */,
                    rd_kafka_partition_leader_query_eonce_timer_cb,
                    rko->rko_u.leaders.eonce);

                /* Request metadata refresh */
                rd_kafka_metadata_refresh_topics(
                    rk, NULL, &query_topics, rd_true /*force*/,
                    rd_false /*!allow_auto_create*/, rd_false /*!cgrp_update*/,
                    "query partition leaders");
        }

        rd_list_destroy(leaders);
        rd_list_destroy(&query_topics);

        /* Wait for next eonce trigger */
        return RD_KAFKA_OP_RES_KEEP; /* rko is still used */

reply:
        /* Decommission worker state and reply to caller */

        if (rd_kafka_timer_stop(&rk->rk_timers, &rko->rko_u.leaders.query_tmr,
                                RD_DO_LOCK))
                rd_kafka_enq_once_del_source(rko->rko_u.leaders.eonce,
                                             "query timer");
        if (rd_kafka_timer_stop(&rk->rk_timers, &rko->rko_u.leaders.timeout_tmr,
                                RD_DO_LOCK))
                rd_kafka_enq_once_del_source(rko->rko_u.leaders.eonce,
                                             "timeout timer");

        if (rko->rko_u.leaders.eonce) {
                rd_kafka_enq_once_disable(rko->rko_u.leaders.eonce);
                rko->rko_u.leaders.eonce = NULL;
        }

        /* No leaders found, set a request-level error */
        if (leaders && rd_list_cnt(leaders) == 0) {
                if (!rko->rko_err)
                        rko->rko_err = RD_KAFKA_RESP_ERR__NOENT;
                rd_list_destroy(leaders);
                leaders = NULL;
        }

        /* Create and enqueue reply rko */
        if (rko->rko_u.leaders.replyq.q) {
                reply = rd_kafka_op_new_cb(rk, RD_KAFKA_OP_LEADERS,
                                           rko->rko_u.leaders.cb);
                rd_kafka_op_get_reply_version(reply, rko);
                reply->rko_err = rko->rko_err;
                reply->rko_u.leaders.partitions =
                    rko->rko_u.leaders.partitions; /* Transfer ownership for
                                                    * partition list that
                                                    * now contains
                                                    * per-partition errors*/
                rko->rko_u.leaders.partitions = NULL;
                reply->rko_u.leaders.leaders  = leaders; /* Possibly NULL */
                reply->rko_u.leaders.opaque   = rko->rko_u.leaders.opaque;

                rd_kafka_replyq_enq(&rko->rko_u.leaders.replyq, reply, 0);
        }

        return RD_KAFKA_OP_RES_HANDLED;
}


static rd_kafka_op_res_t
rd_kafka_topic_partition_list_query_leaders_async_worker_op_cb(
    rd_kafka_t *rk,
    rd_kafka_q_t *rkq,
    rd_kafka_op_t *rko) {
        return rd_kafka_topic_partition_list_query_leaders_async_worker(rko);
}

/**
 * @brief Async variant of rd_kafka_topic_partition_list_query_leaders().
 *
 * The reply rko op will contain:
 * - .leaders which is a list of leaders and their partitions, this may be
 *    NULL for overall errors (such as no leaders are found), or a
 *    partial or complete list of leaders.
 * - .partitions which is a copy of the input list of partitions with the
 *   .err field set to the outcome of the leader query, typically ERR_NO_ERROR
 *   or ERR_UNKNOWN_TOPIC_OR_PART.
 *
 * @locks_acquired rd_kafka_*lock()
 *
 * @remark rd_kafka_*lock() MUST NOT be held
 */
void rd_kafka_topic_partition_list_query_leaders_async(
    rd_kafka_t *rk,
    const rd_kafka_topic_partition_list_t *rktparlist,
    int timeout_ms,
    rd_kafka_replyq_t replyq,
    rd_kafka_op_cb_t *cb,
    void *opaque) {
        rd_kafka_op_t *rko;

        rd_assert(rktparlist && rktparlist->cnt > 0);
        rd_assert(replyq.q);

        rko = rd_kafka_op_new_cb(
            rk, RD_KAFKA_OP_LEADERS,
            rd_kafka_topic_partition_list_query_leaders_async_worker_op_cb);
        rko->rko_u.leaders.replyq = replyq;
        rko->rko_u.leaders.partitions =
            rd_kafka_topic_partition_list_copy(rktparlist);
        rko->rko_u.leaders.ts_timeout = rd_timeout_init(timeout_ms);
        rko->rko_u.leaders.cb         = cb;
        rko->rko_u.leaders.opaque     = opaque;

        /* Create an eonce to be triggered either by metadata cache update
         * (from refresh_topics()), query interval, or timeout. */
        rko->rko_u.leaders.eonce =
            rd_kafka_enq_once_new(rko, RD_KAFKA_REPLYQ(rk->rk_ops, 0));

        rd_kafka_enq_once_add_source(rko->rko_u.leaders.eonce, "timeout timer");
        rd_kafka_timer_start_oneshot(
            &rk->rk_timers, &rko->rko_u.leaders.timeout_tmr, rd_true,
            rd_timeout_remains_us(rko->rko_u.leaders.ts_timeout),
            rd_kafka_partition_leader_query_eonce_timeout_cb,
            rko->rko_u.leaders.eonce);

        if (rd_kafka_topic_partition_list_query_leaders_async_worker(rko) ==
            RD_KAFKA_OP_RES_HANDLED)
                rd_kafka_op_destroy(rko); /* Reply queue already disabled */
}


/**
 * @brief Get leaders for all partitions in \p rktparlist, querying metadata
 *        if needed.
 *
 * @param leaders is a pre-initialized (empty) list which will be populated
 *        with the leader brokers and their partitions
 *        (struct rd_kafka_partition_leader *)
 *
 * @remark Will not trigger topic auto creation (unless configured).
 *
 * @returns an error code on error.
 *
 * @locks rd_kafka_*lock() MUST NOT be held
 */
rd_kafka_resp_err_t rd_kafka_topic_partition_list_query_leaders(
    rd_kafka_t *rk,
    rd_kafka_topic_partition_list_t *rktparlist,
    rd_list_t *leaders,
    int timeout_ms) {
        rd_ts_t ts_end   = rd_timeout_init(timeout_ms);
        rd_ts_t ts_query = 0;
        rd_ts_t now;
        int query_cnt = 0;
        int i         = 0;

        /* Get all the partition leaders, try multiple times:
         * if there are no leaders after the first run fire off a leader
         * query and wait for broker state update before trying again,
         * keep trying and re-querying at increasing intervals until
         * success or timeout. */
        do {
                rd_list_t query_topics;
                int query_intvl;

                rd_list_init(&query_topics, rktparlist->cnt, rd_free);

                rd_kafka_topic_partition_list_get_leaders(
                    rk, rktparlist, leaders, &query_topics,
                    /* Add unknown topics to query_topics only on the
                     * first query, after that we consider them
                     * permanently non-existent */
                    query_cnt == 0, NULL);

                if (rd_list_empty(&query_topics)) {
                        /* No remaining topics to query: leader-list complete.*/
                        rd_list_destroy(&query_topics);

                        /* No leader(s) for partitions means all partitions
                         * are unknown. */
                        if (rd_list_empty(leaders))
                                return RD_KAFKA_RESP_ERR__UNKNOWN_PARTITION;

                        return RD_KAFKA_RESP_ERR_NO_ERROR;
                }

                now = rd_clock();

                /*
                 * Missing leader for some partitions
                 */
                query_intvl = (i + 1) * 100; /* add 100ms per iteration */
                if (query_intvl > 2 * 1000)
                        query_intvl = 2 * 1000; /* Cap to 2s */

                if (now >= ts_query + (query_intvl * 1000)) {
                        /* Query metadata for missing leaders,
                         * possibly creating the topic. */
                        rd_kafka_metadata_refresh_topics(
                            rk, NULL, &query_topics, rd_true /*force*/,
                            rd_false /*!allow_auto_create*/,
                            rd_false /*!cgrp_update*/,
                            "query partition leaders");
                        ts_query = now;
                        query_cnt++;

                } else {
                        /* Wait for broker ids to be updated from
                         * metadata refresh above. */
                        int wait_ms =
                            rd_timeout_remains_limit(ts_end, query_intvl);
                        rd_kafka_metadata_cache_wait_change(rk, wait_ms);
                }

                rd_list_destroy(&query_topics);

                i++;
        } while (ts_end == RD_POLL_INFINITE ||
                 now < ts_end); /* now is deliberately outdated here
                                 * since wait_change() will block.
                                 * This gives us one more chance to spin thru*/

        if (rd_atomic32_get(&rk->rk_broker_up_cnt) == 0)
                return RD_KAFKA_RESP_ERR__ALL_BROKERS_DOWN;

        return RD_KAFKA_RESP_ERR__TIMED_OUT;
}


/**
 * @brief Populate \p rkts with the rd_kafka_topic_t objects for the
 *        partitions in. Duplicates are suppressed.
 *
 * @returns the number of topics added.
 */
int rd_kafka_topic_partition_list_get_topics(
    rd_kafka_t *rk,
    rd_kafka_topic_partition_list_t *rktparlist,
    rd_list_t *rkts) {
        int cnt = 0;

        int i;
        for (i = 0; i < rktparlist->cnt; i++) {
                rd_kafka_topic_partition_t *rktpar = &rktparlist->elems[i];
                rd_kafka_toppar_t *rktp;

                rktp =
                    rd_kafka_topic_partition_get_toppar(rk, rktpar, rd_false);
                if (!rktp) {
                        rktpar->err = RD_KAFKA_RESP_ERR__UNKNOWN_PARTITION;
                        continue;
                }

                if (!rd_list_find(rkts, rktp->rktp_rkt,
                                  rd_kafka_topic_cmp_rkt)) {
                        rd_list_add(rkts, rd_kafka_topic_keep(rktp->rktp_rkt));
                        cnt++;
                }

                rd_kafka_toppar_destroy(rktp);
        }

        return cnt;
}


/**
 * @brief Populate \p topics with the strdupped topic names in \p rktparlist.
 *        Duplicates are suppressed.
 *
 * @param include_regex: include regex topics
 *
 * @returns the number of topics added.
 */
int rd_kafka_topic_partition_list_get_topic_names(
    const rd_kafka_topic_partition_list_t *rktparlist,
    rd_list_t *topics,
    int include_regex) {
        int cnt = 0;
        int i;

        for (i = 0; i < rktparlist->cnt; i++) {
                const rd_kafka_topic_partition_t *rktpar =
                    &rktparlist->elems[i];

                if (!include_regex && *rktpar->topic == '^')
                        continue;

                if (!rd_list_find(topics, rktpar->topic, (void *)strcmp)) {
                        rd_list_add(topics, rd_strdup(rktpar->topic));
                        cnt++;
                }
        }

        return cnt;
}


/**
 * @brief Create a copy of \p rktparlist only containing the partitions
 *        matched by \p match function.
 *
 * \p match shall return 1 for match, else 0.
 *
 * @returns a new list
 */
rd_kafka_topic_partition_list_t *rd_kafka_topic_partition_list_match(
    const rd_kafka_topic_partition_list_t *rktparlist,
    int (*match)(const void *elem, const void *opaque),
    void *opaque) {
        rd_kafka_topic_partition_list_t *newlist;
        int i;

        newlist = rd_kafka_topic_partition_list_new(0);

        for (i = 0; i < rktparlist->cnt; i++) {
                const rd_kafka_topic_partition_t *rktpar =
                    &rktparlist->elems[i];

                if (!match(rktpar, opaque))
                        continue;

                rd_kafka_topic_partition_list_add_copy(newlist, rktpar);
        }

        return newlist;
}

void rd_kafka_topic_partition_list_log(
    rd_kafka_t *rk,
    const char *fac,
    int dbg,
    const rd_kafka_topic_partition_list_t *rktparlist) {
        int i;

        rd_kafka_dbg(rk, NONE | dbg, fac,
                     "List with %d partition(s):", rktparlist->cnt);
        for (i = 0; i < rktparlist->cnt; i++) {
                const rd_kafka_topic_partition_t *rktpar =
                    &rktparlist->elems[i];
                rd_kafka_dbg(rk, NONE | dbg, fac,
                             " %s [%" PRId32 "] offset %s%s%s", rktpar->topic,
                             rktpar->partition,
                             rd_kafka_offset2str(rktpar->offset),
                             rktpar->err ? ": error: " : "",
                             rktpar->err ? rd_kafka_err2str(rktpar->err) : "");
        }
}

/**
 * @returns a comma-separated list of partitions.
 */
const char *rd_kafka_topic_partition_list_str(
    const rd_kafka_topic_partition_list_t *rktparlist,
    char *dest,
    size_t dest_size,
    int fmt_flags) {
        int i;
        size_t of = 0;

        for (i = 0; i < rktparlist->cnt; i++) {
                const rd_kafka_topic_partition_t *rktpar =
                    &rktparlist->elems[i];
                char errstr[128];
                char offsetstr[32];
                int r;

                if (!rktpar->err && (fmt_flags & RD_KAFKA_FMT_F_ONLY_ERR))
                        continue;

                if (rktpar->err && !(fmt_flags & RD_KAFKA_FMT_F_NO_ERR))
                        rd_snprintf(errstr, sizeof(errstr), "(%s)",
                                    rd_kafka_err2str(rktpar->err));
                else
                        errstr[0] = '\0';

                if (rktpar->offset != RD_KAFKA_OFFSET_INVALID)
                        rd_snprintf(offsetstr, sizeof(offsetstr), "@%" PRId64,
                                    rktpar->offset);
                else
                        offsetstr[0] = '\0';

                r = rd_snprintf(&dest[of], dest_size - of,
                                "%s"
                                "%s[%" PRId32
                                "]"
                                "%s"
                                "%s",
                                of == 0 ? "" : ", ", rktpar->topic,
                                rktpar->partition, offsetstr, errstr);

                if ((size_t)r >= dest_size - of) {
                        rd_snprintf(&dest[dest_size - 4], 4, "...");
                        break;
                }

                of += r;
        }

        return dest;
}



/**
 * @brief Update \p dst with info from \p src.
 *
 * Fields updated:
 *  - metadata
 *  - metadata_size
 *  - offset
 *  - offset leader epoch
 *  - err
 *
 * Will only update partitions that are in both dst and src, other partitions
 * will remain unchanged.
 */
void rd_kafka_topic_partition_list_update(
    rd_kafka_topic_partition_list_t *dst,
    const rd_kafka_topic_partition_list_t *src) {
        int i;

        for (i = 0; i < dst->cnt; i++) {
                rd_kafka_topic_partition_t *d = &dst->elems[i];
                rd_kafka_topic_partition_t *s;
                rd_kafka_topic_partition_private_t *s_priv, *d_priv;

                if (!(s = rd_kafka_topic_partition_list_find(
                          (rd_kafka_topic_partition_list_t *)src, d->topic,
                          d->partition)))
                        continue;

                d->offset = s->offset;
                d->err    = s->err;
                if (d->metadata) {
                        rd_free(d->metadata);
                        d->metadata      = NULL;
                        d->metadata_size = 0;
                }
                if (s->metadata_size > 0) {
                        d->metadata      = rd_malloc(s->metadata_size);
                        d->metadata_size = s->metadata_size;
                        memcpy((void *)d->metadata, s->metadata,
                               s->metadata_size);
                }

                s_priv               = rd_kafka_topic_partition_get_private(s);
                d_priv               = rd_kafka_topic_partition_get_private(d);
                d_priv->leader_epoch = s_priv->leader_epoch;
        }
}


/**
 * @returns the sum of \p cb called for each element.
 */
size_t rd_kafka_topic_partition_list_sum(
    const rd_kafka_topic_partition_list_t *rktparlist,
    size_t (*cb)(const rd_kafka_topic_partition_t *rktpar, void *opaque),
    void *opaque) {
        int i;
        size_t sum = 0;

        for (i = 0; i < rktparlist->cnt; i++) {
                const rd_kafka_topic_partition_t *rktpar =
                    &rktparlist->elems[i];
                sum += cb(rktpar, opaque);
        }

        return sum;
}


/**
 * @returns rd_true if there are duplicate topic/partitions in the list,
 *          rd_false if not.
 *
 * @remarks sorts the elements of the list.
 */
rd_bool_t rd_kafka_topic_partition_list_has_duplicates(
    rd_kafka_topic_partition_list_t *rktparlist,
    rd_bool_t ignore_partition) {

        int i;

        if (rktparlist->cnt <= 1)
                return rd_false;

        rd_kafka_topic_partition_list_sort_by_topic(rktparlist);

        for (i = 1; i < rktparlist->cnt; i++) {
                const rd_kafka_topic_partition_t *p1 =
                    &rktparlist->elems[i - 1];
                const rd_kafka_topic_partition_t *p2 = &rktparlist->elems[i];

                if (((p1->partition == p2->partition) || ignore_partition) &&
                    !strcmp(p1->topic, p2->topic)) {
                        return rd_true;
                }
        }

        return rd_false;
}


/**
 * @brief Set \c .err field \p err on all partitions in list.
 */
void rd_kafka_topic_partition_list_set_err(
    rd_kafka_topic_partition_list_t *rktparlist,
    rd_kafka_resp_err_t err) {
        int i;

        for (i = 0; i < rktparlist->cnt; i++)
                rktparlist->elems[i].err = err;
}

/**
 * @brief Get the first set error in the partition list.
 */
rd_kafka_resp_err_t rd_kafka_topic_partition_list_get_err(
    const rd_kafka_topic_partition_list_t *rktparlist) {
        int i;

        for (i = 0; i < rktparlist->cnt; i++)
                if (rktparlist->elems[i].err)
                        return rktparlist->elems[i].err;

        return RD_KAFKA_RESP_ERR_NO_ERROR;
}


/**
 * @returns the number of wildcard/regex topics
 */
int rd_kafka_topic_partition_list_regex_cnt(
    const rd_kafka_topic_partition_list_t *rktparlist) {
        int i;
        int cnt = 0;

        for (i = 0; i < rktparlist->cnt; i++) {
                const rd_kafka_topic_partition_t *rktpar =
                    &rktparlist->elems[i];
                cnt += *rktpar->topic == '^';
        }
        return cnt;
}


/**
 * @brief Reset base sequence for this toppar.
 *
 * See rd_kafka_toppar_pid_change() below.
 *
 * @warning Toppar must be completely drained.
 *
 * @locality toppar handler thread
 * @locks toppar_lock MUST be held.
 */
static void rd_kafka_toppar_reset_base_msgid(rd_kafka_toppar_t *rktp,
                                             uint64_t new_base_msgid) {
        rd_kafka_dbg(
            rktp->rktp_rkt->rkt_rk, TOPIC | RD_KAFKA_DBG_EOS, "RESETSEQ",
            "%.*s [%" PRId32
            "] "
            "resetting epoch base seq from %" PRIu64 " to %" PRIu64,
            RD_KAFKAP_STR_PR(rktp->rktp_rkt->rkt_topic), rktp->rktp_partition,
            rktp->rktp_eos.epoch_base_msgid, new_base_msgid);

        rktp->rktp_eos.next_ack_seq     = 0;
        rktp->rktp_eos.next_err_seq     = 0;
        rktp->rktp_eos.epoch_base_msgid = new_base_msgid;
}


/**
 * @brief Update/change the Producer ID for this toppar.
 *
 * Must only be called when pid is different from the current toppar pid.
 *
 * The epoch base sequence will be set to \p base_msgid, which must be the
 * first message in the partition
 * queue. However, if there are outstanding messages in-flight to the broker
 * we will need to wait for these ProduceRequests to finish (most likely
 * with failure) and have their messages re-enqueued to maintain original order.
 * In this case the pid will not be updated and this function should be
 * called again when there are no outstanding messages.
 *
 * @remark This function must only be called when rktp_xmitq is non-empty.
 *
 * @returns 1 if a new pid was set, else 0.
 *
 * @locality toppar handler thread
 * @locks none
 */
int rd_kafka_toppar_pid_change(rd_kafka_toppar_t *rktp,
                               rd_kafka_pid_t pid,
                               uint64_t base_msgid) {
        int inflight = rd_atomic32_get(&rktp->rktp_msgs_inflight);

        if (unlikely(inflight > 0)) {
                rd_kafka_dbg(
                    rktp->rktp_rkt->rkt_rk, TOPIC | RD_KAFKA_DBG_EOS, "NEWPID",
                    "%.*s [%" PRId32
                    "] will not change %s -> %s yet: "
                    "%d message(s) still in-flight from current "
                    "epoch",
                    RD_KAFKAP_STR_PR(rktp->rktp_rkt->rkt_topic),
                    rktp->rktp_partition, rd_kafka_pid2str(rktp->rktp_eos.pid),
                    rd_kafka_pid2str(pid), inflight);
                return 0;
        }

        rd_assert(base_msgid != 0 &&
                  *"BUG: pid_change() must only be called with "
                  "non-empty xmitq");

        rd_kafka_toppar_lock(rktp);
        rd_kafka_dbg(rktp->rktp_rkt->rkt_rk, TOPIC | RD_KAFKA_DBG_EOS, "NEWPID",
                     "%.*s [%" PRId32
                     "] changed %s -> %s "
                     "with base MsgId %" PRIu64,
                     RD_KAFKAP_STR_PR(rktp->rktp_rkt->rkt_topic),
                     rktp->rktp_partition, rd_kafka_pid2str(rktp->rktp_eos.pid),
                     rd_kafka_pid2str(pid), base_msgid);

        rktp->rktp_eos.pid = pid;
        rd_kafka_toppar_reset_base_msgid(rktp, base_msgid);

        rd_kafka_toppar_unlock(rktp);

        return 1;
}


/**
 * @brief Purge messages in partition queues.
 *        Delivery reports will be enqueued for all purged messages, the error
 *        code is set to RD_KAFKA_RESP_ERR__PURGE_QUEUE.
 *
 * @param include_xmit_msgq If executing from the rktp's current broker handler
 *                          thread, also include the xmit message queue.
 *
 * @warning Only to be used with the producer.
 *
 * @returns the number of messages purged
 *
 * @locality any thread.
 * @locks_acquired rd_kafka_toppar_lock()
 * @locks_required none
 */
int rd_kafka_toppar_purge_queues(rd_kafka_toppar_t *rktp,
                                 int purge_flags,
                                 rd_bool_t include_xmit_msgq) {
        rd_kafka_t *rk       = rktp->rktp_rkt->rkt_rk;
        rd_kafka_msgq_t rkmq = RD_KAFKA_MSGQ_INITIALIZER(rkmq);
        int cnt;

        rd_assert(rk->rk_type == RD_KAFKA_PRODUCER);

        rd_kafka_dbg(rk, TOPIC, "PURGE",
                     "%s [%" PRId32
                     "]: purging queues "
                     "(purge_flags 0x%x, %s xmit_msgq)",
                     rktp->rktp_rkt->rkt_topic->str, rktp->rktp_partition,
                     purge_flags, include_xmit_msgq ? "include" : "exclude");

        if (!(purge_flags & RD_KAFKA_PURGE_F_QUEUE))
                return 0;

        if (include_xmit_msgq) {
                /* xmit_msgq is owned by the toppar handler thread
                 * (broker thread) and requires no locking. */
                rd_assert(rktp->rktp_broker);
                rd_assert(thrd_is_current(rktp->rktp_broker->rkb_thread));
                rd_kafka_msgq_concat(&rkmq, &rktp->rktp_xmit_msgq);
        }

        rd_kafka_toppar_lock(rktp);
        rd_kafka_msgq_concat(&rkmq, &rktp->rktp_msgq);
        cnt = rd_kafka_msgq_len(&rkmq);

        if (cnt > 0 && purge_flags & RD_KAFKA_PURGE_F_ABORT_TXN) {
                /* All messages in-queue are purged
                 * on abort_transaction(). Since these messages
                 * will not be produced (retried) we need to adjust the
                 * idempotence epoch's base msgid to skip the messages. */
                rktp->rktp_eos.epoch_base_msgid += cnt;
                rd_kafka_dbg(rk, TOPIC | RD_KAFKA_DBG_EOS, "ADVBASE",
                             "%.*s [%" PRId32
                             "] "
                             "advancing epoch base msgid to %" PRIu64
                             " due to %d message(s) in aborted transaction",
                             RD_KAFKAP_STR_PR(rktp->rktp_rkt->rkt_topic),
                             rktp->rktp_partition,
                             rktp->rktp_eos.epoch_base_msgid, cnt);
        }
        rd_kafka_toppar_unlock(rktp);

        rd_kafka_dr_msgq(rktp->rktp_rkt, &rkmq, RD_KAFKA_RESP_ERR__PURGE_QUEUE);

        return cnt;
}


/**
 * @brief Purge queues for the unassigned toppars of all known topics.
 *
 * @locality application thread
 * @locks none
 */
void rd_kafka_purge_ua_toppar_queues(rd_kafka_t *rk) {
        rd_kafka_topic_t *rkt;
        int msg_cnt = 0, part_cnt = 0;

        rd_kafka_rdlock(rk);
        TAILQ_FOREACH(rkt, &rk->rk_topics, rkt_link) {
                rd_kafka_toppar_t *rktp;
                int r;

                rd_kafka_topic_rdlock(rkt);
                rktp = rkt->rkt_ua;
                if (rktp)
                        rd_kafka_toppar_keep(rktp);
                rd_kafka_topic_rdunlock(rkt);

                if (unlikely(!rktp))
                        continue;


                rd_kafka_toppar_lock(rktp);

                r = rd_kafka_msgq_len(&rktp->rktp_msgq);
                rd_kafka_dr_msgq(rkt, &rktp->rktp_msgq,
                                 RD_KAFKA_RESP_ERR__PURGE_QUEUE);
                rd_kafka_toppar_unlock(rktp);
                rd_kafka_toppar_destroy(rktp);

                if (r > 0) {
                        msg_cnt += r;
                        part_cnt++;
                }
        }
        rd_kafka_rdunlock(rk);

        rd_kafka_dbg(rk, QUEUE | RD_KAFKA_DBG_TOPIC, "PURGEQ",
                     "Purged %i message(s) from %d UA-partition(s)", msg_cnt,
                     part_cnt);
}


void rd_kafka_partition_leader_destroy_free(void *ptr) {
        struct rd_kafka_partition_leader *leader = ptr;
        rd_kafka_partition_leader_destroy(leader);
}


const char *rd_kafka_fetch_pos2str(const rd_kafka_fetch_pos_t fetchpos) {
        static RD_TLS char ret[2][64];
        static int idx;

        idx = (idx + 1) % 2;

        rd_snprintf(
            ret[idx], sizeof(ret[idx]), "offset %s (leader epoch %" PRId32 ")",
            rd_kafka_offset2str(fetchpos.offset), fetchpos.leader_epoch);

        return ret[idx];
}