rocketmq-client-rust 1.0.0

Rust implementation of Apache rocketmq client
Documentation
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
// Copyright 2023 The RocketMQ Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::Arc;
use std::sync::RwLock as StdRwLock;

use crate::ClientError;
use crate::ClientResult;
use arc_swap::ArcSwap;
use cheetah_string::CheetahString;
use rocketmq_model::common::consumer::consume_from_where::ConsumeFromWhere;
use rocketmq_model::common::message::message_ext::MessageExt;
use rocketmq_model::common::message::message_queue::MessageQueue;
use rocketmq_model::common::topic::TopicValidator;
use rocketmq_protocol::common::message::message_decoder as MessageDecoder;
use rocketmq_protocol::protocol::body::consumer_running_info::ConsumerRunningInfo;
use rocketmq_protocol::protocol::heartbeat::message_model::MessageModel;
use rocketmq_protocol::protocol::heartbeat::subscription_data::SubscriptionData;
use rocketmq_protocol::protocol::namespace_util::NamespaceUtil;
use rocketmq_transport::api::RPCHook;
use tokio::sync::OnceCell;
use tokio::sync::RwLock;

use crate::base::client_config::ClientConfig;
use crate::base::client_options::ClientOptions;
use crate::base::query_result::QueryResult;
use crate::consumer::allocate_message_queue_strategy::AllocateMessageQueueStrategy;
use crate::consumer::consumer_impl::default_lite_pull_consumer_impl::validate_lite_pull_consume_from_where;
use crate::consumer::consumer_impl::default_lite_pull_consumer_impl::DefaultLitePullConsumerImpl;
use crate::consumer::consumer_impl::default_lite_pull_consumer_impl::LitePullConsumerConfig;
use crate::consumer::default_lite_pull_consumer_builder::DefaultLitePullConsumerBuilder;
use crate::consumer::default_lite_pull_consumer_builder::MIN_AUTOCOMMIT_INTERVAL_MILLIS;
use crate::consumer::lite_pull_consumer::{
    AssignmentControl, ConsumerLifecycle, ConsumerOffsetControl, MessagePoll, SubscriptionControl,
};
use crate::consumer::message_queue_listener::ArcMessageQueueListener;
use crate::consumer::message_queue_listener::MessageQueueListener;
use crate::consumer::message_selector::MessageSelector;
use crate::consumer::mq_consumer::MQConsumer;
use crate::consumer::mq_consumer_inner::MQConsumerInner;
use crate::consumer::store::offset_store::OffsetStore;
use crate::consumer::topic_message_queue_change_listener::TopicMessageQueueChangeListener;
use crate::nameserver_discovery::NameServerDiscoveryConfig;
use crate::runtime::ClientRuntime;
use crate::session::ClientSession;
use crate::session::ClientSessionProvider;
use crate::trace::async_trace_dispatcher::AsyncTraceDispatcher;
use crate::trace::hook::consume_message_trace_hook_impl::ConsumeMessageTraceHookImpl;
use crate::trace::trace_dispatcher::TraceDispatcher;
use crate::trace::trace_dispatcher::Type;

/// Default implementation of a lite pull consumer.
///
/// This is the main entry point for creating and using a lite pull consumer. It acts as a facade
/// over the internal implementation (`DefaultLitePullConsumerImpl`) and provides:
///
/// - Configuration management via [`DefaultLitePullConsumerBuilder`]
/// - Namespace handling (automatic topic name wrapping/unwrapping)
/// - Optional message trace integration
/// - A clean public API that delegates to the internal implementation
///
/// # Architecture
///
/// ```text
/// ┌────────────────────────────────────┐
/// │   DefaultLitePullConsumer          │  ← Public Facade
/// │  (config, trace, namespace)        │
/// └──────────────┬─────────────────────┘
///                │ delegates
///                ↓
/// ┌────────────────────────────────────┐
/// │ DefaultLitePullConsumerImpl        │  ← Core Logic
/// │  (lifecycle, pull, commit, etc.)   │
/// └────────────────────────────────────┘
/// ```
///
/// # Examples
///
/// ## Basic usage with auto-commit
///
/// ```rust,ignore
/// use rocketmq_client::DefaultLitePullConsumer;
///
/// let consumer = DefaultLitePullConsumer::builder(client_runtime.clone())
///     .consumer_group("my_consumer_group")
///     .name_server_addr("127.0.0.1:9876")
///     .auto_commit(true)
///     .build()?;
///
/// consumer.start().await?;
/// consumer.subscribe("my_topic").await?;
///
/// loop {
///     let messages = consumer.poll_with_timeout(1000).await;
///     for msg in messages {
///         println!("Received: {:?}", msg);
///     }
///     // Offsets are auto-committed
/// }
/// ```
///
/// ## Manual offset control
///
/// ```rust,ignore
/// let consumer = DefaultLitePullConsumer::builder(client_runtime.clone())
///     .consumer_group("my_consumer_group")
///     .name_server_addr("127.0.0.1:9876")
///     .auto_commit(false)  // Disable auto-commit
///     .build()?;
///
/// consumer.start().await?;
/// consumer.subscribe("my_topic").await?;
///
/// loop {
///     let messages = consumer.poll_with_timeout(1000).await;
///     for msg in messages {
///         // Process message
///     }
///     
///     // Manually commit after processing
///     consumer.commit_all().await?;
/// }
/// ```
///
/// ## Manual queue assignment (no rebalance)
///
/// ```rust,ignore
/// use rocketmq_model::common::message::message_queue::MessageQueue;
///
/// let mq1 = MessageQueue::from_parts("my_topic", "broker-a", 0);
/// let mq2 = MessageQueue::from_parts("my_topic", "broker-a", 1);
///
/// consumer.start().await?;
/// consumer.assign(vec![mq1, mq2]).await?;
///
/// let messages = consumer.poll().await;
/// ```
#[derive(Clone)]
pub struct DefaultLitePullConsumer {
    session: ClientSession,
    /// Client configuration (network, instance name, etc.)
    client_config: Arc<ArcSwap<ClientConfig>>,
    nameserver_discovery: Option<NameServerDiscoveryConfig>,

    /// Consumer-specific configuration (pull batch size, flow control, etc.)
    consumer_config: Arc<ArcSwap<LitePullConsumerConfig>>,

    /// Core implementation (lazy-initialized on start using OnceCell)
    default_lite_pull_consumer_impl: Arc<OnceCell<Arc<DefaultLitePullConsumerImpl>>>,

    /// Optional RPC hook for request/response interception
    rpc_hook: Option<Arc<dyn RPCHook>>,

    /// Optional trace dispatcher for message tracing (with interior mutability)
    trace_dispatcher: Arc<RwLock<Option<Arc<dyn TraceDispatcher + Send + Sync>>>>,

    /// Whether message trace is enabled
    enable_msg_trace: bool,

    /// Custom trace topic (if specified)
    custom_trace_topic: Option<CheetahString>,

    /// User listener notified after LitePull rebalance updates assigned queues.
    message_queue_listener: Arc<StdRwLock<Option<ArcMessageQueueListener>>>,

    /// User-provided or initialized offset store.
    offset_store: Arc<StdRwLock<Option<Arc<OffsetStore>>>>,
}

impl DefaultLitePullConsumer {
    /// Creates a new consumer with the specified configuration.
    ///
    /// Most users should use [`builder()`](Self::builder) instead.
    pub fn new(
        client_runtime: Arc<ClientRuntime>,
        client_config: ClientConfig,
        consumer_config: LitePullConsumerConfig,
        rpc_hook: Option<Arc<dyn RPCHook>>,
        trace_dispatcher: Option<Arc<dyn TraceDispatcher + Send + Sync>>,
        enable_msg_trace: bool,
        custom_trace_topic: Option<CheetahString>,
    ) -> Self {
        Self::new_with_options(
            client_runtime,
            ClientOptions::legacy(client_config),
            consumer_config,
            rpc_hook,
            trace_dispatcher,
            enable_msg_trace,
            custom_trace_topic,
        )
    }

    pub(crate) fn new_with_options(
        client_runtime: Arc<ClientRuntime>,
        options: ClientOptions,
        consumer_config: LitePullConsumerConfig,
        rpc_hook: Option<Arc<dyn RPCHook>>,
        trace_dispatcher: Option<Arc<dyn TraceDispatcher + Send + Sync>>,
        enable_msg_trace: bool,
        custom_trace_topic: Option<CheetahString>,
    ) -> Self {
        Self {
            session: ClientSession::new(client_runtime),
            client_config: Arc::new(ArcSwap::from_pointee(options.client_config().clone())),
            nameserver_discovery: options.nameserver_discovery().cloned(),
            consumer_config: Arc::new(ArcSwap::from_pointee(consumer_config)),
            default_lite_pull_consumer_impl: Arc::new(OnceCell::new()),
            rpc_hook,
            trace_dispatcher: Arc::new(RwLock::new(trace_dispatcher)),
            enable_msg_trace,
            custom_trace_topic,
            message_queue_listener: Arc::new(StdRwLock::new(None)),
            offset_store: Arc::new(StdRwLock::new(None)),
        }
    }

    fn client_config_snapshot(&self) -> Arc<ClientConfig> {
        self.client_config.load_full()
    }

    fn consumer_config_snapshot(&self) -> Arc<LitePullConsumerConfig> {
        self.consumer_config.load_full()
    }

    fn update_client_config(&self, update: impl Fn(&mut ClientConfig)) {
        self.client_config.rcu(|current| {
            let mut next = (**current).clone();
            update(&mut next);
            Arc::new(next)
        });
    }

    fn update_consumer_config(&self, update: impl Fn(&mut LitePullConsumerConfig)) {
        self.consumer_config.rcu(|current| {
            let mut next = (**current).clone();
            update(&mut next);
            Arc::new(next)
        });
    }

    /// Returns a builder for creating a consumer with custom configuration.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let consumer = DefaultLitePullConsumer::builder(client_runtime.clone())
    ///     .consumer_group("my_group")
    ///     .name_server_addr("127.0.0.1:9876")
    ///     .pull_batch_size(32)
    ///     .build()?;
    /// ```
    pub fn builder(client_runtime: Arc<ClientRuntime>) -> DefaultLitePullConsumerBuilder {
        DefaultLitePullConsumerBuilder::new(client_runtime)
    }

    /// Starts the consumer.
    pub async fn start(&self) -> ClientResult<()> {
        <Self as ConsumerLifecycle>::start(self).await
    }

    /// Shuts down the consumer.
    pub async fn shutdown(&self) {
        <Self as ConsumerLifecycle>::shutdown(self).await;
    }

    /// Returns whether the consumer is currently running.
    pub async fn is_running(&self) -> bool {
        <Self as ConsumerLifecycle>::is_running(self).await
    }

    /// Returns a Java-compatible running snapshot for broker admin diagnostics.
    pub async fn consumer_running_info(&self) -> ClientResult<ConsumerRunningInfo> {
        let impl_ = self.try_impl_()?;
        Ok(MQConsumerInner::consumer_running_info(impl_.as_ref()).await)
    }

    /// Subscribes to a topic using the default subscription expression.
    pub async fn subscribe(&self, topic: &str) -> ClientResult<()> {
        <Self as SubscriptionControl>::subscribe(self, topic).await
    }

    /// Subscribes to a topic using a tag or SQL expression.
    pub async fn subscribe_with_expression(&self, topic: &str, sub_expression: &str) -> ClientResult<()> {
        <Self as SubscriptionControl>::subscribe_with_expression(self, topic, sub_expression).await
    }

    /// Subscribes with a queue-change listener.
    pub async fn subscribe_with_listener<MQL>(
        &self,
        topic: &str,
        sub_expression: &str,
        listener: MQL,
    ) -> ClientResult<()>
    where
        MQL: MessageQueueListener + 'static,
    {
        <Self as SubscriptionControl>::subscribe_with_listener(self, topic, sub_expression, listener).await
    }

    /// Subscribes using a server-side selector.
    pub async fn subscribe_with_selector(&self, topic: &str, selector: Option<MessageSelector>) -> ClientResult<()> {
        <Self as SubscriptionControl>::subscribe_with_selector(self, topic, selector).await
    }

    /// Removes the subscription for a topic.
    pub async fn unsubscribe(&self, topic: &str) {
        <Self as SubscriptionControl>::unsubscribe(self, topic).await;
    }

    /// Returns the currently assigned queues.
    pub async fn assignment(&self) -> ClientResult<HashSet<MessageQueue>> {
        <Self as AssignmentControl>::assignment(self).await
    }

    /// Assigns queues manually, bypassing broker rebalance.
    pub async fn assign(&self, message_queues: Vec<MessageQueue>) -> ClientResult<()> {
        <Self as AssignmentControl>::assign(self, message_queues).await
    }

    /// Sets the subscription expression used for manually assigned queues.
    pub async fn set_sub_expression_for_assign(&self, topic: &str, sub_expression: &str) -> ClientResult<()> {
        <Self as AssignmentControl>::set_sub_expression_for_assign(self, topic, sub_expression).await
    }

    /// Builds subscription metadata for heartbeat payloads.
    pub async fn build_subscriptions_for_heartbeat(
        &self,
        sub_expression_map: &mut HashMap<String, MessageSelector>,
    ) -> ClientResult<()> {
        <Self as SubscriptionControl>::build_subscriptions_for_heartbeat(self, sub_expression_map).await
    }

    /// Returns heartbeat subscriptions.
    pub async fn subscriptions_for_heartbeat(&self) -> HashSet<SubscriptionData> {
        <Self as SubscriptionControl>::subscriptions_for_heartbeat(self).await
    }

