duroxide-cdb 0.1.10

A CosmosDB-based provider implementation for Duroxide, a durable task orchestration framework
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
use crate::batch;
use crate::client::{BatchOperation, CosmosDBClient};
use crate::containers;
use crate::errors;
use crate::leases::{InMemoryLeaseProvider, LeaseProvider};
use crate::models::*;
use crate::outbox;
use crate::outbox::OutboxFaultInjector;
use crate::query;
use duroxide::providers::*;
use duroxide::{Event, EventKind, TagFilter};
use std::sync::Arc;
use std::time::Duration;
use tokio_util::sync::CancellationToken;

const MAX_LOCK_RETRIES: usize = 20;

/// Configuration for the CosmosDB provider.
#[derive(Debug, Clone)]
pub struct CosmosDBProviderConfig {
    pub endpoint: String,
    pub key: String,
    pub database: String,
    pub container: String,
    pub orch_concurrency: u32,
    pub worker_concurrency: u32,
    pub reconciler_interval: Duration,
    pub reconciler_age_threshold: Duration,
}

impl Default for CosmosDBProviderConfig {
    fn default() -> Self {
        Self {
            endpoint: String::new(),
            key: String::new(),
            database: "duroxide".to_string(),
            container: "duroxide".to_string(),
            orch_concurrency: 1,
            worker_concurrency: 1,
            reconciler_interval: Duration::from_secs(2),
            reconciler_age_threshold: Duration::from_secs(2),
        }
    }
}

/// CosmosDB provider for duroxide.
/// Implements both Provider and ProviderAdmin traits.
#[derive(Clone)]
pub struct CosmosDBProvider {
    inner: Arc<CosmosDBProviderInner>,
}

struct CosmosDBProviderInner {
    client: CosmosDBClient,
    orch_leases: Box<dyn LeaseProvider>,
    worker_leases: Box<dyn LeaseProvider>,
    cancel: CancellationToken,
    _reconciler_handle: Option<tokio::task::JoinHandle<()>>,
    outbox_fault_injector: Option<OutboxFaultInjector>,
}

impl CosmosDBProvider {
    /// Create a new CosmosDB provider with default settings.
    pub async fn new(endpoint: &str, key: &str, database: &str) -> Result<Self, ProviderError> {
        let config = CosmosDBProviderConfig {
            endpoint: endpoint.to_string(),
            key: key.to_string(),
            database: database.to_string(),
            ..Default::default()
        };
        Self::new_with_config(config).await
    }

    /// Create a new CosmosDB provider with custom configuration.
    pub async fn new_with_config(config: CosmosDBProviderConfig) -> Result<Self, ProviderError> {
        let client = CosmosDBClient::new(
            &config.endpoint,
            &config.key,
            &config.database,
            &config.container,
        )
        .map_err(|e| ProviderError::permanent("new", e))?;

        // Ensure database and container exist
        containers::ensure_infrastructure(&client).await?;

        let cancel = CancellationToken::new();

        // Start outbox reconciler
        let reconciler_handle = outbox::start_reconciler(
            client.clone(),
            config.reconciler_interval,
            config.reconciler_age_threshold,
            cancel.clone(),
        );

        let orch_leases = Box::new(InMemoryLeaseProvider::new(config.orch_concurrency));
        let worker_leases = Box::new(InMemoryLeaseProvider::new(config.worker_concurrency));

        Ok(Self {
            inner: Arc::new(CosmosDBProviderInner {
                client,
                orch_leases,
                worker_leases,
                cancel,
                _reconciler_handle: Some(reconciler_handle),
                outbox_fault_injector: None,
            }),
        })
    }

    /// Create with a specific container name (for test isolation).
    pub async fn new_with_container(
        endpoint: &str,
        key: &str,
        database: &str,
        container: &str,
    ) -> Result<Self, ProviderError> {
        let config = CosmosDBProviderConfig {
            endpoint: endpoint.to_string(),
            key: key.to_string(),
            database: database.to_string(),
            container: container.to_string(),
            ..Default::default()
        };
        Self::new_with_config(config).await
    }

    fn client(&self) -> &CosmosDBClient {
        &self.inner.client
    }

    /// Set a fault injector for outbox delivery testing.
    /// When set, the next N best-effort deliveries will be skipped,
    /// forcing the background reconciler to deliver the intents.
    pub fn set_outbox_fault_injector(&mut self, injector: OutboxFaultInjector) {
        // Safety: we need interior mutability here. The fault injector is
        // Arc<AtomicU32> internally, so it's safe to set before use.
        let inner = Arc::get_mut(&mut self.inner)
            .expect("Cannot set fault injector after provider has been cloned");
        inner.outbox_fault_injector = Some(injector);
    }

    /// Cleanup: delete the container. Used in tests.
    pub async fn cleanup(&self) -> Result<(), ProviderError> {
        self.inner.cancel.cancel();
        self.client().delete_container().await
    }

    async fn load_kv_store_documents(
        &self,
        instance_id: &str,
    ) -> Result<Vec<KeyValueDocument>, ProviderError> {
        let docs =
            query::query_by_type_in_partition(self.client(), instance_id, DOC_TYPE_KV).await?;
        docs.into_iter()
            .map(|doc| {
                serde_json::from_value(doc).map_err(|e| {
                    ProviderError::permanent(
                        "load_kv_store_documents",
                        format!("Deserialize error: {e}"),
                    )
                })
            })
            .collect()
    }

    async fn load_kv_delta_documents(
        &self,
        instance_id: &str,
    ) -> Result<Vec<KeyValueDeltaDocument>, ProviderError> {
        let docs = query::query_by_type_in_partition(self.client(), instance_id, DOC_TYPE_KV_DELTA)
            .await?;
        docs.into_iter()
            .map(|doc| {
                serde_json::from_value(doc).map_err(|e| {
                    ProviderError::permanent(
                        "load_kv_delta_documents",
                        format!("Deserialize error: {e}"),
                    )
                })
            })
            .collect()
    }

    fn apply_kv_history_delta(
        instance_id: &str,
        execution_id: u64,
        now: u64,
        history_delta: &[Event],
        store_docs: &[KeyValueDocument],
        existing_delta_docs: &[KeyValueDeltaDocument],
    ) -> std::collections::HashMap<String, KeyValueDeltaDocument> {
        let mut delta_docs: std::collections::HashMap<String, KeyValueDeltaDocument> =
            existing_delta_docs
                .iter()
                .cloned()
                .map(|doc| (doc.key.clone(), doc))
                .collect();
        let store_keys: Vec<String> = store_docs.iter().map(|doc| doc.key.clone()).collect();

        for event in history_delta {
            match &event.kind {
                EventKind::KeyValueSet {
                    key,
                    value,
                    last_updated_at_ms,
                } => {
                    delta_docs.insert(
                        key.clone(),
                        KeyValueDeltaDocument::new(
                            instance_id,
                            key,
                            Some(value.clone()),
                            execution_id,
                            *last_updated_at_ms,
                        ),
                    );
                }
                EventKind::KeyValueCleared { key } => {
                    delta_docs.insert(
                        key.clone(),
                        KeyValueDeltaDocument::new(instance_id, key, None, execution_id, now),
                    );
                }
                EventKind::KeyValuesCleared => {
                    for doc in delta_docs.values_mut() {
                        doc.value = None;
                        doc.execution_id = execution_id;
                        doc.last_updated_at_ms = now;
                    }
                    for key in &store_keys {
                        delta_docs.entry(key.clone()).or_insert_with(|| {
                            KeyValueDeltaDocument::new(instance_id, key, None, execution_id, now)
                        });
                    }
                }
                _ => {}
            }
        }

        delta_docs
    }

    fn kv_delta_changed_keys(
        history_delta: &[Event],
        store_docs: &[KeyValueDocument],
        existing_delta_docs: &[KeyValueDeltaDocument],
    ) -> (std::collections::HashSet<String>, bool) {
        let mut changed_keys = std::collections::HashSet::new();
        let mut clear_all = false;

        for event in history_delta {
            match &event.kind {
                EventKind::KeyValueSet { key, .. } | EventKind::KeyValueCleared { key } => {
                    changed_keys.insert(key.clone());
                }
                EventKind::KeyValuesCleared => {
                    clear_all = true;
                }
                _ => {}
            }
        }

        if clear_all {
            changed_keys.extend(store_docs.iter().map(|doc| doc.key.clone()));
            changed_keys.extend(existing_delta_docs.iter().map(|doc| doc.key.clone()));
        }

        (changed_keys, clear_all)
    }

    /// Read the instance document. Returns None if not found.
    async fn read_instance(
        &self,
        instance_id: &str,
    ) -> Result<Option<InstanceDocument>, ProviderError> {
        let doc_id = InstanceDocument::doc_id(instance_id);
        let resp = self.client().read_document(&doc_id, instance_id).await?;

        if errors::is_not_found(resp.status) {
            return Ok(None);
        }
        if !resp.is_success() {
            return Err(errors::map_cosmosdb_error(
                "read_instance",
                resp.status,
                &resp.body,
            ));
        }

        let mut inst: InstanceDocument = serde_json::from_str(&resp.body).map_err(|e| {
            ProviderError::permanent("read_instance", format!("Deserialize error: {e}"))
        })?;
        inst.etag = resp.etag;
        Ok(Some(inst))
    }

