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
// 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::BinaryHeap;
use std::collections::HashSet;
use std::future::Future;
use std::hash::Hash;
use std::hash::Hasher;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicI32;
use std::sync::atomic::AtomicU32;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::AtomicU8;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::sync::Mutex as StdMutex;
use std::sync::MutexGuard as StdMutexGuard;
use std::time::Duration;
use std::time::Instant;

use crate::ClientError;
use cheetah_string::CheetahString;
use dashmap::DashMap;
use rocketmq_model::common::message::message_batch::MessageBatch;
use rocketmq_model::common::message::message_queue::MessageQueue;
use rocketmq_model::common::message::message_single::Message;
use rocketmq_model::common::message::MessageConst;
use rocketmq_model::common::message::MessageTrait;
use rocketmq_runtime::common::time_utils::current_millis;
use rocketmq_runtime::BudgetLimit;
use rocketmq_runtime::BudgetedItem;
use rocketmq_runtime::BudgetedQueue;
use rocketmq_runtime::ChildServiceContext;
use rocketmq_runtime::FullPolicy;
use rocketmq_runtime::RateLimit;
use rocketmq_runtime::ResourceBudget;
use rocketmq_runtime::ResourcePermit;
use serde::Serialize;
use tokio::sync::watch;
use tokio::sync::Mutex;

use crate::producer::default_mq_producer::DefaultMQProducer;
use crate::producer::send_callback::ArcSendCallback;
use crate::producer::send_result::SendResult;
use crate::runtime::spawn_client_tracked_task_with_context;
use crate::runtime::ClientTrackedTaskHandle;

const GUARD_TASK_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);

type BatchMap = Arc<DashMap<AggregateKey, Arc<Mutex<MessageAccumulation>>>>;

#[derive(Debug, Clone, Serialize)]
pub struct ProduceAccumulatorGuardLifecycleProbe {
    pub task_count_before_shutdown: usize,
    pub task_count_after_shutdown: usize,
    pub shutdown_elapsed_us: u128,
    pub guard_metrics: ProduceAccumulatorGuardMetricsSnapshot,
    pub healthy: bool,
}

#[derive(Debug, Clone, Copy, Default, Serialize)]
pub struct ProduceAccumulatorGuardMetricsSnapshot {
    pub sync: BatchGuardMetricsSnapshot,
    pub async_send: BatchGuardMetricsSnapshot,
}

#[derive(Debug, Clone, Copy, Default, Serialize)]
pub struct BatchGuardMetricsSnapshot {
    pub wakeup_count: u64,
    pub flush_count: u64,
    pub idle_wakeup_count: u64,
    pub scheduled_count: usize,
    pub retained_bytes: usize,
    pub oldest_queued_age_ms: u64,
    pub throttled_count: u64,
    pub rejected_count: u64,
    pub dropped_count: u64,
}

#[derive(Default)]
struct BatchGuardMetrics {
    wakeup_count: AtomicU64,
    flush_count: AtomicU64,
    idle_wakeup_count: AtomicU64,
}

impl BatchGuardMetrics {
    fn record_wakeup(&self) {
        self.wakeup_count.fetch_add(1, Ordering::Relaxed);
    }

    fn record_flush(&self) {
        self.flush_count.fetch_add(1, Ordering::Relaxed);
    }

    fn record_idle(&self) {
        self.idle_wakeup_count.fetch_add(1, Ordering::Relaxed);
    }

    fn snapshot(&self) -> BatchGuardMetricsSnapshot {
        BatchGuardMetricsSnapshot {
            wakeup_count: self.wakeup_count.load(Ordering::Relaxed),
            flush_count: self.flush_count.load(Ordering::Relaxed),
            idle_wakeup_count: self.idle_wakeup_count.load(Ordering::Relaxed),
            scheduled_count: 0,
            retained_bytes: 0,
            oldest_queued_age_ms: 0,
            throttled_count: 0,
            rejected_count: 0,
            dropped_count: 0,
        }
    }
}

pub struct ProduceAccumulator {
    total_hold_size: AtomicUsize,
    hold_size: AtomicUsize,
    hold_ms: AtomicU32,
    lifecycle: StdMutex<AccumulatorLifecycleState>,
    message_budget: ResourceBudget,
    guard_thread_for_sync_send: GuardForSyncSendService,
    guard_thread_for_async_send: GuardForAsyncSendService,
    currently_hold_size: Arc<AtomicU64>,
    sync_send_batchs: Arc<DashMap<AggregateKey, Arc<Mutex<MessageAccumulation>>>>,
    async_send_batchs: Arc<DashMap<AggregateKey, Arc<Mutex<MessageAccumulation>>>>,
}

#[derive(Default)]
struct AccumulatorLifecycleState {
    started: bool,
    stopping: bool,
}

struct AccumulatorStoppingReset<'a> {
    lifecycle: &'a StdMutex<AccumulatorLifecycleState>,
}

impl Drop for AccumulatorStoppingReset<'_> {
    fn drop(&mut self) {
        let mut lifecycle = match self.lifecycle.lock() {
            Ok(lifecycle) => lifecycle,
            Err(poisoned) => {
                tracing::warn!("ProduceAccumulator lifecycle lock was poisoned");
                poisoned.into_inner()
            }
        };
        lifecycle.stopping = false;
    }
}

impl ProduceAccumulator {
    fn lifecycle(&self) -> StdMutexGuard<'_, AccumulatorLifecycleState> {
        match self.lifecycle.lock() {
            Ok(lifecycle) => lifecycle,
            Err(poisoned) => {
                tracing::warn!("ProduceAccumulator lifecycle lock was poisoned");
                poisoned.into_inner()
            }
        }
    }

    pub fn new(service_context: ChildServiceContext, instance_name: &str) -> Self {
        let resource_budget = crate::runtime::build_client_resource_budget(
            &crate::runtime::ClientRuntimeConfig::default(),
            &service_context.process_budget(),
        )
        .expect("service-context produce accumulator resource budget must be valid");
        Self::with_resource_budget(service_context, instance_name, resource_budget)
    }

    pub(crate) fn with_resource_budget(
        service_context: ChildServiceContext,
        instance_name: &str,
        resource_budget: ResourceBudget,
    ) -> Self {
        const ACCUMULATED_MESSAGE_LIMIT: usize = 262_144;
        let parent_capacity = resource_budget.limit().capacity;
        let message_count = ACCUMULATED_MESSAGE_LIMIT.min(parent_capacity.count).max(1);
        let message_rate = u64::try_from(message_count).unwrap_or(u64::MAX).max(1);
        let message_budget = resource_budget
            .child(
                "accumulated-messages",
                BudgetLimit::new(message_count, parent_capacity.bytes.max(1), FullPolicy::Reject)
                    .with_rate(RateLimit::new(message_rate, message_rate))
                    .with_max_age(Duration::from_secs(60)),
            )
            .expect("clamped accumulated-message limits fit the client resource root");
        Self {
            total_hold_size: AtomicUsize::new(1024 * 1024 * 32),
            hold_size: AtomicUsize::new(1024 * 32),
            hold_ms: AtomicU32::new(10),
            lifecycle: StdMutex::new(AccumulatorLifecycleState::default()),
            message_budget,
            guard_thread_for_async_send: GuardForAsyncSendService::new(
                service_context.component("async-batch-guard"),
                instance_name,
                resource_budget.clone(),
            ),
            guard_thread_for_sync_send: GuardForSyncSendService::new(
                service_context.component("sync-batch-guard"),
                instance_name,
                resource_budget,
            ),
            currently_hold_size: Arc::new(AtomicU64::new(0)),
            sync_send_batchs: Arc::new(DashMap::new()),
            async_send_batchs: Arc::new(DashMap::new()),
        }
    }
}

impl ProduceAccumulator {
    pub fn batch_max_delay_ms(&self) -> u32 {
        self.hold_ms.load(Ordering::Acquire)
    }

    pub fn set_batch_max_delay_ms(&self, hold_ms: u32) -> crate::ClientResult<()> {
        if hold_ms == 0 || hold_ms > 30_000 {
            return Err(crate::mq_client_err!(format!(
                "batchMaxDelayMs expect between 1ms and 30s, but get {hold_ms}!"
            )));
        }
        self.hold_ms.store(hold_ms, Ordering::Release);
        Ok(())
    }

    pub fn batch_max_bytes(&self) -> usize {
        self.hold_size.load(Ordering::Acquire)
    }

    pub fn set_batch_max_bytes(&self, hold_size: u64) -> crate::ClientResult<()> {
        if hold_size == 0 || hold_size > 2 * 1024 * 1024 {
            return Err(crate::mq_client_err!(format!(
                "batchMaxBytes expect between 1B and 2MB, but get {hold_size}!"
            )));
        }
        self.hold_size.store(hold_size as usize, Ordering::Release);
        Ok(())
    }

    pub fn total_batch_max_bytes(&self) -> usize {
        self.total_hold_size.load(Ordering::Acquire)
    }

    pub fn set_total_batch_max_bytes(&self, total_hold_size: u64) -> crate::ClientResult<()> {
        if total_hold_size == 0 {
            return Err(crate::mq_client_err!(format!(
                "totalBatchMaxBytes must bigger then 0, but get {total_hold_size}!"
            )));
        }
        self.total_hold_size.store(total_hold_size as usize, Ordering::Release);
        Ok(())
    }

    pub fn start(&self) -> crate::ClientResult<()> {
        let mut lifecycle = self.lifecycle();
        if lifecycle.stopping {
            tracing::warn!("ProduceAccumulator is stopping");
            return Ok(());
        }
        if lifecycle.started && self.guard_task_count() == 2 {
            tracing::warn!("ProduceAccumulator is already started");
            return Ok(());
        }

        let hold_ms = self.batch_max_delay_ms();
        let hold_size = self.batch_max_bytes();
        self.guard_thread_for_sync_send
            .start(self.sync_send_batchs.clone(), hold_ms)?;
        if let Err(error) = self.guard_thread_for_async_send.start(
            self.async_send_batchs.clone(),
            self.currently_hold_size.clone(),
            hold_size,
            hold_ms,
        ) {
            self.guard_thread_for_sync_send.shutdown();
            return Err(error);
        }
        lifecycle.started = self.guard_task_count() == 2;
        if lifecycle.started {
            Ok(())
        } else {
            Err(crate::mq_client_err!(
                "ProduceAccumulator guard services failed to start"
            ))
        }
    }
    pub fn shutdown(&self) {
        {
            let mut lifecycle = self.lifecycle();
            if lifecycle.stopping {
                return;
            }
            lifecycle.started = false;
            lifecycle.stopping = true;
        }
        let _stopping_reset = AccumulatorStoppingReset {
            lifecycle: &self.lifecycle,
        };

        self.guard_thread_for_sync_send.shutdown();
        self.guard_thread_for_async_send.shutdown();
        self.release_pending_batches_on_shutdown();
    }

    pub async fn shutdown_async(&self) {
        {
            let mut lifecycle = self.lifecycle();
            if lifecycle.stopping {
                return;
            }
            lifecycle.started = false;
            lifecycle.stopping = true;
        }
        let _stopping_reset = AccumulatorStoppingReset {
            lifecycle: &self.lifecycle,
        };

        self.guard_thread_for_sync_send.shutdown_async().await;
        self.guard_thread_for_async_send.shutdown_async().await;
        self.release_pending_batches_on_shutdown_async().await;
    }

    fn guard_task_count(&self) -> usize {
        self.guard_thread_for_sync_send.task_count() + self.guard_thread_for_async_send.task_count()
    }