    /// Java-compatible getter alias for heartbeat subscriptions.
    pub async fn get_subscriptions_for_heartbeat(&self) -> HashSet<SubscriptionData> {
        self.subscriptions_for_heartbeat().await
    }

    /// Polls messages without cloning message payloads.
    pub async fn poll_zero_copy(&self) -> Vec<Arc<MessageExt>> {
        <Self as MessagePoll>::poll_zero_copy(self).await
    }

    /// Polls messages without cloning message payloads with a custom timeout.
    pub async fn poll_with_timeout_zero_copy(&self, timeout: u64) -> Vec<Arc<MessageExt>> {
        <Self as MessagePoll>::poll_with_timeout_zero_copy(self, timeout).await
    }

    /// Polls messages and returns owned copies.
    pub async fn poll(&self) -> Vec<MessageExt> {
        <Self as MessagePoll>::poll(self).await
    }

    /// Polls messages with a custom timeout and returns owned copies.
    pub async fn poll_with_timeout(&self, timeout: u64) -> Vec<MessageExt> {
        <Self as MessagePoll>::poll_with_timeout(self, timeout).await
    }

    /// Returns the configured message model.
    pub async fn message_model(&self) -> MessageModel {
        <Self as SubscriptionControl>::message_model(self).await
    }

    /// Java-compatible getter alias for the configured message model.
    pub async fn get_message_model(&self) -> MessageModel {
        self.message_model().await
    }

    /// Sets the configured message model.
    pub async fn set_message_model(&self, message_model: MessageModel) {
        <Self as SubscriptionControl>::set_message_model(self, message_model).await;
    }

    /// Returns where consumption starts when no offset exists.
    pub async fn consume_from_where(&self) -> ConsumeFromWhere {
        <Self as SubscriptionControl>::consume_from_where(self).await
    }

    /// Java-compatible getter alias for where consumption starts when no offset exists.
    pub async fn get_consume_from_where(&self) -> ConsumeFromWhere {
        self.consume_from_where().await
    }

    /// Sets where consumption starts when no offset exists.
    pub async fn set_consume_from_where(&self, consume_from_where: ConsumeFromWhere) -> ClientResult<()> {
        <Self as SubscriptionControl>::set_consume_from_where(self, consume_from_where).await
    }

    /// Returns the consume timestamp.
    pub async fn consume_timestamp(&self) -> Option<CheetahString> {
        <Self as SubscriptionControl>::consume_timestamp(self).await
    }

    /// Java-compatible getter alias for the consume timestamp.
    pub async fn get_consume_timestamp(&self) -> Option<CheetahString> {
        self.consume_timestamp().await
    }

    /// Sets the consume timestamp.
    pub async fn set_consume_timestamp(&self, consume_timestamp: Option<CheetahString>) {
        <Self as SubscriptionControl>::set_consume_timestamp(self, consume_timestamp).await;
    }

    /// Returns the queue allocation strategy.
    pub async fn allocate_message_queue_strategy(&self) -> Arc<dyn AllocateMessageQueueStrategy + Send + Sync> {
        <Self as SubscriptionControl>::allocate_message_queue_strategy(self).await
    }

    /// Java-compatible getter alias for the queue allocation strategy.
    pub async fn get_allocate_message_queue_strategy(&self) -> Arc<dyn AllocateMessageQueueStrategy + Send + Sync> {
        self.allocate_message_queue_strategy().await
    }

    /// Sets the queue allocation strategy.
    pub async fn set_allocate_message_queue_strategy(
        &self,
        allocate_message_queue_strategy: Arc<dyn AllocateMessageQueueStrategy + Send + Sync>,
    ) {
        <Self as SubscriptionControl>::set_allocate_message_queue_strategy(self, allocate_message_queue_strategy).await;
    }

    /// Returns the message queue listener.
    pub async fn message_queue_listener(&self) -> Option<ArcMessageQueueListener> {
        <Self as SubscriptionControl>::message_queue_listener(self).await
    }

    /// Java-compatible getter alias for the message queue listener.
    pub async fn get_message_queue_listener(&self) -> Option<ArcMessageQueueListener> {
        self.message_queue_listener().await
    }

    /// Sets the message queue listener.
    pub async fn set_message_queue_listener(&self, message_queue_listener: Option<ArcMessageQueueListener>) {
        <Self as SubscriptionControl>::set_message_queue_listener(self, message_queue_listener).await;
    }

    /// Returns the configured offset store.
    pub async fn offset_store(&self) -> Option<Arc<OffsetStore>> {
        <Self as ConsumerOffsetControl>::offset_store(self).await
    }

    /// Java-compatible getter alias for the configured offset store.
    pub async fn get_offset_store(&self) -> Option<Arc<OffsetStore>> {
        self.offset_store().await
    }

    /// Sets the configured offset store.
    pub async fn set_offset_store(&self, offset_store: Option<Arc<OffsetStore>>) -> ClientResult<()> {
        <Self as ConsumerOffsetControl>::set_offset_store(self, offset_store).await
    }

    /// Returns the topic metadata check interval in milliseconds.
    pub async fn topic_metadata_check_interval_millis(&self) -> u64 {
        <Self as SubscriptionControl>::topic_metadata_check_interval_millis(self).await
    }

    /// Java-compatible getter alias for the topic metadata check interval.
    pub async fn get_topic_metadata_check_interval_millis(&self) -> u64 {
        self.topic_metadata_check_interval_millis().await
    }

    /// Sets the topic metadata check interval in milliseconds.
    pub async fn set_topic_metadata_check_interval_millis(&self, interval_millis: u64) {
        <Self as SubscriptionControl>::set_topic_metadata_check_interval_millis(self, interval_millis).await;
    }

    /// Returns the default poll timeout in milliseconds.
    pub async fn poll_timeout_millis(&self) -> u64 {
        <Self as MessagePoll>::poll_timeout_millis(self).await
    }

    /// Java-compatible getter alias for the default poll timeout.
    pub async fn get_poll_timeout_millis(&self) -> u64 {
        self.poll_timeout_millis().await
    }

    /// Sets the default poll timeout in milliseconds.
    pub async fn set_poll_timeout_millis(&self, timeout_millis: u64) {
        <Self as MessagePoll>::set_poll_timeout_millis(self, timeout_millis).await;
    }

    /// Returns the broker suspend max time in milliseconds.
    pub async fn broker_suspend_max_time_millis(&self) -> u64 {
        <Self as MessagePoll>::broker_suspend_max_time_millis(self).await
    }

    /// Java-compatible getter alias for the broker suspend max time.
    pub async fn get_broker_suspend_max_time_millis(&self) -> u64 {
        self.broker_suspend_max_time_millis().await
    }

    /// Sets the broker suspend max time in milliseconds.
    pub async fn set_broker_suspend_max_time_millis(&self, timeout_millis: u64) {
        <Self as MessagePoll>::set_broker_suspend_max_time_millis(self, timeout_millis).await;
    }

    /// Returns the consumer timeout while suspended.
    pub async fn consumer_timeout_millis_when_suspend(&self) -> u64 {
        <Self as MessagePoll>::consumer_timeout_millis_when_suspend(self).await
    }

    /// Java-compatible getter alias for the consumer timeout while suspended.
    pub async fn get_consumer_timeout_millis_when_suspend(&self) -> u64 {
        self.consumer_timeout_millis_when_suspend().await
    }

    /// Sets the consumer timeout while suspended.
    pub async fn set_consumer_timeout_millis_when_suspend(&self, timeout_millis: u64) {
        <Self as MessagePoll>::set_consumer_timeout_millis_when_suspend(self, timeout_millis).await;
    }

    /// Returns the pull RPC timeout in milliseconds.
    pub async fn consumer_pull_timeout_millis(&self) -> u64 {
        <Self as MessagePoll>::consumer_pull_timeout_millis(self).await
    }

    /// Java-compatible getter alias for the pull RPC timeout.
    pub async fn get_consumer_pull_timeout_millis(&self) -> u64 {
        self.consumer_pull_timeout_millis().await
    }

    /// Sets the pull RPC timeout in milliseconds.
    pub async fn set_consumer_pull_timeout_millis(&self, timeout_millis: u64) {
        <Self as MessagePoll>::set_consumer_pull_timeout_millis(self, timeout_millis).await;
    }

    /// Returns the pull batch size.
    pub async fn pull_batch_size(&self) -> i32 {
        <Self as MessagePoll>::pull_batch_size(self).await
    }

    /// Java-compatible getter alias for the pull batch size.
    pub async fn get_pull_batch_size(&self) -> i32 {
        self.pull_batch_size().await
    }

    /// Sets the pull batch size.
    pub async fn set_pull_batch_size(&self, pull_batch_size: i32) {
        <Self as MessagePoll>::set_pull_batch_size(self, pull_batch_size).await;
    }

    /// Returns the configured pull thread count.
    pub async fn pull_thread_nums(&self) -> usize {
        <Self as MessagePoll>::pull_thread_nums(self).await
    }

    /// Java-compatible getter alias for the configured pull thread count.
    pub async fn get_pull_thread_nums(&self) -> usize {
        self.pull_thread_nums().await
    }

    /// Sets the configured pull thread count.
    pub async fn set_pull_thread_nums(&self, pull_thread_nums: usize) {
        <Self as MessagePoll>::set_pull_thread_nums(self, pull_thread_nums).await;
    }

    /// Sets the maximum number of concurrent broker pull RPCs before startup.
    ///
    /// # Errors
    ///
    /// Returns an error when `pull_thread_nums` is zero or the consumer has
    /// already started.
    pub async fn try_set_pull_thread_nums(&self, pull_thread_nums: usize) -> ClientResult<()> {
        if pull_thread_nums == 0 {
            return Err(crate::mq_client_err!("pullThreadNums must be greater than 0"));
        }
        if let Some(impl_) = self.default_lite_pull_consumer_impl.get() {
            impl_.try_set_pull_thread_nums(pull_thread_nums)?;
        }
        self.update_consumer_config(|config| config.pull_thread_nums = pull_thread_nums);
        Ok(())
    }

    /// Returns the all-queue pull threshold.
    pub async fn pull_threshold_for_all(&self) -> i64 {
        <Self as MessagePoll>::pull_threshold_for_all(self).await
    }

    /// Java-compatible getter alias for the all-queue pull threshold.
    pub async fn get_pull_threshold_for_all(&self) -> i64 {
        self.pull_threshold_for_all().await
    }

    /// Sets the all-queue pull threshold.
    pub async fn set_pull_threshold_for_all(&self, pull_threshold_for_all: i64) {
        <Self as MessagePoll>::set_pull_threshold_for_all(self, pull_threshold_for_all).await;
    }

    /// Returns the per-queue pull threshold.
    pub async fn pull_threshold_for_queue(&self) -> i64 {
        <Self as MessagePoll>::pull_threshold_for_queue(self).await
    }

    /// Java-compatible getter alias for the per-queue pull threshold.
    pub async fn get_pull_threshold_for_queue(&self) -> i64 {
        self.pull_threshold_for_queue().await
    }

    /// Sets the per-queue pull threshold.
    pub async fn set_pull_threshold_for_queue(&self, pull_threshold_for_queue: i64) {
        <Self as MessagePoll>::set_pull_threshold_for_queue(self, pull_threshold_for_queue).await;
    }

    /// Returns the per-queue pull size threshold.
    pub async fn pull_threshold_size_for_queue(&self) -> i32 {
        <Self as MessagePoll>::pull_threshold_size_for_queue(self).await
    }

    /// Java-compatible getter alias for the per-queue pull size threshold.
    pub async fn get_pull_threshold_size_for_queue(&self) -> i32 {
        self.pull_threshold_size_for_queue().await
    }

    /// Sets the per-queue pull size threshold.
    pub async fn set_pull_threshold_size_for_queue(&self, pull_threshold_size_for_queue: i32) {
        <Self as MessagePoll>::set_pull_threshold_size_for_queue(self, pull_threshold_size_for_queue).await;
    }

    /// Returns the max consume span.
    pub async fn consume_max_span(&self) -> i64 {
        <Self as MessagePoll>::consume_max_span(self).await
    }

    /// Java-compatible getter alias for the max consume span.
    pub async fn get_consume_max_span(&self) -> i64 {
        self.consume_max_span().await
    }

    /// Sets the max consume span.
    pub async fn set_consume_max_span(&self, consume_max_span: i64) {
        <Self as MessagePoll>::set_consume_max_span(self, consume_max_span).await;
    }

    /// Returns whether pulls use the configured broker id.
    pub async fn is_connect_broker_by_user(&self) -> bool {
        <Self as SubscriptionControl>::is_connect_broker_by_user(self).await
    }

    /// Sets whether pulls use the configured broker id.
    pub async fn set_connect_broker_by_user(&self, connect_broker_by_user: bool) {
        <Self as SubscriptionControl>::set_connect_broker_by_user(self, connect_broker_by_user).await;
    }

    /// Returns the configured default broker id.
    pub async fn default_broker_id(&self) -> u64 {
        <Self as SubscriptionControl>::default_broker_id(self).await
    }

    /// Java-compatible getter alias for the configured default broker id.
    pub async fn get_default_broker_id(&self) -> u64 {
        self.default_broker_id().await
    }

    /// Sets the configured default broker id.
    pub async fn set_default_broker_id(&self, broker_id: u64) {
        <Self as SubscriptionControl>::set_default_broker_id(self, broker_id).await;
    }

    /// Fetches message queues for a topic.
    pub async fn fetch_message_queues(&self, topic: &str) -> ClientResult<Vec<MessageQueue>> {
        <Self as ConsumerOffsetControl>::fetch_message_queues(self, topic).await
    }