    /// Try to lock an instance by conditional replace.
    /// If no instance document exists yet (first StartOrchestration), creates one.
    /// `work_item_json` is used to extract orchestration name/version for new instances.
    async fn try_lock_instance(
        &self,
        instance_id: &str,
        lock_timeout: Duration,
        now: u64,
        work_item_json: Option<&str>,
    ) -> Result<Option<(InstanceDocument, String)>, ProviderError> {
        let inst = match self.read_instance(instance_id).await? {
            Some(i) => i,
            None => {
                // Extract orchestration name/version from the work item if available
                let (orch_name, orch_version) = if let Some(json) = work_item_json {
                    match serde_json::from_str::<WorkItem>(json) {
                        Ok(WorkItem::StartOrchestration {
                            orchestration,
                            version,
                            ..
                        }) => (orchestration, version.unwrap_or_default()),
                        _ => (String::new(), String::new()),
                    }
                } else {
                    (String::new(), String::new())
                };

                // Lazy instance creation: create a skeleton instance doc
                let lock_token = uuid::Uuid::new_v4().to_string();
                let locked_until = now + lock_timeout.as_millis() as u64;

                let mut new_inst =
                    InstanceDocument::new(instance_id, &orch_name, &orch_version, 1, None, now);
                new_inst.lock_token = Some(lock_token.clone());
                new_inst.locked_until = Some(locked_until);

                let doc_json = serde_json::to_value(&new_inst).map_err(|e| {
                    ProviderError::permanent("try_lock_instance", format!("Serialize error: {e}"))
                })?;

                let resp = self
                    .client()
                    .create_document(instance_id, &doc_json)
                    .await?;
                if resp.is_success() {
                    new_inst.etag = resp.etag;
                    return Ok(Some((new_inst, lock_token)));
                } else if errors::is_conflict(resp.status) {
                    // Another dispatcher created it first; re-read
                    match self.read_instance(instance_id).await? {
                        Some(i) => i,
                        None => return Ok(None),
                    }
                } else {
                    return Err(errors::map_cosmosdb_error(
                        "try_lock_instance",
                        resp.status,
                        &resp.body,
                    ));
                }
            }
        };

        // Check if already locked
        if let Some(locked_until) = inst.locked_until {
            if locked_until > now {
                return Ok(None); // Locked by another dispatcher
            }
        }

        let etag = inst.etag.clone().unwrap_or_default();
        let lock_token = uuid::Uuid::new_v4().to_string();
        let locked_until = now + lock_timeout.as_millis() as u64;

        let mut updated = inst.clone();
        updated.lock_token = Some(lock_token.clone());
        updated.locked_until = Some(locked_until);
        updated.updated_at = now;

        let doc_json = serde_json::to_value(&updated).map_err(|e| {
            ProviderError::permanent("try_lock_instance", format!("Serialize error: {e}"))
        })?;

        let resp = self
            .client()
            .replace_document(&updated.id, instance_id, &doc_json, Some(&etag))
            .await?;

        if resp.is_success() {
            Ok(Some((updated, lock_token)))
        } else if errors::is_precondition_failed(resp.status) || errors::is_conflict(resp.status) {
            Ok(None) // ETag race
        } else {
            Err(errors::map_cosmosdb_error(
                "try_lock_instance",
                resp.status,
                &resp.body,
            ))
        }
    }

    /// Unlock an instance.
    async fn unlock_instance(&self, instance_id: &str) -> Result<(), ProviderError> {
        let Some(inst) = self.read_instance(instance_id).await? else {
            return Ok(());
        };

        let etag = inst.etag.clone().unwrap_or_default();
        let mut updated = inst;
        updated.lock_token = None;
        updated.locked_until = None;

        let doc_json = serde_json::to_value(&updated).map_err(|e| {
            ProviderError::permanent("unlock_instance", format!("Serialize error: {e}"))
        })?;

        let resp = self
            .client()
            .replace_document(&updated.id, instance_id, &doc_json, Some(&etag))
            .await?;

        if resp.is_success() || errors::is_precondition_failed(resp.status) {
            Ok(())
        } else {
            Err(errors::map_cosmosdb_error(
                "unlock_instance",
                resp.status,
                &resp.body,
            ))
        }
    }
}

impl Drop for CosmosDBProviderInner {
    fn drop(&mut self) {
        self.cancel.cancel();
    }
}

// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// Provider trait implementation
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

#[async_trait::async_trait]
impl Provider for CosmosDBProvider {
    fn name(&self) -> &str {
        "duroxide-cdb"
    }

    fn version(&self) -> &str {
        env!("CARGO_PKG_VERSION")
    }

    // ─── fetch_orchestration_item ────────────────────────────────

    async fn fetch_orchestration_item(
        &self,
        lock_timeout: Duration,
        _poll_timeout: Duration,
        filter: Option<&DispatcherCapabilityFilter>,
    ) -> Result<Option<(OrchestrationItem, String, u32)>, ProviderError> {
        let caller_id = task_id_u64();
        let my_slots = self.inner.orch_leases.acquire_slots(caller_id).await;
        let now = now_ms();

        // Capability filter: compute packed version bounds for initial query filtering
        let (min_packed, max_packed) = if let Some(f) = filter {
            if f.supported_duroxide_versions.is_empty() {
                return Ok(None);
            }
            let min = f
                .supported_duroxide_versions
                .iter()
                .map(|r| pack_semver(&r.min))
                .min()
                .unwrap();
            let max = f
                .supported_duroxide_versions
                .iter()
                .map(|r| pack_semver(&r.max))
                .max()
                .unwrap();
            (Some(min), Some(max))
        } else {
            (None, None)
        };

        let mut excluded = Vec::new();

        for _attempt in 0..MAX_LOCK_RETRIES {
            // Step 1: Find candidate (no version filtering on queue items)
            let candidate = query::find_candidate_orch_item(
                self.client(),
                now,
                &my_slots,
                None, // Don't filter by version in queue query
                None,
                &excluded,
            )
            .await?;

            let Some(candidate) = candidate else {
                return Ok(None);
            };

            let instance_id = &candidate.instance_id;

            // Step 2: Try to lock the instance
            let lock_result = self
                .try_lock_instance(instance_id, lock_timeout, now, Some(&candidate.work_item))
                .await?;

            let Some((locked_instance, lock_token)) = lock_result else {
                excluded.push(instance_id.to_string());
                continue;
            };

            // Step 2b: Check capability filter against instance's pinned version
            if let (Some(min_v), Some(max_v)) = (min_packed, max_packed) {
                if let Some(pinned) = locked_instance.pinned_duroxide_version_packed {
                    if pinned < min_v || pinned > max_v {
                        // Incompatible version - unlock and skip
                        self.unlock_instance(instance_id).await?;
                        excluded.push(instance_id.to_string());
                        continue;
                    }
                }
                // If pinned is None, it's compatible (unpinned = legacy)
            }

            // Step 3: Collect all pending messages
            let messages = query::collect_orch_messages(self.client(), instance_id, now).await?;

            if messages.is_empty() {
                // Messages were consumed between step 1 and 3
                self.unlock_instance(instance_id).await?;
                excluded.push(instance_id.to_string());
                continue;
            }

            // Tag all messages with lock
            let max_attempt = messages.iter().map(|m| m.attempt_count).max().unwrap_or(0);
            for msg in &messages {
                let mut updated_msg = msg.clone();
                updated_msg.lock_token = Some(lock_token.clone());
                updated_msg.locked_until = Some(now + lock_timeout.as_millis() as u64);
                updated_msg.attempt_count += 1;

                let doc_json = serde_json::to_value(&updated_msg).map_err(|e| {
                    ProviderError::permanent(
                        "fetch_orchestration_item",
                        format!("Serialize error: {e}"),
                    )
                })?;

                let _ = self
                    .client()
                    .replace_document(&msg.id, instance_id, &doc_json, msg.etag.as_deref())
                    .await?;
            }

            let attempt_count = (max_attempt + 1) as u32;

            // Deserialize work items
            let work_items: Vec<WorkItem> = messages
                .iter()
                .map(|m| {
                    serde_json::from_str(&m.work_item).map_err(|e| {
                        ProviderError::permanent(
                            "fetch_orchestration_item",
                            format!("Failed to deserialize work item: {e}"),
                        )
                    })
                })
                .collect::<Result<Vec<_>, _>>()?;

            // Step 4: Fetch history
            let execution_id = locked_instance.current_execution_id;
            let history_docs =
                query::fetch_history(self.client(), instance_id, execution_id).await?;

            let (history, history_error) = {
                let mut events = Vec::new();
                let mut error = None;
                for doc in &history_docs {
                    match serde_json::from_str::<Event>(&doc.event_data) {
                        Ok(event) => events.push(event),
                        Err(e) => {
                            error = Some(format!(
                                "Failed to deserialize history event {}: {e}",
                                doc.event_id
                            ));
                            events.clear();
                            break;
                        }
                    }
                }
                (events, error)
            };

            // Step 5: Load KV snapshot from kv_store only. Current-execution
            // mutations remain in kv_delta until the execution reaches a terminal state.
            let kv_snapshot: std::collections::HashMap<String, duroxide::providers::KvEntry> = self
                .load_kv_store_documents(instance_id)
                .await?
                .into_iter()
                .map(|doc| {
                    (
                        doc.key,
                        duroxide::providers::KvEntry {
                            value: doc.value,
                            last_updated_at_ms: doc.last_updated_at_ms,
                        },
                    )
                })
                .collect();

            // Step 6: Build OrchestrationItem

            // Orphan queue messages: if orchestration_name is empty (no StartOrchestration
            // seen), there's no history, and ALL messages are QueueMessage items, these are
            // orphan events enqueued before the orchestration started. Drop them by acking
            // with empty deltas. Other work items (CancelInstance, etc.) may legitimately
            // race with StartOrchestration and must not be dropped.
            if locked_instance.orchestration_name.is_empty()
                && history.is_empty()
                && work_items
                    .iter()
                    .all(|m| matches!(m, WorkItem::QueueMessage { .. }))
            {
                let message_count = work_items.len();
                tracing::warn!(
                    target = "duroxide::providers::cosmosdb",
                    instance = %instance_id,
                    message_count,
                    "Dropping orphan queue messages — events enqueued before orchestration started are not supported"
                );
                self.ack_orchestration_item(
                    &lock_token,
                    execution_id,
                    vec![],
                    vec![],
                    vec![],
                    ExecutionMetadata::default(),
                    vec![],
                )
                .await?;
                return Ok(None);
            }

            let item = OrchestrationItem {
                instance: instance_id.to_string(),
                orchestration_name: locked_instance.orchestration_name.clone(),
                execution_id,
                version: locked_instance.orchestration_version.clone(),
                history,
                messages: work_items,
                history_error,
                kv_snapshot,
            };

            return Ok(Some((item, lock_token, attempt_count)));
        }

        // All retries exhausted
        Ok(None)
    }