    pub fn guard_metrics_snapshot(&self) -> ProduceAccumulatorGuardMetricsSnapshot {
        ProduceAccumulatorGuardMetricsSnapshot {
            sync: self.guard_thread_for_sync_send.metrics_snapshot(),
            async_send: self.guard_thread_for_async_send.metrics_snapshot(),
        }
    }

    pub(crate) fn try_add_message<T: MessageTrait>(&self, message: &T) -> bool {
        let body_size = message.get_body().map_or(0, |body| body.len()) as u64;
        if body_size == 0 {
            return true;
        }
        self.currently_hold_size
            .try_update(Ordering::AcqRel, Ordering::Acquire, |current| {
                let next = current.checked_add(body_size)?;
                (next <= self.total_batch_max_bytes() as u64).then_some(next)
            })
            .is_ok()
    }

    fn release_hold_size(&self, size: u64) {
        release_hold_size(&self.currently_hold_size, size);
    }

    fn release_pending_batches_on_shutdown(&self) {
        let error_message = "ProduceAccumulator is shutdown";
        let sync_batches = self
            .sync_send_batchs
            .iter()
            .map(|entry| entry.value().clone())
            .collect::<Vec<_>>();
        self.sync_send_batchs.clear();
        for batch in sync_batches {
            match batch.try_lock() {
                Ok(mut batch_guard) => {
                    close_pending_batch(&mut batch_guard, &self.currently_hold_size, error_message, false);
                }
                Err(_) => tracing::warn!("skip locked sync batch during ProduceAccumulator shutdown"),
            }
        }

        let async_batches = self
            .async_send_batchs
            .iter()
            .map(|entry| entry.value().clone())
            .collect::<Vec<_>>();
        self.async_send_batchs.clear();
        for batch in async_batches {
            match batch.try_lock() {
                Ok(mut batch_guard) => {
                    close_pending_batch(&mut batch_guard, &self.currently_hold_size, error_message, true);
                }
                Err(_) => tracing::warn!("skip locked async batch during ProduceAccumulator shutdown"),
            }
        }
    }

    async fn release_pending_batches_on_shutdown_async(&self) {
        let error_message = "ProduceAccumulator is shutdown";
        let sync_batches = self
            .sync_send_batchs
            .iter()
            .map(|entry| entry.value().clone())
            .collect::<Vec<_>>();
        self.sync_send_batchs.clear();
        for batch in sync_batches {
            let mut batch_guard = batch.lock().await;
            close_pending_batch(&mut batch_guard, &self.currently_hold_size, error_message, false);
        }

        let async_batches = self
            .async_send_batchs
            .iter()
            .map(|entry| entry.value().clone())
            .collect::<Vec<_>>();
        self.async_send_batchs.clear();
        for batch in async_batches {
            let mut batch_guard = batch.lock().await;
            close_pending_batch(&mut batch_guard, &self.currently_hold_size, error_message, true);
        }
    }

    pub(crate) async fn send<M: MessageTrait + Send + Sync + 'static>(
        &self,
        message: M,
        mq: Option<MessageQueue>,
        default_mq_producer: DefaultMQProducer,
    ) -> crate::ClientResult<Option<SendResult>> {
        let partition_key = AggregateKey::new_from_message_queue(&message, mq);
        let hold_size = self.batch_max_bytes();
        let hold_ms = self.batch_max_delay_ms();
        let reserved_size = message.get_body().map_or(0, |body| body.len()) as u64;
        let resource_permit = match self
            .message_budget
            .try_acquire_data(estimated_message_retained_bytes(&message))
        {
            Ok(permit) => permit,
            Err(_rejection) => {
                self.release_hold_size(reserved_size);
                return Err(crate::mq_client_err!("producer accumulation capacity is exhausted"));
            }
        };

        let batch = match self
            .get_or_create_sync_send_batch(partition_key.clone(), &default_mq_producer, hold_ms)
            .await
        {
            Ok(batch) => batch,
            Err(error) => {
                self.release_hold_size(reserved_size);
                return Err(error);
            }
        };

        // Lock the batch for exclusive access and add message
        let add_result = {
            let mut batch_guard = batch.lock().await;
            batch_guard.add_with_resource_permit(message, None, hold_size, hold_ms as u64, resource_permit)
        };
        let add_outcome = match add_result {
            Ok(outcome) => outcome,
            Err(error) => {
                self.release_hold_size(reserved_size);
                return Err(error);
            }
        };

        // Check if add failed (batch closed)
        let Some(add_outcome) = add_outcome else {
            // Batch is closed, cannot retry because message is already consumed
            remove_batch_if_same(&self.sync_send_batchs, &partition_key, &batch);
            self.release_hold_size(reserved_size);
            return Err(crate::mq_client_err!("Batch is closed, cannot add message"));
        };

        let msg_index = add_outcome.index;
        let notify = add_outcome.notify;
        if add_outcome.should_flush {
            let batch_to_send = remove_batch_if_same(&self.sync_send_batchs, &partition_key, &batch);
            if let Some(batch_arc) = batch_to_send {
                self.send_batch_sync(batch_arc).await?;
            }
        }

        // Wait for batch to be ready and sent
        loop {
            // Check if batch is closed (sent)
            let (state, should_send) = {
                let batch_guard = batch.lock().await;
                let state = batch_guard.state();
                let should_send = batch_guard.ready_to_send(hold_size, hold_ms as u64);
                (state, should_send)
            };

            if state == BatchState::Closed {
                // Batch has been sent, get result
                let (error, result) = {
                    let batch_guard = batch.lock().await;
                    (
                        batch_guard.send_error.clone(),
                        batch_guard
                            .send_results
                            .as_ref()
                            .and_then(|results| results.get(msg_index).cloned()),
                    )
                };

                if let Some(error) = error {
                    return Err(error);
                }
                return Ok(result);
            }

            if state == BatchState::Open && should_send {
                // Try to remove and send the batch
                let batch_to_send = remove_batch_if_same(&self.sync_send_batchs, &partition_key, &batch);

                if let Some(batch_arc) = batch_to_send {
                    // Send the batch (without holding the lock)
                    self.send_batch_sync(batch_arc).await?;
                    // Continue to wait loop to get result
                    continue;
                }
            }

            // Wait for notification instead of polling
            notify.notified().await;
        }
    }

    pub(crate) async fn send_callback<M>(
        &self,
        message: M,
        mq: Option<MessageQueue>,
        send_callback: Option<ArcSendCallback>,
        default_mq_producer: DefaultMQProducer,
    ) -> crate::ClientResult<()>
    where
        M: MessageTrait + Send + Sync + 'static,
    {
        let partition_key = AggregateKey::new_from_message_queue(&message, mq);
        let hold_size = self.batch_max_bytes();
        let hold_ms = self.batch_max_delay_ms();
        let reserved_size = message.get_body().map_or(0, |body| body.len()) as u64;
        let resource_permit = match self
            .message_budget
            .try_acquire_data(estimated_message_retained_bytes(&message))
        {
            Ok(permit) => permit,
            Err(_rejection) => {
                self.release_hold_size(reserved_size);
                return Err(crate::mq_client_err!("producer accumulation capacity is exhausted"));
            }
        };

        let batch = match self
            .get_or_create_async_send_batch(partition_key.clone(), &default_mq_producer, hold_ms)
            .await
        {
            Ok(batch) => batch,
            Err(error) => {
                self.release_hold_size(reserved_size);
                return Err(error);
            }
        };

        // Lock the batch for exclusive access
        let add_result = {
            let mut batch_guard = batch.lock().await;
            batch_guard.add_with_resource_permit(message, send_callback, hold_size, hold_ms as u64, resource_permit)
        };
        let add_outcome = match add_result {
            Ok(outcome) => outcome,
            Err(error) => {
                self.release_hold_size(reserved_size);
                return Err(error);
            }
        };

        // Try to add message to batch
        match add_outcome {
            Some(add_outcome) => {
                // Message added successfully, check if ready to send
                if add_outcome.should_flush {
                    // Remove batch from map
                    let batch_to_send = remove_batch_if_same(&self.async_send_batchs, &partition_key, &batch);

                    if let Some(batch_arc) = batch_to_send {
                        // Send the batch (without holding the lock)
                        self.send_batch_async(batch_arc).await?;
                    }
                }
                Ok(())
            }
            None => {
                // Batch is closed, remove it and return error
                remove_batch_if_same(&self.async_send_batchs, &partition_key, &batch);
                self.release_hold_size(reserved_size);
                Err(crate::mq_client_err!("Batch is closed, please retry"))
            }
        }
    }

    async fn get_or_create_sync_send_batch(
        &self,
        aggregate_key: AggregateKey,
        default_mq_producer: &DefaultMQProducer,
        hold_ms: u32,
    ) -> crate::ClientResult<Arc<Mutex<MessageAccumulation>>> {
        match self.sync_send_batchs.entry(aggregate_key.clone()) {
            dashmap::mapref::entry::Entry::Occupied(entry) => Ok(entry.get().clone()),
            dashmap::mapref::entry::Entry::Vacant(entry) => {
                let accumulation = MessageAccumulation::new(aggregate_key.clone(), default_mq_producer.clone());
                let create_time = accumulation.create_time;
                let deadline_ms = accumulation.deadline_ms(hold_ms as u64);
                let batch = Arc::new(Mutex::new(accumulation));
                // Keep the DashMap shard exclusively borrowed until the
                // deadline command is accepted. Concurrent senders must never
                // observe a batch that has no scheduler ownership.
                let inserted = entry.insert(batch.clone());
                if let Err(error) =
                    self.guard_thread_for_sync_send
                        .schedule_batch(aggregate_key.clone(), create_time, deadline_ms)
                {
                    {
                        let mut accumulation = batch
                            .try_lock()
                            .expect("new sync accumulation is inaccessible while its map shard is locked");
                        accumulation.send_error = Some(error.clone());
                        accumulation.mark_closed();
                        accumulation.completion_notify.notify_waiters();
                    }
                    drop(inserted);
                    remove_batch_if_same(&self.sync_send_batchs, &aggregate_key, &batch);
                    return Err(error);
                }
                drop(inserted);
                Ok(batch)
            }
        }
    }

    async fn get_or_create_async_send_batch(
        &self,
        aggregate_key: AggregateKey,
        default_mq_producer: &DefaultMQProducer,
        hold_ms: u32,
    ) -> crate::ClientResult<Arc<Mutex<MessageAccumulation>>> {
        match self.async_send_batchs.entry(aggregate_key.clone()) {
            dashmap::mapref::entry::Entry::Occupied(entry) => Ok(entry.get().clone()),
            dashmap::mapref::entry::Entry::Vacant(entry) => {
                let accumulation = MessageAccumulation::new(aggregate_key.clone(), default_mq_producer.clone());
                let create_time = accumulation.create_time;
                let deadline_ms = accumulation.deadline_ms(hold_ms as u64);
                let batch = Arc::new(Mutex::new(accumulation));
                // Keep the DashMap shard exclusively borrowed until the
                // deadline command is accepted. Concurrent senders must never
                // observe a batch that has no scheduler ownership.
                let inserted = entry.insert(batch.clone());
                if let Err(error) =
                    self.guard_thread_for_async_send
                        .schedule_batch(aggregate_key.clone(), create_time, deadline_ms)
                {
                    {
                        let mut accumulation = batch
                            .try_lock()
                            .expect("new async accumulation is inaccessible while its map shard is locked");
                        accumulation.send_error = Some(error.clone());
                        accumulation.mark_closed();
                        accumulation.completion_notify.notify_waiters();
                    }
                    drop(inserted);
                    remove_batch_if_same(&self.async_send_batchs, &aggregate_key, &batch);
                    return Err(error);
                }
                drop(inserted);
                Ok(batch)
            }
        }
    }

    /// Send a batch synchronously (extracted to avoid holding lock across await)
    async fn send_batch_sync(&self, batch: Arc<Mutex<MessageAccumulation>>) -> crate::ClientResult<()> {
        // Extract all data from the batch without holding the lock across await
        let (messages, resource_permits, mq, producer, total_size, count, notify, aggregate_key, keys) = {
            let mut batch_guard = batch.lock().await;
            if !batch_guard.try_mark_closing() {
                return Ok(());
            }
            let notify = batch_guard.completion_notify.clone();

            if batch_guard.messages.is_empty() {
                let error = crate::mq_client_err!("No messages to send");
                batch_guard.send_error = Some(error.clone());
                batch_guard.mark_closed();
                notify.notify_waiters();
                return Err(error);
            }

            let total_size = batch_guard.messages_size.load(Ordering::Acquire) as u64;
            let messages = std::mem::take(&mut batch_guard.messages);
            let resource_permits = std::mem::take(&mut batch_guard.resource_permits);
            let mq = batch_guard.aggregate_key.mq.clone();
            let producer = batch_guard.default_mq_producer.clone();
            let count = batch_guard.count;
            let aggregate_key = batch_guard.aggregate_key.clone();
            let keys = batch_guard.keys.clone();

            (
                messages,
                resource_permits,
                mq,
                producer,
                total_size,
                count,
                notify,
                aggregate_key,
                keys,
            )
        }; // Lock released here
        let _resource_permits = resource_permits;

        let batch_msg = match build_message_batch(messages, &aggregate_key, &keys) {
            Ok(batch_msg) => batch_msg,
            Err(error) => {
                self.release_hold_size(total_size);
                let mut batch_guard = batch.lock().await;
                batch_guard.send_error = Some(error.clone());
                batch_guard.mark_closed();
                notify.notify_waiters();
                return Err(error);
            }
        };

        // Send without holding any locks
        let send_result = match producer.send_direct(batch_msg, mq, None).await {
            Ok(result) => result,
            Err(error) => {
                self.release_hold_size(total_size);
                let mut batch_guard = batch.lock().await;
                batch_guard.send_error = Some(error.clone());
                batch_guard.mark_closed();
                notify.notify_waiters();
                return Err(error);
            }
        };

        // Decrement currently_hold_size
        self.release_hold_size(total_size);

        // Store results in batch for waiting threads to retrieve
        if let Some(result) = send_result {
            let send_results = match split_send_results(&result, count) {
                Ok(results) => results,
                Err(error) => {
                    let mut batch_guard = batch.lock().await;
                    batch_guard.send_error = Some(error.clone());
                    batch_guard.mark_closed();
                    notify.notify_waiters();
                    return Err(error);
                }
            };
            let mut batch_guard = batch.lock().await;
            batch_guard.send_results = Some(send_results);
            batch_guard.mark_closed();
        } else {
            let batch_guard = batch.lock().await;
            batch_guard.mark_closed();
        }

        // Notify all waiting threads
        notify.notify_waiters();

        Ok(())
    }

    /// Send a batch asynchronously (extracted to avoid holding lock across await)
    async fn send_batch_async(&self, batch: Arc<Mutex<MessageAccumulation>>) -> crate::ClientResult<()> {
        // Extract all data from the batch without holding the lock across await
        let (messages, resource_permits, mq, producer, total_size, callbacks, aggregate_key, keys, notify) = {
            let mut batch_guard = batch.lock().await;
            if !batch_guard.try_mark_closing() {
                return Ok(());
            }
            let notify = batch_guard.completion_notify.clone();

            if batch_guard.messages.is_empty() {
                let error = crate::mq_client_err!("No messages to send");
                batch_guard.send_error = Some(error.clone());
                batch_guard.mark_closed();
                notify.notify_waiters();
                return Err(error);
            }

            let total_size = batch_guard.messages_size.load(Ordering::Acquire) as u64;
            let messages = std::mem::take(&mut batch_guard.messages);
            let resource_permits = std::mem::take(&mut batch_guard.resource_permits);
            let callbacks = std::mem::take(&mut batch_guard.send_callbacks);
            let mq = batch_guard.aggregate_key.mq.clone();
            let producer = batch_guard.default_mq_producer.clone();
            let aggregate_key = batch_guard.aggregate_key.clone();
            let keys = batch_guard.keys.clone();

            (
                messages,
                resource_permits,
                mq,
                producer,
                total_size,
                callbacks,
                aggregate_key,
                keys,
                notify,
            )
        }; // Lock released here

        let batch_msg = match build_message_batch(messages, &aggregate_key, &keys) {
            Ok(batch_msg) => batch_msg,
            Err(error) => {
                self.release_hold_size(total_size);
                let mut batch_guard = batch.lock().await;
                batch_guard.send_error = Some(error.clone());
                batch_guard.mark_closed();
                notify.notify_waiters();
                for callback in &callbacks {
                    callback.on_exception(&error);
                }
                return Err(error);
            }
        };

        let currently_hold_size = self.currently_hold_size.clone();
        let callback_currently_hold_size = currently_hold_size.clone();
        let callbacks = Arc::new(callbacks);
        let callbacks_for_send_error = callbacks.clone();
        let permit_owner = Arc::new(StdMutex::new(Some(resource_permits)));
        let callback_permit_owner = Arc::clone(&permit_owner);

        // Create combined callback
        let combined_callback = move |result: Option<&SendResult>, error: Option<&ClientError>| {
            release_resource_permits(&callback_permit_owner);
            release_hold_size(&callback_currently_hold_size, total_size);
            // Invoke all registered callbacks
            if let Some(result) = result {
                match split_send_results(result, callbacks.len()) {
                    Ok(send_results) => {
                        for (callback, result) in callbacks.iter().zip(send_results.iter()) {
                            callback.on_success(result);
                        }
                    }
                    Err(error) => {
                        for callback in callbacks.iter() {
                            callback.on_exception(&error);
                        }
                    }
                }
            } else if let Some(error) = error {
                for callback in callbacks.iter() {
                    callback.on_exception(error);
                }
            }
        };

        // Send without holding any locks
        let send_result = producer
            .send_direct(batch_msg, mq, Some(Arc::new(combined_callback)))
            .await;

        if let Err(error) = &send_result {
            release_resource_permits(&permit_owner);
            release_hold_size(&currently_hold_size, total_size);
            let mut batch_guard = batch.lock().await;
            batch_guard.send_error = Some(error.clone());
            batch_guard.mark_closed();
            notify.notify_waiters();
            for callback in callbacks_for_send_error.iter() {
                callback.on_exception(error);
            }
        } else {
            let batch_guard = batch.lock().await;
            batch_guard.mark_closed();
            notify.notify_waiters();
        }

        send_result.map(|_| ())
    }
}