    /// Returns the committed offset for a queue.
    pub async fn committed(&self, message_queue: &MessageQueue) -> ClientResult<i64> {
        <Self as ConsumerOffsetControl>::committed(self, message_queue).await
    }

    /// Commits all offsets to the configured offset store.
    pub async fn commit_all(&self) -> ClientResult<()> {
        <Self as ConsumerOffsetControl>::commit_all(self).await
    }

    /// Commits explicit offsets.
    pub async fn commit_with_map(&self, offset_map: HashMap<MessageQueue, i64>, persist: bool) {
        <Self as ConsumerOffsetControl>::commit_with_map(self, offset_map, persist).await;
    }

    /// Commits all offsets.
    pub async fn commit(&self) {
        <Self as ConsumerOffsetControl>::commit(self).await;
    }

    /// Commits offsets for selected queues.
    pub async fn commit_with_set(&self, message_queues: HashSet<MessageQueue>, persist: bool) {
        <Self as ConsumerOffsetControl>::commit_with_set(self, message_queues, persist).await;
    }

    /// Java-compatible alias for committing all offsets.
    pub async fn commit_sync(&self) {
        <Self as ConsumerOffsetControl>::commit_sync(self).await;
    }

    /// Java-compatible alias for committing explicit offsets.
    pub async fn commit_sync_with_map(&self, offset_map: HashMap<MessageQueue, i64>, persist: bool) {
        <Self as ConsumerOffsetControl>::commit_sync_with_map(self, offset_map, persist).await;
    }

    /// Returns whether auto commit is enabled.
    pub async fn is_auto_commit(&self) -> bool {
        <Self as ConsumerOffsetControl>::is_auto_commit(self).await
    }

    /// Sets whether auto commit is enabled.
    pub async fn set_auto_commit(&self, auto_commit: bool) {
        <Self as ConsumerOffsetControl>::set_auto_commit(self, auto_commit).await;
    }

    /// Returns whether unit mode is enabled.
    pub async fn is_unit_mode(&self) -> bool {
        <Self as SubscriptionControl>::is_unit_mode(self).await
    }

    /// Sets whether unit mode is enabled.
    pub async fn set_unit_mode(&self, unit_mode: bool) {
        <Self as SubscriptionControl>::set_unit_mode(self, unit_mode).await;
    }

    /// Returns the auto commit interval in milliseconds.
    pub async fn auto_commit_interval_millis(&self) -> u64 {
        <Self as ConsumerOffsetControl>::auto_commit_interval_millis(self).await
    }

    /// Java-compatible getter alias for the auto commit interval.
    pub async fn get_auto_commit_interval_millis(&self) -> u64 {
        self.auto_commit_interval_millis().await
    }

    /// Sets the auto commit interval in milliseconds.
    pub async fn set_auto_commit_interval_millis(&self, interval_millis: u64) {
        <Self as ConsumerOffsetControl>::set_auto_commit_interval_millis(self, interval_millis).await;
    }

    /// Queries the offset for a timestamp.
    pub async fn offset_for_timestamp(&self, message_queue: &MessageQueue, timestamp: u64) -> ClientResult<i64> {
        <Self as ConsumerOffsetControl>::offset_for_timestamp(self, message_queue, timestamp).await
    }

    /// Queries the earliest store time for a queue.
    pub async fn earliest_msg_store_time(&self, message_queue: &MessageQueue) -> ClientResult<i64> {
        <Self as ConsumerOffsetControl>::earliest_msg_store_time(self, message_queue).await
    }

    /// Queries the broker max offset for a queue.
    pub async fn max_offset(&self, message_queue: &MessageQueue) -> ClientResult<i64> {
        <Self as ConsumerOffsetControl>::max_offset(self, message_queue).await
    }

    /// Queries the broker min offset for a queue.
    pub async fn min_offset(&self, message_queue: &MessageQueue) -> ClientResult<i64> {
        <Self as ConsumerOffsetControl>::min_offset(self, message_queue).await
    }

    /// Creates a topic through the Java-compatible MQAdmin facade.
    pub async fn create_topic(
        &self,
        key: &str,
        new_topic: &str,
        queue_num: i32,
        attributes: HashMap<String, String>,
    ) -> ClientResult<()> {
        self.create_topic_with_flag(key, new_topic, queue_num, 0, attributes)
            .await
    }

    /// Creates a topic with an explicit topic system flag.
    pub async fn create_topic_with_flag(
        &self,
        key: &str,
        new_topic: &str,
        queue_num: i32,
        topic_sys_flag: i32,
        attributes: HashMap<String, String>,
    ) -> ClientResult<()> {
        let new_topic = self.with_namespace(new_topic);
        self.try_impl_()?
            .create_topic(key, new_topic.as_str(), queue_num, topic_sys_flag, attributes)
            .await
    }

    /// Queries messages by key in a time range.
    pub async fn query_message(
        &self,
        topic: &str,
        key: &str,
        max_num: i32,
        begin: u64,
        end: u64,
    ) -> ClientResult<QueryResult> {
        let topic = self.with_namespace(topic);
        self.try_impl_()?
            .query_message(topic.as_str(), key, max_num, begin, end)
            .await
    }

    /// Views a message by offset message id or Java-compatible unique message id.
    pub async fn view_message(&self, topic: &str, msg_id: &str) -> ClientResult<MessageExt> {
        let topic = self.with_namespace(topic);
        let impl_ = self.try_impl_()?;
        if MessageDecoder::decode_message_id(msg_id).is_ok() {
            impl_.view_message(topic.as_str(), msg_id).await
        } else {
            impl_.query_message_by_uniq_key(topic.as_str(), msg_id).await
        }
    }

    /// Pauses fetching from selected queues.
    pub async fn pause(&self, message_queues: Vec<MessageQueue>) {
        <Self as AssignmentControl>::pause(self, message_queues).await;
    }

    /// Resumes fetching from selected queues.
    pub async fn resume(&self, message_queues: Vec<MessageQueue>) {
        <Self as AssignmentControl>::resume(self, message_queues).await;
    }

    /// Returns whether a queue is paused.
    pub async fn is_paused(&self, message_queue: &MessageQueue) -> bool {
        <Self as AssignmentControl>::is_paused(self, message_queue).await
    }

    /// Seeks a queue to an offset.
    pub async fn seek(&self, message_queue: &MessageQueue, offset: i64) -> ClientResult<()> {
        <Self as AssignmentControl>::seek(self, message_queue, offset).await
    }

    /// Seeks a queue to the beginning.
    pub async fn seek_to_begin(&self, message_queue: &MessageQueue) -> ClientResult<()> {
        <Self as AssignmentControl>::seek_to_begin(self, message_queue).await
    }

    /// Seeks a queue to the end.
    pub async fn seek_to_end(&self, message_queue: &MessageQueue) -> ClientResult<()> {
        <Self as AssignmentControl>::seek_to_end(self, message_queue).await
    }

    /// Updates the name server address.
    pub async fn update_name_server_address(&self, name_server_address: &str) {
        <Self as SubscriptionControl>::update_name_server_address(self, name_server_address).await;
    }

    /// Registers a topic queue-change listener.
    pub async fn register_topic_message_queue_change_listener<TL>(&self, topic: &str, listener: TL) -> ClientResult<()>
    where
        TL: TopicMessageQueueChangeListener + 'static,
    {
        <Self as SubscriptionControl>::register_topic_message_queue_change_listener(self, topic, listener).await
    }

    /// Returns the consumer group name from the current immutable configuration snapshot.
    pub fn consumer_group(&self) -> CheetahString {
        self.consumer_config.load().consumer_group.clone()
    }

    /// Java-compatible getter alias for the consumer group name.
    pub fn get_consumer_group(&self) -> CheetahString {
        self.consumer_group()
    }

    /// Sets the consumer group name before the consumer starts.
    ///
    /// Like Java `DefaultLitePullConsumer.setConsumerGroup`, this updates the facade
    /// configuration. If the internal implementation has already been initialized,
    /// the value is synchronized into the impl and rebalance configuration while it
    /// is still in the create state.
    pub fn set_consumer_group(&self, consumer_group: impl Into<CheetahString>) -> ClientResult<()> {
        let consumer_group = consumer_group.into();
        if let Some(impl_) = self.default_lite_pull_consumer_impl.get() {
            impl_.set_consumer_group(consumer_group.clone())?;
        }
        self.update_consumer_config(|config| config.consumer_group = consumer_group.clone());
        Ok(())
    }

    /// Returns the namespace (if configured).
    pub fn namespace(&self) -> Option<CheetahString> {
        self.client_config.load().resolved_namespace()
    }

    /// Returns the custom trace topic, if configured.
    pub fn customized_trace_topic(&self) -> Option<CheetahString> {
        self.custom_trace_topic.clone()
    }

    /// Java-compatible getter alias for the custom trace topic.
    pub fn get_customized_trace_topic(&self) -> Option<CheetahString> {
        self.customized_trace_topic()
    }

    /// Sets the custom trace topic used when message tracing is enabled.
    pub fn set_customized_trace_topic(&mut self, customized_trace_topic: impl Into<CheetahString>) {
        self.custom_trace_topic = Some(customized_trace_topic.into());
    }

    /// Clears the custom trace topic so the default system trace topic is used.
    pub fn clear_customized_trace_topic(&mut self) {
        self.custom_trace_topic = None;
    }

    /// Returns whether message trace is enabled.
    pub fn is_enable_msg_trace(&self) -> bool {
        self.enable_msg_trace
    }

    /// Enables or disables message trace for subsequent startup.
    pub fn set_enable_msg_trace(&mut self, enable_msg_trace: bool) {
        self.enable_msg_trace = enable_msg_trace;
    }

    /// Returns whether outbound remoting connections should use TLS.
    pub fn is_use_tls(&self) -> bool {
        self.client_config.load().is_use_tls()
    }

    /// Enables or disables TLS on the published client configuration and trace dispatcher.
    pub async fn set_use_tls(&self, use_tls: bool) {
        self.update_client_config(|config| config.set_use_tls(use_tls));
        if let Some(impl_) = self.default_lite_pull_consumer_impl.get() {
            impl_.set_use_tls(use_tls);
        }
        if let Some(dispatcher) = self.trace_dispatcher.read().await.as_ref().cloned() {
            if let Some(async_dispatcher) = dispatcher.as_any().downcast_ref::<AsyncTraceDispatcher>() {
                async_dispatcher.set_use_tls(use_tls);
            }
        }
    }

    /// Returns the trace dispatcher, if tracing has been configured or initialized.
    pub async fn trace_dispatcher(&self) -> Option<Arc<dyn TraceDispatcher + Send + Sync>> {
        self.trace_dispatcher.read().await.as_ref().cloned()
    }

    /// Java-compatible getter alias for the trace dispatcher.
    pub async fn get_trace_dispatcher(&self) -> Option<Arc<dyn TraceDispatcher + Send + Sync>> {
        self.trace_dispatcher().await
    }

    /// Returns the current immutable client configuration snapshot.
    pub fn client_config(&self) -> Arc<ClientConfig> {
        self.client_config_snapshot()
    }

    /// Returns the current immutable consumer configuration snapshot.
    pub fn consumer_config(&self) -> Arc<LitePullConsumerConfig> {
        self.consumer_config_snapshot()
    }

    /// Wraps a topic name with the namespace (if configured).
    fn with_namespace(&self, resource: &str) -> CheetahString {
        let resource = CheetahString::from(resource);
        let namespace = self.client_config.load().resolved_namespace().unwrap_or_default();
        if namespace.is_empty() || NamespaceUtil::is_already_with_namespace(resource.as_str(), namespace.as_str()) {
            resource
        } else {
            NamespaceUtil::wrap_namespace(namespace, resource)
        }
    }

    pub(crate) fn classic_topic_with_namespace(&self, topic: &str) -> CheetahString {
        self.with_namespace(topic)
    }

    pub(crate) fn set_classic_pull_message_queue_listener(
        &self,
        listener: Option<ArcMessageQueueListener>,
    ) -> ClientResult<()> {
        self.set_message_queue_listener_local(listener.clone());
        if let Some(implementation) = self.default_lite_pull_consumer_impl.get() {
            implementation.set_message_queue_listener(listener);
        }
        Ok(())
    }

    /// Removes namespace from a topic name (if configured).
    fn without_namespace(&self, resource: &str) -> CheetahString {
        match self.client_config.load().resolved_namespace() {
            Some(namespace) if !namespace.is_empty() => {
                NamespaceUtil::without_namespace_with_namespace(resource, namespace.as_str()).into()
            }
            _ => NamespaceUtil::without_namespace(resource).into(),
        }
    }

    /// Wraps the consumer group with namespace before startup, matching Java LitePull start().
    fn consumer_group_with_namespace(&self) -> CheetahString {
        let consumer_group = self.consumer_config.load().consumer_group.clone();
        let namespace = self.client_config.load().resolved_namespace().unwrap_or_default();
        if namespace.is_empty() || NamespaceUtil::is_already_with_namespace(consumer_group.as_str(), namespace.as_str())
        {
            consumer_group
        } else {
            NamespaceUtil::wrap_namespace(namespace, consumer_group)
        }
    }

    /// Wraps a message queue with namespace.
    pub(crate) fn queue_with_namespace(&self, mq: &MessageQueue) -> MessageQueue {
        self.client_config.load().queue_with_resolved_namespace(mq.clone())
    }

    /// Removes namespace from a message queue.
    fn queue_without_namespace(&self, mq: &MessageQueue) -> MessageQueue {
        match self.client_config.load().resolved_namespace() {
            Some(namespace) if !namespace.is_empty() => {
                let unwrapped_topic = NamespaceUtil::without_namespace_with_namespace(mq.topic(), namespace.as_str());
                MessageQueue::from_parts(unwrapped_topic, mq.broker_name().clone(), mq.queue_id())
            }
            Some(_) | None => mq.clone(),
        }
    }