    // ─── ack_orchestration_item ──────────────────────────────────

    async fn ack_orchestration_item(
        &self,
        lock_token: &str,
        execution_id: u64,
        history_delta: Vec<Event>,
        worker_items: Vec<WorkItem>,
        orchestrator_items: Vec<WorkItem>,
        metadata: ExecutionMetadata,
        cancelled_activities: Vec<ScheduledActivityIdentifier>,
    ) -> Result<(), ProviderError> {
        // Find the locked instance
        let instance = query::find_instance_by_lock_token(self.client(), lock_token)
            .await?
            .ok_or_else(|| {
                ProviderError::permanent(
                    "ack_orchestration_item",
                    format!("Invalid lock token or lock expired: {lock_token}"),
                )
            })?;

        let instance_id = &instance.instance_id;
        let now = now_ms();

        // Verify lock hasn't expired
        if let Some(locked_until) = instance.locked_until {
            if locked_until <= now {
                return Err(ProviderError::permanent(
                    "ack_orchestration_item",
                    format!("Lock has expired for instance {instance_id}"),
                ));
            }
        }

        // Classify items by partition
        let mut same_partition_worker = Vec::new();
        let mut same_partition_orch = Vec::new();
        let mut cross_partition_intents = Vec::new();

        // Build a set of cancelled activity identities for fast lookup
        let cancelled_set: std::collections::HashSet<(String, u64, u64)> = cancelled_activities
            .iter()
            .map(|c| (c.instance.clone(), c.execution_id, c.activity_id))
            .collect();

        // Process worker items, filtering out any that match a cancelled activity
        for (seq, item) in worker_items.iter().enumerate() {
            // Check if this worker item is being cancelled in the same ack
            let is_cancelled = match item {
                WorkItem::ActivityExecute {
                    instance,
                    execution_id,
                    id,
                    ..
                } => cancelled_set.contains(&(instance.clone(), *execution_id, *id)),
                _ => false,
            };
            if is_cancelled {
                continue; // Skip: this activity is both scheduled and cancelled
            }

            let target_instance = work_item_instance(item);
            let item_json = serde_json::to_string(item).map_err(|e| {
                ProviderError::permanent("ack_orchestration_item", format!("Serialize error: {e}"))
            })?;

            if target_instance == instance_id {
                // Same partition
                let (exec_id, activity_id, session_id, tag) = match item {
                    WorkItem::ActivityExecute {
                        execution_id,
                        id,
                        session_id,
                        tag,
                        ..
                    } => (
                        Some(*execution_id),
                        Some(*id),
                        session_id.clone(),
                        tag.clone(),
                    ),
                    _ => (None, None, None, None),
                };
                let doc = QueueItemDocument::new_worker_queue(
                    instance_id,
                    item_json,
                    exec_id,
                    activity_id,
                    session_id,
                    tag,
                    now,
                );
                same_partition_worker.push(serde_json::to_value(&doc).unwrap());
            } else {
                // Cross partition: create outbox intent
                let (exec_id, activity_id, session_id, tag) = match item {
                    WorkItem::ActivityExecute {
                        execution_id,
                        id,
                        session_id,
                        tag,
                        ..
                    } => (
                        Some(*execution_id),
                        Some(*id),
                        session_id.clone(),
                        tag.clone(),
                    ),
                    _ => (None, None, None, None),
                };
                let target_doc = QueueItemDocument::new_worker_queue(
                    target_instance,
                    item_json,
                    exec_id,
                    activity_id,
                    session_id,
                    tag,
                    now,
                );
                let target_json = serde_json::to_string(&target_doc).unwrap();
                let idem_key = idempotency_key(instance_id, execution_id, seq as u64);
                let intent = OutboxIntentDocument::new(
                    instance_id,
                    target_instance,
                    DOC_TYPE_WORKER_QUEUE,
                    target_json,
                    idem_key,
                    now,
                );
                cross_partition_intents.push(intent);
            }
        }

        // Process orchestrator items
        for (seq, item) in orchestrator_items.iter().enumerate() {
            let target_instance = work_item_instance(item);
            let item_json = serde_json::to_string(item).map_err(|e| {
                ProviderError::permanent("ack_orchestration_item", format!("Serialize error: {e}"))
            })?;

            let delay = match item {
                WorkItem::TimerFired { fire_at_ms, .. } => {
                    let fire_at = *fire_at_ms;
                    if fire_at > now {
                        fire_at
                    } else {
                        now
                    }
                }
                _ => now,
            };

            if target_instance == instance_id {
                let doc = QueueItemDocument::new_orch_queue(instance_id, item_json, delay, now);
                same_partition_orch.push(serde_json::to_value(&doc).unwrap());
            } else {
                let target_doc =
                    QueueItemDocument::new_orch_queue(target_instance, item_json, delay, now);
                let target_json = serde_json::to_string(&target_doc).unwrap();
                let idem_key =
                    idempotency_key(instance_id, execution_id, (worker_items.len() + seq) as u64);
                let intent = OutboxIntentDocument::new(
                    instance_id,
                    target_instance,
                    DOC_TYPE_ORCH_QUEUE,
                    target_json,
                    idem_key,
                    now,
                );
                cross_partition_intents.push(intent);
            }
        }

        // Find messages to delete (locked by our token)
        let locked_messages =
            query::find_items_by_lock_token(self.client(), lock_token, DOC_TYPE_ORCH_QUEUE).await?;
        let messages_to_delete: Vec<String> =
            locked_messages.iter().map(|m| m.id.clone()).collect();

        // Find cancelled activity doc IDs
        let mut cancelled_doc_ids = Vec::new();
        for cancelled in &cancelled_activities {
            // Query worker queue for matching activity
            let sql = format!(
                "SELECT c.id FROM c WHERE c.instanceId = @instanceId AND c.type = '{}' \
                 AND c.executionId = @execId AND c.activityId = @activityId",
                DOC_TYPE_WORKER_QUEUE
            );
            let params = vec![
                crate::client::QueryParameter::new(
                    "@instanceId",
                    serde_json::json!(&cancelled.instance),
                ),
                crate::client::QueryParameter::new(
                    "@execId",
                    serde_json::json!(cancelled.execution_id),
                ),
                crate::client::QueryParameter::new(
                    "@activityId",
                    serde_json::json!(cancelled.activity_id),
                ),
            ];
            let results = self
                .client()
                .query(&sql, params, Some(&cancelled.instance))
                .await?;
            for doc in results {
                if let Some(id) = doc.get("id").and_then(|v| v.as_str()) {
                    cancelled_doc_ids.push(id.to_string());
                }
            }
        }

        // Build history delta entries using event_id from each Event
        let history_entries: Vec<(u64, String)> = history_delta
            .iter()
            .map(|event| {
                let event_id = event.event_id;
                let event_json = serde_json::to_string(event).unwrap();
                (event_id, event_json)
            })
            .collect();

        // Build instance update document
        let mut updated_instance = instance.clone();
        updated_instance.current_execution_id = execution_id;
        updated_instance.updated_at = now;
        updated_instance.lock_token = None;
        updated_instance.locked_until = None;

        if let Some(status) = &metadata.status {
            updated_instance.status = status.clone();
        }
        if let Some(output) = &metadata.output {
            updated_instance.output = Some(output.clone());
        }
        if let Some(name) = &metadata.orchestration_name {
            updated_instance.orchestration_name = name.clone();
        }
        if let Some(version) = &metadata.orchestration_version {
            updated_instance.orchestration_version = version.clone();
        }
        if let Some(parent) = &metadata.parent_instance_id {
            updated_instance.parent_instance_id = Some(parent.clone());
        }
        if let Some(pinned) = &metadata.pinned_duroxide_version {
            updated_instance.pinned_duroxide_version_packed = Some(pack_semver(pinned));
        }

        // Derive custom_status from history_delta events.
        // Scan reverse to find the last CustomStatusUpdated event.
        let custom_status_from_delta = history_delta.iter().rev().find_map(|e| match &e.kind {
            EventKind::CustomStatusUpdated { status } => Some(status.clone()),
            _ => None,
        });

        match custom_status_from_delta {
            Some(Some(custom_status)) => {
                updated_instance.custom_status = Some(custom_status);
                updated_instance.custom_status_version += 1;
            }
            Some(None) => {
                updated_instance.custom_status = None;
                updated_instance.custom_status_version += 1;
            }
            None => {
                // No CustomStatusUpdated in delta — preserve existing value
            }
        }

        let instance_json = serde_json::to_value(&updated_instance).map_err(|e| {
            ProviderError::permanent("ack_orchestration_item", format!("Serialize error: {e}"))
        })?;

        // Build outbox intent JSON values
        let outbox_json: Vec<serde_json::Value> = cross_partition_intents
            .iter()
            .map(|intent| serde_json::to_value(intent).unwrap())
            .collect();

        let existing_store_docs = self.load_kv_store_documents(instance_id).await?;
        let existing_delta_docs = self.load_kv_delta_documents(instance_id).await?;
        let delta_state = Self::apply_kv_history_delta(
            instance_id,
            execution_id,
            now,
            &history_delta,
            &existing_store_docs,
            &existing_delta_docs,
        );
        let (changed_delta_keys, clear_all) =
            Self::kv_delta_changed_keys(&history_delta, &existing_store_docs, &existing_delta_docs);
        let is_terminal = metadata
            .status
            .as_deref()
            .is_some_and(|status| matches!(status, "Completed" | "ContinuedAsNew" | "Failed"));

        // Build KV batch operations using the kv_store + kv_delta model.
        let existing_store_keys: std::collections::HashSet<String> = existing_store_docs
            .iter()
            .map(|doc| doc.key.clone())
            .collect();
        let mut kv_ops: Vec<BatchOperation> = Vec::new();

        if is_terminal {
            let mut delta_docs: Vec<KeyValueDeltaDocument> = delta_state.into_values().collect();
            delta_docs.sort_by(|a, b| a.key.cmp(&b.key));

            for delta_doc in delta_docs {
                match delta_doc.value.as_deref() {
                    Some(value) => {
                        let store_doc = KeyValueDocument::new(
                            instance_id,
                            &delta_doc.key,
                            value,
                            delta_doc.execution_id,
                            delta_doc.last_updated_at_ms,
                        );
                        let json = serde_json::to_value(&store_doc).unwrap();
                        kv_ops.push(BatchOperation::Upsert { body: json });
                    }
                    None => {
                        if existing_store_keys.contains(&delta_doc.key) {
                            kv_ops.push(BatchOperation::Delete {
                                id: KeyValueDocument::doc_id(instance_id, &delta_doc.key),
                            });
                        }
                    }
                }
            }

            for delta_doc in &existing_delta_docs {
                kv_ops.push(BatchOperation::Delete {
                    id: delta_doc.id.clone(),
                });
            }
        } else {
            let mut keys_to_upsert: Vec<String> = if clear_all {
                delta_state.keys().cloned().collect()
            } else {
                changed_delta_keys.into_iter().collect()
            };
            keys_to_upsert.sort();
            keys_to_upsert.dedup();

            for key in keys_to_upsert {
                if let Some(delta_doc) = delta_state.get(&key) {
                    let json = serde_json::to_value(delta_doc).unwrap();
                    kv_ops.push(BatchOperation::Upsert { body: json });
                }
            }
        }

        // Build and execute transactional batch
        // Note: cancelled_doc_ids are NOT included in the batch because the
        // worker dispatcher may have already fetched and deleted them. A batch
        // delete of a non-existent doc returns 404, which fails the entire
        // transactional batch (424). Instead, we delete them best-effort after.
        let ops = batch::build_ack_batch(
            instance_id,
            execution_id,
            lock_token,
            &messages_to_delete,
            &history_entries,
            same_partition_worker,
            same_partition_orch,
            outbox_json,
            kv_ops,
            &[], // no cancelled deletes in the batch
            instance_json,
        );

        batch::execute_batch(self.client(), instance_id, ops).await?;

        // Best-effort delete of cancelled activity worker_queue docs.
        // These may already be gone if the worker consumed them before
        // the orchestration decided to cancel.
        for doc_id in &cancelled_doc_ids {
            let _ = self.client().delete_document(doc_id, instance_id).await;
        }

        // Best-effort delivery of cross-partition intents
        outbox::deliver_intents_best_effort(
            self.client(),
            &cross_partition_intents,
            self.inner.outbox_fault_injector.as_ref(),
        )
        .await;

        Ok(())
    }