fn release_hold_size(currently_hold_size: &AtomicU64, size: u64) {
    if size == 0 {
        return;
    }
    let _ = currently_hold_size.try_update(Ordering::AcqRel, Ordering::Acquire, |current| {
        Some(current.saturating_sub(size))
    });
}

fn release_resource_permits(permit_owner: &StdMutex<Option<Vec<ResourcePermit>>>) {
    match permit_owner.lock() {
        Ok(mut permits) => {
            permits.take();
        }
        Err(poisoned) => {
            poisoned.into_inner().take();
        }
    }
}

fn estimated_message_retained_bytes(message: &impl MessageTrait) -> usize {
    let property_bytes = message.get_properties().iter().fold(0usize, |total, (key, value)| {
        total
            .saturating_add(std::mem::size_of::<(CheetahString, CheetahString)>())
            .saturating_add(key.len())
            .saturating_add(value.len())
    });
    std::mem::size_of_val(message)
        .saturating_add(message.topic().len())
        .saturating_add(message.get_body().map_or(0, bytes::Bytes::len))
        .saturating_add(message.get_compressed_body().map_or(0, bytes::Bytes::len))
        .saturating_add(message.transaction_id().map_or(0, CheetahString::len))
        .saturating_add(property_bytes)
}

fn close_pending_batch(
    batch: &mut MessageAccumulation,
    currently_hold_size: &AtomicU64,
    error_message: &str,
    notify_callbacks: bool,
) {
    if !batch.try_mark_closing() {
        return;
    }

    let total_size = batch.messages_size.load(Ordering::Acquire) as u64;
    release_hold_size(currently_hold_size, total_size);
    batch.resource_permits.clear();
    let error = crate::mq_client_err!(error_message.to_string());
    batch.send_error = Some(error.clone());
    batch.mark_closed();
    batch.completion_notify.notify_waiters();

    if notify_callbacks {
        for callback in &batch.send_callbacks {
            callback.on_exception(&error);
        }
    }
}

fn split_send_results(send_result: &SendResult, count: usize) -> crate::ClientResult<Vec<SendResult>> {
    let Some(msg_id) = send_result.msg_id.as_ref() else {
        return Err(crate::mq_client_err!("sendResult is illegal"));
    };

    if !msg_id.as_str().contains(',') {
        return Ok(vec![send_result.clone(); count]);
    }

    let Some(offset_msg_id) = send_result.offset_msg_id.as_ref() else {
        return Err(crate::mq_client_err!("sendResult is illegal"));
    };

    let msg_ids = msg_id.as_str().split(',').collect::<Vec<_>>();
    let offset_msg_ids = offset_msg_id.split(',').collect::<Vec<_>>();
    if msg_ids.len() != count || offset_msg_ids.len() != count {
        return Err(crate::mq_client_err!("sendResult is illegal"));
    }

    Ok((0..count)
        .map(|index| {
            let mut result = send_result.clone();
            result.msg_id = Some(CheetahString::from_slice(msg_ids[index]));
            result.offset_msg_id = Some(offset_msg_ids[index].to_string());
            result.queue_offset += index as u64;
            result
        })
        .collect())
}

fn build_message_batch(
    messages: Vec<Message>,
    aggregate_key: &AggregateKey,
    keys: &HashSet<String>,
) -> crate::ClientResult<MessageBatch> {
    let mut batch = MessageBatch::generate_from_messages(messages)?;
    batch.set_topic(aggregate_key.topic.clone());
    batch.set_wait_store_msg_ok(aggregate_key.wait_store_msg_ok);
    if let Some(tag) = aggregate_key.tag.as_ref() {
        batch.set_tags(tag.clone());
    }
    if !keys.is_empty() {
        let mut sorted_keys = keys.iter().map(String::as_str).collect::<Vec<_>>();
        sorted_keys.sort_unstable();
        batch.set_keys(CheetahString::from_string(
            sorted_keys.join(MessageConst::KEY_SEPARATOR),
        ));
    }
    Ok(batch)
}

#[doc(hidden)]
pub async fn run_produce_accumulator_guard_lifecycle_probe(
    service_context: ChildServiceContext,
) -> ProduceAccumulatorGuardLifecycleProbe {
    let accumulator = ProduceAccumulator::new(service_context, "produce_accumulator_guard_probe");
    let started = accumulator.start().is_ok();

    let mut task_count_before_shutdown = accumulator.guard_task_count();
    for _ in 0..100 {
        if task_count_before_shutdown == 2 {
            break;
        }
        tokio::time::sleep(Duration::from_millis(1)).await;
        task_count_before_shutdown = accumulator.guard_task_count();
    }

    let shutdown_started_at = Instant::now();
    accumulator.shutdown_async().await;
    let shutdown_elapsed_us = shutdown_started_at.elapsed().as_micros();
    let task_count_after_shutdown = accumulator.guard_task_count();
    let guard_metrics = accumulator.guard_metrics_snapshot();
    let healthy = started && task_count_before_shutdown == 2 && task_count_after_shutdown == 0;

    ProduceAccumulatorGuardLifecycleProbe {
        task_count_before_shutdown,
        task_count_after_shutdown,
        shutdown_elapsed_us,
        guard_metrics,
        healthy,
    }
}