    /// Initializes the trace dispatcher if message trace is enabled.
    async fn init_trace_dispatcher_internal(&self, impl_: &Arc<DefaultLitePullConsumerImpl>) -> ClientResult<()> {
        if !self.enable_msg_trace {
            return Ok(());
        }

        let dispatcher_arc = {
            let mut dispatcher_guard = self.trace_dispatcher.write().await;
            if let Some(dispatcher) = dispatcher_guard.as_ref() {
                dispatcher.clone()
            } else {
                let client_config = self.client_config_snapshot();
                let consumer_config = self.consumer_config_snapshot();
                let trace_topic = self
                    .custom_trace_topic
                    .as_ref()
                    .map(|t| t.as_str())
                    .unwrap_or(TopicValidator::RMQ_SYS_TRACE_TOPIC);

                let dispatcher = AsyncTraceDispatcher::new(
                    self.session.runtime(),
                    consumer_config.consumer_group.as_str(),
                    Type::Consume,
                    client_config.trace_msg_batch_num,
                    trace_topic,
                    self.rpc_hook.clone(),
                );
                dispatcher.set_namespace_v2(client_config.namespace_v2.clone());
                dispatcher.set_use_tls(client_config.use_tls);

                let dispatcher_arc: Arc<dyn TraceDispatcher + Send + Sync> = Arc::new(dispatcher);
                *dispatcher_guard = Some(dispatcher_arc.clone());
                dispatcher_arc
            }
        };

        let hook = Arc::new(ConsumeMessageTraceHookImpl::new(dispatcher_arc));
        impl_.register_consume_message_hook(hook);

        Ok(())
    }

    /// Starts the configured trace dispatcher after the consumer implementation is running.
    async fn start_trace_dispatcher(&self) {
        if !self.enable_msg_trace {
            return;
        }

        let dispatcher = self.trace_dispatcher.read().await.as_ref().cloned();
        let Some(dispatcher) = dispatcher else {
            return;
        };

        let client_config = self.client_config_snapshot();
        let name_server_addr = client_config
            .namesrv_addr
            .as_ref()
            .map(|addr| addr.as_str())
            .unwrap_or_default();
        if let Err(error) = dispatcher.start(name_server_addr, client_config.access_channel) {
            tracing::warn!("trace dispatcher start failed: {}", error);
        }
    }

    /// Returns a reference to the internal implementation after it has been initialized.
    pub(crate) fn try_impl_(&self) -> ClientResult<&Arc<DefaultLitePullConsumerImpl>> {
        self.default_lite_pull_consumer_impl
            .get()
            .ok_or_else(|| ClientError::not_initialized("DefaultLitePullConsumer not started. Call start() first."))
    }

    /// Returns the internal implementation, initializing it without starting network services.
    ///
    /// Java's LitePull consumer allows `subscribe`, `assign`, and
    /// `setSubExpressionForAssign` while the implementation is still in
    /// `CREATE_JUST`. Those calls populate local subscription state and only
    /// trigger broker route updates after `start()`.
    async fn get_or_init_impl(&self) -> ClientResult<&Arc<DefaultLitePullConsumerImpl>> {
        self.default_lite_pull_consumer_impl
            .get_or_try_init(|| async {
                let impl_ = Arc::new(DefaultLitePullConsumerImpl::try_new_with_options(
                    self.session.runtime(),
                    ClientOptions::from_parts(
                        self.client_config_snapshot().as_ref().clone(),
                        self.nameserver_discovery.clone(),
                    ),
                    self.consumer_config_snapshot(),
                )?);
                impl_.bind_self();
                impl_.set_rpc_hook(self.rpc_hook.clone());
                impl_.set_message_queue_listener(self.current_message_queue_listener());

                self.init_trace_dispatcher_internal(&impl_).await?;

                let consumer_group = self.consumer_group_with_namespace();
                self.set_consumer_group(consumer_group.clone())?;
                impl_.set_consumer_group(consumer_group)?;
                if let Some(offset_store) = self.current_offset_store() {
                    impl_.set_offset_store(Some(offset_store))?;
                }

                Ok::<Arc<DefaultLitePullConsumerImpl>, crate::ClientError>(impl_)
            })
            .await
    }

    fn current_message_queue_listener(&self) -> Option<ArcMessageQueueListener> {
        self.message_queue_listener
            .read()
            .ok()
            .and_then(|listener| listener.clone())
    }

    fn set_message_queue_listener_local(&self, listener: Option<ArcMessageQueueListener>) {
        match self.message_queue_listener.write() {
            Ok(mut current) => *current = listener,
            Err(error) => tracing::warn!("LitePull message queue listener lock poisoned: {}", error),
        }
    }

    fn current_offset_store(&self) -> Option<Arc<OffsetStore>> {
        self.offset_store.read().ok().and_then(|store| store.clone())
    }

    fn set_offset_store_local(&self, offset_store: Option<Arc<OffsetStore>>) {
        match self.offset_store.write() {
            Ok(mut current) => *current = offset_store,
            Err(error) => tracing::warn!("LitePull offset store lock poisoned: {}", error),
        }
    }

    pub(crate) async fn register_classic_pull_subscription(&self, topic: &CheetahString) -> ClientResult<()> {
        self.get_or_init_impl()
            .await?
            .register_classic_pull_subscription(topic)
            .await
    }
}

#[allow(unused)]
impl ClientSessionProvider for DefaultLitePullConsumer {
    fn client_session(&self) -> Option<&ClientSession> {
        Some(&self.session)
    }
}

impl SubscriptionControl for DefaultLitePullConsumer {
    async fn subscribe(&self, topic: &str) -> ClientResult<()> {
        self.subscribe_with_expression(topic, "*").await
    }

    async fn subscribe_with_expression(&self, topic: &str, sub_expression: &str) -> ClientResult<()> {
        let wrapped_topic = self.with_namespace(topic);
        self.get_or_init_impl()
            .await?
            .subscribe(wrapped_topic, sub_expression)
            .await
    }

    async fn subscribe_with_listener<MQL>(&self, topic: &str, sub_expression: &str, listener: MQL) -> ClientResult<()>
    where
        MQL: MessageQueueListener + 'static,
    {
        let wrapped_topic = self.with_namespace(topic);
        let listener: ArcMessageQueueListener = Arc::new(listener);
        self.get_or_init_impl()
            .await?
            .subscribe_with_listener_arc(wrapped_topic, sub_expression, listener.clone())
            .await?;
        self.set_message_queue_listener_local(Some(listener));
        Ok(())
    }

    async fn subscribe_with_selector(&self, topic: &str, selector: Option<MessageSelector>) -> ClientResult<()> {
        let wrapped_topic = self.with_namespace(topic);
        self.get_or_init_impl()
            .await?
            .subscribe_with_selector(wrapped_topic, selector)
            .await
    }

    async fn unsubscribe(&self, topic: &str) {
        let wrapped_topic = self.with_namespace(topic);
        match self.try_impl_() {
            Ok(impl_) => {
                if let Err(e) = impl_.unsubscribe(wrapped_topic).await {
                    tracing::warn!(topic = %topic, error = %e, "unsubscribe failed");
                }
            }
            Err(e) => tracing::warn!(topic = %topic, error = %e, "unsubscribe failed"),
        }
    }

    async fn build_subscriptions_for_heartbeat(
        &self,
        sub_expression_map: &mut HashMap<String, MessageSelector>,
    ) -> ClientResult<()> {
        self.try_impl_()?
            .build_subscriptions_for_heartbeat(sub_expression_map)
            .await
    }

    async fn subscriptions_for_heartbeat(&self) -> HashSet<SubscriptionData> {
        self.default_lite_pull_consumer_impl
            .get()
            .map_or_else(HashSet::new, |impl_| impl_.subscriptions_for_heartbeat())
    }

    async fn message_model(&self) -> MessageModel {
        self.consumer_config.load().message_model
    }

    async fn set_message_model(&self, message_model: MessageModel) {
        self.update_consumer_config(|config| config.message_model = message_model);
        if let Some(impl_) = self.default_lite_pull_consumer_impl.get() {
            impl_.set_message_model(message_model);
        }
    }

    async fn consume_from_where(&self) -> ConsumeFromWhere {
        self.consumer_config.load().consume_from_where
    }

    async fn set_consume_from_where(&self, consume_from_where: ConsumeFromWhere) -> ClientResult<()> {
        validate_lite_pull_consume_from_where(consume_from_where)?;
        self.update_consumer_config(|config| config.consume_from_where = consume_from_where);
        if let Some(impl_) = self.default_lite_pull_consumer_impl.get() {
            impl_.set_consume_from_where(consume_from_where)?;
        }
        Ok(())
    }

    async fn consume_timestamp(&self) -> Option<CheetahString> {
        self.consumer_config.load().consume_timestamp.clone()
    }

    async fn set_consume_timestamp(&self, consume_timestamp: Option<CheetahString>) {
        self.update_consumer_config(|config| config.consume_timestamp = consume_timestamp.clone());
        if let Some(impl_) = self.default_lite_pull_consumer_impl.get() {
            impl_.set_consume_timestamp(consume_timestamp);
        }
    }

    async fn allocate_message_queue_strategy(&self) -> Arc<dyn AllocateMessageQueueStrategy + Send + Sync> {
        let configured_strategy = self.consumer_config.load().allocate_message_queue_strategy.clone();
        self.default_lite_pull_consumer_impl
            .get()
            .map_or_else(|| configured_strategy, |impl_| impl_.allocate_message_queue_strategy())
    }

    async fn set_allocate_message_queue_strategy(
        &self,
        allocate_message_queue_strategy: Arc<dyn AllocateMessageQueueStrategy + Send + Sync>,
    ) {
        self.update_consumer_config(|config| {
            config.allocate_message_queue_strategy = allocate_message_queue_strategy.clone();
        });
        if let Some(impl_) = self.default_lite_pull_consumer_impl.get() {
            impl_.set_allocate_message_queue_strategy(allocate_message_queue_strategy);
        }
    }

    async fn message_queue_listener(&self) -> Option<ArcMessageQueueListener> {
        self.default_lite_pull_consumer_impl
            .get()
            .and_then(|impl_| impl_.message_queue_listener())
            .or_else(|| self.current_message_queue_listener())
    }

    async fn set_message_queue_listener(&self, message_queue_listener: Option<ArcMessageQueueListener>) {
        self.set_message_queue_listener_local(message_queue_listener.clone());
        if let Some(impl_) = self.default_lite_pull_consumer_impl.get() {
            impl_.set_message_queue_listener(message_queue_listener);
        }
    }

    async fn topic_metadata_check_interval_millis(&self) -> u64 {
        self.consumer_config.load().topic_metadata_check_interval_millis
    }

    async fn set_topic_metadata_check_interval_millis(&self, interval_millis: u64) {
        self.update_consumer_config(|config| config.topic_metadata_check_interval_millis = interval_millis);
        if let Some(impl_) = self.default_lite_pull_consumer_impl.get() {
            impl_.set_topic_metadata_check_interval_millis(interval_millis);
        }
    }

    async fn is_connect_broker_by_user(&self) -> bool {
        let configured = self.consumer_config.load().connect_broker_by_user;
        self.default_lite_pull_consumer_impl
            .get()
            .map_or(configured, |impl_| impl_.is_connect_broker_by_user())
    }

    async fn set_connect_broker_by_user(&self, connect_broker_by_user: bool) {
        self.update_consumer_config(|config| config.connect_broker_by_user = connect_broker_by_user);
        if let Some(impl_) = self.default_lite_pull_consumer_impl.get() {
            impl_.set_connect_broker_by_user(connect_broker_by_user);
        }
    }

    async fn default_broker_id(&self) -> u64 {
        let configured = self.consumer_config.load().default_broker_id;
        self.default_lite_pull_consumer_impl
            .get()
            .map_or(configured, |impl_| impl_.default_broker_id())
    }

    async fn set_default_broker_id(&self, broker_id: u64) {
        self.update_consumer_config(|config| config.default_broker_id = broker_id);
        if let Some(impl_) = self.default_lite_pull_consumer_impl.get() {
            impl_.set_default_broker_id(broker_id);
        }
    }

    async fn is_unit_mode(&self) -> bool {
        self.consumer_config.load().unit_mode
    }

    async fn set_unit_mode(&self, unit_mode: bool) {
        self.update_consumer_config(|config| config.unit_mode = unit_mode);
        if let Some(impl_) = self.default_lite_pull_consumer_impl.get() {
            impl_.set_unit_mode(unit_mode);
        }
    }

    async fn update_name_server_address(&self, name_server_address: &str) {
        self.update_client_config(|config| {
            config.set_namesrv_addr(CheetahString::from_slice(name_server_address));
        });

        if let Some(impl_) = self.default_lite_pull_consumer_impl.get() {
            let addresses: Vec<String> = name_server_address
                .split(';')
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .collect();
            impl_.update_name_server_address(addresses).await;
        }
    }

    async fn register_topic_message_queue_change_listener<TL>(&self, topic: &str, listener: TL) -> ClientResult<()>
    where
        TL: TopicMessageQueueChangeListener + 'static,
    {
        let wrapped_topic = self.with_namespace(topic);
        let listener_arc: Arc<dyn TopicMessageQueueChangeListener + Send + Sync> = Arc::new(listener);
        self.try_impl_()?
            .register_topic_message_queue_change_listener(wrapped_topic, listener_arc)
            .await
    }
}