    // ─── abandon_orchestration_item ──────────────────────────────

    async fn abandon_orchestration_item(
        &self,
        lock_token: &str,
        delay: Option<Duration>,
        ignore_attempt: bool,
    ) -> Result<(), ProviderError> {
        let now = now_ms();

        // Find and unlock instance
        let instance = query::find_instance_by_lock_token(self.client(), lock_token).await?;
        let inst = instance.ok_or_else(|| {
            ProviderError::permanent("abandon_orchestration_item", "Invalid lock token")
        })?;

        let mut updated = inst.clone();
        updated.lock_token = None;
        updated.locked_until = None;
        updated.updated_at = now;
        let doc_json = serde_json::to_value(&updated).unwrap();
        let _ = self
            .client()
            .replace_document(
                &updated.id,
                &inst.instance_id,
                &doc_json,
                inst.etag.as_deref(),
            )
            .await;

        // Find and unlock queue messages
        let messages =
            query::find_items_by_lock_token(self.client(), lock_token, DOC_TYPE_ORCH_QUEUE).await?;
        for msg in &messages {
            let mut updated = msg.clone();
            updated.lock_token = None;
            updated.locked_until = None;
            if let Some(d) = delay {
                updated.visible_at = now + d.as_millis() as u64;
            }
            if ignore_attempt && updated.attempt_count > 0 {
                updated.attempt_count -= 1;
            }

            let doc_json = serde_json::to_value(&updated).unwrap();
            let _ = self
                .client()
                .replace_document(&msg.id, &msg.instance_id, &doc_json, msg.etag.as_deref())
                .await;
        }

        Ok(())
    }

    // ─── read ────────────────────────────────────────────────────

    async fn read(&self, instance: &str) -> Result<Vec<Event>, ProviderError> {
        let inst = self.read_instance(instance).await?;
        let execution_id = inst.map(|i| i.current_execution_id).unwrap_or(1);
        self.read_with_execution(instance, execution_id).await
    }

    async fn read_with_execution(
        &self,
        instance: &str,
        execution_id: u64,
    ) -> Result<Vec<Event>, ProviderError> {
        let docs = query::fetch_history(self.client(), instance, execution_id).await?;
        let mut events = Vec::new();
        for doc in docs {
            let event: Event = serde_json::from_str(&doc.event_data).map_err(|e| {
                ProviderError::permanent(
                    "read_with_execution",
                    format!("Failed to deserialize event: {e}"),
                )
            })?;
            events.push(event);
        }
        Ok(events)
    }

    async fn append_with_execution(
        &self,
        instance: &str,
        execution_id: u64,
        new_events: Vec<Event>,
    ) -> Result<(), ProviderError> {
        // Get next event ID
        let existing = query::fetch_history(self.client(), instance, execution_id).await?;
        let next_id = existing
            .iter()
            .map(|h| h.event_id)
            .max()
            .map(|m| m + 1)
            .unwrap_or(0);

        for (i, event) in new_events.iter().enumerate() {
            let event_id = next_id + i as u64;
            let event_json = serde_json::to_string(event).map_err(|e| {
                ProviderError::permanent("append_with_execution", format!("Serialize error: {e}"))
            })?;
            let doc = HistoryDocument::new(instance, execution_id, event_id, event_json);
            let doc_json = serde_json::to_value(&doc).unwrap();

            let resp = self.client().create_document(instance, &doc_json).await?;
            if !resp.is_success() && !errors::is_conflict(resp.status) {
                return Err(errors::map_cosmosdb_error(
                    "append_with_execution",
                    resp.status,
                    &resp.body,
                ));
            }
        }

        Ok(())
    }

    // ─── Worker queue operations ─────────────────────────────────

    async fn enqueue_for_worker(&self, item: WorkItem) -> Result<(), ProviderError> {
        let instance_id = work_item_instance(&item).to_string();
        let item_json = serde_json::to_string(&item).map_err(|e| {
            ProviderError::permanent("enqueue_for_worker", format!("Serialize error: {e}"))
        })?;

        let (exec_id, activity_id, session_id, tag) = match &item {
            WorkItem::ActivityExecute {
                execution_id,
                id,
                session_id,
                tag,
                ..
            } => (
                Some(*execution_id),
                Some(*id),
                session_id.clone(),
                tag.clone(),
            ),
            _ => (None, None, None, None),
        };

        let now = now_ms();
        let doc = QueueItemDocument::new_worker_queue(
            &instance_id,
            item_json,
            exec_id,
            activity_id,
            session_id,
            tag,
            now,
        );
        let doc_json = serde_json::to_value(&doc).unwrap();

        let resp = self
            .client()
            .create_document(&instance_id, &doc_json)
            .await?;
        if !resp.is_success() {
            return Err(errors::map_cosmosdb_error(
                "enqueue_for_worker",
                resp.status,
                &resp.body,
            ));
        }

        Ok(())
    }