#[cfg(test)]
mod tests {
    use crate::test_support::error_assertions::client_exception;
    use std::future::pending;
    use std::sync::atomic::Ordering;

    use super::*;

    struct DropFlag(Arc<AtomicBool>);

    impl Drop for DropFlag {
        fn drop(&mut self) {
            self.0.store(true, Ordering::Release);
        }
    }

    fn test_context() -> ChildServiceContext {
        crate::runtime::test_service_context("produce-accumulator-test")
    }

    #[test]
    fn try_add_message_counts_body_size() {
        let accumulator = ProduceAccumulator::new(test_context(), "test");
        let message = Message::builder()
            .topic("test-topic")
            .body_slice(b"hello")
            .build_unchecked();

        assert!(accumulator.try_add_message(&message));
        assert_eq!(accumulator.currently_hold_size.load(Ordering::Acquire), 5);
    }

    #[test]
    fn try_add_message_allows_missing_body_without_accounting() {
        let accumulator = ProduceAccumulator::new(test_context(), "test");
        let mut message = Message::builder()
            .topic("test-topic")
            .body_slice(b"hello")
            .build_unchecked();
        assert_eq!(message.take_body().as_deref(), Some(&b"hello"[..]));

        assert!(accumulator.try_add_message(&message));
        assert_eq!(accumulator.currently_hold_size.load(Ordering::Acquire), 0);
    }

    #[test]
    fn try_add_message_rejects_when_total_hold_size_reaches_limit_like_java() {
        let accumulator = ProduceAccumulator::new(test_context(), "test");
        accumulator.set_total_batch_max_bytes(5).unwrap();
        let message = Message::builder()
            .topic("test-topic")
            .body_slice(b"hello")
            .build_unchecked();

        assert!(accumulator.try_add_message(&message));
        assert_eq!(accumulator.currently_hold_size.load(Ordering::Acquire), 5);
        assert!(!accumulator.try_add_message(&message));
    }

    #[test]
    fn try_add_message_concurrent_capacity_reservation_does_not_exceed_limit() {
        let accumulator = ProduceAccumulator::new(test_context(), "test");
        accumulator.set_total_batch_max_bytes(64).unwrap();
        let accumulator = Arc::new(accumulator);
        let successes = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let message = Message::builder()
            .topic("test-topic")
            .body_slice(b"x")
            .build_unchecked();

        let threads = (0..16)
            .map(|_| {
                let accumulator = accumulator.clone();
                let successes = successes.clone();
                let message = message.clone();
                std::thread::spawn(move || {
                    for _ in 0..16 {
                        if accumulator.try_add_message(&message) {
                            successes.fetch_add(1, Ordering::AcqRel);
                        }
                    }
                })
            })
            .collect::<Vec<_>>();

        for thread in threads {
            thread.join().expect("capacity reservation thread should finish");
        }

        assert!(successes.load(Ordering::Acquire) <= 64);
        assert!(accumulator.currently_hold_size.load(Ordering::Acquire) <= 64);
    }

    #[test]
    fn accumulated_message_owns_its_parent_budget_permit_until_drop() {
        let tree = rocketmq_runtime::ResourceBudgetTree::new(
            "client-accumulator-permit-test",
            BudgetLimit::new(1, 1024, FullPolicy::Reject),
        )
        .expect("root budget");
        let budget = tree
            .root()
            .child(
                "accumulated-messages",
                BudgetLimit::new(1, 1024, FullPolicy::Reject)
                    .with_rate(RateLimit::new(1, 1))
                    .with_max_age(Duration::from_secs(60)),
            )
            .expect("message budget");
        let permit = budget.try_acquire_data(5).expect("message permit");
        let mut accumulation = MessageAccumulation::new(
            AggregateKey::new(CheetahString::from("test-topic"), None, true, None),
            DefaultMQProducer::unbound(),
        );
        let message = Message::builder()
            .topic("test-topic")
            .body_slice(b"hello")
            .build_unchecked();

        assert!(accumulation
            .add_with_resource_permit(message, None, usize::MAX, 30_000, permit)
            .expect("add message")
            .is_some());
        assert_eq!(budget.snapshot().current_count, 1);
        assert_eq!(budget.snapshot().current_bytes, 5);

        drop(accumulation);
        assert_eq!(budget.snapshot().current_count, 0);
        assert_eq!(budget.snapshot().current_bytes, 0);
    }

    #[test]
    fn message_accumulation_ready_to_send_requires_size_over_hold_size_like_java() {
        let producer = DefaultMQProducer::unbound();
        let aggregate_key = AggregateKey::new(CheetahString::from("test-topic"), None, true, None);
        let mut accumulation = MessageAccumulation::new(aggregate_key, producer);
        let message = Message::builder()
            .topic("test-topic")
            .body_slice(b"hello")
            .build_unchecked();

        assert!(accumulation.add(message, None, 5, 30_000).unwrap().is_some());

        assert!(!accumulation.ready_to_send(5, 30_000));
        assert!(accumulation.ready_to_send(4, 30_000));
    }

    #[test]
    fn message_accumulation_add_returns_index_and_flush_decision() {
        let producer = DefaultMQProducer::unbound();
        let aggregate_key = AggregateKey::new(CheetahString::from("test-topic"), None, true, None);
        let mut accumulation = MessageAccumulation::new(aggregate_key, producer);
        let first = Message::builder()
            .topic("test-topic")
            .body_slice(b"abc")
            .build_unchecked();
        let second = Message::builder()
            .topic("test-topic")
            .body_slice(b"def")
            .build_unchecked();

        let first_outcome = accumulation
            .add(first, None, 5, 30_000)
            .unwrap()
            .expect("first message should be added");
        let second_outcome = accumulation
            .add(second, None, 5, 30_000)
            .unwrap()
            .expect("second message should be added");

        assert_eq!(first_outcome.index, 0);
        assert!(!first_outcome.should_flush);
        assert_eq!(second_outcome.index, 1);
        assert!(second_outcome.should_flush);
    }

    #[test]
    fn message_accumulation_closing_state_is_claimed_once() {
        let producer = DefaultMQProducer::unbound();
        let aggregate_key = AggregateKey::new(CheetahString::from("test-topic"), None, true, None);
        let accumulation = MessageAccumulation::new(aggregate_key, producer);

        assert_eq!(accumulation.state(), BatchState::Open);
        assert!(accumulation.try_mark_closing());
        assert_eq!(accumulation.state(), BatchState::Closing);
        assert!(!accumulation.try_mark_closing());
        accumulation.mark_closed();
        assert_eq!(accumulation.state(), BatchState::Closed);
    }

    #[test]
    fn message_accumulation_preserves_typed_send_error() {
        let producer = DefaultMQProducer::unbound();
        let aggregate_key = AggregateKey::new(CheetahString::from("test-topic"), None, true, None);
        let mut accumulation = MessageAccumulation::new(aggregate_key, producer);
        let error = ClientError::internal(
            "send accumulated messages",
            std::io::Error::new(std::io::ErrorKind::ConnectionReset, "broker disconnected"),
        );

        accumulation.send_error = Some(error.clone());

        let stored = accumulation.send_error.clone().expect("stored send error");
        assert_eq!(stored.descriptor().code(), error.descriptor().code());
        assert_eq!(
            stored.source_ref::<std::io::Error>().expect("typed I/O source").kind(),
            std::io::ErrorKind::ConnectionReset
        );
    }

    #[test]
    fn close_pending_batch_does_not_release_batch_already_claimed_for_send() {
        let producer = DefaultMQProducer::unbound();
        let aggregate_key = AggregateKey::new(CheetahString::from("test-topic"), None, true, None);
        let mut accumulation = MessageAccumulation::new(aggregate_key, producer);
        let message = Message::builder()
            .topic("test-topic")
            .body_slice(b"hello")
            .build_unchecked();
        assert!(accumulation.add(message, None, usize::MAX, 30_000).unwrap().is_some());
        assert!(accumulation.try_mark_closing());

        let currently_hold_size = AtomicU64::new(5);
        close_pending_batch(
            &mut accumulation,
            &currently_hold_size,
            "ProduceAccumulator is shutdown",
            false,
        );

        assert_eq!(accumulation.state(), BatchState::Closing);
        assert_eq!(currently_hold_size.load(Ordering::Acquire), 5);
    }

    #[test]
    fn message_accumulation_batch_sets_java_accumulator_keys_and_tags() {
        let producer = DefaultMQProducer::unbound();
        let aggregate_key = AggregateKey::new(
            CheetahString::from("test-topic"),
            None,
            true,
            Some(CheetahString::from("TagA")),
        );
        let mut accumulation = MessageAccumulation::new(aggregate_key, producer);
        let first = Message::builder()
            .topic("test-topic")
            .tags("TagA")
            .keys(vec!["key-b".to_string(), "key-a".to_string()])
            .body_slice(b"hello")
            .build_unchecked();
        let second = Message::builder()
            .topic("test-topic")
            .tags("TagA")
            .keys(vec!["key-c".to_string(), "key-a".to_string()])
            .body_slice(b"world")
            .build_unchecked();

        assert!(accumulation.add(first, None, usize::MAX, 30_000).unwrap().is_some());
        assert!(accumulation.add(second, None, usize::MAX, 30_000).unwrap().is_some());

        let messages = std::mem::take(&mut accumulation.messages);
        let batch = build_message_batch(messages, &accumulation.aggregate_key, &accumulation.keys).unwrap();

        assert_eq!(batch.topic().as_str(), "test-topic");
        assert!(batch.is_wait_store_msg_ok());
        assert_eq!(batch.tags().as_deref(), Some("TagA"));
        assert_eq!(batch.get_keys().as_deref(), Some("key-a key-b key-c"));
    }

    #[test]
    fn batch_config_setters_match_java_validation() {
        let accumulator = ProduceAccumulator::new(test_context(), "test");

        accumulator.set_batch_max_delay_ms(1).unwrap();
        accumulator.set_batch_max_bytes(1).unwrap();
        accumulator.set_total_batch_max_bytes(1).unwrap();

        assert_eq!(accumulator.batch_max_delay_ms(), 1);
        assert_eq!(accumulator.batch_max_bytes(), 1);
        assert_eq!(accumulator.total_batch_max_bytes(), 1);
        assert!(accumulator.set_batch_max_delay_ms(0).is_err());
        assert!(accumulator.set_batch_max_delay_ms(30_001).is_err());
        assert!(accumulator.set_batch_max_bytes(0).is_err());
        assert!(accumulator.set_batch_max_bytes(2 * 1024 * 1024 + 1).is_err());
        assert!(accumulator.set_total_batch_max_bytes(0).is_err());
    }

    #[test]
    fn batch_config_updates_are_visible_through_shared_ownership() {
        let accumulator = Arc::new(ProduceAccumulator::new(test_context(), "shared-config-test"));
        let shared = accumulator.clone();

        std::thread::spawn(move || {
            shared.set_batch_max_delay_ms(25).unwrap();
            shared.set_batch_max_bytes(4096).unwrap();
            shared.set_total_batch_max_bytes(65_536).unwrap();
        })
        .join()
        .expect("shared accumulator configuration thread should finish");

        assert_eq!(accumulator.batch_max_delay_ms(), 25);
        assert_eq!(accumulator.batch_max_bytes(), 4096);
        assert_eq!(accumulator.total_batch_max_bytes(), 65_536);
    }