impl AssignmentControl for DefaultLitePullConsumer {
    async fn assignment(&self) -> ClientResult<HashSet<MessageQueue>> {
        let assignment = self.try_impl_()?.assignment().await;

        // Remove namespace from all queues
        let mut result = HashSet::with_capacity(assignment.len());
        for mq in assignment {
            result.insert(self.queue_without_namespace(&mq));
        }

        Ok(result)
    }

    async fn assign(&self, message_queues: Vec<MessageQueue>) -> ClientResult<()> {
        // Wrap namespace for all queues
        let wrapped_queues: Vec<_> = message_queues.iter().map(|mq| self.queue_with_namespace(mq)).collect();

        self.get_or_init_impl().await?.assign(wrapped_queues).await
    }

    async fn set_sub_expression_for_assign(&self, topic: &str, sub_expression: &str) -> ClientResult<()> {
        let wrapped_topic = self.with_namespace(topic);
        self.get_or_init_impl()
            .await?
            .set_sub_expression_for_assign(wrapped_topic, sub_expression)
            .await
    }

    async fn pause(&self, message_queues: Vec<MessageQueue>) {
        let wrapped_queues: Vec<_> = message_queues.iter().map(|mq| self.queue_with_namespace(mq)).collect();

        match self.try_impl_() {
            Ok(impl_) => impl_.pause(&wrapped_queues).await,
            Err(e) => tracing::warn!("pause failed: {}", e),
        }
    }

    async fn resume(&self, message_queues: Vec<MessageQueue>) {
        let wrapped_queues: Vec<_> = message_queues.iter().map(|mq| self.queue_with_namespace(mq)).collect();

        match self.try_impl_() {
            Ok(impl_) => impl_.resume(&wrapped_queues).await,
            Err(e) => tracing::warn!("resume failed: {}", e),
        }
    }

    async fn is_paused(&self, message_queue: &MessageQueue) -> bool {
        let wrapped_mq = self.queue_with_namespace(message_queue);
        match self.try_impl_() {
            Ok(impl_) => impl_.is_paused(&wrapped_mq).await,
            Err(e) => {
                tracing::warn!("is_paused failed: {}", e);
                false
            }
        }
    }

    async fn seek(&self, message_queue: &MessageQueue, offset: i64) -> ClientResult<()> {
        let wrapped_mq = self.queue_with_namespace(message_queue);
        self.try_impl_()?.seek(&wrapped_mq, offset).await
    }

    async fn seek_to_begin(&self, message_queue: &MessageQueue) -> ClientResult<()> {
        let wrapped_mq = self.queue_with_namespace(message_queue);
        self.try_impl_()?.seek_to_begin(&wrapped_mq).await
    }

    async fn seek_to_end(&self, message_queue: &MessageQueue) -> ClientResult<()> {
        let wrapped_mq = self.queue_with_namespace(message_queue);
        self.try_impl_()?.seek_to_end(&wrapped_mq).await
    }
}

impl MessagePoll for DefaultLitePullConsumer {
    /// Zero-copy implementation.
    async fn poll_zero_copy(&self) -> Vec<Arc<MessageExt>> {
        let poll_timeout_millis = self.consumer_config.load().poll_timeout_millis;
        match self.try_impl_() {
            Ok(impl_) => match impl_.poll(poll_timeout_millis).await {
                Ok(messages) => messages,
                Err(e) => {
                    tracing::error!(error = %e, "poll failed");
                    Vec::new()
                }
            },
            Err(e) => {
                tracing::error!(error = %e, "poll failed");
                Vec::new()
            }
        }
    }

    /// Zero-copy implementation with custom timeout.
    async fn poll_with_timeout_zero_copy(&self, timeout: u64) -> Vec<Arc<MessageExt>> {
        match self.try_impl_() {
            Ok(impl_) => match impl_.poll_with_timeout(timeout).await {
                Ok(messages) => messages,
                Err(e) => {
                    tracing::error!(timeout_ms = timeout, error = %e, "poll failed");
                    Vec::new()
                }
            },
            Err(e) => {
                tracing::error!(timeout_ms = timeout, error = %e, "poll failed");
                Vec::new()
            }
        }
    }

    /// Delegates to zero-copy implementation and creates owned message copies.
    async fn poll(&self) -> Vec<MessageExt> {
        self.poll_zero_copy()
            .await
            .into_iter()
            .map(|arc_mut| (*arc_mut).clone())
            .collect()
    }

    /// Delegates to zero-copy implementation with timeout and creates owned message copies.
    async fn poll_with_timeout(&self, timeout: u64) -> Vec<MessageExt> {
        self.poll_with_timeout_zero_copy(timeout)
            .await
            .into_iter()
            .map(|arc_mut| (*arc_mut).clone())
            .collect()
    }

    async fn poll_timeout_millis(&self) -> u64 {
        self.consumer_config.load().poll_timeout_millis
    }

    async fn set_poll_timeout_millis(&self, timeout_millis: u64) {
        self.update_consumer_config(|config| config.poll_timeout_millis = timeout_millis);
        if let Some(impl_) = self.default_lite_pull_consumer_impl.get() {
            impl_.set_poll_timeout_millis(timeout_millis);
        }
    }

    async fn broker_suspend_max_time_millis(&self) -> u64 {
        self.consumer_config.load().broker_suspend_max_time_millis
    }

    async fn set_broker_suspend_max_time_millis(&self, timeout_millis: u64) {
        self.update_consumer_config(|config| config.broker_suspend_max_time_millis = timeout_millis);
        if let Some(impl_) = self.default_lite_pull_consumer_impl.get() {
            impl_.set_broker_suspend_max_time_millis(timeout_millis);
        }
    }

    async fn consumer_timeout_millis_when_suspend(&self) -> u64 {
        self.consumer_config.load().consumer_timeout_millis_when_suspend
    }

    async fn set_consumer_timeout_millis_when_suspend(&self, timeout_millis: u64) {
        self.update_consumer_config(|config| config.consumer_timeout_millis_when_suspend = timeout_millis);
        if let Some(impl_) = self.default_lite_pull_consumer_impl.get() {
            impl_.set_consumer_timeout_millis_when_suspend(timeout_millis);
        }
    }

    async fn consumer_pull_timeout_millis(&self) -> u64 {
        self.consumer_config.load().consumer_pull_timeout_millis
    }

    async fn set_consumer_pull_timeout_millis(&self, timeout_millis: u64) {
        self.update_consumer_config(|config| config.consumer_pull_timeout_millis = timeout_millis);
        if let Some(impl_) = self.default_lite_pull_consumer_impl.get() {
            impl_.set_consumer_pull_timeout_millis(timeout_millis);
        }
    }

    async fn pull_batch_size(&self) -> i32 {
        self.consumer_config.load().pull_batch_size
    }

    async fn set_pull_batch_size(&self, pull_batch_size: i32) {
        self.update_consumer_config(|config| config.pull_batch_size = pull_batch_size);
        if let Some(impl_) = self.default_lite_pull_consumer_impl.get() {
            impl_.set_pull_batch_size(pull_batch_size);
        }
    }

    async fn pull_thread_nums(&self) -> usize {
        self.consumer_config.load().pull_thread_nums
    }

    async fn set_pull_thread_nums(&self, pull_thread_nums: usize) {
        if let Err(error) = self.try_set_pull_thread_nums(pull_thread_nums).await {
            tracing::warn!("Ignoring invalid pullThreadNums update: {error}");
        }
    }

    async fn pull_threshold_for_all(&self) -> i64 {
        self.consumer_config.load().pull_threshold_for_all
    }

    async fn set_pull_threshold_for_all(&self, pull_threshold_for_all: i64) {
        self.update_consumer_config(|config| config.pull_threshold_for_all = pull_threshold_for_all);
        if let Some(impl_) = self.default_lite_pull_consumer_impl.get() {
            impl_.set_pull_threshold_for_all(pull_threshold_for_all);
        }
    }

    async fn pull_threshold_for_queue(&self) -> i64 {
        self.consumer_config.load().pull_threshold_for_queue
    }

    async fn set_pull_threshold_for_queue(&self, pull_threshold_for_queue: i64) {
        self.update_consumer_config(|config| config.pull_threshold_for_queue = pull_threshold_for_queue);
        if let Some(impl_) = self.default_lite_pull_consumer_impl.get() {
            impl_.set_pull_threshold_for_queue(pull_threshold_for_queue);
        }
    }

    async fn pull_threshold_size_for_queue(&self) -> i32 {
        self.consumer_config.load().pull_threshold_size_for_queue
    }

    async fn set_pull_threshold_size_for_queue(&self, pull_threshold_size_for_queue: i32) {
        self.update_consumer_config(|config| config.pull_threshold_size_for_queue = pull_threshold_size_for_queue);
        if let Some(impl_) = self.default_lite_pull_consumer_impl.get() {
            impl_.set_pull_threshold_size_for_queue(pull_threshold_size_for_queue);
        }
    }

    async fn consume_max_span(&self) -> i64 {
        self.consumer_config.load().consume_max_span
    }

    async fn set_consume_max_span(&self, consume_max_span: i64) {
        self.update_consumer_config(|config| config.consume_max_span = consume_max_span);
        if let Some(impl_) = self.default_lite_pull_consumer_impl.get() {
            impl_.set_consume_max_span(consume_max_span);
        }
    }
}

impl ConsumerOffsetControl for DefaultLitePullConsumer {
    async fn offset_store(&self) -> Option<Arc<OffsetStore>> {
        self.default_lite_pull_consumer_impl
            .get()
            .and_then(|impl_| impl_.offset_store())
            .or_else(|| self.current_offset_store())
    }

    async fn set_offset_store(&self, offset_store: Option<Arc<OffsetStore>>) -> ClientResult<()> {
        if let Some(impl_) = self.default_lite_pull_consumer_impl.get() {
            impl_.set_offset_store(offset_store.clone())?;
        }
        self.set_offset_store_local(offset_store);
        Ok(())
    }

    async fn fetch_message_queues(&self, topic: &str) -> ClientResult<Vec<MessageQueue>> {
        let wrapped_topic = self.with_namespace(topic);
        let queues = self.try_impl_()?.fetch_message_queues(wrapped_topic).await?;

        // Remove namespace from all queues and convert to Vec
        let result: Vec<_> = queues.into_iter().map(|mq| self.queue_without_namespace(&mq)).collect();

        Ok(result)
    }

    async fn committed(&self, message_queue: &MessageQueue) -> ClientResult<i64> {
        let wrapped_mq = self.queue_with_namespace(message_queue);
        self.try_impl_()?.committed(&wrapped_mq).await
    }

    async fn commit_all(&self) -> ClientResult<()> {
        self.try_impl_()?.commit_all().await
    }

    async fn commit_with_map(&self, offset_map: HashMap<MessageQueue, i64>, persist: bool) {
        // Wrap namespace for all queues
        let mut wrapped_offsets = HashMap::with_capacity(offset_map.len());
        for (mq, offset) in offset_map {
            wrapped_offsets.insert(self.queue_with_namespace(&mq), offset);
        }

        match self.try_impl_() {
            Ok(impl_) => {
                if let Err(e) = impl_.commit(wrapped_offsets, persist).await {
                    tracing::warn!("commit_with_map failed: {}", e);
                }
            }
            Err(e) => tracing::warn!("commit_with_map failed: {}", e),
        }
    }

    async fn commit(&self) {
        if let Err(e) = self.commit_all().await {
            tracing::warn!("commit failed: {}", e);
        }
    }

    async fn commit_with_set(&self, message_queues: HashSet<MessageQueue>, persist: bool) {
        // Wrap namespace for all queues
        let wrapped_queues: HashSet<_> = message_queues.iter().map(|mq| self.queue_with_namespace(mq)).collect();
        let impl_ = match self.try_impl_() {
            Ok(impl_) => impl_,
            Err(e) => {
                tracing::warn!("commit_with_set failed: {}", e);
                return;
            }
        };

        if let Err(e) = impl_.commit_message_queues(&wrapped_queues, persist).await {
            tracing::warn!("commit_with_set failed: {}", e);
        }
    }

    async fn commit_sync(&self) {
        // Commit all offsets (trait note: misleading name, doesn't actually block)
        if let Err(e) = self.commit_all().await {
            tracing::warn!("commit_sync failed: {}", e);
        }
    }

    async fn commit_sync_with_map(&self, offset_map: HashMap<MessageQueue, i64>, persist: bool) {
        // Commit specific offsets (trait note: misleading name, doesn't actually block)
        self.commit_with_map(offset_map, persist).await;
    }

    async fn is_auto_commit(&self) -> bool {
        self.consumer_config.load().auto_commit
    }

    async fn set_auto_commit(&self, auto_commit: bool) {
        self.update_consumer_config(|config| config.auto_commit = auto_commit);
        if let Some(impl_) = self.default_lite_pull_consumer_impl.get() {
            impl_.set_auto_commit(auto_commit);
        }
    }

    async fn auto_commit_interval_millis(&self) -> u64 {
        self.consumer_config.load().auto_commit_interval_millis
    }

    async fn set_auto_commit_interval_millis(&self, interval_millis: u64) {
        if interval_millis < MIN_AUTOCOMMIT_INTERVAL_MILLIS {
            return;
        }
        self.update_consumer_config(|config| config.auto_commit_interval_millis = interval_millis);
        if let Some(impl_) = self.default_lite_pull_consumer_impl.get() {
            impl_.set_auto_commit_interval_millis(interval_millis);
        }
    }

    async fn offset_for_timestamp(&self, message_queue: &MessageQueue, timestamp: u64) -> ClientResult<i64> {
        let wrapped_mq = self.queue_with_namespace(message_queue);
        self.try_impl_()?.offset_for_timestamp(&wrapped_mq, timestamp).await
    }