    async fn fetch_work_item(
        &self,
        lock_timeout: Duration,
        _poll_timeout: Duration,
        session: Option<&SessionFetchConfig>,
        tag_filter: &TagFilter,
    ) -> Result<Option<(WorkItem, String, u32)>, ProviderError> {
        // TagFilter::None means this worker doesn't process any activities
        if matches!(tag_filter, TagFilter::None) {
            return Ok(None);
        }

        let caller_id = task_id_u64();
        let my_slots = self.inner.worker_leases.acquire_slots(caller_id).await;
        let now = now_ms();

        let mut excluded = Vec::new();

        for _attempt in 0..10 {
            let candidate = query::find_candidate_work_item(
                self.client(),
                now,
                &my_slots,
                session.map(|s| s.owner_id.as_str()),
                &excluded,
                tag_filter,
            )
            .await?;

            let Some(candidate) = candidate else {
                return Ok(None);
            };

            // Session routing check before locking
            if let Some(ref sid) = candidate.session_id {
                if let Some(config) = session {
                    // Check existing session ownership
                    let session_doc_id = SessionDocument::doc_id(&candidate.instance_id, sid);
                    if let Ok(resp) = self
                        .client()
                        .read_document(&session_doc_id, &candidate.instance_id)
                        .await
                    {
                        if resp.is_success() {
                            if let Ok(session_doc) =
                                serde_json::from_str::<SessionDocument>(&resp.body)
                            {
                                // Session exists - check if it's still locked by another worker
                                if session_doc.locked_until > now
                                    && session_doc.owner_id != config.owner_id
                                {
                                    // Session owned by another worker, skip this item
                                    excluded.push(candidate.id.clone());
                                    continue;
                                }
                            }
                        }
                    }
                } else {
                    // No session config but item has session - skip
                    excluded.push(candidate.id.clone());
                    continue;
                }
            }

            // Try to lock the work item via conditional replace
            let etag = candidate.etag.clone().unwrap_or_default();
            let lock_token = uuid::Uuid::new_v4().to_string();

            let mut updated = candidate.clone();
            updated.lock_token = Some(lock_token.clone());
            updated.locked_until = Some(now + lock_timeout.as_millis() as u64);
            updated.attempt_count += 1;

            let doc_json = serde_json::to_value(&updated).map_err(|e| {
                ProviderError::permanent("fetch_work_item", format!("Serialize error: {e}"))
            })?;

            let resp = self
                .client()
                .replace_document(
                    &candidate.id,
                    &candidate.instance_id,
                    &doc_json,
                    Some(&etag),
                )
                .await?;

            if resp.is_success() {
                // If session-bound, atomically upsert session
                if let (Some(ref sid), Some(config)) = (&candidate.session_id, session) {
                    // Use fresh timestamp for session lock — network latency
                    // since the start of fetch_work_item can be significant
                    let session_now = now_ms();
                    let session_locked_until = session_now + config.lock_timeout.as_millis() as u64;
                    let session_doc_id = SessionDocument::doc_id(&candidate.instance_id, sid);

                    // Try to read existing session
                    let existing_session = self
                        .client()
                        .read_document(&session_doc_id, &candidate.instance_id)
                        .await;

                    let session_claimed = match existing_session {
                        Ok(resp) if resp.is_success() => {
                            // Session exists, check ownership
                            match serde_json::from_str::<SessionDocument>(&resp.body) {
                                Ok(mut existing) => {
                                    if existing.locked_until <= session_now
                                        || existing.owner_id == config.owner_id
                                    {
                                        // Expired or we own it - update
                                        existing.owner_id = config.owner_id.clone();
                                        existing.locked_until = session_locked_until;
                                        existing.last_activity = session_now;
                                        let session_json = serde_json::to_value(&existing).unwrap();
                                        let update_resp = self
                                            .client()
                                            .replace_document(
                                                &session_doc_id,
                                                &candidate.instance_id,
                                                &session_json,
                                                resp.etag.as_deref(),
                                            )
                                            .await;
                                        update_resp.map(|r| r.is_success()).unwrap_or(false)
                                    } else {
                                        // Another worker owns this session
                                        false
                                    }
                                }
                                Err(_) => false,
                            }
                        }
                        _ => {
                            // Session doesn't exist, create it
                            let new_session = SessionDocument {
                                id: session_doc_id.clone(),
                                instance_id: candidate.instance_id.clone(),
                                doc_type: DOC_TYPE_SESSION.to_string(),
                                session_id: sid.clone(),
                                owner_id: config.owner_id.clone(),
                                locked_until: session_locked_until,
                                last_activity: session_now,
                                created_at: session_now,
                                etag: None,
                                rid: None,
                                self_link: None,
                                ts: None,
                                attachments: None,
                            };
                            let session_json = serde_json::to_value(&new_session).unwrap();
                            let create_resp = self
                                .client()
                                .create_document(&candidate.instance_id, &session_json)
                                .await;
                            match create_resp {
                                Ok(r) => r.is_success(),
                                Err(_) => false,
                            }
                        }
                    };

                    if !session_claimed {
                        // Failed to claim session - unlock work item and skip
                        let mut rollback = updated.clone();
                        rollback.lock_token = None;
                        rollback.locked_until = None;
                        rollback.attempt_count -= 1;
                        let rollback_json = serde_json::to_value(&rollback).unwrap();
                        let _ = self
                            .client()
                            .replace_document(
                                &candidate.id,
                                &candidate.instance_id,
                                &rollback_json,
                                None, // no etag check for rollback
                            )
                            .await;
                        excluded.push(candidate.id.clone());
                        continue;
                    }
                }

                // Parse the work item
                let work_item: WorkItem =
                    serde_json::from_str(&candidate.work_item).map_err(|e| {
                        ProviderError::permanent(
                            "fetch_work_item",
                            format!("Failed to deserialize work item: {e}"),
                        )
                    })?;

                return Ok(Some((work_item, lock_token, updated.attempt_count as u32)));
            } else if errors::is_precondition_failed(resp.status)
                || errors::is_conflict(resp.status)
            {
                excluded.push(candidate.id.clone());
                continue;
            } else {
                return Err(errors::map_cosmosdb_error(
                    "fetch_work_item",
                    resp.status,
                    &resp.body,
                ));
            }
        }

        Ok(None)
    }

    async fn ack_work_item(
        &self,
        token: &str,
        completion: Option<WorkItem>,
    ) -> Result<(), ProviderError> {
        let now = now_ms();

        // Find the locked worker item
        let items =
            query::find_items_by_lock_token(self.client(), token, DOC_TYPE_WORKER_QUEUE).await?;

        let item = items.first().ok_or_else(|| {
            ProviderError::permanent(
                "ack_work_item",
                "Activity was cancelled or lock expired (worker queue row not found or lock invalid)",
            )
        })?;

        // Verify lock hasn't expired
        if let Some(locked_until) = item.locked_until {
            if locked_until <= now {
                return Err(ProviderError::permanent(
                    "ack_work_item",
                    "Activity was cancelled or lock expired (worker queue row not found or lock invalid)",
                ));
            }
        }

        let instance_id = &item.instance_id;
        let session_id = item.session_id.clone();

        if let Some(completion_item) = completion {
            // Create completion in orch_queue + delete worker item in same partition
            let target_instance = work_item_instance(&completion_item).to_string();
            let item_json = serde_json::to_string(&completion_item).map_err(|e| {
                ProviderError::permanent("ack_work_item", format!("Serialize error: {e}"))
            })?;

            if target_instance == *instance_id {
                // Same partition: transactional batch
                let orch_doc =
                    QueueItemDocument::new_orch_queue(&target_instance, item_json, now, now);
                let orch_json = serde_json::to_value(&orch_doc).unwrap();

                let ops = vec![
                    BatchOperation::Delete {
                        id: item.id.clone(),
                    },
                    BatchOperation::Create { body: orch_json },
                ];
                batch::execute_batch(self.client(), instance_id, ops).await?;
            } else {
                // Different partition: delete worker item, then create orch item separately
                let _ = self.client().delete_document(&item.id, instance_id).await?;

                let orch_doc =
                    QueueItemDocument::new_orch_queue(&target_instance, item_json, now, now);
                let orch_json = serde_json::to_value(&orch_doc).unwrap();

                let resp = self
                    .client()
                    .create_document(&target_instance, &orch_json)
                    .await?;
                if !resp.is_success() {
                    return Err(errors::map_cosmosdb_error(
                        "ack_work_item",
                        resp.status,
                        &resp.body,
                    ));
                }
            }
        } else {
            // No completion: just delete the worker item (cancelled)
            let _ = self.client().delete_document(&item.id, instance_id).await?;
        }

        // Piggyback: update last_activity_at for session-bound items
        if let Some(ref sid) = session_id {
            let session_doc_id = SessionDocument::doc_id(instance_id, sid);
            let piggyback_now = now_ms(); // Fresh timestamp for accurate idle tracking
            if let Ok(resp) = self
                .client()
                .read_document(&session_doc_id, instance_id)
                .await
            {
                if resp.is_success() {
                    if let Ok(mut session_doc) = serde_json::from_str::<SessionDocument>(&resp.body)
                    {
                        if session_doc.locked_until > piggyback_now {
                            session_doc.last_activity = piggyback_now;
                            session_doc.etag = resp.etag;
                            let doc_json = serde_json::to_value(&session_doc).unwrap();
                            let _ = self
                                .client()
                                .replace_document(
                                    &session_doc_id,
                                    instance_id,
                                    &doc_json,
                                    session_doc.etag.as_deref(),
                                )
                                .await;
                        }
                    }
                }
            }
        }

        Ok(())
    }