    #[test]
    fn start_without_tokio_runtime_does_not_spawn_panic() {
        let accumulator = ProduceAccumulator::new(test_context(), "accumulator-explicit-runtime-test");

        accumulator.start().expect("start accumulator");
        accumulator.start().expect("idempotent accumulator start");
        assert_eq!(accumulator.guard_thread_for_sync_send.task_count(), 1);
        assert_eq!(accumulator.guard_thread_for_async_send.task_count(), 1);

        accumulator.shutdown();
        accumulator.shutdown();
        assert_eq!(accumulator.guard_thread_for_sync_send.task_count(), 0);
        assert_eq!(accumulator.guard_thread_for_async_send.task_count(), 0);
        std::thread::sleep(Duration::from_millis(20));
    }

    #[test]
    fn start_does_not_restart_guards_during_shutdown_transition() {
        let accumulator = ProduceAccumulator::new(test_context(), "accumulator-stopping-test");
        accumulator.lifecycle().stopping = true;

        accumulator.start().expect("start accumulator");

        assert_eq!(accumulator.guard_task_count(), 0);
        accumulator.lifecycle().stopping = false;
    }

    #[tokio::test]
    async fn shutdown_async_stops_guard_tasks() {
        let accumulator = ProduceAccumulator::new(test_context(), "accumulator-async-shutdown-test");

        accumulator.start().expect("start accumulator");
        assert_eq!(accumulator.guard_thread_for_sync_send.task_count(), 1);
        assert_eq!(accumulator.guard_thread_for_async_send.task_count(), 1);

        accumulator.shutdown_async().await;
        accumulator.shutdown_async().await;

        assert_eq!(accumulator.guard_thread_for_sync_send.task_count(), 0);
        assert_eq!(accumulator.guard_thread_for_async_send.task_count(), 0);
    }

    #[tokio::test]
    async fn shutdown_async_releases_pending_async_batch_hold_size_and_callbacks() {
        let accumulator = ProduceAccumulator::new(test_context(), "accumulator-shutdown-release-test");
        let aggregate_key = AggregateKey::new(CheetahString::from("test-topic"), None, true, None);
        let mut accumulation = MessageAccumulation::new(aggregate_key.clone(), DefaultMQProducer::unbound());
        let callback_invoked = Arc::new(AtomicBool::new(false));
        let callback_invoked_for_callback = callback_invoked.clone();
        let callback: ArcSendCallback = Arc::new(move |_result: Option<&SendResult>, error: Option<&ClientError>| {
            assert!(error.is_some());
            callback_invoked_for_callback.store(true, Ordering::Release);
        });
        let message = Message::builder()
            .topic("test-topic")
            .body_slice(b"hello")
            .build_unchecked();
        assert!(accumulation
            .add(message, Some(callback), usize::MAX, 30_000)
            .unwrap()
            .is_some());
        accumulator.currently_hold_size.store(5, Ordering::Release);
        accumulator
            .async_send_batchs
            .insert(aggregate_key, Arc::new(Mutex::new(accumulation)));

        accumulator.release_pending_batches_on_shutdown_async().await;

        assert_eq!(accumulator.currently_hold_size.load(Ordering::Acquire), 0);
        assert!(callback_invoked.load(Ordering::Acquire));
        assert!(accumulator.async_send_batchs.is_empty());
    }

    #[tokio::test]
    async fn sync_guard_notifies_batch_at_deadline() {
        let accumulator = ProduceAccumulator::new(test_context(), "accumulator-sync-deadline-test");
        accumulator.set_batch_max_delay_ms(100).unwrap();
        accumulator.start().expect("start accumulator");

        let aggregate_key = AggregateKey::new(CheetahString::from("test-topic"), None, true, None);
        let batch = accumulator
            .get_or_create_sync_send_batch(aggregate_key, &DefaultMQProducer::unbound(), 100)
            .await
            .expect("schedule sync batch");
        let notify = {
            let mut batch_guard = batch.lock().await;
            let message = Message::builder()
                .topic("test-topic")
                .body_slice(b"hello")
                .build_unchecked();
            assert!(batch_guard.add(message, None, usize::MAX, 100).unwrap().is_some());
            batch_guard.completion_notify.clone()
        };

        tokio::time::timeout(Duration::from_secs(1), notify.notified())
            .await
            .expect("sync guard should notify when the batch deadline expires");

        let metrics = accumulator.guard_metrics_snapshot();
        assert!(metrics.sync.wakeup_count >= 1);
        assert_eq!(metrics.sync.flush_count, 1);

        accumulator.shutdown_async().await;
    }

    #[tokio::test]
    async fn guard_deadline_queue_lazily_ignores_removed_batch() {
        let accumulator = ProduceAccumulator::new(test_context(), "accumulator-stale-deadline-test");
        accumulator.set_batch_max_delay_ms(30).unwrap();
        accumulator.start().expect("start accumulator");

        let aggregate_key = AggregateKey::new(CheetahString::from("test-topic"), None, true, None);
        let batch = accumulator
            .get_or_create_sync_send_batch(aggregate_key.clone(), &DefaultMQProducer::unbound(), 30)
            .await
            .expect("schedule sync batch");
        {
            let mut batch_guard = batch.lock().await;
            let message = Message::builder()
                .topic("test-topic")
                .body_slice(b"hello")
                .build_unchecked();
            assert!(batch_guard.add(message, None, usize::MAX, 30).unwrap().is_some());
        }
        accumulator.sync_send_batchs.remove(&aggregate_key);

        tokio::time::sleep(Duration::from_millis(150)).await;

        let metrics = accumulator.guard_metrics_snapshot();
        assert!(metrics.sync.wakeup_count >= 1);
        assert_eq!(metrics.sync.flush_count, 0);
        assert!(metrics.sync.idle_wakeup_count >= 1);

        accumulator.shutdown_async().await;
    }

    #[tokio::test]
    async fn batch_creation_rolls_back_when_deadline_schedulers_are_not_running() {
        let accumulator = ProduceAccumulator::new(test_context(), "accumulator-schedule-rollback-test");
        let producer = DefaultMQProducer::unbound();
        let sync_key = AggregateKey::new(CheetahString::from("sync-topic"), None, true, None);
        let async_key = AggregateKey::new(CheetahString::from("async-topic"), None, false, None);

        assert!(accumulator
            .get_or_create_sync_send_batch(sync_key.clone(), &producer, 10)
            .await
            .is_err());
        assert!(!accumulator.sync_send_batchs.contains_key(&sync_key));

        assert!(accumulator
            .get_or_create_async_send_batch(async_key.clone(), &producer, 10)
            .await
            .is_err());
        assert!(!accumulator.async_send_batchs.contains_key(&async_key));
    }

    #[test]
    fn conditional_batch_removal_never_deletes_a_replacement() {
        let batches = DashMap::new();
        let key = AggregateKey::new(CheetahString::from("test-topic"), None, true, None);
        let original = Arc::new(Mutex::new(MessageAccumulation::new(
            key.clone(),
            DefaultMQProducer::unbound(),
        )));
        let replacement = Arc::new(Mutex::new(MessageAccumulation::new(
            key.clone(),
            DefaultMQProducer::unbound(),
        )));
        batches.insert(key.clone(), replacement.clone());

        assert!(remove_batch_if_same(&batches, &key, &original).is_none());
        let current = batches.get(&key).expect("replacement remains registered");
        assert!(Arc::ptr_eq(current.value(), &replacement));
    }

    #[tokio::test]
    async fn produce_accumulator_guard_lifecycle_probe_reports_clean_shutdown() {
        let probe = run_produce_accumulator_guard_lifecycle_probe(test_context()).await;

        assert!(probe.healthy, "{probe:?}");
        assert_eq!(probe.task_count_before_shutdown, 2, "{probe:?}");
        assert_eq!(probe.task_count_after_shutdown, 0, "{probe:?}");
    }

    #[tokio::test]
    async fn guard_task_shutdown_waits_for_worker_completion() {
        let (shutdown_tx, mut shutdown_rx) = watch::channel(false);
        let completed = Arc::new(AtomicBool::new(false));
        let completed_in_task = completed.clone();
        let task = spawn_guard_task(
            &test_context(),
            "rocketmq-client-batch-guard-test",
            shutdown_tx,
            async move {
                let _ = shutdown_rx.changed().await;
                completed_in_task.store(true, Ordering::Release);
            },
        )
        .expect("test task should spawn");

        assert!(task.shutdown_async(Duration::from_secs(1)).await);
        assert!(completed.load(Ordering::Acquire));
    }

    #[tokio::test]
    async fn guard_task_shutdown_aborts_after_timeout() {
        let (shutdown_tx, _shutdown_rx) = watch::channel(false);
        let dropped = Arc::new(AtomicBool::new(false));
        let dropped_in_task = dropped.clone();
        let task = spawn_guard_task(
            &test_context(),
            "rocketmq-client-batch-guard-test",
            shutdown_tx,
            async move {
                let _drop_flag = DropFlag(dropped_in_task);
                pending::<()>().await;
            },
        )
        .expect("test task should spawn");

        assert!(!task.shutdown_async(Duration::from_millis(20)).await);
        assert!(dropped.load(Ordering::Acquire));
    }

    #[test]
    fn split_send_results_matches_java_batch_success_shape() {
        let send_result = SendResult::new(
            crate::producer::send_status::SendStatus::SendOk,
            Some(CheetahString::from("msg-a,msg-b")),
            Some("offset-a,offset-b".to_string()),
            None,
            17,
        );

        let split = split_send_results(&send_result, 2).expect("valid per-message batch result");

        assert_eq!(split.len(), 2);
        assert_eq!(split[0].msg_id.as_ref().unwrap().as_str(), "msg-a");
        assert_eq!(split[0].offset_msg_id.as_deref(), Some("offset-a"));
        assert_eq!(split[0].queue_offset, 17);
        assert_eq!(split[1].msg_id.as_ref().unwrap().as_str(), "msg-b");
        assert_eq!(split[1].offset_msg_id.as_deref(), Some("offset-b"));
        assert_eq!(split[1].queue_offset, 18);
    }

    #[test]
    fn split_send_results_keeps_original_when_ids_are_not_per_message_like_java() {
        let send_result = SendResult::new(
            crate::producer::send_status::SendStatus::SendOk,
            Some(CheetahString::from("single-msg-id")),
            Some("offset-a,offset-b".to_string()),
            None,
            17,
        );

        let split = split_send_results(&send_result, 2).expect("single msg id keeps Java batch-queue result");

        assert_eq!(split.len(), 2);
        assert_eq!(split[0].msg_id.as_ref().unwrap().as_str(), "single-msg-id");
        assert_eq!(split[0].offset_msg_id.as_deref(), Some("offset-a,offset-b"));
        assert_eq!(split[0].queue_offset, 17);
        assert_eq!(split[1].msg_id.as_ref().unwrap().as_str(), "single-msg-id");
        assert_eq!(split[1].offset_msg_id.as_deref(), Some("offset-a,offset-b"));
        assert_eq!(split[1].queue_offset, 17);
    }

    #[test]
    fn split_send_results_rejects_mismatched_comma_msg_ids_like_java() {
        let send_result = SendResult::new(
            crate::producer::send_status::SendStatus::SendOk,
            Some(CheetahString::from("msg-a,msg-b")),
            Some("offset-a".to_string()),
            None,
            17,
        );

        let error = split_send_results(&send_result, 2).expect_err("mismatched per-message ids are illegal");

        assert!(client_exception(&error).to_string().contains("sendResult is illegal"));
    }