    async fn earliest_msg_store_time(&self, message_queue: &MessageQueue) -> ClientResult<i64> {
        let wrapped_mq = self.queue_with_namespace(message_queue);
        self.try_impl_()?.earliest_msg_store_time(&wrapped_mq).await
    }

    async fn max_offset(&self, message_queue: &MessageQueue) -> ClientResult<i64> {
        let wrapped_mq = self.queue_with_namespace(message_queue);
        self.try_impl_()?.max_offset_public(&wrapped_mq).await
    }

    async fn min_offset(&self, message_queue: &MessageQueue) -> ClientResult<i64> {
        let wrapped_mq = self.queue_with_namespace(message_queue);
        self.try_impl_()?.min_offset_public(&wrapped_mq).await
    }
}

impl ConsumerLifecycle for DefaultLitePullConsumer {
    async fn start(&self) -> ClientResult<()> {
        let impl_ = self.get_or_init_impl().await?;

        impl_.start().await?;
        self.set_offset_store_local(impl_.offset_store());
        self.start_trace_dispatcher().await;
        Ok(())
    }

    async fn shutdown(&self) {
        if let Some(impl_) = self.default_lite_pull_consumer_impl.get() {
            let _ = impl_.shutdown().await;
        }

        // Shutdown trace dispatcher
        let dispatcher = { self.trace_dispatcher.write().await.take() };
        if let Some(dispatcher) = dispatcher {
            if let Some(async_dispatcher) = dispatcher.as_any().downcast_ref::<AsyncTraceDispatcher>() {
                async_dispatcher.shutdown_async().await;
            } else {
                dispatcher.shutdown();
            }
        }
    }

    async fn is_running(&self) -> bool {
        match self.default_lite_pull_consumer_impl.get() {
            Some(impl_) => impl_.is_running().await,
            None => false,
        }
    }
}

impl MQConsumer for DefaultLitePullConsumer {
    async fn create_topic(
        &mut self,
        key: &str,
        new_topic: &str,
        queue_num: i32,
        attributes: HashMap<String, String>,
    ) -> ClientResult<()> {
        DefaultLitePullConsumer::create_topic(self, key, new_topic, queue_num, attributes).await
    }

    async fn create_topic_with_flag(
        &mut self,
        key: &str,
        new_topic: &str,
        queue_num: i32,
        topic_sys_flag: i32,
        attributes: HashMap<String, String>,
    ) -> ClientResult<()> {
        DefaultLitePullConsumer::create_topic_with_flag(self, key, new_topic, queue_num, topic_sys_flag, attributes)
            .await
    }

    async fn query_message(
        &mut self,
        topic: &str,
        key: &str,
        max_num: i32,
        begin: u64,
        end: u64,
    ) -> ClientResult<QueryResult> {
        DefaultLitePullConsumer::query_message(self, topic, key, max_num, begin, end).await
    }

    async fn view_message(&mut self, topic: &str, msg_id: &str) -> ClientResult<MessageExt> {
        DefaultLitePullConsumer::view_message(self, topic, msg_id).await
    }

    async fn send_message_back(&mut self, _msg: MessageExt, _delay_level: i32, _broker_name: &str) -> ClientResult<()> {
        // Lite pull consumer doesn't support send message back
        // This is typically used in push consumer for retry
        Err(crate::mq_client_err!(
            -1,
            "sendMessageBack is not supported in lite pull consumer"
        ))
    }

    async fn fetch_subscribe_message_queues(&mut self, topic: &str) -> ClientResult<Vec<MessageQueue>> {
        let queues = self.fetch_message_queues(topic).await?;
        Ok(queues.into_iter().collect())
    }

    async fn search_offset(&mut self, mq: &MessageQueue, timestamp: u64) -> ClientResult<i64> {
        <Self as ConsumerOffsetControl>::offset_for_timestamp(self, mq, timestamp).await
    }

    async fn max_offset(&mut self, mq: &MessageQueue) -> ClientResult<i64> {
        <Self as ConsumerOffsetControl>::max_offset(self, mq).await
    }

    async fn min_offset(&mut self, mq: &MessageQueue) -> ClientResult<i64> {
        <Self as ConsumerOffsetControl>::min_offset(self, mq).await
    }

    async fn earliest_msg_store_time(&mut self, mq: &MessageQueue) -> ClientResult<i64> {
        <Self as ConsumerOffsetControl>::earliest_msg_store_time(self, mq).await
    }
}

#[cfg(test)]
mod tests {
    use crate::test_support::error_assertions::assert_not_initialized;
    use crate::test_support::error_assertions::client_exception;
    use std::any::Any;
    use std::sync::atomic::AtomicUsize;
    use std::sync::atomic::Ordering;
    use std::sync::Mutex as StdMutex;

    use super::*;
    use crate::base::access_channel::AccessChannel;
    use crate::common::acl_client_rpc_hook::AclClientRPCHook;
    use crate::common::session_credentials::SessionCredentials;
    use crate::consumer::mq_consumer_inner::MQConsumerInner;
    use crate::consumer::rebalance_strategy::allocate_message_queue_averagely_by_circle::AllocateMessageQueueAveragelyByCircle;
    use crate::consumer::store::read_offset_type::ReadOffsetType;

    fn test_runtime() -> Arc<ClientRuntime> {
        crate::runtime::test_client_runtime("default-lite-pull-consumer-test")
    }

    #[derive(Default)]
    struct CapturingTraceDispatcher {
        start_count: AtomicUsize,
        shutdown_count: AtomicUsize,
        append_count: AtomicUsize,
        last_name_srv_addr: StdMutex<Option<String>>,
        last_access_channel: StdMutex<Option<AccessChannel>>,
    }

    impl TraceDispatcher for CapturingTraceDispatcher {
        fn start(&self, name_srv_addr: &str, access_channel: AccessChannel) -> ClientResult<()> {
            self.start_count.fetch_add(1, Ordering::SeqCst);
            *self.last_name_srv_addr.lock().expect("name server lock") = Some(name_srv_addr.to_string());
            *self.last_access_channel.lock().expect("access channel lock") = Some(access_channel);
            Ok(())
        }

        fn append(&self, _ctx: &dyn Any) -> bool {
            self.append_count.fetch_add(1, Ordering::SeqCst);
            true
        }

        fn flush(&self) -> ClientResult<()> {
            Ok(())
        }

        fn shutdown(&self) {
            self.shutdown_count.fetch_add(1, Ordering::SeqCst);
        }

        fn as_any(&self) -> &dyn Any {
            self
        }

        fn as_mut_any(&mut self) -> &mut dyn Any {
            self
        }
    }

    struct NoopMessageQueueListener;

    impl MessageQueueListener for NoopMessageQueueListener {
        fn message_queue_changed(
            &self,
            _topic: &str,
            _mq_all: &HashSet<MessageQueue>,
            _mq_assigned: &HashSet<MessageQueue>,
        ) {
        }
    }

    fn new_unstarted_consumer() -> DefaultLitePullConsumer {
        DefaultLitePullConsumer::builder(test_runtime())
            .consumer_group("lite_pull_group")
            .build()
            .expect("builder should create consumer")
    }

    fn new_namespaced_consumer_with_impl() -> (DefaultLitePullConsumer, Arc<DefaultLitePullConsumerImpl>) {
        let client_runtime = test_runtime();
        let consumer = DefaultLitePullConsumer::builder(Arc::clone(&client_runtime))
            .consumer_group("lite_pull_namespace_group")
            .namespace("ns")
            .build()
            .expect("builder should create namespaced consumer");
        let impl_ = Arc::new(DefaultLitePullConsumerImpl::new(
            client_runtime,
            consumer.client_config_snapshot(),
            consumer.consumer_config_snapshot(),
        ));
        impl_.bind_self();
        if consumer.default_lite_pull_consumer_impl.set(impl_.clone()).is_err() {
            panic!("test consumer impl should be set once");
        }

        (consumer, impl_)
    }

    #[tokio::test]
    async fn assignment_before_start_returns_not_initialized_error() {
        let consumer = new_unstarted_consumer();

        let error = consumer
            .assignment()
            .await
            .expect_err("assignment before start should fail");

        assert_not_initialized(&error, "DefaultLitePullConsumer not started. Call start() first.");
    }

    #[tokio::test]
    async fn consumer_running_info_before_start_returns_not_initialized_error() {
        let consumer = new_unstarted_consumer();

        let error = consumer
            .consumer_running_info()
            .await
            .expect_err("running info before start should fail");

        assert_not_initialized(&error, "DefaultLitePullConsumer not started. Call start() first.");
    }

    #[tokio::test]
    async fn subscribe_before_start_initializes_impl_and_records_subscription_like_java() {
        let consumer = DefaultLitePullConsumer::builder(test_runtime())
            .consumer_group("lite_pull_pre_start_subscribe_group")
            .namespace("ns")
            .build()
            .expect("builder should create consumer");

        consumer
            .subscribe_with_expression("TopicPreStart", "TagA")
            .await
            .expect("LitePull should accept subscribe before start like Java");

        assert!(!consumer.is_running().await);
        let impl_ = consumer
            .try_impl_()
            .expect("pre-start subscribe should initialize the implementation");
        let subscriptions = impl_.subscriptions();
        let subscription = subscriptions
            .iter()
            .find(|subscription| subscription.topic.as_str() == "ns%TopicPreStart")
            .expect("pre-start subscribe should be stored in rebalance subscriptions");

        assert_eq!(subscription.sub_string.as_str(), "TagA");
    }

    #[tokio::test]
    async fn initialization_propagates_rpc_hook_to_impl() {
        let rpc_hook = Arc::new(AclClientRPCHook::new(SessionCredentials::with_keys(
            "access_key",
            "secret_key",
        )));
        let consumer = DefaultLitePullConsumer::builder(test_runtime())
            .consumer_group("lite_pull_rpc_hook_group")
            .rpc_hook(rpc_hook)
            .build()
            .expect("builder should create consumer with RPC hook");

        let impl_ = consumer
            .get_or_init_impl()
            .await
            .expect("impl initialization should keep RPC hook");

        assert!(impl_.has_rpc_hook(), "LitePull impl should retain builder RPC hook");
    }

    #[tokio::test]
    async fn mq_consumer_offset_facade_delegates_to_lite_pull_impl_path() {
        let mut consumer = new_unstarted_consumer();
        let mq = MessageQueue::from_parts("TopicLite", "broker-a", 0);

        let search_error = <DefaultLitePullConsumer as MQConsumer>::search_offset(&mut consumer, &mq, 1)
            .await
            .expect_err("searchOffset should enter LitePull path and fail because the consumer is not started");
        let max_error = <DefaultLitePullConsumer as MQConsumer>::max_offset(&mut consumer, &mq)
            .await
            .expect_err("maxOffset should enter LitePull path and fail because the consumer is not started");
        let min_error = <DefaultLitePullConsumer as MQConsumer>::min_offset(&mut consumer, &mq)
            .await
            .expect_err("minOffset should enter LitePull path and fail because the consumer is not started");
        let earliest_error = <DefaultLitePullConsumer as MQConsumer>::earliest_msg_store_time(&mut consumer, &mq)
            .await
            .expect_err("earliestMsgStoreTime should enter LitePull path and fail because the consumer is not started");

        for error in [search_error, max_error, min_error, earliest_error] {
            assert_not_initialized(&error, "DefaultLitePullConsumer not started. Call start() first.");
        }
    }

    #[tokio::test]
    async fn mq_consumer_admin_facade_delegates_to_lite_pull_impl_path() {
        let mut consumer = new_unstarted_consumer();

        let create_error = <DefaultLitePullConsumer as MQConsumer>::create_topic(
            &mut consumer,
            TopicValidator::AUTO_CREATE_TOPIC_KEY_TOPIC,
            "TopicLiteAdmin",
            1,
            HashMap::new(),
        )
        .await
        .expect_err("createTopic should enter LitePull path and fail because the consumer is not started");
        let create_with_flag_error = <DefaultLitePullConsumer as MQConsumer>::create_topic_with_flag(
            &mut consumer,
            TopicValidator::AUTO_CREATE_TOPIC_KEY_TOPIC,
            "TopicLiteAdmin",
            1,
            0,
            HashMap::new(),
        )
        .await
        .expect_err("createTopicWithFlag should enter LitePull path and fail because the consumer is not started");
        let query_error =
            <DefaultLitePullConsumer as MQConsumer>::query_message(&mut consumer, "TopicLiteAdmin", "key", 32, 0, 1)
                .await
                .expect_err("queryMessage should enter LitePull path and fail because the consumer is not started");
        let view_error =
            <DefaultLitePullConsumer as MQConsumer>::view_message(&mut consumer, "TopicLiteAdmin", "not-a-msg-id")
                .await
                .expect_err("viewMessage should enter LitePull path and fail because the consumer is not started");

        for error in [create_error, create_with_flag_error, query_error, view_error] {
            assert_not_initialized(&error, "DefaultLitePullConsumer not started. Call start() first.");
        }
    }

    #[tokio::test]
    async fn consumer_running_info_facade_returns_lite_pull_snapshot() {
        let (consumer, _impl_) = new_namespaced_consumer_with_impl();
        consumer
            .subscribe_with_expression("TopicLiteRunningInfo", "TagA")
            .await
            .expect("subscribe should update running-info subscriptions");
        consumer.set_pull_batch_size(17).await;
        consumer.set_auto_commit(false).await;
        consumer.set_auto_commit_interval_millis(2_000).await;

        let info = consumer
            .consumer_running_info()
            .await
            .expect("running info facade should delegate to impl");

        assert_eq!(
            info.properties
                .get(ConsumerRunningInfo::PROP_CONSUME_TYPE)
                .map(String::as_str),
            Some("CONSUME_ACTIVELY")
        );
        assert_eq!(
            info.properties.get("consumerGroup").map(String::as_str),
            Some("lite_pull_namespace_group")
        );
        assert_eq!(info.properties.get("pullBatchSize").map(String::as_str), Some("17"));
        assert_eq!(info.properties.get("autoCommit").map(String::as_str), Some("false"));
        assert_eq!(
            info.properties.get("autoCommitIntervalMillis").map(String::as_str),
            Some("2000")
        );
        assert!(info
            .subscription_set
            .iter()
            .any(|subscription| subscription.topic.as_str() == "ns%TopicLiteRunningInfo"
                && subscription.sub_string.as_str() == "TagA"));
    }