    async fn renew_work_item_lock(
        &self,
        token: &str,
        extend_for: Duration,
    ) -> Result<(), ProviderError> {
        let now = now_ms();
        let items =
            query::find_items_by_lock_token(self.client(), token, DOC_TYPE_WORKER_QUEUE).await?;

        let item = items.first().ok_or_else(|| {
            ProviderError::permanent(
                "renew_work_item_lock",
                format!("No worker item found with lock token {token}"),
            )
        })?;

        // Check if expired
        if let Some(locked_until) = item.locked_until {
            if locked_until <= now {
                return Err(ProviderError::permanent(
                    "renew_work_item_lock",
                    "Lock has expired".to_string(),
                ));
            }
        }

        let mut updated = item.clone();
        updated.locked_until = Some(now + extend_for.as_millis() as u64);

        let doc_json = serde_json::to_value(&updated).unwrap();
        let resp = self
            .client()
            .replace_document(&item.id, &item.instance_id, &doc_json, item.etag.as_deref())
            .await?;

        if resp.is_success() {
            // Piggyback: update last_activity_at for session-bound items
            if let Some(ref sid) = item.session_id {
                let piggyback_now = now_ms(); // Fresh timestamp for accurate idle tracking
                let session_doc_id = SessionDocument::doc_id(&item.instance_id, sid);
                if let Ok(sess_resp) = self
                    .client()
                    .read_document(&session_doc_id, &item.instance_id)
                    .await
                {
                    if sess_resp.is_success() {
                        if let Ok(mut session_doc) =
                            serde_json::from_str::<SessionDocument>(&sess_resp.body)
                        {
                            if session_doc.locked_until > piggyback_now {
                                session_doc.last_activity = piggyback_now;
                                let sess_json = serde_json::to_value(&session_doc).unwrap();
                                let _ = self
                                    .client()
                                    .replace_document(
                                        &session_doc_id,
                                        &item.instance_id,
                                        &sess_json,
                                        sess_resp.etag.as_deref(),
                                    )
                                    .await;
                            }
                        }
                    }
                }
            }
            Ok(())
        } else {
            Err(errors::map_cosmosdb_error(
                "renew_work_item_lock",
                resp.status,
                &resp.body,
            ))
        }
    }

    async fn renew_session_lock(
        &self,
        owner_ids: &[&str],
        extend_for: Duration,
        idle_timeout: Duration,
    ) -> Result<usize, ProviderError> {
        if owner_ids.is_empty() {
            return Ok(0);
        }

        let now = now_ms();
        let locked_until = now + extend_for.as_millis() as u64;
        let idle_cutoff = now.saturating_sub(idle_timeout.as_millis() as u64);

        // Query all session documents
        let sql = format!("SELECT * FROM c WHERE c.type = '{}'", DOC_TYPE_SESSION);
        let results = self.client().query(&sql, vec![], None).await?;

        let mut count = 0usize;
        for doc in results {
            if let Ok(session) = serde_json::from_value::<SessionDocument>(doc) {
                // Only renew sessions that:
                // 1. Are owned by one of our worker IDs
                // 2. Have not expired yet
                // 3. Have recent activity (not idle)
                if owner_ids.contains(&session.owner_id.as_str())
                    && session.locked_until > now
                    && session.last_activity > idle_cutoff
                {
                    let mut updated = session.clone();
                    updated.locked_until = locked_until;
                    let doc_json = serde_json::to_value(&updated).unwrap();
                    if let Ok(resp) = self
                        .client()
                        .replace_document(
                            &session.id,
                            &session.instance_id,
                            &doc_json,
                            session.etag.as_deref(),
                        )
                        .await
                    {
                        if resp.is_success() {
                            count += 1;
                        }
                    }
                }
            }
        }

        Ok(count)
    }

    async fn cleanup_orphaned_sessions(
        &self,
        _idle_timeout: Duration,
    ) -> Result<usize, ProviderError> {
        let now = now_ms();

        // Query all expired sessions
        let sql = format!(
            "SELECT * FROM c WHERE c.type = '{}' AND c.lockedUntil < @now",
            DOC_TYPE_SESSION
        );
        let params = vec![crate::client::QueryParameter::new(
            "@now",
            serde_json::json!(now),
        )];
        let results = self.client().query(&sql, params, None).await?;

        let mut count = 0usize;
        for doc in results {
            if let Ok(session) = serde_json::from_value::<SessionDocument>(doc) {
                // Check if there are any pending worker queue items for this session
                let check_sql = format!(
                    "SELECT VALUE COUNT(1) FROM c WHERE c.type = '{}' AND c.sessionId = @sid AND c.instanceId = @iid",
                    DOC_TYPE_WORKER_QUEUE
                );
                let check_params = vec![
                    crate::client::QueryParameter::new(
                        "@sid",
                        serde_json::json!(&session.session_id),
                    ),
                    crate::client::QueryParameter::new(
                        "@iid",
                        serde_json::json!(&session.instance_id),
                    ),
                ];
                let worker_count = self
                    .client()
                    .query(&check_sql, check_params, Some(&session.instance_id))
                    .await?;
                let has_items = worker_count
                    .into_iter()
                    .next()
                    .and_then(|v| v.as_u64())
                    .unwrap_or(0)
                    > 0;

                if !has_items {
                    // No pending work items - delete the session
                    let _ = self
                        .client()
                        .delete_document(&session.id, &session.instance_id)
                        .await;
                    count += 1;
                }
            }
        }

        Ok(count)
    }

    async fn abandon_work_item(
        &self,
        token: &str,
        delay: Option<Duration>,
        ignore_attempt: bool,
    ) -> Result<(), ProviderError> {
        let now = now_ms();
        let items =
            query::find_items_by_lock_token(self.client(), token, DOC_TYPE_WORKER_QUEUE).await?;

        for item in &items {
            let mut updated = item.clone();
            updated.lock_token = None;
            updated.locked_until = None;
            if let Some(d) = delay {
                updated.visible_at = now + d.as_millis() as u64;
            }
            if ignore_attempt && updated.attempt_count > 0 {
                updated.attempt_count -= 1;
            }

            let doc_json = serde_json::to_value(&updated).unwrap();
            let _ = self
                .client()
                .replace_document(&item.id, &item.instance_id, &doc_json, item.etag.as_deref())
                .await;
        }

        Ok(())
    }

    async fn renew_orchestration_item_lock(
        &self,
        token: &str,
        extend_for: Duration,
    ) -> Result<(), ProviderError> {
        let now = now_ms();

        // Renew instance lock
        let instance = query::find_instance_by_lock_token(self.client(), token).await?;
        let inst = instance.ok_or_else(|| {
            ProviderError::permanent(
                "renew_orchestration_item_lock",
                format!("No instance found with lock token {token}"),
            )
        })?;

        // Check if expired
        if let Some(locked_until) = inst.locked_until {
            if locked_until <= now {
                return Err(ProviderError::permanent(
                    "renew_orchestration_item_lock",
                    "Lock has expired".to_string(),
                ));
            }
        }

        let mut updated_inst = inst.clone();
        updated_inst.locked_until = Some(now + extend_for.as_millis() as u64);
        let doc_json = serde_json::to_value(&updated_inst).unwrap();
        let resp = self
            .client()
            .replace_document(&inst.id, &inst.instance_id, &doc_json, inst.etag.as_deref())
            .await?;

        if !resp.is_success() {
            return Err(errors::map_cosmosdb_error(
                "renew_orchestration_item_lock",
                resp.status,
                &resp.body,
            ));
        }

        // Renew locks on all tagged queue messages
        let messages =
            query::find_items_by_lock_token(self.client(), token, DOC_TYPE_ORCH_QUEUE).await?;
        for msg in &messages {
            let mut updated = msg.clone();
            updated.locked_until = Some(now + extend_for.as_millis() as u64);
            let doc_json = serde_json::to_value(&updated).unwrap();
            let _ = self
                .client()
                .replace_document(&msg.id, &msg.instance_id, &doc_json, msg.etag.as_deref())
                .await;
        }

        Ok(())
    }

    // ─── Orchestrator queue ──────────────────────────────────────