    #[test]
    fn split_send_results_rejects_missing_offset_msg_id_for_comma_msg_ids_like_java() {
        let send_result = SendResult::new(
            crate::producer::send_status::SendStatus::SendOk,
            Some(CheetahString::from("msg-a,msg-b")),
            None,
            None,
            17,
        );

        let error = split_send_results(&send_result, 2).expect_err("per-message msg id requires offset msg id");

        assert!(client_exception(&error).to_string().contains("sendResult is illegal"));
    }

    #[test]
    fn split_send_results_rejects_missing_msg_id_with_typed_error() {
        let send_result = SendResult::new(
            crate::producer::send_status::SendStatus::SendOk,
            None,
            Some("offset-a,offset-b".to_string()),
            None,
            17,
        );

        let error = split_send_results(&send_result, 2).expect_err("missing msg id is illegal");

        assert!(client_exception(&error).to_string().contains("sendResult is illegal"));
    }
}

#[derive(Clone, Debug, Default)]
pub struct AggregateKey {
    pub topic: CheetahString,
    pub mq: Option<MessageQueue>,
    pub wait_store_msg_ok: bool,
    pub tag: Option<CheetahString>,
}

impl AggregateKey {
    pub fn new_from_message<M: MessageTrait>(message: &M) -> Self {
        Self {
            topic: message.topic().clone(),
            mq: None,
            wait_store_msg_ok: message.is_wait_store_msg_ok(),
            tag: message.tags(),
        }
    }

    pub fn new_from_message_queue<M: MessageTrait>(message: &M, mq: Option<MessageQueue>) -> Self {
        Self {
            topic: message.topic().clone(),
            mq,
            wait_store_msg_ok: message.is_wait_store_msg_ok(),
            tag: message.tags(),
        }
    }

    pub fn new(
        topic: CheetahString,
        mq: Option<MessageQueue>,
        wait_store_msg_ok: bool,
        tag: Option<CheetahString>,
    ) -> Self {
        Self {
            topic,
            mq,
            wait_store_msg_ok,
            tag,
        }
    }
}

impl PartialEq for AggregateKey {
    fn eq(&self, other: &Self) -> bool {
        self.wait_store_msg_ok == other.wait_store_msg_ok
            && self.topic == other.topic
            && self.mq == other.mq
            && self.tag == other.tag
    }
}

impl Eq for AggregateKey {}

impl Hash for AggregateKey {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.topic.hash(state);
        self.mq.hash(state);
        self.wait_store_msg_ok.hash(state);
        self.tag.hash(state);
    }
}

struct MessageAccumulation {
    default_mq_producer: DefaultMQProducer,
    messages: Vec<Message>,
    resource_permits: Vec<ResourcePermit>,
    send_callbacks: Vec<ArcSendCallback>,
    keys: HashSet<String>,
    state: AtomicU8,
    send_results: Option<Vec<SendResult>>, // Stores results for sync send
    send_error: Option<ClientError>,
    aggregate_key: AggregateKey,
    messages_size: Arc<AtomicI32>,
    count: usize,
    create_time: u64,
    completion_notify: Arc<tokio::sync::Notify>,
}

#[derive(Clone)]
struct AddOutcome {
    index: usize,
    should_flush: bool,
    notify: Arc<tokio::sync::Notify>,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum BatchState {
    Open = 0,
    Closing = 1,
    Closed = 2,
}

impl BatchState {
    fn from_u8(value: u8) -> Self {
        match value {
            0 => Self::Open,
            1 => Self::Closing,
            _ => Self::Closed,
        }
    }
}

#[derive(Clone)]
struct GuardScheduleCommand {
    aggregate_key: AggregateKey,
    create_time: u64,
    deadline_ms: u64,
}

impl GuardScheduleCommand {
    fn retained_bytes(&self) -> usize {
        let queue_bytes = self
            .aggregate_key
            .mq
            .as_ref()
            .map_or(0, |queue| queue.topic().len().saturating_add(queue.broker_name().len()));
        std::mem::size_of::<Self>()
            .saturating_add(self.aggregate_key.topic.len())
            .saturating_add(self.aggregate_key.tag.as_ref().map_or(0, CheetahString::len))
            .saturating_add(queue_bytes)
    }
}

struct GuardDeadline {
    aggregate_key: AggregateKey,
    create_time: u64,
    deadline_ms: u64,
    sequence: u64,
    _permit: ResourcePermit,
}

impl PartialEq for GuardDeadline {
    fn eq(&self, other: &Self) -> bool {
        self.deadline_ms == other.deadline_ms
            && self.sequence == other.sequence
            && self.create_time == other.create_time
            && self.aggregate_key == other.aggregate_key
    }
}

impl Eq for GuardDeadline {}

impl Ord for GuardDeadline {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        other
            .deadline_ms
            .cmp(&self.deadline_ms)
            .then_with(|| other.sequence.cmp(&self.sequence))
    }
}

impl PartialOrd for GuardDeadline {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl MessageAccumulation {
    pub fn new(aggregate_key: AggregateKey, default_mq_producer: DefaultMQProducer) -> Self {
        Self {
            default_mq_producer,
            messages: vec![],
            resource_permits: vec![],
            send_callbacks: vec![],
            keys: HashSet::new(),
            state: AtomicU8::new(BatchState::Open as u8),
            send_results: None,
            send_error: None,
            aggregate_key,
            messages_size: Arc::new(AtomicI32::new(0)),
            count: 0,
            create_time: current_millis(),
            completion_notify: Arc::new(tokio::sync::Notify::new()),
        }
    }

    fn deadline_ms(&self, hold_ms: u64) -> u64 {
        self.create_time.saturating_add(hold_ms)
    }

    fn state(&self) -> BatchState {
        BatchState::from_u8(self.state.load(Ordering::Acquire))
    }

    fn try_mark_closing(&self) -> bool {
        self.state
            .compare_exchange(
                BatchState::Open as u8,
                BatchState::Closing as u8,
                Ordering::AcqRel,
                Ordering::Acquire,
            )
            .is_ok()
    }

    fn mark_closed(&self) {
        self.state.store(BatchState::Closed as u8, Ordering::Release);
    }

    /// Check if batch is ready to send based on size or time thresholds
    fn ready_to_send(&self, hold_size: usize, hold_ms: u64) -> bool {
        // Condition 1: Size threshold
        let current_size = self.messages_size.load(Ordering::Acquire);
        if current_size > hold_size as i32 {
            return true;
        }

        // Condition 2: Time threshold
        let elapsed = current_millis() - self.create_time;
        if elapsed >= hold_ms {
            return true;
        }

        false
    }

    pub fn add<M: MessageTrait + Send + Sync + 'static>(
        &mut self,
        msg: M,
        send_callback: Option<ArcSendCallback>,
        hold_size: usize,
        hold_ms: u64,
    ) -> crate::ClientResult<Option<AddOutcome>> {
        self.add_inner(msg, send_callback, hold_size, hold_ms, None)
    }

    fn add_with_resource_permit<M: MessageTrait + Send + Sync + 'static>(
        &mut self,
        msg: M,
        send_callback: Option<ArcSendCallback>,
        hold_size: usize,
        hold_ms: u64,
        resource_permit: ResourcePermit,
    ) -> crate::ClientResult<Option<AddOutcome>> {
        self.add_inner(msg, send_callback, hold_size, hold_ms, Some(resource_permit))
    }

    fn add_inner<M: MessageTrait + Send + Sync + 'static>(
        &mut self,
        msg: M,
        send_callback: Option<ArcSendCallback>,
        hold_size: usize,
        hold_ms: u64,
        resource_permit: Option<ResourcePermit>,
    ) -> crate::ClientResult<Option<AddOutcome>> {
        // Check if batch is already closed
        if self.state() != BatchState::Open {
            return Ok(None);
        }

        // Calculate message body size
        let body_size = msg.get_body().map(|b| b.len()).unwrap_or(0) as i32;
        if let Some(keys) = msg.get_keys_ref() {
            self.keys.extend(
                keys.as_str()
                    .split(MessageConst::KEY_SEPARATOR)
                    .filter(|key| !key.is_empty())
                    .map(ToOwned::to_owned),
            );
        }

        // Add message to batch
        self.messages.push(msg.into_message());
        if let Some(resource_permit) = resource_permit {
            self.resource_permits.push(resource_permit);
        }

        // Add callback if provided
        if let Some(callback) = send_callback {
            self.send_callbacks.push(callback);
        }

        // Update message size counter
        if body_size > 0 {
            self.messages_size.fetch_add(body_size, Ordering::AcqRel);
        }

        // Increment count
        let index = self.count;
        self.count += 1;

        Ok(Some(AddOutcome {
            index,
            should_flush: self.ready_to_send(hold_size, hold_ms),
            notify: self.completion_notify.clone(),
        }))
    }
}

struct GuardForSyncSendService {
    service_context: ChildServiceContext,
    service_name: String,
    resource_budget: ResourceBudget,
    stopped: Arc<AtomicBool>,
    state: StdMutex<GuardServiceState>,
    metrics: Arc<BatchGuardMetrics>,
}

#[derive(Default)]
struct GuardServiceState {
    task_handle: Option<GuardTaskHandle>,
    schedule_queue: Option<BudgetedQueue<GuardScheduleCommand>>,
    stopping: bool,
}

struct GuardStoppingReset<'a> {
    state: &'a StdMutex<GuardServiceState>,
    service_name: &'a str,
}

impl Drop for GuardStoppingReset<'_> {
    fn drop(&mut self) {
        let mut state = match self.state.lock() {
            Ok(state) => state,
            Err(poisoned) => {
                tracing::warn!("{} batch guard lifecycle lock was poisoned", self.service_name);
                poisoned.into_inner()
            }
        };
        state.stopping = false;
    }
}

enum GuardTaskHandle {
    Tracked {
        shutdown_tx: watch::Sender<bool>,
        handle: ClientTrackedTaskHandle,
    },
}

impl GuardTaskHandle {
    fn is_finished(&self) -> bool {
        match self {
            Self::Tracked { handle, .. } => handle.task_count() == 0,
        }
    }

    async fn shutdown_async(self, timeout: Duration) -> bool {
        match self {
            Self::Tracked { shutdown_tx, handle } => {
                let _ = shutdown_tx.send(true);
                let report = handle.shutdown(timeout).await;
                if !report.is_healthy() {
                    tracing::warn!(report = %report.to_json(), "batch guard task shutdown report is unhealthy");
                }
                report.is_healthy()
            }
        }
    }

    fn shutdown_blocking(self, timeout: Duration) -> bool {
        match self {
            Self::Tracked { shutdown_tx, handle } => {
                let _ = shutdown_tx.send(true);
                let (report, completed) = handle.shutdown_blocking(timeout);
                if !completed || !report.is_healthy() {
                    tracing::warn!(
                        completed_before_timeout = completed,
                        report = %report.to_json(),
                        "batch guard task blocking shutdown report is unhealthy"
                    );
                }
                completed && report.is_healthy()
            }
        }
    }

    fn task_count(&self) -> usize {
        match self {
            Self::Tracked { handle, .. } => handle.task_count(),
        }
    }
}