    #[tokio::test]
    async fn assign_surfaces_impl_errors_like_java() {
        let (consumer, _impl_) = new_namespaced_consumer_with_impl();

        let error = consumer
            .assign(Vec::new())
            .await
            .expect_err("empty manual assignment should be rejected");

        assert!(client_exception(&error)
            .to_string()
            .contains("Message queues can not be null or empty."));
    }

    #[tokio::test]
    async fn offset_metadata_queries_before_start_return_not_initialized_error() {
        let consumer = new_unstarted_consumer();
        let queue = MessageQueue::from_parts("TopicA", "broker-a", 0);

        let earliest_error = consumer
            .earliest_msg_store_time(&queue)
            .await
            .expect_err("earliest store time before start should fail");
        let max_error = consumer
            .max_offset(&queue)
            .await
            .expect_err("max offset before start should fail");
        let min_error = consumer
            .min_offset(&queue)
            .await
            .expect_err("min offset before start should fail");

        assert_not_initialized(
            &earliest_error,
            "DefaultLitePullConsumer not started. Call start() first.",
        );
        assert_not_initialized(&max_error, "DefaultLitePullConsumer not started. Call start() first.");
        assert_not_initialized(&min_error, "DefaultLitePullConsumer not started. Call start() first.");
    }

    #[tokio::test]
    async fn poll_before_start_returns_empty_vec_without_panic() {
        let consumer = new_unstarted_consumer();

        assert!(consumer.poll_zero_copy().await.is_empty());
        assert!(consumer.poll_with_timeout_zero_copy(1).await.is_empty());
    }

    #[tokio::test]
    async fn lite_pull_facade_namespace_subscribe_wraps_builder_namespace_like_java() {
        let (consumer, impl_) = new_namespaced_consumer_with_impl();

        assert_eq!(consumer.namespace().as_deref(), Some("ns"));
        consumer
            .subscribe_with_expression("TopicA", "TagA")
            .await
            .expect("subscribe should succeed with injected impl");

        let subscriptions = impl_.subscriptions();
        let subscription = subscriptions
            .iter()
            .find(|subscription| subscription.topic.as_str() == "ns%TopicA")
            .expect("namespaced topic should be subscribed");
        assert_eq!(subscription.sub_string.as_str(), "TagA");
        assert!(!subscriptions
            .iter()
            .any(|subscription| subscription.topic.as_str() == "TopicA"));
    }

    #[tokio::test]
    async fn subscriptions_for_heartbeat_returns_current_rebalance_subscriptions_like_java_getter() {
        let (consumer, _impl_) = new_namespaced_consumer_with_impl();

        assert!(consumer.subscriptions_for_heartbeat().await.is_empty());

        consumer
            .subscribe_with_expression("TopicA", "TagA")
            .await
            .expect("subscribe should succeed with injected impl");

        let subscriptions = consumer.subscriptions_for_heartbeat().await;
        assert_eq!(subscriptions.len(), 1);
        let subscription = subscriptions.iter().next().expect("subscription should exist");
        assert_eq!(subscription.topic.as_str(), "ns%TopicA");
        assert_eq!(subscription.sub_string.as_str(), "TagA");
    }

    #[tokio::test]
    async fn lite_pull_java_getter_aliases_delegate_to_config() {
        let consumer = new_unstarted_consumer();

        assert_eq!(consumer.get_message_model().await, consumer.message_model().await);
        assert_eq!(
            consumer.get_consume_from_where().await,
            consumer.consume_from_where().await
        );
        assert_eq!(
            consumer.get_consume_timestamp().await,
            consumer.consume_timestamp().await
        );
        assert_eq!(
            consumer.get_allocate_message_queue_strategy().await.get_name(),
            consumer.allocate_message_queue_strategy().await.get_name()
        );
        assert_eq!(
            consumer.get_offset_store().await.is_some(),
            consumer.offset_store().await.is_some()
        );
        assert_eq!(
            consumer.get_topic_metadata_check_interval_millis().await,
            consumer.topic_metadata_check_interval_millis().await
        );
        assert_eq!(
            consumer.get_poll_timeout_millis().await,
            consumer.poll_timeout_millis().await
        );
        assert_eq!(
            consumer.get_consumer_timeout_millis_when_suspend().await,
            consumer.consumer_timeout_millis_when_suspend().await
        );
        assert_eq!(
            consumer.get_consumer_pull_timeout_millis().await,
            consumer.consumer_pull_timeout_millis().await
        );
        assert_eq!(consumer.get_pull_batch_size().await, consumer.pull_batch_size().await);
        assert_eq!(
            consumer.get_pull_threshold_for_all().await,
            consumer.pull_threshold_for_all().await
        );
        assert_eq!(
            consumer.get_pull_threshold_for_queue().await,
            consumer.pull_threshold_for_queue().await
        );
        assert_eq!(
            consumer.get_pull_threshold_size_for_queue().await,
            consumer.pull_threshold_size_for_queue().await
        );
        assert_eq!(
            consumer.get_auto_commit_interval_millis().await,
            consumer.auto_commit_interval_millis().await
        );
    }

    #[tokio::test]
    async fn set_sub_expression_for_assign_surfaces_impl_errors_like_java() {
        let (consumer, _impl_) = new_namespaced_consumer_with_impl();

        let error = consumer
            .set_sub_expression_for_assign("TopicA", " ")
            .await
            .expect_err("blank assign filter should be rejected");
        assert!(client_exception(&error)
            .to_string()
            .contains("subExpression can not be null or empty."));

        consumer
            .set_sub_expression_for_assign("TopicA", "TagA")
            .await
            .expect("valid assign filter should be accepted before start");
    }

    #[tokio::test]
    async fn set_auto_commit_updates_initialized_impl_like_java_facade_reference() {
        let (consumer, impl_) = new_namespaced_consumer_with_impl();

        assert!(consumer.is_auto_commit().await);
        assert!(impl_.is_auto_commit());

        consumer.set_auto_commit(false).await;

        assert!(!consumer.is_auto_commit().await);
        assert!(!impl_.is_auto_commit());

        consumer.set_auto_commit(true).await;

        assert!(consumer.is_auto_commit().await);
        assert!(impl_.is_auto_commit());
    }

    #[tokio::test]
    async fn set_auto_commit_interval_updates_initialized_impl_and_ignores_invalid_like_java() {
        let (consumer, impl_) = new_namespaced_consumer_with_impl();

        assert_eq!(consumer.auto_commit_interval_millis().await, 5000);
        assert_eq!(impl_.auto_commit_interval_millis(), 5000);

        consumer.set_auto_commit_interval_millis(2000).await;

        assert_eq!(consumer.auto_commit_interval_millis().await, 2000);
        assert_eq!(impl_.auto_commit_interval_millis(), 2000);

        consumer
            .set_auto_commit_interval_millis(MIN_AUTOCOMMIT_INTERVAL_MILLIS - 1)
            .await;

        assert_eq!(consumer.auto_commit_interval_millis().await, 2000);
        assert_eq!(impl_.auto_commit_interval_millis(), 2000);
    }

    #[tokio::test]
    async fn set_unit_mode_updates_initialized_impl_and_heartbeat_source_like_java() {
        let (consumer, impl_) = new_namespaced_consumer_with_impl();

        assert!(!consumer.is_unit_mode().await);
        assert!(!impl_.is_unit_mode());
        assert!(!MQConsumerInner::is_unit_mode(impl_.as_ref()));

        consumer.set_unit_mode(true).await;

        assert!(consumer.is_unit_mode().await);
        assert!(impl_.is_unit_mode());
        assert!(MQConsumerInner::is_unit_mode(impl_.as_ref()));
    }

    #[test]
    fn set_consumer_group_updates_initialized_impl_and_rebalance_before_start_like_java() {
        let (consumer, impl_) = new_namespaced_consumer_with_impl();

        consumer
            .set_consumer_group("lite_pull_updated_group")
            .expect("consumer group should be mutable before start");

        assert_eq!(consumer.consumer_group().as_str(), "lite_pull_updated_group");
        assert_eq!(impl_.consumer_group_config().as_str(), "lite_pull_updated_group");
        assert_eq!(
            MQConsumerInner::group_name(impl_.as_ref()).as_str(),
            "lite_pull_updated_group"
        );
        assert_eq!(
            impl_.rebalance_consumer_group_name().as_deref(),
            Some("lite_pull_updated_group")
        );
    }

    #[test]
    fn start_namespace_wraps_consumer_group_like_java_lite_pull_start() {
        let (consumer, _impl_) = new_namespaced_consumer_with_impl();

        assert_eq!(
            consumer.consumer_group_with_namespace().as_str(),
            "ns%lite_pull_namespace_group"
        );

        consumer
            .set_consumer_group("ns%lite_pull_namespace_group")
            .expect("pre-wrapped group should be accepted before start");

        assert_eq!(
            consumer.consumer_group_with_namespace().as_str(),
            "ns%lite_pull_namespace_group"
        );
    }

    #[tokio::test]
    async fn set_message_queue_listener_updates_initialized_impl_like_java() {
        let (consumer, impl_) = new_namespaced_consumer_with_impl();

        assert!(consumer.message_queue_listener().await.is_none());
        assert!(impl_.message_queue_listener().is_none());

        let listener: ArcMessageQueueListener = Arc::new(NoopMessageQueueListener);
        consumer.set_message_queue_listener(Some(listener.clone())).await;

        let facade_listener = consumer
            .message_queue_listener()
            .await
            .expect("facade should return configured listener");
        let impl_listener = impl_
            .message_queue_listener()
            .expect("impl should receive configured listener");
        assert!(Arc::ptr_eq(&facade_listener, &listener));
        assert!(Arc::ptr_eq(&impl_listener, &listener));

        consumer.set_message_queue_listener(None).await;

        assert!(consumer.message_queue_listener().await.is_none());
        assert!(impl_.message_queue_listener().is_none());
    }

    #[tokio::test]
    async fn set_offset_store_updates_initialized_impl_and_rebalance_like_java() {
        let (consumer, impl_) = new_namespaced_consumer_with_impl();
        let queue = MessageQueue::from_parts("TopicA", "broker-a", 0);
        let offset_store = Arc::new(OffsetStore::new_test());

        assert!(consumer.offset_store().await.is_none());
        assert!(impl_.offset_store().is_none());
        assert!(!impl_.rebalance_has_offset_store());

        consumer
            .set_offset_store(Some(offset_store.clone()))
            .await
            .expect("offset store should be mutable before start");
        offset_store.update_offset(&queue, 42, false).await;

        let facade_store = consumer
            .offset_store()
            .await
            .expect("facade should expose configured offset store");
        let impl_store = impl_
            .offset_store()
            .expect("impl should receive configured offset store");
        assert_eq!(
            facade_store.read_offset(&queue, ReadOffsetType::ReadFromMemory).await,
            42
        );
        assert_eq!(impl_store.read_offset(&queue, ReadOffsetType::ReadFromMemory).await, 42);
        assert!(impl_.rebalance_has_offset_store());

        consumer
            .set_offset_store(None)
            .await
            .expect("offset store should be clearable before start");

        assert!(consumer.offset_store().await.is_none());
        assert!(impl_.offset_store().is_none());
        assert!(!impl_.rebalance_has_offset_store());
    }

    #[tokio::test]
    async fn set_allocate_message_queue_strategy_updates_initialized_impl_and_rebalance_like_java() {
        let (consumer, impl_) = new_namespaced_consumer_with_impl();

        assert_eq!(consumer.allocate_message_queue_strategy().await.get_name(), "AVG");
        assert_eq!(impl_.allocate_message_queue_strategy().get_name(), "AVG");
        assert_eq!(impl_.rebalance_allocate_message_queue_strategy_name(), None);

        consumer
            .set_allocate_message_queue_strategy(Arc::new(AllocateMessageQueueAveragelyByCircle))
            .await;

        assert_eq!(
            consumer.allocate_message_queue_strategy().await.get_name(),
            "AVG_BY_CIRCLE"
        );
        assert_eq!(impl_.allocate_message_queue_strategy().get_name(), "AVG_BY_CIRCLE");
        assert_eq!(
            impl_.rebalance_allocate_message_queue_strategy_name(),
            Some("AVG_BY_CIRCLE")
        );
    }