    async fn enqueue_for_orchestrator(
        &self,
        item: WorkItem,
        delay: Option<Duration>,
    ) -> Result<(), ProviderError> {
        let instance_id = work_item_instance(&item).to_string();
        let item_json = serde_json::to_string(&item).map_err(|e| {
            ProviderError::permanent("enqueue_for_orchestrator", format!("Serialize error: {e}"))
        })?;

        let now = now_ms();
        let visible_at = delay.map(|d| now + d.as_millis() as u64).unwrap_or(now);

        let doc = QueueItemDocument::new_orch_queue(&instance_id, item_json, visible_at, now);
        let doc_json = serde_json::to_value(&doc).unwrap();

        let resp = self
            .client()
            .create_document(&instance_id, &doc_json)
            .await?;
        if !resp.is_success() {
            return Err(errors::map_cosmosdb_error(
                "enqueue_for_orchestrator",
                resp.status,
                &resp.body,
            ));
        }

        Ok(())
    }

    // ─── Management capability ───────────────────────────────────

    fn as_management_capability(&self) -> Option<&dyn ProviderAdmin> {
        Some(self)
    }

    // ─── Custom status ───────────────────────────────────────────

    async fn get_custom_status(
        &self,
        instance: &str,
        last_seen_version: u64,
    ) -> Result<Option<(Option<String>, u64)>, ProviderError> {
        let inst = self.read_instance(instance).await?;
        match inst {
            Some(i) => {
                if i.custom_status_version > last_seen_version {
                    Ok(Some((i.custom_status, i.custom_status_version)))
                } else {
                    Ok(None)
                }
            }
            None => Ok(None),
        }
    }

    async fn get_kv_value(
        &self,
        instance_id: &str,
        key: &str,
    ) -> Result<Option<String>, ProviderError> {
        let delta_doc_id = KeyValueDeltaDocument::doc_id(instance_id, key);
        let delta_resp = self
            .client()
            .read_document(&delta_doc_id, instance_id)
            .await?;

        if delta_resp.is_success() {
            let doc: KeyValueDeltaDocument =
                serde_json::from_str(&delta_resp.body).map_err(|e| {
                    ProviderError::permanent("get_kv_value", format!("Deserialize error: {e}"))
                })?;
            return Ok(doc.value);
        }
        if !errors::is_not_found(delta_resp.status) {
            return Err(errors::map_cosmosdb_error(
                "get_kv_value",
                delta_resp.status,
                &delta_resp.body,
            ));
        }

        let store_doc_id = KeyValueDocument::doc_id(instance_id, key);
        let store_resp = self
            .client()
            .read_document(&store_doc_id, instance_id)
            .await?;

        if errors::is_not_found(store_resp.status) {
            return Ok(None);
        }
        if !store_resp.is_success() {
            return Err(errors::map_cosmosdb_error(
                "get_kv_value",
                store_resp.status,
                &store_resp.body,
            ));
        }

        let doc: KeyValueDocument = serde_json::from_str(&store_resp.body).map_err(|e| {
            ProviderError::permanent("get_kv_value", format!("Deserialize error: {e}"))
        })?;
        Ok(Some(doc.value))
    }

    async fn get_kv_all_values(
        &self,
        instance_id: &str,
    ) -> Result<std::collections::HashMap<String, String>, ProviderError> {
        let mut map: std::collections::HashMap<String, String> = self
            .load_kv_store_documents(instance_id)
            .await?
            .into_iter()
            .map(|doc| (doc.key, doc.value))
            .collect();

        for delta_doc in self.load_kv_delta_documents(instance_id).await? {
            match delta_doc.value {
                Some(value) => {
                    map.insert(delta_doc.key, value);
                }
                None => {
                    map.remove(&delta_doc.key);
                }
            }
        }

        Ok(map)
    }

    async fn get_instance_stats(
        &self,
        instance_id: &str,
    ) -> Result<Option<duroxide::SystemStats>, ProviderError> {
        let inst = match self.read_instance(instance_id).await? {
            Some(inst) => inst,
            None => return Ok(None),
        };

        let history_docs =
            query::query_by_type_in_partition(self.client(), instance_id, DOC_TYPE_HISTORY)
                .await?
                .into_iter()
                .map(|doc| {
                    serde_json::from_value::<HistoryDocument>(doc).map_err(|e| {
                        ProviderError::permanent(
                            "get_instance_stats",
                            format!("Deserialize history document error: {e}"),
                        )
                    })
                })
                .collect::<Result<Vec<_>, _>>()?;

        let (history_event_count, history_size_bytes) = history_docs
            .iter()
            .filter(|doc| doc.execution_id == inst.current_execution_id)
            .fold((0_u64, 0_u64), |(count, size), doc| {
                (count + 1, size + doc.event_data.len() as u64)
            });

        let kv_values = self.get_kv_all_values(instance_id).await?;
        let kv_user_key_count = kv_values.len() as u64;
        let kv_total_value_bytes = kv_values.values().map(|value| value.len() as u64).sum();

        let queue_pending_count = match history_docs
            .iter()
            .find(|doc| doc.execution_id == inst.current_execution_id && doc.event_id == 1)
        {
            Some(doc) => {
                let event = serde_json::from_str::<Event>(&doc.event_data).map_err(|e| {
                    ProviderError::permanent(
                        "get_instance_stats",
                        format!("Failed to deserialize OrchestrationStarted event: {e}"),
                    )
                })?;
                match event.kind {
                    EventKind::OrchestrationStarted {
                        carry_forward_events: Some(events),
                        ..
                    } => events.len() as u64,
                    _ => 0,
                }
            }
            None => 0,
        };

        Ok(Some(duroxide::SystemStats {
            history_event_count,
            history_size_bytes,
            queue_pending_count,
            kv_user_key_count,
            kv_total_value_bytes,
        }))
    }
}

// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// ProviderAdmin trait implementation
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

#[async_trait::async_trait]
impl ProviderAdmin for CosmosDBProvider {
    async fn list_instances(&self) -> Result<Vec<String>, ProviderError> {
        let instances = query::query_instances(self.client(), None).await?;
        Ok(instances.iter().map(|i| i.instance_id.clone()).collect())
    }

    async fn list_instances_by_status(&self, status: &str) -> Result<Vec<String>, ProviderError> {
        let instances = query::query_instances(self.client(), Some(status)).await?;
        Ok(instances.iter().map(|i| i.instance_id.clone()).collect())
    }

    async fn list_executions(&self, instance: &str) -> Result<Vec<u64>, ProviderError> {
        let sql = format!(
            "SELECT DISTINCT VALUE c.executionId FROM c \
             WHERE c.instanceId = @instanceId AND c.type = '{}'",
            DOC_TYPE_HISTORY
        );
        let params = vec![crate::client::QueryParameter::new(
            "@instanceId",
            serde_json::json!(instance),
        )];
        let results = self.client().query(&sql, params, Some(instance)).await?;
        let mut exec_ids: Vec<u64> = results.into_iter().filter_map(|v| v.as_u64()).collect();
        exec_ids.sort();

        if exec_ids.is_empty() {
            // Check if instance exists
            let inst = self.read_instance(instance).await?;
            if let Some(i) = inst {
                exec_ids.push(i.current_execution_id);
            }
        }

        Ok(exec_ids)
    }

    async fn read_history_with_execution_id(
        &self,
        instance: &str,
        execution_id: u64,
    ) -> Result<Vec<Event>, ProviderError> {
        self.read_with_execution(instance, execution_id).await
    }

    async fn read_history(&self, instance: &str) -> Result<Vec<Event>, ProviderError> {
        self.read(instance).await
    }

    async fn latest_execution_id(&self, instance: &str) -> Result<u64, ProviderError> {
        let inst = self.read_instance(instance).await?.ok_or_else(|| {
            ProviderError::permanent(
                "latest_execution_id",
                format!("Instance {instance} not found"),
            )
        })?;
        Ok(inst.current_execution_id)
    }

    async fn get_instance_info(&self, instance: &str) -> Result<InstanceInfo, ProviderError> {
        let inst = self.read_instance(instance).await?.ok_or_else(|| {
            ProviderError::permanent(
                "get_instance_info",
                format!("Instance {instance} not found"),
            )
        })?;

        Ok(InstanceInfo {
            instance_id: inst.instance_id,
            orchestration_name: inst.orchestration_name,
            orchestration_version: inst.orchestration_version,
            current_execution_id: inst.current_execution_id,
            status: inst.status,
            output: inst.output,
            created_at: inst.created_at,
            updated_at: inst.updated_at,
            parent_instance_id: inst.parent_instance_id,
        })
    }

    async fn get_execution_info(
        &self,
        instance: &str,
        execution_id: u64,
    ) -> Result<ExecutionInfo, ProviderError> {
        let events = self.read_with_execution(instance, execution_id).await?;
        let inst = self.read_instance(instance).await?;

        let event_count = events.len();
        let started_at = inst.as_ref().map(|i| i.created_at).unwrap_or(0);

        let status = if let Some(i) = &inst {
            if i.current_execution_id == execution_id {
                i.status.clone()
            } else {
                "ContinuedAsNew".to_string()
            }
        } else {
            "Unknown".to_string()
        };

        let completed_at = if status == "Running" {
            None
        } else {
            inst.as_ref().map(|i| i.updated_at)
        };

        Ok(ExecutionInfo {
            execution_id,
            status,
            output: inst.and_then(|i| i.output),
            started_at,
            completed_at,
            event_count,
        })
    }