fn spawn_guard_task<F>(
    service_context: &ChildServiceContext,
    thread_name: &'static str,
    shutdown_tx: watch::Sender<bool>,
    task: F,
) -> Option<GuardTaskHandle>
where
    F: Future<Output = ()> + Send + 'static,
{
    match spawn_client_tracked_task_with_context(service_context, thread_name, Box::pin(task)) {
        Ok(handle) => Some(GuardTaskHandle::Tracked { shutdown_tx, handle }),
        Err(error) => {
            tracing::error!("Failed to spawn {} background task: {}", thread_name, error);
            None
        }
    }
}

enum GuardWakeEvent {
    Deadline,
    Schedule(Box<BudgetedItem<GuardScheduleCommand>>),
    Shutdown,
}

fn push_guard_deadline(
    deadlines: &mut BinaryHeap<GuardDeadline>,
    command: BudgetedItem<GuardScheduleCommand>,
    sequence: &mut u64,
) {
    let (command, permit, _) = command.into_parts();
    deadlines.push(GuardDeadline {
        aggregate_key: command.aggregate_key,
        create_time: command.create_time,
        deadline_ms: command.deadline_ms,
        sequence: *sequence,
        _permit: permit,
    });
    *sequence = sequence.wrapping_add(1);
}

async fn wait_guard_deadline_or_schedule(
    shutdown_rx: &mut watch::Receiver<bool>,
    schedule_queue: &BudgetedQueue<GuardScheduleCommand>,
    next_deadline_ms: Option<u64>,
) -> GuardWakeEvent {
    if *shutdown_rx.borrow() {
        return GuardWakeEvent::Shutdown;
    }

    if let Some(deadline_ms) = next_deadline_ms {
        let delay = Duration::from_millis(deadline_ms.saturating_sub(current_millis()));
        if delay.is_zero() {
            return GuardWakeEvent::Deadline;
        }

        tokio::select! {
            _ = tokio::time::sleep(delay) => GuardWakeEvent::Deadline,
            command = schedule_queue.recv_budgeted() => {
                command.map_or(GuardWakeEvent::Shutdown, |command| GuardWakeEvent::Schedule(Box::new(command)))
            }
            _ = shutdown_rx.changed() => GuardWakeEvent::Shutdown,
        }
    } else {
        tokio::select! {
            command = schedule_queue.recv_budgeted() => {
                command.map_or(GuardWakeEvent::Shutdown, |command| GuardWakeEvent::Schedule(Box::new(command)))
            }
            _ = shutdown_rx.changed() => GuardWakeEvent::Shutdown,
        }
    }
}

fn build_guard_schedule_queue(
    parent_budget: &ResourceBudget,
    queue_name: &'static str,
) -> crate::ClientResult<BudgetedQueue<GuardScheduleCommand>> {
    const SCHEDULE_CAPACITY: usize = 65_536;
    let queue_bytes = (parent_budget.limit().capacity.bytes / 64).max(1);
    let budget = parent_budget
        .child(
            queue_name,
            BudgetLimit::new(SCHEDULE_CAPACITY, queue_bytes, FullPolicy::Reject)
                .with_rate(RateLimit::new(SCHEDULE_CAPACITY as u64, SCHEDULE_CAPACITY as u64))
                .with_max_age(Duration::from_secs(300)),
        )
        .map_err(|error| ClientError::config_invalid_source("client.producer.accumulatorScheduleQueue", true, error))?;
    Ok(BudgetedQueue::new(budget))
}

fn guard_metrics_snapshot(
    metrics: &BatchGuardMetrics,
    schedule_queue: Option<&BudgetedQueue<GuardScheduleCommand>>,
) -> BatchGuardMetricsSnapshot {
    let mut snapshot = metrics.snapshot();
    if let Some(queue) = schedule_queue {
        let queue = queue.snapshot();
        snapshot.scheduled_count = queue.reserved_count;
        snapshot.retained_bytes = queue.retained_bytes;
        snapshot.oldest_queued_age_ms = queue
            .oldest_age
            .and_then(|age| u64::try_from(age.as_millis()).ok())
            .unwrap_or(0);
        snapshot.throttled_count = queue.throttled_count;
        snapshot.rejected_count = queue.rejected_count;
        snapshot.dropped_count = queue.dropped_count;
    }
    snapshot
}

fn remove_batch_if_same(
    batches: &DashMap<AggregateKey, Arc<Mutex<MessageAccumulation>>>,
    key: &AggregateKey,
    expected: &Arc<Mutex<MessageAccumulation>>,
) -> Option<Arc<Mutex<MessageAccumulation>>> {
    batches
        .remove_if(key, |_, current| Arc::ptr_eq(current, expected))
        .map(|(_, batch)| batch)
}

async fn drain_due_sync_batches(
    deadlines: &mut BinaryHeap<GuardDeadline>,
    batches: &DashMap<AggregateKey, Arc<Mutex<MessageAccumulation>>>,
    hold_ms: u64,
    metrics: &BatchGuardMetrics,
) {
    let now = current_millis();
    while deadlines.peek().is_some_and(|deadline| deadline.deadline_ms <= now) {
        let deadline = deadlines.pop().expect("deadline should exist after peek");
        let Some(batch) = batches.get(&deadline.aggregate_key).map(|entry| entry.value().clone()) else {
            metrics.record_idle();
            continue;
        };

        let mut remove_empty = false;
        let mut notify = None;
        {
            let batch_guard = batch.lock().await;
            if batch_guard.create_time != deadline.create_time || batch_guard.state() != BatchState::Open {
                metrics.record_idle();
                continue;
            }

            if batch_guard.messages_size.load(Ordering::Acquire) == 0 {
                batch_guard.mark_closed();
                remove_empty = true;
            } else if batch_guard.deadline_ms(hold_ms) <= now {
                notify = Some(batch_guard.completion_notify.clone());
            } else {
                metrics.record_idle();
            }
        }

        if remove_empty {
            remove_batch_if_same(batches, &deadline.aggregate_key, &batch);
            metrics.record_idle();
        } else if let Some(notify) = notify {
            metrics.record_flush();
            notify.notify_waiters();
        }
    }
}

async fn drain_due_async_batches(
    deadlines: &mut BinaryHeap<GuardDeadline>,
    batches: &DashMap<AggregateKey, Arc<Mutex<MessageAccumulation>>>,
    currently_hold_size: &Arc<AtomicU64>,
    hold_size: usize,
    hold_ms: u64,
    metrics: &BatchGuardMetrics,
) {
    let now = current_millis();
    while deadlines.peek().is_some_and(|deadline| deadline.deadline_ms <= now) {
        let deadline = deadlines.pop().expect("deadline should exist after peek");
        let Some(batch) = batches.get(&deadline.aggregate_key).map(|entry| entry.value().clone()) else {
            metrics.record_idle();
            continue;
        };

        let mut remove_empty = false;
        let mut should_send = false;
        {
            let batch_guard = batch.lock().await;
            if batch_guard.create_time != deadline.create_time || batch_guard.state() != BatchState::Open {
                metrics.record_idle();
                continue;
            }

            if batch_guard.messages_size.load(Ordering::Acquire) == 0 {
                batch_guard.mark_closed();
                remove_empty = true;
            } else if batch_guard.ready_to_send(hold_size, hold_ms) {
                should_send = true;
            } else {
                metrics.record_idle();
            }
        }

        if remove_empty {
            remove_batch_if_same(batches, &deadline.aggregate_key, &batch);
            metrics.record_idle();
            continue;
        }

        if should_send {
            if let Some(batch) = remove_batch_if_same(batches, &deadline.aggregate_key, &batch) {
                metrics.record_flush();
                if let Err(error) =
                    GuardForAsyncSendService::send_batch_async_internal(batch, currently_hold_size.clone()).await
                {
                    tracing::error!("Failed to send batch via guard thread: {:?}", error);
                }
            } else {
                metrics.record_idle();
            }
        }
    }
}

impl GuardForSyncSendService {
    pub fn new(service_context: ChildServiceContext, service_name: &str, resource_budget: ResourceBudget) -> Self {
        Self {
            service_context,
            service_name: service_name.to_string(),
            resource_budget,
            stopped: Arc::new(AtomicBool::new(false)),
            state: StdMutex::new(GuardServiceState::default()),
            metrics: Arc::new(BatchGuardMetrics::default()),
        }
    }

    fn state(&self) -> StdMutexGuard<'_, GuardServiceState> {
        match self.state.lock() {
            Ok(state) => state,
            Err(poisoned) => {
                tracing::warn!("{} sync batch guard lifecycle lock was poisoned", self.service_name);
                poisoned.into_inner()
            }
        }
    }

    pub fn start(&self, batches: BatchMap, hold_ms: u32) -> crate::ClientResult<()> {
        let mut state = self.state();
        if state.stopping {
            return Err(crate::mq_client_err!("sync batch guard is stopping"));
        }
        if state.task_handle.as_ref().is_some_and(|handle| !handle.is_finished()) {
            tracing::warn!("{} sync batch guard already started", self.service_name);
            return Ok(());
        }

        let service_name = self.service_name.clone();
        let stopped = self.stopped.clone();
        let metrics = self.metrics.clone();
        let schedule_queue = build_guard_schedule_queue(&self.resource_budget, "sync-batch-deadlines")?;
        let task_schedule_queue = schedule_queue.clone();
        let (shutdown_tx, mut shutdown_rx) = watch::channel(false);
        self.stopped.store(false, Ordering::Release);

        let task_handle = spawn_guard_task(
            &self.service_context,
            "rocketmq-client-sync-batch-guard",
            shutdown_tx,
            async move {
                tracing::info!("{} service started", service_name);

                let mut deadlines = BinaryHeap::new();
                let mut sequence = 0u64;

                loop {
                    if stopped.load(Ordering::Acquire) {
                        break;
                    }

                    let next_deadline_ms = deadlines.peek().map(|deadline: &GuardDeadline| deadline.deadline_ms);
                    match wait_guard_deadline_or_schedule(&mut shutdown_rx, &task_schedule_queue, next_deadline_ms)
                        .await
                    {
                        GuardWakeEvent::Schedule(command) => {
                            push_guard_deadline(&mut deadlines, *command, &mut sequence);
                        }
                        GuardWakeEvent::Deadline => {
                            metrics.record_wakeup();
                            drain_due_sync_batches(&mut deadlines, &batches, hold_ms as u64, &metrics).await;
                        }
                        GuardWakeEvent::Shutdown => break,
                    }
                }

                tracing::info!("{} service ended", service_name);
            },
        );
        let task_handle = task_handle.ok_or_else(|| crate::mq_client_err!("failed to spawn sync batch guard"))?;
        state.schedule_queue = Some(schedule_queue);
        state.task_handle = Some(task_handle);
        Ok(())
    }

    fn schedule_batch(
        &self,
        aggregate_key: AggregateKey,
        create_time: u64,
        deadline_ms: u64,
    ) -> crate::ClientResult<()> {
        let schedule_queue = self.state().schedule_queue.clone();
        let Some(schedule_queue) = schedule_queue else {
            return Err(crate::mq_client_err!("sync batch deadline scheduler is not running"));
        };
        let command = GuardScheduleCommand {
            aggregate_key,
            create_time,
            deadline_ms,
        };
        let retained_bytes = command.retained_bytes();
        match schedule_queue.try_push_data(command, retained_bytes) {
            rocketmq_runtime::QueuePushOutcome::Rejected { .. } => {
                Err(crate::mq_client_err!("sync batch deadline queue is full"))
            }
            rocketmq_runtime::QueuePushOutcome::Enqueued
            | rocketmq_runtime::QueuePushOutcome::Coalesced { .. }
            | rocketmq_runtime::QueuePushOutcome::DroppedStale { .. } => Ok(()),
        }
    }

    fn metrics_snapshot(&self) -> BatchGuardMetricsSnapshot {
        guard_metrics_snapshot(&self.metrics, self.state().schedule_queue.as_ref())
    }

    pub fn shutdown(&self) {
        self.stopped.store(true, Ordering::Release);
        let handle = {
            let mut state = self.state();
            if state.stopping {
                return;
            }
            state.stopping = true;
            if let Some(queue) = state.schedule_queue.take() {
                queue.close();
            }
            state.task_handle.take()
        };
        let _stopping_reset = GuardStoppingReset {
            state: &self.state,
            service_name: &self.service_name,
        };
        if let Some(handle) = handle {
            if !handle.shutdown_blocking(GUARD_TASK_SHUTDOWN_TIMEOUT) {
                tracing::warn!(
                    "{} sync batch guard did not stop before timeout; aborted",
                    self.service_name
                );
            }
        }
    }

    pub async fn shutdown_async(&self) {
        self.stopped.store(true, Ordering::Release);
        let handle = {
            let mut state = self.state();
            if state.stopping {
                return;
            }
            state.stopping = true;
            if let Some(queue) = state.schedule_queue.take() {
                queue.close();
            }
            state.task_handle.take()
        };
        let _stopping_reset = GuardStoppingReset {
            state: &self.state,
            service_name: &self.service_name,
        };
        if let Some(handle) = handle {
            if !handle.shutdown_async(GUARD_TASK_SHUTDOWN_TIMEOUT).await {
                tracing::warn!(
                    "{} sync batch guard did not stop before timeout; aborted",
                    self.service_name
                );
            }
        }
    }

    fn task_count(&self) -> usize {
        self.state()
            .task_handle
            .as_ref()
            .map(GuardTaskHandle::task_count)
            .unwrap_or_default()
    }
}