    #[tokio::test]
    #[allow(deprecated)]
    async fn core_runtime_config_setters_update_initialized_impl_like_java_facade_reference() {
        let (consumer, impl_) = new_namespaced_consumer_with_impl();

        assert_eq!(consumer.message_model().await, MessageModel::Clustering);
        assert_eq!(impl_.message_model_config(), MessageModel::Clustering);
        assert_eq!(MQConsumerInner::message_model(impl_.as_ref()), MessageModel::Clustering);

        consumer.set_message_model(MessageModel::Broadcasting).await;

        assert_eq!(consumer.message_model().await, MessageModel::Broadcasting);
        assert_eq!(impl_.message_model_config(), MessageModel::Broadcasting);
        assert_eq!(
            MQConsumerInner::message_model(impl_.as_ref()),
            MessageModel::Broadcasting
        );

        assert_eq!(
            consumer.consume_from_where().await,
            ConsumeFromWhere::ConsumeFromLastOffset
        );
        consumer
            .set_consume_from_where(ConsumeFromWhere::ConsumeFromFirstOffset)
            .await
            .expect("valid Java LitePull consumeFromWhere should be accepted");

        assert_eq!(
            consumer.consume_from_where().await,
            ConsumeFromWhere::ConsumeFromFirstOffset
        );
        assert_eq!(
            impl_.consume_from_where_config(),
            ConsumeFromWhere::ConsumeFromFirstOffset
        );
        assert_eq!(
            MQConsumerInner::consume_from_where(impl_.as_ref()),
            ConsumeFromWhere::ConsumeFromFirstOffset
        );

        let error = consumer
            .set_consume_from_where(ConsumeFromWhere::ConsumeFromMaxOffset)
            .await
            .expect_err("Java LitePull rejects legacy consumeFromWhere values");
        assert!(client_exception(&error)
            .to_string()
            .contains("Invalid ConsumeFromWhere Value"));
        assert_eq!(
            consumer.consume_from_where().await,
            ConsumeFromWhere::ConsumeFromFirstOffset
        );

        let timestamp = CheetahString::from_static_str("20250102030405");
        consumer.set_consume_timestamp(Some(timestamp.clone())).await;

        assert_eq!(consumer.consume_timestamp().await, Some(timestamp.clone()));
        assert_eq!(impl_.consume_timestamp(), Some(timestamp));

        assert_eq!(consumer.topic_metadata_check_interval_millis().await, 30_000);
        assert_eq!(impl_.topic_metadata_check_interval_millis(), 30_000);

        consumer.set_topic_metadata_check_interval_millis(12_345).await;

        assert_eq!(consumer.topic_metadata_check_interval_millis().await, 12_345);
        assert_eq!(impl_.topic_metadata_check_interval_millis(), 12_345);
    }

    #[tokio::test]
    async fn set_poll_timeout_updates_initialized_impl_like_java_facade_reference() {
        let (consumer, impl_) = new_namespaced_consumer_with_impl();

        assert_eq!(consumer.poll_timeout_millis().await, 5000);
        assert_eq!(impl_.poll_timeout_millis(), 5000);

        consumer.set_poll_timeout_millis(1234).await;

        assert_eq!(consumer.poll_timeout_millis().await, 1234);
        assert_eq!(impl_.poll_timeout_millis(), 1234);
    }

    #[tokio::test]
    async fn long_polling_timeout_setters_update_initialized_impl_like_java_facade_reference() {
        let (consumer, impl_) = new_namespaced_consumer_with_impl();

        assert_eq!(consumer.broker_suspend_max_time_millis().await, 20_000);
        assert_eq!(impl_.broker_suspend_max_time_millis(), 20_000);
        assert_eq!(consumer.consumer_timeout_millis_when_suspend().await, 30_000);
        assert_eq!(impl_.consumer_timeout_millis_when_suspend(), 30_000);
        assert_eq!(consumer.consumer_pull_timeout_millis().await, 10_000);
        assert_eq!(impl_.consumer_pull_timeout_millis(), 10_000);

        consumer.set_broker_suspend_max_time_millis(11_111).await;
        consumer.set_consumer_timeout_millis_when_suspend(22_222).await;
        consumer.set_consumer_pull_timeout_millis(12_345).await;

        assert_eq!(consumer.broker_suspend_max_time_millis().await, 11_111);
        assert_eq!(impl_.broker_suspend_max_time_millis(), 11_111);
        assert_eq!(consumer.consumer_timeout_millis_when_suspend().await, 22_222);
        assert_eq!(impl_.consumer_timeout_millis_when_suspend(), 22_222);
        assert_eq!(consumer.consumer_pull_timeout_millis().await, 12_345);
        assert_eq!(impl_.consumer_pull_timeout_millis(), 12_345);
    }

    #[tokio::test]
    async fn pull_flow_control_setters_update_initialized_impl_like_java_facade_reference() {
        let (consumer, impl_) = new_namespaced_consumer_with_impl();

        consumer.set_pull_batch_size(64).await;
        consumer.set_pull_thread_nums(12).await;
        consumer.set_pull_threshold_for_all(20_000).await;
        consumer.set_pull_threshold_for_queue(2_000).await;
        consumer.set_pull_threshold_size_for_queue(256).await;
        consumer.set_consume_max_span(4_000).await;

        assert_eq!(consumer.pull_batch_size().await, 64);
        assert_eq!(impl_.pull_batch_size(), 64);
        assert_eq!(consumer.pull_thread_nums().await, 12);
        assert_eq!(impl_.pull_thread_nums(), 12);
        assert_eq!(consumer.pull_threshold_for_all().await, 20_000);
        assert_eq!(impl_.pull_threshold_for_all(), 20_000);
        assert_eq!(consumer.pull_threshold_for_queue().await, 2_000);
        assert_eq!(impl_.pull_threshold_for_queue(), 2_000);
        assert_eq!(consumer.pull_threshold_size_for_queue().await, 256);
        assert_eq!(impl_.pull_threshold_size_for_queue(), 256);
        assert_eq!(consumer.consume_max_span().await, 4_000);
        assert_eq!(impl_.consume_max_span(), 4_000);
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn concurrent_facade_updates_publish_complete_immutable_snapshots() {
        let consumer = Arc::new(new_unstarted_consumer());
        let original = consumer.consumer_config();
        let barrier = Arc::new(tokio::sync::Barrier::new(4));

        let batch_consumer = consumer.clone();
        let batch_barrier = barrier.clone();
        let batch = tokio::spawn(async move {
            batch_barrier.wait().await;
            batch_consumer.set_pull_batch_size(64).await;
        });

        let threads_consumer = consumer.clone();
        let threads_barrier = barrier.clone();
        let threads = tokio::spawn(async move {
            threads_barrier.wait().await;
            threads_consumer.set_pull_thread_nums(12).await;
        });

        let threshold_consumer = consumer.clone();
        let threshold_barrier = barrier.clone();
        let threshold = tokio::spawn(async move {
            threshold_barrier.wait().await;
            threshold_consumer.set_pull_threshold_for_all(20_000).await;
        });

        let span_consumer = consumer.clone();
        let span = tokio::spawn(async move {
            barrier.wait().await;
            span_consumer.set_consume_max_span(4_000).await;
        });

        for update in [batch, threads, threshold, span] {
            update.await.expect("facade config update should complete");
        }

        let current = consumer.consumer_config();
        assert_eq!(current.pull_batch_size, 64);
        assert_eq!(current.pull_thread_nums, 12);
        assert_eq!(current.pull_threshold_for_all, 20_000);
        assert_eq!(current.consume_max_span, 4_000);
        assert_ne!(original.pull_batch_size, current.pull_batch_size);
        assert_ne!(original.pull_thread_nums, current.pull_thread_nums);
        assert_ne!(original.pull_threshold_for_all, current.pull_threshold_for_all);
        assert_ne!(original.consume_max_span, current.consume_max_span);
    }

    #[tokio::test]
    async fn broker_selection_setters_update_facade_config_like_java() {
        let (consumer, impl_) = new_namespaced_consumer_with_impl();

        assert!(!consumer.is_connect_broker_by_user().await);
        assert_eq!(
            consumer.default_broker_id().await,
            rocketmq_model::common::mix_all::MASTER_ID
        );
        assert!(!impl_.is_connect_broker_by_user());
        assert_eq!(impl_.default_broker_id(), rocketmq_model::common::mix_all::MASTER_ID);

        consumer.set_connect_broker_by_user(true).await;
        consumer.set_default_broker_id(3).await;

        assert!(consumer.is_connect_broker_by_user().await);
        assert_eq!(consumer.default_broker_id().await, 3);
        assert!(impl_.is_connect_broker_by_user());
        assert_eq!(impl_.default_broker_id(), 3);
    }

    #[test]
    fn lite_pull_facade_namespace_helpers_use_primary_namespace_like_java() {
        let (consumer, _) = new_namespaced_consumer_with_impl();
        let queue = MessageQueue::from_parts("TopicB", "broker-a", 3);

        assert_eq!(consumer.with_namespace("TopicB").as_str(), "ns%TopicB");
        assert_eq!(consumer.with_namespace("ns%TopicB").as_str(), "ns%TopicB");
        assert_eq!(consumer.without_namespace("ns%TopicB").as_str(), "TopicB");
        assert_eq!(consumer.queue_with_namespace(&queue).topic_str(), "ns%TopicB");
        assert_eq!(
            consumer
                .queue_without_namespace(&MessageQueue::from_parts("ns%TopicB", "broker-a", 3))
                .topic_str(),
            "TopicB"
        );
    }

    #[tokio::test]
    async fn trace_config_accessors_match_java_facade_fields() {
        let mut consumer = new_unstarted_consumer();

        assert!(!consumer.is_enable_msg_trace());
        assert!(consumer.customized_trace_topic().is_none());
        assert!(consumer.trace_dispatcher().await.is_none());

        consumer.set_enable_msg_trace(true);
        consumer.set_customized_trace_topic("TraceTopic");

        assert!(consumer.is_enable_msg_trace());
        assert_eq!(consumer.customized_trace_topic().as_deref(), Some("TraceTopic"));

        consumer.clear_customized_trace_topic();

        assert!(consumer.customized_trace_topic().is_none());
    }

    #[tokio::test]
    async fn lite_pull_use_tls_facade_updates_shared_impl_config_like_java_client_config() {
        let (consumer, impl_) = new_namespaced_consumer_with_impl();

        assert!(!consumer.is_use_tls());
        assert!(!impl_.client_config.load().is_use_tls());

        consumer.set_use_tls(true).await;

        assert!(consumer.is_use_tls());
        assert!(consumer.client_config().is_use_tls());
        assert!(impl_.client_config.load().is_use_tls());
    }

    #[tokio::test]
    async fn lite_pull_use_tls_facade_updates_async_trace_dispatcher() {
        let dispatcher = Arc::new(AsyncTraceDispatcher::new(
            test_runtime(),
            "lite_pull_tls_trace_group",
            Type::Consume,
            1,
            "",
            None,
        ));
        let consumer = DefaultLitePullConsumer::new(
            test_runtime(),
            ClientConfig::default(),
            LitePullConsumerConfig {
                consumer_group: CheetahString::from_static_str("lite_pull_tls_trace_group"),
                ..Default::default()
            },
            None,
            Some(dispatcher.clone()),
            true,
            None,
        );

        assert!(!consumer.is_use_tls());
        assert!(!dispatcher.is_use_tls());

        consumer.set_use_tls(true).await;

        assert!(consumer.is_use_tls());
        assert!(dispatcher.is_use_tls());
    }

    #[tokio::test]
    async fn trace_init_uses_configured_batch_num_like_java() {
        let client_runtime = test_runtime();
        let mut client_config = ClientConfig::default();
        client_config.set_trace_msg_batch_num(6);
        let consumer = DefaultLitePullConsumer::new(
            Arc::clone(&client_runtime),
            client_config,
            LitePullConsumerConfig {
                consumer_group: CheetahString::from_static_str("lite_pull_trace_batch_group"),
                ..Default::default()
            },
            None,
            None,
            true,
            None,
        );
        let impl_ = Arc::new(DefaultLitePullConsumerImpl::new(
            client_runtime,
            consumer.client_config_snapshot(),
            consumer.consumer_config_snapshot(),
        ));
        impl_.bind_self();

        consumer
            .init_trace_dispatcher_internal(&impl_)
            .await
            .expect("trace init should create dispatcher");
        let dispatcher = consumer
            .trace_dispatcher
            .read()
            .await
            .as_ref()
            .expect("trace dispatcher should be initialized")
            .clone();
        let async_dispatcher = dispatcher
            .as_any()
            .downcast_ref::<AsyncTraceDispatcher>()
            .expect("default trace dispatcher should be AsyncTraceDispatcher");
        assert_eq!(async_dispatcher.batch_num(), 6);
    }

    #[tokio::test]
    async fn trace_init_registers_custom_dispatcher_and_starts_with_client_config() {
        let client_runtime = test_runtime();
        let dispatcher = Arc::new(CapturingTraceDispatcher::default());
        let mut client_config = ClientConfig::default();
        client_config.set_namesrv_addr(CheetahString::from_static_str("127.0.0.1:9876"));
        client_config.set_access_channel(AccessChannel::Cloud);

        let consumer = DefaultLitePullConsumer::new(
            Arc::clone(&client_runtime),
            client_config,
            LitePullConsumerConfig {
                consumer_group: CheetahString::from_static_str("lite_pull_trace_group"),
                ..Default::default()
            },
            None,
            Some(dispatcher.clone()),
            true,
            None,
        );
        let impl_ = Arc::new(DefaultLitePullConsumerImpl::new(
            client_runtime,
            consumer.client_config_snapshot(),
            consumer.consumer_config_snapshot(),
        ));
        impl_.bind_self();

        consumer
            .init_trace_dispatcher_internal(&impl_)
            .await
            .expect("trace init should register hook");
        assert_eq!(impl_.consume_message_hook_count(), 1);

        consumer.start_trace_dispatcher().await;
        assert_eq!(dispatcher.start_count.load(Ordering::SeqCst), 1);
        assert_eq!(
            dispatcher
                .last_name_srv_addr
                .lock()
                .expect("name server lock")
                .as_deref(),
            Some("127.0.0.1:9876")
        );
        assert_eq!(
            *dispatcher.last_access_channel.lock().expect("access channel lock"),
            Some(AccessChannel::Cloud)
        );
    }
}