    async fn get_system_metrics(&self) -> Result<SystemMetrics, ProviderError> {
        let instances = query::query_instances(self.client(), None).await?;

        let total = instances.len() as u64;
        let running = instances.iter().filter(|i| i.status == "Running").count() as u64;
        let completed = instances.iter().filter(|i| i.status == "Completed").count() as u64;
        let failed = instances.iter().filter(|i| i.status == "Failed").count() as u64;

        // Count executions and events
        let total_events =
            query::count_by_type(self.client(), DOC_TYPE_HISTORY, None).await? as u64;

        Ok(SystemMetrics {
            total_instances: total,
            total_executions: total, // Approximation — each instance has at least 1
            running_instances: running,
            completed_instances: completed,
            failed_instances: failed,
            total_events,
        })
    }

    async fn get_queue_depths(&self) -> Result<QueueDepths, ProviderError> {
        let now = now_ms();
        let now_filter = format!("c.visibleAt <= {now} AND (NOT IS_DEFINED(c.lockedUntil) OR c.lockedUntil = null OR c.lockedUntil <= {now})");

        let orch =
            query::count_by_type(self.client(), DOC_TYPE_ORCH_QUEUE, Some(&now_filter)).await?;

        let worker =
            query::count_by_type(self.client(), DOC_TYPE_WORKER_QUEUE, Some(&now_filter)).await?;

        // Timer queue: orch queue items with visibleAt > now
        let timer_filter = format!("c.visibleAt > {now}");
        let timer =
            query::count_by_type(self.client(), DOC_TYPE_ORCH_QUEUE, Some(&timer_filter)).await?;

        Ok(QueueDepths {
            orchestrator_queue: orch,
            worker_queue: worker,
            timer_queue: timer,
        })
    }

    async fn list_children(&self, instance_id: &str) -> Result<Vec<String>, ProviderError> {
        let sql = format!(
            "SELECT c.instanceId FROM c WHERE c.type = '{}' AND c.parentInstanceId = @parentId",
            DOC_TYPE_INSTANCE
        );
        let params = vec![crate::client::QueryParameter::new(
            "@parentId",
            serde_json::json!(instance_id),
        )];
        let results = self.client().query(&sql, params, None).await?;
        Ok(results
            .into_iter()
            .filter_map(|v| {
                v.get("instanceId")
                    .and_then(|id| id.as_str())
                    .map(|s| s.to_string())
            })
            .collect())
    }

    async fn get_parent_id(&self, instance_id: &str) -> Result<Option<String>, ProviderError> {
        let inst = self.read_instance(instance_id).await?.ok_or_else(|| {
            ProviderError::permanent("get_parent_id", format!("Instance {instance_id} not found"))
        })?;
        Ok(inst.parent_instance_id)
    }

    async fn delete_instances_atomic(
        &self,
        ids: &[String],
        force: bool,
    ) -> Result<DeleteInstanceResult, ProviderError> {
        if ids.is_empty() {
            return Ok(DeleteInstanceResult::default());
        }

        // Phase 1: Pre-checks (before any mutations)
        // Check running status for all instances
        if !force {
            for id in ids {
                if let Some(inst) = self.read_instance(id).await? {
                    if inst.status == "Running" {
                        return Err(ProviderError::permanent(
                            "delete_instances_atomic",
                            format!("Instance {id} is still running. Use force=true to delete anyway, or cancel first."),
                        ));
                    }
                }
            }
        }

        // Orphan detection: check if any instance not in our delete set
        // has a parent in our delete set
        let id_set: std::collections::HashSet<&String> = ids.iter().collect();
        for id in ids {
            let children = self.list_children(id).await.unwrap_or_default();
            for child in &children {
                if !id_set.contains(child) {
                    return Err(ProviderError::permanent(
                        "delete_instances_atomic",
                        format!(
                            "Cannot delete: instance {id} has child {child} that was created after tree traversal. \
                             Re-fetch the tree and retry."
                        ),
                    ));
                }
            }
        }

        // Phase 2: Count resources and delete
        let mut result = DeleteInstanceResult::default();

        for id in ids {
            // Count events in this partition
            let history_filter = format!("c.instanceId = '{id}'");
            let events_count =
                query::count_by_type(self.client(), DOC_TYPE_HISTORY, Some(&history_filter))
                    .await
                    .unwrap_or(0) as u64;

            let orch_q_count =
                query::count_by_type(self.client(), DOC_TYPE_ORCH_QUEUE, Some(&history_filter))
                    .await
                    .unwrap_or(0) as u64;

            let worker_q_count =
                query::count_by_type(self.client(), DOC_TYPE_WORKER_QUEUE, Some(&history_filter))
                    .await
                    .unwrap_or(0) as u64;

            // Count distinct execution IDs
            let exec_count = if self.read_instance(id).await?.is_some() {
                1u64
            } else {
                0u64
            };

            // Get all documents in this partition and delete them
            let docs = query::query_all_in_partition(self.client(), id).await?;
            for doc in &docs {
                if let Some(doc_id) = doc.get("id").and_then(|v| v.as_str()) {
                    let _ = self.client().delete_document(doc_id, id).await;
                }
            }

            result.instances_deleted += 1;
            result.executions_deleted += exec_count;
            result.events_deleted += events_count;
            result.queue_messages_deleted += orch_q_count + worker_q_count;
        }

        Ok(result)
    }

    async fn delete_instance_bulk(
        &self,
        filter: InstanceFilter,
    ) -> Result<DeleteInstanceResult, ProviderError> {
        // Find eligible instances: root instances (no parent) in terminal states
        let all_instances = query::query_instances(self.client(), None).await?;

        let mut candidates: Vec<InstanceDocument> = all_instances
            .into_iter()
            .filter(|inst| {
                // Only root instances (no parent)
                inst.parent_instance_id.is_none()
                // Only terminal states
                && (inst.status == "Completed" || inst.status == "Failed" || inst.status == "ContinuedAsNew")
            })
            .collect();

        // Apply instance_ids filter if provided
        if let Some(ref ids) = filter.instance_ids {
            if ids.is_empty() {
                return Ok(DeleteInstanceResult::default());
            }
            candidates.retain(|inst| ids.contains(&inst.instance_id));
        }

        // Apply completed_before filter
        if let Some(before) = filter.completed_before {
            candidates.retain(|inst| inst.updated_at < before);
        }

        // Apply limit
        let limit = filter.limit.unwrap_or(1000) as usize;
        candidates.truncate(limit);

        if candidates.is_empty() {
            return Ok(DeleteInstanceResult::default());
        }

        // Delete each instance (with cascade) using get_instance_tree
        let mut result = DeleteInstanceResult::default();
        for inst in &candidates {
            let tree = self.get_instance_tree(&inst.instance_id).await?;
            let delete_result = self.delete_instances_atomic(&tree.all_ids, true).await?;
            result.instances_deleted += delete_result.instances_deleted;
            result.executions_deleted += delete_result.executions_deleted;
            result.events_deleted += delete_result.events_deleted;
            result.queue_messages_deleted += delete_result.queue_messages_deleted;
        }

        Ok(result)
    }

    async fn prune_executions(
        &self,
        instance_id: &str,
        options: PruneOptions,
    ) -> Result<PruneResult, ProviderError> {
        let inst = self.read_instance(instance_id).await?.ok_or_else(|| {
            ProviderError::permanent(
                "prune_executions",
                format!("Instance {instance_id} not found"),
            )
        })?;

        let current_exec = inst.current_execution_id;
        let mut all_execs = self.list_executions(instance_id).await?;
        all_execs.sort();

        // Determine which executions to prune:
        // 1. Never prune the current execution
        // 2. Never prune running executions (current is always running if status == Running)
        // 3. keep_last: keep the top N executions (by execution_id), prune the rest
        //    (current is always in the top N since it's the highest)
        let mut protected: std::collections::HashSet<u64> = std::collections::HashSet::new();
        protected.insert(current_exec);

        if let Some(keep_last) = options.keep_last {
            let keep = keep_last as usize;
            // Keep the top N by execution_id (highest N)
            let skip = all_execs.len().saturating_sub(keep);
            for &exec_id in &all_execs[skip..] {
                protected.insert(exec_id);
            }
        }

        let to_prune: Vec<u64> = all_execs
            .into_iter()
            .filter(|e| !protected.contains(e))
            .collect();

        let mut events_deleted = 0u64;
        let mut execs_deleted = 0u64;

        for exec_id in &to_prune {
            let docs = query::fetch_history(self.client(), instance_id, *exec_id).await?;
            for doc in &docs {
                let _ = self.client().delete_document(&doc.id, instance_id).await;
                events_deleted += 1;
            }

            // KV entries are instance-scoped and must survive execution pruning.

            execs_deleted += 1;
        }

        Ok(PruneResult {
            instances_processed: 1,
            executions_deleted: execs_deleted,
            events_deleted,
        })
    }

    async fn prune_executions_bulk(
        &self,
        filter: InstanceFilter,
        options: PruneOptions,
    ) -> Result<PruneResult, ProviderError> {
        let instances = if let Some(ids) = &filter.instance_ids {
            ids.clone()
        } else {
            self.list_instances().await?
        };

        let mut total = PruneResult::default();
        for id in &instances {
            match self.prune_executions(id, options.clone()).await {
                Ok(r) => {
                    total.instances_processed += r.instances_processed;
                    total.executions_deleted += r.executions_deleted;
                    total.events_deleted += r.events_deleted;
                }
                Err(_) => continue,
            }
        }

        Ok(total)
    }
}