struct GuardForAsyncSendService {
    service_context: ChildServiceContext,
    service_name: String,
    resource_budget: ResourceBudget,
    stopped: Arc<AtomicBool>,
    state: StdMutex<GuardServiceState>,
    metrics: Arc<BatchGuardMetrics>,
}

impl GuardForAsyncSendService {
    pub fn new(service_context: ChildServiceContext, service_name: &str, resource_budget: ResourceBudget) -> Self {
        Self {
            service_context,
            service_name: service_name.to_string(),
            resource_budget,
            stopped: Arc::new(AtomicBool::new(false)),
            state: StdMutex::new(GuardServiceState::default()),
            metrics: Arc::new(BatchGuardMetrics::default()),
        }
    }

    fn state(&self) -> StdMutexGuard<'_, GuardServiceState> {
        match self.state.lock() {
            Ok(state) => state,
            Err(poisoned) => {
                tracing::warn!("{} async batch guard lifecycle lock was poisoned", self.service_name);
                poisoned.into_inner()
            }
        }
    }

    pub fn start(
        &self,
        batches: BatchMap,
        currently_hold_size: Arc<AtomicU64>,
        hold_size: usize,
        hold_ms: u32,
    ) -> crate::ClientResult<()> {
        let mut state = self.state();
        if state.stopping {
            return Err(crate::mq_client_err!("async batch guard is stopping"));
        }
        if state.task_handle.as_ref().is_some_and(|handle| !handle.is_finished()) {
            tracing::warn!("{} async batch guard already started", self.service_name);
            return Ok(());
        }

        let service_name = self.service_name.clone();
        let stopped = self.stopped.clone();
        let metrics = self.metrics.clone();
        let schedule_queue = build_guard_schedule_queue(&self.resource_budget, "async-batch-deadlines")?;
        let task_schedule_queue = schedule_queue.clone();
        let (shutdown_tx, mut shutdown_rx) = watch::channel(false);
        self.stopped.store(false, Ordering::Release);

        let task_handle = spawn_guard_task(
            &self.service_context,
            "rocketmq-client-async-batch-guard",
            shutdown_tx,
            async move {
                tracing::info!("{} service started", service_name);

                let mut deadlines = BinaryHeap::new();
                let mut sequence = 0u64;

                loop {
                    if stopped.load(Ordering::Acquire) {
                        break;
                    }

                    let next_deadline_ms = deadlines.peek().map(|deadline: &GuardDeadline| deadline.deadline_ms);
                    match wait_guard_deadline_or_schedule(&mut shutdown_rx, &task_schedule_queue, next_deadline_ms)
                        .await
                    {
                        GuardWakeEvent::Schedule(command) => {
                            push_guard_deadline(&mut deadlines, *command, &mut sequence);
                        }
                        GuardWakeEvent::Deadline => {
                            metrics.record_wakeup();
                            drain_due_async_batches(
                                &mut deadlines,
                                &batches,
                                &currently_hold_size,
                                hold_size,
                                hold_ms as u64,
                                &metrics,
                            )
                            .await;
                        }
                        GuardWakeEvent::Shutdown => break,
                    }
                }

                tracing::info!("{} service ended", service_name);
            },
        );
        let task_handle = task_handle.ok_or_else(|| crate::mq_client_err!("failed to spawn async batch guard"))?;
        state.schedule_queue = Some(schedule_queue);
        state.task_handle = Some(task_handle);
        Ok(())
    }

    fn schedule_batch(
        &self,
        aggregate_key: AggregateKey,
        create_time: u64,
        deadline_ms: u64,
    ) -> crate::ClientResult<()> {
        let schedule_queue = self.state().schedule_queue.clone();
        let Some(schedule_queue) = schedule_queue else {
            return Err(crate::mq_client_err!("async batch deadline scheduler is not running"));
        };
        let command = GuardScheduleCommand {
            aggregate_key,
            create_time,
            deadline_ms,
        };
        let retained_bytes = command.retained_bytes();
        match schedule_queue.try_push_data(command, retained_bytes) {
            rocketmq_runtime::QueuePushOutcome::Rejected { .. } => {
                Err(crate::mq_client_err!("async batch deadline queue is full"))
            }
            rocketmq_runtime::QueuePushOutcome::Enqueued
            | rocketmq_runtime::QueuePushOutcome::Coalesced { .. }
            | rocketmq_runtime::QueuePushOutcome::DroppedStale { .. } => Ok(()),
        }
    }

    fn metrics_snapshot(&self) -> BatchGuardMetricsSnapshot {
        guard_metrics_snapshot(&self.metrics, self.state().schedule_queue.as_ref())
    }

    /// Internal method to send batch (used by guard thread)
    async fn send_batch_async_internal(
        batch: Arc<Mutex<MessageAccumulation>>,
        currently_hold_size: Arc<AtomicU64>,
    ) -> crate::ClientResult<()> {
        // Extract all data from the batch without holding the lock across await
        let (messages, resource_permits, mq, producer, total_size, callbacks, aggregate_key, keys, notify) = {
            let mut batch_guard = batch.lock().await;
            if !batch_guard.try_mark_closing() {
                return Ok(());
            }
            let notify = batch_guard.completion_notify.clone();

            if batch_guard.messages.is_empty() {
                let error = crate::mq_client_err!("No messages to send");
                batch_guard.send_error = Some(error.clone());
                batch_guard.mark_closed();
                notify.notify_waiters();
                return Err(error);
            }

            let total_size = batch_guard.messages_size.load(Ordering::Acquire) as u64;
            let messages = std::mem::take(&mut batch_guard.messages);
            let resource_permits = std::mem::take(&mut batch_guard.resource_permits);
            let callbacks = std::mem::take(&mut batch_guard.send_callbacks);
            let mq = batch_guard.aggregate_key.mq.clone();
            let producer = batch_guard.default_mq_producer.clone();
            let aggregate_key = batch_guard.aggregate_key.clone();
            let keys = batch_guard.keys.clone();

            (
                messages,
                resource_permits,
                mq,
                producer,
                total_size,
                callbacks,
                aggregate_key,
                keys,
                notify,
            )
        }; // Lock released here

        let batch_msg = match build_message_batch(messages, &aggregate_key, &keys) {
            Ok(batch_msg) => batch_msg,
            Err(error) => {
                release_hold_size(&currently_hold_size, total_size);
                let mut batch_guard = batch.lock().await;
                batch_guard.send_error = Some(error.clone());
                batch_guard.mark_closed();
                notify.notify_waiters();
                for callback in &callbacks {
                    callback.on_exception(&error);
                }
                return Err(error);
            }
        };

        let callback_currently_hold_size = currently_hold_size.clone();
        let callbacks = Arc::new(callbacks);
        let callbacks_for_send_error = callbacks.clone();
        let permit_owner = Arc::new(StdMutex::new(Some(resource_permits)));
        let callback_permit_owner = Arc::clone(&permit_owner);

        // Create combined callback
        let combined_callback = move |result: Option<&SendResult>, error: Option<&ClientError>| {
            release_resource_permits(&callback_permit_owner);
            release_hold_size(&callback_currently_hold_size, total_size);
            if let Some(result) = result {
                match split_send_results(result, callbacks.len()) {
                    Ok(send_results) => {
                        for (callback, result) in callbacks.iter().zip(send_results.iter()) {
                            callback.on_success(result);
                        }
                    }
                    Err(error) => {
                        for callback in callbacks.iter() {
                            callback.on_exception(&error);
                        }
                    }
                }
            } else if let Some(error) = error {
                for callback in callbacks.iter() {
                    callback.on_exception(error);
                }
            }
        };

        // Send without holding any locks
        let send_result = producer
            .send_direct(batch_msg, mq, Some(Arc::new(combined_callback)))
            .await;

        if let Err(error) = &send_result {
            release_resource_permits(&permit_owner);
            release_hold_size(&currently_hold_size, total_size);
            let mut batch_guard = batch.lock().await;
            batch_guard.send_error = Some(error.clone());
            batch_guard.mark_closed();
            notify.notify_waiters();
            for callback in callbacks_for_send_error.iter() {
                callback.on_exception(error);
            }
        } else {
            let batch_guard = batch.lock().await;
            batch_guard.mark_closed();
            notify.notify_waiters();
        }

        send_result.map(|_| ())
    }

    pub fn shutdown(&self) {
        self.stopped.store(true, Ordering::Release);
        let handle = {
            let mut state = self.state();
            if state.stopping {
                return;
            }
            state.stopping = true;
            if let Some(queue) = state.schedule_queue.take() {
                queue.close();
            }
            state.task_handle.take()
        };
        let _stopping_reset = GuardStoppingReset {
            state: &self.state,
            service_name: &self.service_name,
        };
        if let Some(handle) = handle {
            if !handle.shutdown_blocking(GUARD_TASK_SHUTDOWN_TIMEOUT) {
                tracing::warn!(
                    "{} async batch guard did not stop before timeout; aborted",
                    self.service_name
                );
            }
        }
    }

    pub async fn shutdown_async(&self) {
        self.stopped.store(true, Ordering::Release);
        let handle = {
            let mut state = self.state();
            if state.stopping {
                return;
            }
            state.stopping = true;
            if let Some(queue) = state.schedule_queue.take() {
                queue.close();
            }
            state.task_handle.take()
        };
        let _stopping_reset = GuardStoppingReset {
            state: &self.state,
            service_name: &self.service_name,
        };
        if let Some(handle) = handle {
            if !handle.shutdown_async(GUARD_TASK_SHUTDOWN_TIMEOUT).await {
                tracing::warn!(
                    "{} async batch guard did not stop before timeout; aborted",
                    self.service_name
                );
            }
        }
    }

    fn task_count(&self) -> usize {
        self.state()
            .task_handle
            .as_ref()
            .map(GuardTaskHandle::task_count)
            .unwrap_or_default()
    }
}