clickhouse-cloud-api 0.2.1

Typed Rust client for the ClickHouse Cloud API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
mod common;

use clickhouse_cloud_api::models::*;
use clickhouse_cloud_api::Client;
use common::support::*;

#[tokio::test]
#[ignore = "requires live ClickHouse Cloud credentials and provisions real resources"]
async fn cloud_service_crud_lifecycle() -> TestResult<()> {
    let ctx = TestContext::from_env()?;
    let client = create_client()?;
    let mut cleanup = CleanupRegistry::default();

    let test_result = async {
        log_run_header("cloud_service_crud_lifecycle", &ctx);
        let mut failures = FailureRecorder::default();
        let base_memory_gb = 8.0_f64;
        let scaled_memory_gb = 16.0_f64;
        // The deprecated `instance_scaling_update` endpoint validates
        // `minTotalMemoryGb`/`maxTotalMemoryGb` as multiples of 12, unlike
        // the modern `instance_replica_scaling_update` endpoint which
        // accepts multiples of 4. Use a dedicated pair of values for the
        // deprecated round-trip to satisfy that constraint.
        let deprecated_base_total_memory_gb = 12.0_f64;
        let deprecated_scaled_total_memory_gb = 24.0_f64;
        let base_replicas = 1.0_f64;
        let scaled_replicas = 3.0_f64;
        let primary_ip = "203.0.113.10/32";
        let secondary_ip = "203.0.113.11/32";

        // ── Org Checks ──────────────────────────────────────────────

        log_phase("Org Checks");
        let org = failures
            .run(&ctx, StepKind::Blocking, "verify org access", || {
                let client = client.clone();
                let org_id = ctx.org_id.clone();
                async move {
                    let resp = client.organization_get(&org_id).await?;
                    resp.result.ok_or_else(|| "org get returned no result".into())
                }
            })
            .await?
            .expect("blocking steps always return a value");
        assert_eq!(org.id.to_string(), ctx.org_id);
        let current_org_name = org.name.clone();

        let org_list = failures
            .run(
                &ctx,
                StepKind::Blocking,
                "verify org list includes target org",
                || {
                    let client = client.clone();
                    async move {
                        let resp = client.organization_get_list().await?;
                        resp.result.ok_or_else(|| "org list returned no result".into())
                    }
                },
            )
            .await?
            .expect("blocking steps always return a value");
        assert!(
            org_list
                .iter()
                .any(|o| o.id.to_string() == ctx.org_id),
            "org list did not include target org {}",
            ctx.org_id
        );

        failures
            .run(&ctx, StepKind::NonBlocking, "idempotent org update", || {
                let client = client.clone();
                let org_id = ctx.org_id.clone();
                let name = current_org_name.clone();
                async move {
                    let resp = client
                        .organization_update(
                            &org_id,
                            &OrganizationPatchRequest {
                                name: Some(name),
                                ..Default::default()
                            },
                        )
                        .await?;
                    let updated = resp.result.ok_or("org update returned no result")?;
                    let updated_id = updated.id.to_string();
                    if updated_id != org_id {
                        return Err(
                            format!("org update returned unexpected org id {updated_id}").into()
                        );
                    }
                    Ok(())
                }
            })
            .await?;

        failures
            .run(&ctx, StepKind::NonBlocking, "org usage", || {
                let client = client.clone();
                let org_id = ctx.org_id.clone();
                async move {
                    let resp = client
                        .usage_cost_get(&org_id, "2025-01-01", "2025-01-31", &[])
                        .await?;
                    if resp.result.is_none() {
                        return Err("org usage returned no result".into());
                    }
                    Ok(())
                }
            })
            .await?;

        // ── 1. Provision ─────────────────────────────────────────────

        log_phase("Provision Service");

        let list_before = failures
            .run(
                &ctx,
                StepKind::Blocking,
                "check for leftover tagged services",
                || {
                    let client = client.clone();
                    let org_id = ctx.org_id.clone();
                    let filters = ctx.run_tag_filters();
                    async move {
                        let filter_refs: Vec<&str> = filters.iter().map(|s| s.as_str()).collect();
                        let resp = client.instance_get_list(&org_id, &filter_refs).await?;
                        resp.result
                            .ok_or_else(|| "service list returned no result".into())
                    }
                },
            )
            .await?
            .expect("blocking steps always return a value");
        assert!(
            list_before.is_empty(),
            "found an existing tagged test service for this run id before create"
        );

        let create_body = ServicePostRequest {
            name: ctx.service_name(),
            provider: ServicePostRequestProvider::Unknown(ctx.provider.clone()),
            region: ServicePostRequestRegion::Unknown(ctx.region.clone()),
            min_replica_memory_gb: Some(base_memory_gb),
            max_replica_memory_gb: Some(base_memory_gb),
            num_replicas: Some(base_replicas),
            idle_scaling: Some(true),
            idle_timeout_minutes: Some(5.0),
            tags: Some(ctx.run_tags()),
            ..Default::default()
        };

        let created = failures
            .run(&ctx, StepKind::Blocking, "create service", || {
                let client = client.clone();
                let org_id = ctx.org_id.clone();
                let body = create_body.clone();
                async move {
                    let resp = client.instance_create(&org_id, &body).await?;
                    resp.result
                        .ok_or_else(|| "service create returned no result".into())
                }
            })
            .await?
            .expect("blocking steps always return a value");

        let service = &created.service;
        let service_id = service.id.to_string();
        let _password = created.password.clone();
        eprintln!("service_id: <redacted>");
        cleanup.register_service(service_id.clone());

        let ready = failures
            .run(
                &ctx,
                StepKind::Blocking,
                "wait for service steady state",
                || {
                    let client = client.clone();
                    let org_id = ctx.org_id.clone();
                    let service_id = service_id.clone();
                    async move {
                        poll_until(
                            "service steady state",
                            ctx.steady_state_timeout,
                            ctx.poll_interval,
                            || {
                                let client = client.clone();
                                let org_id = org_id.clone();
                                let service_id = service_id.clone();
                                async move {
                                    let resp =
                                        client.instance_get(&org_id, &service_id).await?;
                                    let svc = resp.result.ok_or("service get returned no result")?;
                                    let state = svc.state.to_string();
                                    if matches!(state.as_str(), "running" | "idle") {
                                        Ok(Some(svc))
                                    } else {
                                        Ok(None)
                                    }
                                }
                            },
                        )
                        .await
                    }
                },
            )
            .await?
            .expect("blocking steps always return a value");

        assert_eq!(ready.name, ctx.service_name());
        assert_eq!(ready.min_replica_memory_gb, base_memory_gb);
        assert_eq!(ready.max_replica_memory_gb, base_memory_gb);
        assert_eq!(ready.num_replicas, base_replicas);

        let listed = failures
            .run(
                &ctx,
                StepKind::Blocking,
                "verify service is discoverable in list",
                || {
                    let client = client.clone();
                    let org_id = ctx.org_id.clone();
                    let filters = ctx.run_tag_filters();
                    async move {
                        let filter_refs: Vec<&str> = filters.iter().map(|s| s.as_str()).collect();
                        let resp = client.instance_get_list(&org_id, &filter_refs).await?;
                        resp.result
                            .ok_or_else(|| "service list returned no result".into())
                    }
                },
            )
            .await?
            .expect("blocking steps always return a value");
        assert!(
            listed
                .iter()
                .any(|s| s.id.to_string() == service_id),
            "created service was not visible in service list"
        );

        // ── 2. Query API Endpoint ────────────────────────────────────
        //
        // Exercise the path that `cloud service query` uses: create a
        // dedicated API key, bind it to the service's query endpoint with
        // role `sql_console_admin`, run `SELECT 1` over HTTP via
        // queries.clickhouse.cloud, and assert the result.

        log_phase("Query API Endpoint");

        let query_key = failures
            .run(&ctx, StepKind::Blocking, "create query API key", || {
                let client = client.clone();
                let org_id = ctx.org_id.clone();
                let key_name = format!("{}-query", ctx.service_name());
                async move {
                    let body = ApiKeyPostRequest {
                        name: key_name,
                        assigned_role_ids: vec![],
                        expire_at: None,
                        hash_data: None,
                        ip_access_list: vec![IpAccessListEntry {
                            source: "0.0.0.0/0".to_string(),
                            description: Some(
                                "clickhousectl integration test query key".to_string(),
                            ),
                        }],
                        roles: None,
                        state: ApiKeyPostRequestState::Enabled,
                    };
                    let resp = client.openapi_key_create(&org_id, &body).await?;
                    resp.result
                        .ok_or_else(|| "api key create returned no result".into())
                }
            })
            .await?
            .expect("blocking steps always return a value");
        // `query_key.key_id` is the credential id used for HTTP auth on the
        // query endpoint. Management endpoints (GET/DELETE /keys/{id}) and the
        // endpoint binding's `openApiKeys` array reference the API key's
        // resource UUID instead — `query_key.key.id`.
        let api_key_uuid = query_key.key.id.to_string();
        cleanup.register_api_key(api_key_uuid.clone());

        // Before binding the key to a query endpoint, calling the Query API
        // must fail. We don't pin the exact status (the control plane can
        // return 401/403/404 here depending on which check trips first); we
        // just require a 4xx so the test catches the regression where the
        // endpoint silently works without a binding.
        failures
            .run(
                &ctx,
                StepKind::Blocking,
                "query before endpoint enabled fails",
                || {
                    let client = client.clone();
                    let service_id = service_id.clone();
                    let key_id = query_key.key_id.clone();
                    let key_secret = query_key.key_secret.clone();
                    async move {
                        match client
                            .run_query(
                                &service_id,
                                &key_id,
                                &key_secret,
                                "SELECT 1",
                                None,
                                "TabSeparated",
                            )
                            .await
                        {
                            Ok(response) => {
                                let status = response.status();
                                let body = response.text().await.unwrap_or_default();
                                Err(format!(
                                    "expected 4xx before endpoint enabled, got {status}: {}",
                                    body.trim()
                                )
                                .into())
                            }
                            Err(clickhouse_cloud_api::Error::Api { status, message })
                                if (400..500).contains(&status) =>
                            {
                                eprintln!(
                                    "  query without endpoint correctly rejected: {status}: {message}"
                                );
                                Ok(())
                            }
                            Err(e) => Err(format!(
                                "expected 4xx before endpoint enabled, got unexpected error: {e}"
                            )
                            .into()),
                        }
                    }
                },
            )
            .await?;

        let initial_endpoint = failures
            .run(
                &ctx,
                StepKind::Blocking,
                "upsert query endpoint with admin role",
                || {
                    let client = client.clone();
                    let org_id = ctx.org_id.clone();
                    let service_id = service_id.clone();
                    let api_key_uuid = api_key_uuid.clone();
                    async move {
                        let body = InstanceServiceQueryApiEndpointsPostRequest {
                            roles: vec!["sql_console_admin".to_string()],
                            open_api_keys: vec![api_key_uuid],
                            allowed_origins: "*".to_string(),
                        };
                        let resp = client
                            .instance_query_endpoint_upsert(&org_id, &service_id, &body)
                            .await?;
                        resp.result
                            .ok_or_else(|| "query endpoint upsert returned no result".into())
                    }
                },
            )
            .await?
            .expect("blocking steps always return a value");
        // Register the binding for cleanup BEFORE doing anything else with it.
        // The registry deletes query endpoints before API keys, so a panic
        // mid-phase still leaves the org tidy.
        cleanup.register_query_endpoint(service_id.clone());

        // GET the binding back and assert it matches the upsert. Catches
        // regressions where the control plane stores something different from
        // what we sent (roles silently demoted, openApiKeys dropped, etc).
        failures
            .run(
                &ctx,
                StepKind::NonBlocking,
                "get query endpoint matches upsert",
                || {
                    let client = client.clone();
                    let org_id = ctx.org_id.clone();
                    let service_id = service_id.clone();
                    let api_key_uuid = api_key_uuid.clone();
                    let initial_endpoint = initial_endpoint.clone();
                    async move {
                        let resp = client
                            .instance_query_endpoint_get(&org_id, &service_id)
                            .await?;
                        let endpoint = resp
                            .result
                            .ok_or("query endpoint get returned no result")?;
                        if endpoint.id != initial_endpoint.id {
                            return Err(format!(
                                "get returned different endpoint id: {} (upsert) vs {} (get)",
                                initial_endpoint.id, endpoint.id
                            )
                            .into());
                        }
                        if !endpoint.roles.iter().any(|r| r == "sql_console_admin") {
                            return Err(format!(
                                "get missing sql_console_admin role: {:?}",
                                endpoint.roles
                            )
                            .into());
                        }
                        if !endpoint.open_api_keys.contains(&api_key_uuid) {
                            return Err(format!(
                                "get missing our key from openApiKeys: {:?}",
                                endpoint.open_api_keys
                            )
                            .into());
                        }
                        if endpoint.allowed_origins != "*" {
                            return Err(format!(
                                "get returned unexpected allowedOrigins: {:?}",
                                endpoint.allowed_origins
                            )
                            .into());
                        }
                        Ok(())
                    }
                },
            )
            .await?;

        // Endpoint propagation can lag a few seconds behind the upsert; poll
        // for the first successful query rather than asserting on the first
        // try.
        failures
            .run(&ctx, StepKind::Blocking, "run SELECT 1 via Query API", || {
                let client = client.clone();
                let service_id = service_id.clone();
                let key_id = query_key.key_id.clone();
                let key_secret = query_key.key_secret.clone();
                async move {
                    poll_until(
                        "query API SELECT 1",
                        std::time::Duration::from_secs(120),
                        std::time::Duration::from_secs(5),
                        || {
                            let client = client.clone();
                            let service_id = service_id.clone();
                            let key_id = key_id.clone();
                            let key_secret = key_secret.clone();
                            async move {
                                match client
                                    .run_query(
                                        &service_id,
                                        &key_id,
                                        &key_secret,
                                        "SELECT 1",
                                        None,
                                        "TabSeparated",
                                    )
                                    .await
                                {
                                    Ok(response) => {
                                        let body = response.text().await.map_err(|e| {
                                            format!("query response read failed: {e}")
                                        })?;
                                        let trimmed = body.trim();
                                        if trimmed == "1" {
                                            Ok(Some(()))
                                        } else {
                                            Err(format!(
                                                "unexpected query response: {trimmed:?}"
                                            )
                                            .into())
                                        }
                                    }
                                    Err(clickhouse_cloud_api::Error::Api {
                                        status, message,
                                    }) if status == 401 || status == 403 || status == 404 => {
                                        // Propagation delay — keep polling.
                                        eprintln!(
                                            "  query endpoint not ready yet ({status}): {message}"
                                        );
                                        Ok(None)
                                    }
                                    Err(e) => Err(e.into()),
                                }
                            }
                        },
                    )
                    .await
                }
            })
            .await?;

        // The query endpoint binding uses `sql_console_admin`, so the key
        // must be able to write — `cloud service query` is the canonical
        // path for INSERTs and DDL, not just SELECT. Walk through
        // CREATE TABLE / INSERT / SELECT to catch regressions where the
        // role on the binding is silently demoted to read-only.
        failures
            .run(
                &ctx,
                StepKind::Blocking,
                "CREATE TABLE + INSERT + SELECT via Query API",
                || {
                    let client = client.clone();
                    let service_id = service_id.clone();
                    let key_id = query_key.key_id.clone();
                    let key_secret = query_key.key_secret.clone();
                    async move {
                        async fn exec(
                            client: &clickhouse_cloud_api::Client,
                            service_id: &str,
                            key_id: &str,
                            key_secret: &str,
                            sql: &str,
                        ) -> Result<String, Box<dyn std::error::Error>> {
                            let response = client
                                .run_query(
                                    service_id,
                                    key_id,
                                    key_secret,
                                    sql,
                                    None,
                                    "TabSeparated",
                                )
                                .await?;
                            response
                                .text()
                                .await
                                .map_err(|e| format!("query response read failed: {e}").into())
                        }

                        exec(
                            &client,
                            &service_id,
                            &key_id,
                            &key_secret,
                            "CREATE TABLE clickhousectl_it_write (x UInt32) ENGINE = MergeTree ORDER BY x",
                        )
                        .await
                        .map_err(|e| -> Box<dyn std::error::Error> {
                            format!("CREATE TABLE failed (role may not grant writes): {e}").into()
                        })?;
                        exec(
                            &client,
                            &service_id,
                            &key_id,
                            &key_secret,
                            "INSERT INTO clickhousectl_it_write VALUES (1), (2), (3)",
                        )
                        .await
                        .map_err(|e| -> Box<dyn std::error::Error> {
                            format!("INSERT failed: {e}").into()
                        })?;
                        let body = exec(
                            &client,
                            &service_id,
                            &key_id,
                            &key_secret,
                            "SELECT sum(x) FROM clickhousectl_it_write",
                        )
                        .await?;
                        let trimmed = body.trim();
                        if trimmed != "6" {
                            return Err(format!(
                                "unexpected sum after INSERT: got {trimmed:?}, expected \"6\""
                            )
                            .into());
                        }
                        // Tidy up: the service is about to be deleted anyway,
                        // but leaving artifacts behind makes debugging harder
                        // if cleanup ever short-circuits.
                        exec(
                            &client,
                            &service_id,
                            &key_id,
                            &key_secret,
                            "DROP TABLE clickhousectl_it_write",
                        )
                        .await?;
                        Ok(())
                    }
                },
            )
            .await?;

        // Re-upserting the same endpoint must be idempotent: the resource id
        // should not change, and the existing credentials should keep working.
        // Catches regressions where the control plane rotates the binding or
        // strips `openApiKeys` on a no-op write.
        failures
            .run(
                &ctx,
                StepKind::Blocking,
                "re-upsert query endpoint is idempotent",
                || {
                    let client = client.clone();
                    let org_id = ctx.org_id.clone();
                    let service_id = service_id.clone();
                    let api_key_uuid = api_key_uuid.clone();
                    let initial_endpoint = initial_endpoint.clone();
                    async move {
                        let body = InstanceServiceQueryApiEndpointsPostRequest {
                            roles: vec!["sql_console_admin".to_string()],
                            open_api_keys: vec![api_key_uuid.clone()],
                            allowed_origins: "*".to_string(),
                        };
                        let resp = client
                            .instance_query_endpoint_upsert(&org_id, &service_id, &body)
                            .await?;
                        let endpoint = resp
                            .result
                            .ok_or("re-upsert returned no result")?;
                        if endpoint.id != initial_endpoint.id {
                            return Err(format!(
                                "re-upsert changed endpoint id: {} -> {}",
                                initial_endpoint.id, endpoint.id
                            )
                            .into());
                        }
                        if !endpoint.open_api_keys.contains(&api_key_uuid) {
                            return Err(format!(
                                "re-upsert dropped our key from openApiKeys: {:?}",
                                endpoint.open_api_keys
                            )
                            .into());
                        }
                        if !endpoint.roles.iter().any(|r| r == "sql_console_admin") {
                            return Err(format!(
                                "re-upsert dropped sql_console_admin role: {:?}",
                                endpoint.roles
                            )
                            .into());
                        }
                        Ok(())
                    }
                },
            )
            .await?;

        failures
            .run(
                &ctx,
                StepKind::Blocking,
                "SELECT 1 still works after re-upsert",
                || {
                    let client = client.clone();
                    let service_id = service_id.clone();
                    let key_id = query_key.key_id.clone();
                    let key_secret = query_key.key_secret.clone();
                    async move {
                        let response = client
                            .run_query(
                                &service_id,
                                &key_id,
                                &key_secret,
                                "SELECT 1",
                                None,
                                "TabSeparated",
                            )
                            .await?;
                        let body = response
                            .text()
                            .await
                            .map_err(|e| format!("query response read failed: {e}"))?;
                        let trimmed = body.trim();
                        if trimmed == "1" {
                            Ok(())
                        } else {
                            Err(format!(
                                "unexpected query response after re-upsert: {trimmed:?}"
                            )
                            .into())
                        }
                    }
                },
            )
            .await?;

        // Delete the binding BEFORE the API key so we can distinguish
        // "binding cleanup works" from "API key was already gone."
        failures
            .run(&ctx, StepKind::NonBlocking, "delete query endpoint", || {
                let client = client.clone();
                let org_id = ctx.org_id.clone();
                let service_id = service_id.clone();
                async move {
                    client
                        .instance_query_endpoint_delete(&org_id, &service_id)
                        .await?;
                    Ok(())
                }
            })
            .await?;
        cleanup.unregister_query_endpoint(&service_id);

        // GET must now report the binding is gone. The control plane returns
        // 404 once the binding is deleted; accept any 4xx in case the exact
        // status drifts, but require an error rather than a stale 200.
        failures
            .run(
                &ctx,
                StepKind::NonBlocking,
                "get query endpoint after delete returns 4xx",
                || {
                    let client = client.clone();
                    let org_id = ctx.org_id.clone();
                    let service_id = service_id.clone();
                    async move {
                        match client
                            .instance_query_endpoint_get(&org_id, &service_id)
                            .await
                        {
                            Ok(resp) => {
                                Err(format!(
                                    "expected 4xx after delete, got 200 with result: {:?}",
                                    resp.result
                                )
                                .into())
                            }
                            Err(clickhouse_cloud_api::Error::Api { status, message })
                                if (400..500).contains(&status) =>
                            {
                                eprintln!(
                                    "  query endpoint correctly absent after delete: {status}: {message}"
                                );
                                Ok(())
                            }
                            Err(e) => Err(format!(
                                "expected 4xx after delete, got unexpected error: {e}"
                            )
                            .into()),
                        }
                    }
                },
            )
            .await?;

        failures
            .run(&ctx, StepKind::Blocking, "delete query API key", || {
                let client = client.clone();
                let org_id = ctx.org_id.clone();
                let api_key_uuid = api_key_uuid.clone();
                async move {
                    client.openapi_key_delete(&org_id, &api_key_uuid).await?;
                    Ok(())
                }
            })
            .await?;
        cleanup.unregister_api_key(&api_key_uuid);

        // ── 3. Stop / Start ──────────────────────────────────────────

        log_phase("Stop And Start");
        failures
            .run(&ctx, StepKind::Blocking, "stop service", || {
                let client = client.clone();
                let org_id = ctx.org_id.clone();
                let service_id = service_id.clone();
                let timeout = ctx.create_timeout;
                let interval = ctx.poll_interval;
                async move {
                    client
                        .instance_state_update(
                            &org_id,
                            &service_id,
                            &ServiceStatePatchRequest {
                                command: Some(ServiceStatePatchRequestCommand::Stop),
                            },
                        )
                        .await?;
                    poll_until("service stopped", timeout, interval, || {
                        let client = client.clone();
                        let org_id = org_id.clone();
                        let service_id = service_id.clone();
                        async move {
                            let resp = client.instance_get(&org_id, &service_id).await?;
                            let svc = resp.result.ok_or("service get returned no result")?;
                            let state = svc.state.to_string();
                            if matches!(state.as_str(), "idle" | "stopped") {
                                Ok(Some(()))
                            } else {
                                Ok(None)
                            }
                        }
                    })
                    .await?;
                    Ok(())
                }
            })
            .await?;

        failures
            .run(&ctx, StepKind::Blocking, "start service", || {
                let client = client.clone();
                let org_id = ctx.org_id.clone();
                let service_id = service_id.clone();
                let timeout = ctx.steady_state_timeout;
                let interval = ctx.poll_interval;
                async move {
                    client
                        .instance_state_update(
                            &org_id,
                            &service_id,
                            &ServiceStatePatchRequest {
                                command: Some(ServiceStatePatchRequestCommand::Start),
                            },
                        )
                        .await?;
                    poll_until("service restarted", timeout, interval, || {
                        let client = client.clone();
                        let org_id = org_id.clone();
                        let service_id = service_id.clone();
                        async move {
                            let resp = client.instance_get(&org_id, &service_id).await?;
                            let svc = resp.result.ok_or("service get returned no result")?;
                            let state = svc.state.to_string();
                            if matches!(state.as_str(), "running" | "idle") {
                                Ok(Some(()))
                            } else {
                                Ok(None)
                            }
                        }
                    })
                    .await?;
                    Ok(())
                }
            })
            .await?;

        // ── 4. Rename & Settings ─────────────────────────────────────

        log_phase("Rename And Settings");
        failures
            .run(&ctx, StepKind::Blocking, "rename service", || {
                let client = client.clone();
                let org_id = ctx.org_id.clone();
                let service_id = service_id.clone();
                let new_name = ctx.updated_service_name();
                async move {
                    client
                        .instance_update(
                            &org_id,
                            &service_id,
                            &ServicePatchRequest {
                                name: Some(new_name),
                                ..Default::default()
                            },
                        )
                        .await?;
                    Ok(())
                }
            })
            .await?;

        let updated = failures
            .run(
                &ctx,
                StepKind::Blocking,
                "wait for rename visibility in get",
                || {
                    let client = client.clone();
                    let org_id = ctx.org_id.clone();
                    let service_id = service_id.clone();
                    let expected_name = ctx.updated_service_name();
                    let timeout = ctx.create_timeout;
                    let interval = ctx.poll_interval;
                    async move {
                        poll_until("service rename visibility in get", timeout, interval, || {
                            let client = client.clone();
                            let org_id = org_id.clone();
                            let service_id = service_id.clone();
                            let expected_name = expected_name.clone();
                            async move {
                                let resp = client.instance_get(&org_id, &service_id).await?;
                                let svc =
                                    resp.result.ok_or("service get returned no result")?;
                                if svc.name == expected_name {
                                    Ok(Some(svc))
                                } else {
                                    Ok(None)
                                }
                            }
                        })
                        .await
                    }
                },
            )
            .await?
            .expect("blocking steps always return a value");
        assert_eq!(updated.name, ctx.updated_service_name());

        let renamed_list = failures
            .run(
                &ctx,
                StepKind::Blocking,
                "verify rename is visible in list",
                || {
                    let client = client.clone();
                    let org_id = ctx.org_id.clone();
                    let service_id = service_id.clone();
                    let expected_name = ctx.updated_service_name();
                    let filters = ctx.run_tag_filters();
                    let timeout = ctx.create_timeout;
                    let interval = ctx.poll_interval;
                    async move {
                        poll_until("service rename visibility in list", timeout, interval, || {
                            let client = client.clone();
                            let org_id = org_id.clone();
                            let service_id = service_id.clone();
                            let expected_name = expected_name.clone();
                            let filters = filters.clone();
                            async move {
                                let filter_refs: Vec<&str> =
                                    filters.iter().map(|s| s.as_str()).collect();
                                let resp =
                                    client.instance_get_list(&org_id, &filter_refs).await?;
                                let services = resp
                                    .result
                                    .ok_or("service list returned no result")?;
                                let found = services.iter().find(|s| {
                                    s.id.to_string() == service_id
                                });
                                if found.is_some_and(|s| s.name == expected_name) {
                                    Ok(Some(services))
                                } else {
                                    Ok(None)
                                }
                            }
                        })
                        .await
                    }
                },
            )
            .await?
            .expect("blocking steps always return a value");
        let renamed_svc = renamed_list
            .iter()
            .find(|s| s.id.to_string() == service_id);
        assert_eq!(
            renamed_svc.map(|s| s.name.as_str()),
            Some(ctx.updated_service_name().as_str())
        );

        failures
            .run(&ctx, StepKind::NonBlocking, "idempotent rename", || {
                let client = client.clone();
                let org_id = ctx.org_id.clone();
                let service_id = service_id.clone();
                let name = ctx.updated_service_name();
                async move {
                    client
                        .instance_update(
                            &org_id,
                            &service_id,
                            &ServicePatchRequest {
                                name: Some(name),
                                ..Default::default()
                            },
                        )
                        .await?;
                    Ok(())
                }
            })
            .await?;

        failures
            .run(
                &ctx,
                StepKind::NonBlocking,
                "service update enable_core_dumps",
                || {
                    let client = client.clone();
                    let org_id = ctx.org_id.clone();
                    let service_id = service_id.clone();
                    async move {
                        let resp = client.instance_get(&org_id, &service_id).await?;
                        let svc = resp.result.ok_or("service get returned no result")?;
                        let current_value = svc.enable_core_dumps;
                        client
                            .instance_update(
                                &org_id,
                                &service_id,
                                &ServicePatchRequest {
                                    enable_core_dumps: Some(current_value),
                                    ..Default::default()
                                },
                            )
                            .await?;
                        Ok(())
                    }
                },
            )
            .await?;

        failures
            .run(&ctx, StepKind::NonBlocking, "add service tag", || {
                let client = client.clone();
                let org_id = ctx.org_id.clone();
                let service_id = service_id.clone();
                async move {
                    client
                        .instance_update(
                            &org_id,
                            &service_id,
                            &ServicePatchRequest {
                                tags: Some(InstanceTagsPatch {
                                    add: vec![ResourceTagsV1 {
                                        key: "phase".to_string(),
                                        value: Some("updated".to_string()),
                                    }],
                                    remove: vec![],
                                }),
                                ..Default::default()
                            },
                        )
                        .await?;
                    Ok(())
                }
            })
            .await?;

        failures
            .run(&ctx, StepKind::NonBlocking, "service prometheus", || {
                let client = client.clone();
                let org_id = ctx.org_id.clone();
                let service_id = service_id.clone();
                async move {
                    let metrics = client
                        .instance_prometheus_get(&org_id, &service_id, None)
                        .await?;
                    if metrics.trim().is_empty() {
                        return Err("service prometheus returned empty output".into());
                    }
                    Ok(())
                }
            })
            .await?;

        // ── 5. ClickHouse Settings ───────────────────────────────────
        //
        // Round-trip a service-level ClickHouse setting through the four
        // settings endpoints (`schema`, `list`, `update`, `get`) and capture
        // the original value so cleanup can restore it.
        //
        // The schema endpoint does not expose a "restartRequired" flag, so we
        // pick from a curated allowlist of well-known runtime-changeable
        // settings (no restart required). We intersect the allowlist with the
        // schema returned at test time, so we only touch a setting the cloud
        // control plane currently advertises as configurable. If none of the
        // allowlisted settings appear in the schema this phase records a
        // non-blocking failure rather than guessing at an unknown setting.

        log_phase("ClickHouse Settings");

        let settings_schema = failures
            .run(
                &ctx,
                StepKind::NonBlocking,
                "clickhouse settings schema get",
                || {
                    let client = client.clone();
                    let org_id = ctx.org_id.clone();
                    let service_id = service_id.clone();
                    async move {
                        let resp = client
                            .service_clickhouse_settings_schema_get(&org_id, &service_id)
                            .await?;
                        let schema = resp
                            .result
                            .ok_or("clickhouse settings schema returned no result")?;
                        if schema.settings.is_empty() {
                            return Err("clickhouse settings schema returned no entries".into());
                        }
                        Ok(schema)
                    }
                },
            )
            .await?;

        if let Some(schema) = settings_schema {
            // Curated allowlist of ClickHouse settings that are safe to mutate
            // on a running service and do not require a restart. All of these
            // are per-query / per-user runtime knobs — changing them does not
            // bounce the server. Ordered by preference; first match wins.
            //
            // Hardcoded because the schema endpoint does not carry a
            // restart-required marker today; using a curated list is the
            // conservative alternative to picking blindly. The cloud schema
            // exposes a curated subset of OSS settings, so we list multiple
            // alternatives — if the cloud control plane stops exposing one,
            // the next match is used.
            const NO_RESTART_CANDIDATES: &[&str] = &[
                "max_concurrent_queries_for_user",
                "max_threads",
                "max_memory_usage_for_user",
                "min_insert_block_size_rows",
                "min_insert_block_size_bytes",
                "max_insert_block_size",
                "max_partitions_per_insert_block",
                "max_block_size",
                "max_concurrent_queries",
                "max_concurrent_select_queries",
                "max_concurrent_insert_queries",
                "max_execution_time",
                "max_result_rows",
            ];

            let chosen = NO_RESTART_CANDIDATES.iter().find_map(|name| {
                schema
                    .settings
                    .iter()
                    .find(|entry| entry.name == *name)
                    .cloned()
            });

            if let Some(entry) = chosen {
                let setting_name = entry.name.clone();
                eprintln!("  chose setting: {setting_name} (type: {})", entry.r#type);

                let list_resp = failures
                    .run(
                        &ctx,
                        StepKind::NonBlocking,
                        "clickhouse settings list get",
                        || {
                            let client = client.clone();
                            let org_id = ctx.org_id.clone();
                            let service_id = service_id.clone();
                            async move {
                                let resp = client
                                    .service_clickhouse_settings_list_get(
                                        &org_id,
                                        &service_id,
                                    )
                                    .await?;
                                let list = resp.result.ok_or(
                                    "clickhouse settings list returned no result",
                                )?;
                                if list.settings.is_empty() {
                                    return Err(
                                        "clickhouse settings list returned no entries".into(),
                                    );
                                }
                                Ok(list)
                            }
                        },
                    )
                    .await?;

                let original_value = list_resp.as_ref().and_then(|list| {
                    list.settings
                        .iter()
                        .find(|s| s.name == setting_name)
                        .map(|s| s.value.clone())
                });

                if let Some(original) = original_value {
                    eprintln!("  current value: {original}");

                    // Pick a new numeric value that differs from the current
                    // one. The candidates are all integer-typed settings, so
                    // we parse the current value as an integer; if parsing
                    // fails we bail to the next pre-set safe value below.
                    let new_value = match original.parse::<u64>() {
                        Ok(0) => "1".to_string(),
                        Ok(n) => (n.saturating_add(1)).to_string(),
                        Err(_) => "1".to_string(),
                    };

                    // Register the restore BEFORE attempting the mutation so
                    // a failed mid-mutation still triggers a cleanup attempt.
                    cleanup.register_clickhouse_setting_restore(
                        service_id.clone(),
                        setting_name.clone(),
                        original.clone(),
                    );

                    // The `settings` field on the API is a JSON-encoded string
                    // (the spec example is "{\"compatibility\":\"24.8\"}"). Build
                    // it with serde_json so the inner JSON escapes correctly
                    // regardless of what the setting name/value look like.
                    let patch_body_settings = serde_json::to_string(
                        &serde_json::json!({ setting_name.clone(): new_value.clone() }),
                    )?;
                    let update_ok = failures
                        .run(
                            &ctx,
                            StepKind::NonBlocking,
                            "clickhouse settings update",
                            || {
                                let client = client.clone();
                                let org_id = ctx.org_id.clone();
                                let service_id = service_id.clone();
                                let body = ServiceClickhouseSettingsPatchRequest {
                                    settings: Some(patch_body_settings.clone()),
                                };
                                async move {
                                    let resp = client
                                        .service_clickhouse_settings_update(
                                            &org_id,
                                            &service_id,
                                            &body,
                                        )
                                        .await?;
                                    if resp.result.is_none() {
                                        return Err(
                                            "clickhouse settings update returned no result"
                                                .into(),
                                        );
                                    }
                                    Ok(())
                                }
                            },
                        )
                        .await?;

                    if update_ok.is_some() {
                        failures
                            .run(
                                &ctx,
                                StepKind::NonBlocking,
                                "clickhouse setting get reflects update",
                                || {
                                    let client = client.clone();
                                    let org_id = ctx.org_id.clone();
                                    let service_id = service_id.clone();
                                    let setting_name = setting_name.clone();
                                    let expected = new_value.clone();
                                    let interval = ctx.poll_interval;
                                    async move {
                                        // The control plane may take a few
                                        // seconds to propagate the change to
                                        // the per-setting GET endpoint, so
                                        // poll briefly rather than asserting
                                        // on the first read.
                                        poll_until(
                                            "clickhouse setting reflects update",
                                            std::time::Duration::from_secs(60),
                                            interval,
                                            || {
                                                let client = client.clone();
                                                let org_id = org_id.clone();
                                                let service_id = service_id.clone();
                                                let setting_name = setting_name.clone();
                                                let expected = expected.clone();
                                                async move {
                                                    let resp = client
                                                        .service_clickhouse_setting_get(
                                                            &org_id,
                                                            &service_id,
                                                            &setting_name,
                                                        )
                                                        .await?;
                                                    let got = resp.result.ok_or(
                                                        "clickhouse setting get returned no result",
                                                    )?;
                                                    if got.value == expected {
                                                        Ok(Some(()))
                                                    } else {
                                                        Ok(None)
                                                    }
                                                }
                                            },
                                        )
                                        .await
                                    }
                                },
                            )
                            .await?;
                    }
                } else {
                    failures
                        .run(
                            &ctx,
                            StepKind::NonBlocking,
                            "clickhouse settings round-trip: capture original value",
                            || {
                                let setting_name = setting_name.clone();
                                async move {
                                    let err: Box<dyn std::error::Error> = format!(
                                        "setting {setting_name} not present in settings list — \
                                         cannot capture original value for round-trip"
                                    )
                                    .into();
                                    Err::<(), _>(err)
                                }
                            },
                        )
                        .await?;
                }
            } else {
                // The schema endpoint was reachable (proven by the prior
                // step) but none of the curated no-restart-required
                // candidates are exposed. Rather than recording a hard
                // failure that would abort the run in fail-fast mode, log
                // the schema's setting names so the allowlist can be
                // updated, and skip the mutation phase. The earlier
                // `clickhouse settings schema get` step still records
                // coverage of the schema endpoint.
                let exposed: Vec<&str> =
                    schema.settings.iter().map(|s| s.name.as_str()).collect();
                eprintln!(
                    "  SKIP clickhouse settings round-trip: none of {:?} matched the \
                     {} settings the cloud schema currently exposes: {:?}",
                    NO_RESTART_CANDIDATES,
                    exposed.len(),
                    exposed,
                );
            }
        }

        // ── 6. Private Endpoints ─────────────────────────────────────
        //
        // Cover `instance_private_endpoint_create` and
        // `instance_private_endpoint_config_get` against the live service.
        //
        // `instance_private_endpoint_config_get` should always succeed: it
        // returns the service-side endpoint service id + private DNS hostname
        // and does not need a real provider-side endpoint to exist.
        //
        // `instance_private_endpoint_create` requires a `ServicPrivateEndpointePostRequest`
        // whose `id` is a provider-specific identifier (AWS `vpce-…`, GCP
        // numeric PSC id, Azure GUID). The control plane validates that id
        // against the underlying provider, so a synthetic value with no real
        // cloud resource behind it is expected to be rejected with a 4xx.
        //
        // The assertion is therefore: the call must either succeed (in which
        // case we register inline cleanup, re-read config, and remove the
        // binding) OR fail with an unambiguous 4xx structured error. Any
        // other outcome — 5xx, network error, or a 200 with malformed payload
        // — is treated as a real failure recorded via FailureRecorder. This
        // is the "assertion-on-error" fallback called out in issue #160.

        log_phase("Private Endpoints");

        failures
            .run(
                &ctx,
                StepKind::NonBlocking,
                "private endpoint config get",
                || {
                    let client = client.clone();
                    let org_id = ctx.org_id.clone();
                    let service_id = service_id.clone();
                    async move {
                        let resp = client
                            .instance_private_endpoint_config_get(&org_id, &service_id)
                            .await?;
                        let config = resp.result.ok_or(
                            "instance_private_endpoint_config_get returned no result",
                        )?;
                        if config.endpoint_service_id.is_empty() {
                            return Err(
                                "private endpoint config returned empty endpointServiceId"
                                    .into(),
                            );
                        }
                        if config.private_dns_hostname.is_empty() {
                            return Err(
                                "private endpoint config returned empty privateDnsHostname"
                                    .into(),
                            );
                        }
                        eprintln!(
                            "  private endpoint config: endpointServiceId len={} privateDnsHostname len={}",
                            config.endpoint_service_id.len(),
                            config.private_dns_hostname.len()
                        );
                        Ok(())
                    }
                },
            )
            .await?;

        // Build a provider-shaped but synthetic endpoint id. `ctx.run_id`
        // is embedded so concurrent test runs and post-mortems can trace
        // which run wrote which (rejected) id.
        let synthetic_endpoint_id = synthetic_private_endpoint_id(&ctx);
        let create_body = ServicPrivateEndpointePostRequest {
            id: synthetic_endpoint_id.clone(),
            description: format!("clickhousectl-it private endpoint {}", ctx.run_id),
        };

        // The endpoint we just attempted to attach (only set if create
        // succeeded). Hosts the inline cleanup that fires after the
        // re-read of `private_endpoint_config_get`.
        let mut created_endpoint_id: Option<String> = None;

        failures
            .run(
                &ctx,
                StepKind::NonBlocking,
                "private endpoint create (synthetic id)",
                || {
                    let client = client.clone();
                    let org_id = ctx.org_id.clone();
                    let service_id = service_id.clone();
                    let create_body = create_body.clone();
                    let synthetic_endpoint_id = synthetic_endpoint_id.clone();
                    let created_endpoint_id = &mut created_endpoint_id;
                    async move {
                        match client
                            .instance_private_endpoint_create(
                                &org_id,
                                &service_id,
                                &create_body,
                            )
                            .await
                        {
                            Ok(resp) => {
                                let endpoint = resp.result.ok_or(
                                    "instance_private_endpoint_create returned no result",
                                )?;
                                if endpoint.id != synthetic_endpoint_id {
                                    return Err(format!(
                                        "private endpoint create returned unexpected id: \
                                         got {}, expected {}",
                                        endpoint.id, synthetic_endpoint_id
                                    )
                                    .into());
                                }
                                eprintln!(
                                    "  private endpoint create unexpectedly succeeded \
                                     (provider={}, region={}); registering inline cleanup",
                                    endpoint.cloud_provider, endpoint.region
                                );
                                *created_endpoint_id = Some(endpoint.id);
                                Ok(())
                            }
                            Err(clickhouse_cloud_api::Error::Api { status, message })
                                if (400..500).contains(&status) =>
                            {
                                // Expected path: the API rejected the
                                // synthetic id because no real cloud resource
                                // backs it. The structured error shape
                                // (status + message) is what we assert on.
                                eprintln!(
                                    "  private endpoint create correctly rejected \
                                     synthetic id with {status}: {message}"
                                );
                                if message.trim().is_empty() {
                                    return Err(format!(
                                        "private endpoint create returned {status} \
                                         with empty error body"
                                    )
                                    .into());
                                }
                                Ok(())
                            }
                            Err(e) => Err(format!(
                                "private endpoint create returned unexpected error \
                                 (expected 4xx or success): {e}"
                            )
                            .into()),
                        }
                    }
                },
            )
            .await?;

        // Re-read the config endpoint after the create attempt: even when
        // the create is rejected we want a second `config_get` call in the
        // mix so transient deserialization regressions on the GET path
        // surface.
        failures
            .run(
                &ctx,
                StepKind::NonBlocking,
                "private endpoint config get after create attempt",
                || {
                    let client = client.clone();
                    let org_id = ctx.org_id.clone();
                    let service_id = service_id.clone();
                    async move {
                        let resp = client
                            .instance_private_endpoint_config_get(&org_id, &service_id)
                            .await?;
                        resp.result
                            .ok_or("private endpoint config get returned no result")?;
                        Ok(())
                    }
                },
            )
            .await?;

        // If create succeeded, the synthetic endpoint is now associated with
        // the service via `privateEndpointIds`. Detach it inline so the
        // service can later be deleted cleanly — the service delete path
        // does not implicitly free a private endpoint binding.
        if let Some(endpoint_id) = created_endpoint_id.clone() {
            failures
                .run(
                    &ctx,
                    StepKind::NonBlocking,
                    "detach synthetic private endpoint from service",
                    || {
                        let client = client.clone();
                        let org_id = ctx.org_id.clone();
                        let service_id = service_id.clone();
                        let endpoint_id = endpoint_id.clone();
                        async move {
                            client
                                .instance_update(
                                    &org_id,
                                    &service_id,
                                    &ServicePatchRequest {
                                        private_endpoint_ids: Some(
                                            InstancePrivateEndpointsPatch {
                                                add: vec![],
                                                remove: vec![endpoint_id],
                                            },
                                        ),
                                        ..Default::default()
                                    },
                                )
                                .await?;
                            Ok(())
                        }
                    },
                )
                .await?;
        }

        // ── 7. IP Access ─────────────────────────────────────────────

        log_phase("IP Access");
        failures
            .run(
                &ctx,
                StepKind::NonBlocking,
                "add first ip allow entry",
                || {
                    let client = client.clone();
                    let org_id = ctx.org_id.clone();
                    let service_id = service_id.clone();
                    let timeout = ctx.create_timeout;
                    let interval = ctx.poll_interval;
                    async move {
                        client
                            .instance_update(
                                &org_id,
                                &service_id,
                                &ServicePatchRequest {
                                    ip_access_list: Some(IpAccessListPatch {
                                        add: vec![IpAccessListEntry {
                                            source: primary_ip.to_string(),
                                            description: Some("test primary".to_string()),
                                        }],
                                        remove: vec![],
                                    }),
                                    ..Default::default()
                                },
                            )
                            .await?;
                        poll_for_ip_presence(
                            &client,
                            &org_id,
                            &service_id,
                            primary_ip,
                            true,
                            timeout,
                            interval,
                        )
                        .await
                    }
                },
            )
            .await?;

        failures
            .run(
                &ctx,
                StepKind::NonBlocking,
                "add second ip allow entry",
                || {
                    let client = client.clone();
                    let org_id = ctx.org_id.clone();
                    let service_id = service_id.clone();
                    let timeout = ctx.create_timeout;
                    let interval = ctx.poll_interval;
                    async move {
                        client
                            .instance_update(
                                &org_id,
                                &service_id,
                                &ServicePatchRequest {
                                    ip_access_list: Some(IpAccessListPatch {
                                        add: vec![IpAccessListEntry {
                                            source: secondary_ip.to_string(),
                                            description: Some("test secondary".to_string()),
                                        }],
                                        remove: vec![],
                                    }),
                                    ..Default::default()
                                },
                            )
                            .await?;
                        poll_until(
                            "multiple ip allow visibility",
                            timeout,
                            interval,
                            || {
                                let client = client.clone();
                                let org_id = org_id.clone();
                                let service_id = service_id.clone();
                                async move {
                                    let resp =
                                        client.instance_get(&org_id, &service_id).await?;
                                    let svc =
                                        resp.result.ok_or("service get returned no result")?;
                                    if has_ip_entry(&svc, primary_ip)
                                        && has_ip_entry(&svc, secondary_ip)
                                    {
                                        Ok(Some(()))
                                    } else {
                                        Ok(None)
                                    }
                                }
                            },
                        )
                        .await?;
                        Ok(())
                    }
                },
            )
            .await?;

        failures
            .run(
                &ctx,
                StepKind::NonBlocking,
                "remove one ip allow entry while keeping another",
                || {
                    let client = client.clone();
                    let org_id = ctx.org_id.clone();
                    let service_id = service_id.clone();
                    let timeout = ctx.create_timeout;
                    let interval = ctx.poll_interval;
                    async move {
                        client
                            .instance_update(
                                &org_id,
                                &service_id,
                                &ServicePatchRequest {
                                    ip_access_list: Some(IpAccessListPatch {
                                        add: vec![],
                                        remove: vec![IpAccessListEntry {
                                            source: primary_ip.to_string(),
                                            description: None,
                                        }],
                                    }),
                                    ..Default::default()
                                },
                            )
                            .await?;
                        poll_until(
                            "partial ip allow removal",
                            timeout,
                            interval,
                            || {
                                let client = client.clone();
                                let org_id = org_id.clone();
                                let service_id = service_id.clone();
                                async move {
                                    let resp =
                                        client.instance_get(&org_id, &service_id).await?;
                                    let svc =
                                        resp.result.ok_or("service get returned no result")?;
                                    if !has_ip_entry(&svc, primary_ip)
                                        && has_ip_entry(&svc, secondary_ip)
                                    {
                                        Ok(Some(()))
                                    } else {
                                        Ok(None)
                                    }
                                }
                            },
                        )
                        .await?;
                        Ok(())
                    }
                },
            )
            .await?;

        failures
            .run(
                &ctx,
                StepKind::NonBlocking,
                "remove remaining ip allow entry",
                || {
                    let client = client.clone();
                    let org_id = ctx.org_id.clone();
                    let service_id = service_id.clone();
                    let timeout = ctx.create_timeout;
                    let interval = ctx.poll_interval;
                    async move {
                        client
                            .instance_update(
                                &org_id,
                                &service_id,
                                &ServicePatchRequest {
                                    ip_access_list: Some(IpAccessListPatch {
                                        add: vec![],
                                        remove: vec![IpAccessListEntry {
                                            source: secondary_ip.to_string(),
                                            description: None,
                                        }],
                                    }),
                                    ..Default::default()
                                },
                            )
                            .await?;
                        poll_for_ip_presence(
                            &client,
                            &org_id,
                            &service_id,
                            secondary_ip,
                            false,
                            timeout,
                            interval,
                        )
                        .await
                    }
                },
            )
            .await?;

        // ── 8. Scaling ───────────────────────────────────────────────

        log_phase("Scaling");
        failures
            .run(&ctx, StepKind::Blocking, "scale out to 3 replicas", || {
                let client = client.clone();
                let org_id = ctx.org_id.clone();
                let service_id = service_id.clone();
                let timeout = ctx.steady_state_timeout;
                let interval = ctx.poll_interval;
                async move {
                    scale_service_and_wait(
                        &client,
                        &org_id,
                        &service_id,
                        Some(base_memory_gb),
                        Some(base_memory_gb),
                        Some(scaled_replicas),
                        "replica scale out",
                        timeout,
                        interval,
                    )
                    .await
                }
            })
            .await?;

        failures
            .run(&ctx, StepKind::Blocking, "scale up to 16 GB", || {
                let client = client.clone();
                let org_id = ctx.org_id.clone();
                let service_id = service_id.clone();
                let timeout = ctx.steady_state_timeout;
                let interval = ctx.poll_interval;
                async move {
                    scale_service_and_wait(
                        &client,
                        &org_id,
                        &service_id,
                        Some(scaled_memory_gb),
                        Some(scaled_memory_gb),
                        Some(scaled_replicas),
                        "vertical scale up",
                        timeout,
                        interval,
                    )
                    .await
                }
            })
            .await?;

        failures
            .run(&ctx, StepKind::Blocking, "scale down to 8 GB", || {
                let client = client.clone();
                let org_id = ctx.org_id.clone();
                let service_id = service_id.clone();
                let timeout = ctx.steady_state_timeout;
                let interval = ctx.poll_interval;
                async move {
                    scale_service_and_wait(
                        &client,
                        &org_id,
                        &service_id,
                        Some(base_memory_gb),
                        Some(base_memory_gb),
                        Some(scaled_replicas),
                        "vertical scale down",
                        timeout,
                        interval,
                    )
                    .await
                }
            })
            .await?;

        failures
            .run(&ctx, StepKind::Blocking, "scale in to 1 replica", || {
                let client = client.clone();
                let org_id = ctx.org_id.clone();
                let service_id = service_id.clone();
                let timeout = ctx.steady_state_timeout;
                let interval = ctx.poll_interval;
                async move {
                    scale_service_and_wait(
                        &client,
                        &org_id,
                        &service_id,
                        Some(base_memory_gb),
                        Some(base_memory_gb),
                        Some(base_replicas),
                        "replica scale in",
                        timeout,
                        interval,
                    )
                    .await
                }
            })
            .await?;

        // Vertical scaling round-trip via the deprecated
        // `instance_scaling_update` endpoint (PATCH /scaling). This is
        // distinct from `instance_replica_scaling_update` (PATCH
        // /replicaScaling) exercised above: the deprecated endpoint takes
        // `minTotalMemoryGb` / `maxTotalMemoryGb` and only the vertical
        // axis. The deprecated endpoint additionally requires the totals to
        // be multiples of 12, so we first move via the modern endpoint to
        // `deprecated_base_total_memory_gb` before the round-trip. We stay
        // at 1 replica so the total-memory body maps directly to
        // per-replica memory.
        failures
            .run(
                &ctx,
                StepKind::Blocking,
                "land on multiple-of-12 memory before deprecated phase",
                || {
                    let client = client.clone();
                    let org_id = ctx.org_id.clone();
                    let service_id = service_id.clone();
                    let timeout = ctx.steady_state_timeout;
                    let interval = ctx.poll_interval;
                    async move {
                        scale_service_and_wait(
                            &client,
                            &org_id,
                            &service_id,
                            Some(deprecated_base_total_memory_gb),
                            Some(deprecated_base_total_memory_gb),
                            Some(base_replicas),
                            "modern scale to deprecated base",
                            timeout,
                            interval,
                        )
                        .await
                    }
                },
            )
            .await?;

        let pre_vertical = failures
            .run(
                &ctx,
                StepKind::Blocking,
                "capture pre-state for deprecated vertical scaling",
                || {
                    let client = client.clone();
                    let org_id = ctx.org_id.clone();
                    let service_id = service_id.clone();
                    async move {
                        let resp = client.instance_get(&org_id, &service_id).await?;
                        resp.result
                            .ok_or_else(|| "service get returned no result".into())
                    }
                },
            )
            .await?
            .expect("blocking steps always return a value");
        // Sanity: the deprecated body's totals only equal per-replica when
        // num_replicas == 1. We rely on the previous step landing us there.
        assert_eq!(pre_vertical.num_replicas, base_replicas);
        let pre_min_total = pre_vertical.min_total_memory_gb;
        let pre_max_total = pre_vertical.max_total_memory_gb;

        failures
            .run(
                &ctx,
                StepKind::NonBlocking,
                "deprecated vertical scale up to 24 GB",
                || {
                    let client = client.clone();
                    let org_id = ctx.org_id.clone();
                    let service_id = service_id.clone();
                    let timeout = ctx.steady_state_timeout;
                    let interval = ctx.poll_interval;
                    async move {
                        scale_service_vertical_and_wait(
                            &client,
                            &org_id,
                            &service_id,
                            Some(deprecated_scaled_total_memory_gb),
                            Some(deprecated_scaled_total_memory_gb),
                            "deprecated vertical scale up",
                            timeout,
                            interval,
                        )
                        .await
                    }
                },
            )
            .await?;

        failures
            .run(
                &ctx,
                StepKind::NonBlocking,
                "deprecated vertical scale back to pre-state",
                || {
                    let client = client.clone();
                    let org_id = ctx.org_id.clone();
                    let service_id = service_id.clone();
                    let timeout = ctx.steady_state_timeout;
                    let interval = ctx.poll_interval;
                    async move {
                        scale_service_vertical_and_wait(
                            &client,
                            &org_id,
                            &service_id,
                            Some(pre_min_total),
                            Some(pre_max_total),
                            "deprecated vertical scale restore",
                            timeout,
                            interval,
                        )
                        .await
                    }
                },
            )
            .await?;

        // ── 9. Scaling Schedule (Beta) ───────────────────────────────
        //
        // Exercise the Beta scaling_schedule_{get,upsert,delete} trio
        // for shape coverage. Schedule entries are chosen to be inert:
        //
        //  - replica counts and memory match the current service state
        //    (1 replica, 8 GB), so even if an entry happens to be active
        //    during the test run it cannot drive any real scaling action;
        //  - the upsert window covers a single hour (1 a.m. – 2 a.m. UTC)
        //    on Sunday only, with the same inert replica config so the
        //    entry's effect is always a no-op regardless of when the
        //    suite runs.
        //
        // The pre-state (typically an empty schedule) is captured here
        // and restored as a cleanup step, not a test-body step.

        log_phase("Scaling Schedule");

        let pre_schedule = failures
            .run(
                &ctx,
                StepKind::NonBlocking,
                "scaling_schedule get pre-state",
                || {
                    let client = client.clone();
                    let org_id = ctx.org_id.clone();
                    let service_id = service_id.clone();
                    async move {
                        // A freshly-created service has no autoscaling schedule
                        // configured, and the API responds with 404 rather than
                        // an empty `ScalingSchedule`. Treat that as the canonical
                        // empty pre-state so the round-trip can still exercise
                        // upsert/replace; any other error still surfaces.
                        match client.scaling_schedule_get(&org_id, &service_id).await {
                            Ok(resp) => resp
                                .result
                                .ok_or_else(|| "scaling_schedule get returned no result".into()),
                            Err(clickhouse_cloud_api::Error::Api { status: 404, .. }) => {
                                Ok(ScalingSchedule::default())
                            }
                            Err(e) => Err(e.into()),
                        }
                    }
                },
            )
            .await?;

        // Only run the round-trip if we successfully captured the
        // pre-state. If the initial GET failed, restoring afterwards
        // would risk leaving a synthetic schedule on the service.
        if let Some(pre_state) = pre_schedule {
            // Skip restore registration when pre-state is empty: the API
            // rejects upserts with an empty `entries` array, and there is
            // nothing meaningful to restore. Cleanup of synthetic entries
            // is still covered by the service-delete teardown below.
            if !pre_state.entries.is_empty() {
                cleanup
                    .register_scaling_schedule_restore(service_id.clone(), pre_state.clone());
            }
            eprintln!(
                "  captured scaling_schedule pre-state: {} entries",
                pre_state.entries.len()
            );

            // 9a. Upsert a synthetic-but-inert schedule.
            let upsert_entry = ScalingScheduleEntryRequest {
                name: "clickhousectl-it-upsert-window".to_string(),
                weekdays: vec![0], // Sunday only
                start_hour_utc: 1,
                end_hour_utc: 2,
                min_replica_memory_gb: Some(base_memory_gb),
                max_replica_memory_gb: Some(base_memory_gb),
                min_replicas: Some(base_replicas as i64),
                max_replicas: Some(base_replicas as i64),
                idle_scaling: Some(true),
                idle_timeout_minutes: Some(5),
            };

            let upserted = failures
                .run(
                    &ctx,
                    StepKind::NonBlocking,
                    "scaling_schedule upsert inert window",
                    || {
                        let client = client.clone();
                        let org_id = ctx.org_id.clone();
                        let service_id = service_id.clone();
                        let entry = upsert_entry.clone();
                        async move {
                            let body = ScalingSchedulePostRequest {
                                entries: vec![entry],
                            };
                            let resp = client
                                .scaling_schedule_upsert(&org_id, &service_id, &body)
                                .await?;
                            resp.result.ok_or_else(|| {
                                "scaling_schedule upsert returned no result".into()
                            })
                        }
                    },
                )
                .await?;

            // 9b. GET and confirm the upsert is visible.
            if upserted.is_some() {
                failures
                    .run(
                        &ctx,
                        StepKind::NonBlocking,
                        "scaling_schedule get reflects upsert",
                        || {
                            let client = client.clone();
                            let org_id = ctx.org_id.clone();
                            let service_id = service_id.clone();
                            let expected_name = upsert_entry.name.clone();
                            async move {
                                let resp = client
                                    .scaling_schedule_get(&org_id, &service_id)
                                    .await?;
                                let schedule = resp.result.ok_or(
                                    "scaling_schedule get returned no result after upsert",
                                )?;
                                if schedule.entries.len() != 1 {
                                    return Err(format!(
                                        "expected 1 entry after upsert, got {}",
                                        schedule.entries.len()
                                    )
                                    .into());
                                }
                                let entry = &schedule.entries[0];
                                if entry.name != expected_name {
                                    return Err(format!(
                                        "upserted entry name mismatch: got {:?}, expected {:?}",
                                        entry.name, expected_name
                                    )
                                    .into());
                                }
                                if entry.start_hour_utc != 1 || entry.end_hour_utc != 2 {
                                    return Err(format!(
                                        "upserted entry window mismatch: got {}-{} UTC, expected 1-2",
                                        entry.start_hour_utc, entry.end_hour_utc
                                    )
                                    .into());
                                }
                                Ok(())
                            }
                        },
                    )
                    .await?;
            }

            // 9c. Delete the schedule.
            let deleted = failures
                .run(
                    &ctx,
                    StepKind::NonBlocking,
                    "scaling_schedule delete",
                    || {
                        let client = client.clone();
                        let org_id = ctx.org_id.clone();
                        let service_id = service_id.clone();
                        async move {
                            client
                                .scaling_schedule_delete(&org_id, &service_id)
                                .await?;
                            Ok(())
                        }
                    },
                )
                .await?;

            // 9d. GET should now return 404 (no schedule configured).
            if deleted.is_some() {
                failures
                    .run(
                        &ctx,
                        StepKind::NonBlocking,
                        "scaling_schedule get returns 404 after delete",
                        || {
                            let client = client.clone();
                            let org_id = ctx.org_id.clone();
                            let service_id = service_id.clone();
                            async move {
                                match client
                                    .scaling_schedule_get(&org_id, &service_id)
                                    .await
                                {
                                    Err(clickhouse_cloud_api::Error::Api {
                                        status: 404,
                                        ..
                                    }) => Ok(()),
                                    Ok(_) => Err(
                                        "scaling_schedule get returned a schedule after delete"
                                            .into(),
                                    ),
                                    Err(e) => Err(e.into()),
                                }
                            }
                        },
                    )
                    .await?;
            }
        }

        // ── 10. Password ─────────────────────────────────────────────
        //
        // `instance_password_update` rotates the service password. The
        // query path used by the rest of the suite is openapi-key-based,
        // so the rotated password is not consumed anywhere — the pass
        // condition is just a successful response that surfaces a fresh
        // password. We pass an empty body so the server generates a new
        // password and returns it; no re-rotation is needed because the
        // service is about to be deleted.

        log_phase("Password");
        failures
            .run(
                &ctx,
                StepKind::NonBlocking,
                "rotate service password",
                || {
                    let client = client.clone();
                    let org_id = ctx.org_id.clone();
                    let service_id = service_id.clone();
                    let run_id = ctx.run_id.clone();
                    async move {
                        let resp = client
                            .instance_password_update(
                                &org_id,
                                &service_id,
                                &ServicePasswordPatchRequest::default(),
                            )
                            .await?;
                        let result = resp
                            .result
                            .ok_or("password update returned no result")?;
                        if result.password.is_empty() {
                            return Err("password update response had empty password".into());
                        }
                        eprintln!(
                            "  password rotated (length={}, run_id={})",
                            result.password.len(),
                            run_id
                        );
                        Ok(())
                    }
                },
            )
            .await?;

        // ── 11. Delete ───────────────────────────────────────────────

        log_phase("Delete");

        // Stop service before delete (library has no --force equivalent)
        failures
            .run(&ctx, StepKind::Blocking, "stop service before delete", || {
                let client = client.clone();
                let org_id = ctx.org_id.clone();
                let service_id = service_id.clone();
                let timeout = ctx.create_timeout;
                let interval = ctx.poll_interval;
                async move {
                    client
                        .instance_state_update(
                            &org_id,
                            &service_id,
                            &ServiceStatePatchRequest {
                                command: Some(ServiceStatePatchRequestCommand::Stop),
                            },
                        )
                        .await?;
                    poll_until("service stopped for delete", timeout, interval, || {
                        let client = client.clone();
                        let org_id = org_id.clone();
                        let service_id = service_id.clone();
                        async move {
                            let resp = client.instance_get(&org_id, &service_id).await?;
                            let svc = resp.result.ok_or("service get returned no result")?;
                            let state = svc.state.to_string();
                            if matches!(state.as_str(), "idle" | "stopped") {
                                Ok(Some(()))
                            } else {
                                Ok(None)
                            }
                        }
                    })
                    .await?;
                    Ok(())
                }
            })
            .await?;

        failures
            .run(&ctx, StepKind::Blocking, "delete service", || {
                let client = client.clone();
                let org_id = ctx.org_id.clone();
                let service_id = service_id.clone();
                async move {
                    client.instance_delete(&org_id, &service_id).await?;
                    Ok(())
                }
            })
            .await?;

        failures
            .run(
                &ctx,
                StepKind::Blocking,
                "confirm service is gone after delete",
                || {
                    let client = client.clone();
                    let org_id = ctx.org_id.clone();
                    let service_id = service_id.clone();
                    let timeout = ctx.delete_timeout;
                    let interval = ctx.poll_interval;
                    async move {
                        poll_until("service deletion", timeout, interval, || {
                            let client = client.clone();
                            let org_id = org_id.clone();
                            let service_id = service_id.clone();
                            async move {
                                match client.instance_get(&org_id, &service_id).await {
                                    Ok(_) => Ok(None),
                                    Err(clickhouse_cloud_api::Error::Api {
                                        status: 404, ..
                                    }) => Ok(Some(())),
                                    Err(e) => {
                                        let message = e.to_string();
                                        if message.contains("404")
                                            || message.contains("not found")
                                        {
                                            Ok(Some(()))
                                        } else {
                                            Err(e.into())
                                        }
                                    }
                                }
                            }
                        })
                        .await?;
                        Ok(())
                    }
                },
            )
            .await?;
        cleanup.unregister_scaling_schedule_restore(&service_id);
        cleanup.unregister_service(&service_id);

        failures.finish()
    }
    .await;

    let cleanup_result = cleanup
        .cleanup(&client, &ctx.org_id, ctx.delete_timeout, ctx.poll_interval, None)
        .await;

    match (test_result, cleanup_result) {
        (Ok(()), Ok(())) => Ok(()),
        (Err(error), Ok(())) => Err(error),
        (Ok(()), Err(cleanup_error)) => Err(cleanup_error.into()),
        (Err(error), Err(cleanup_error)) => {
            Err(format!("{error}\ncleanup failed:\n{cleanup_error}").into())
        }
    }
}

fn has_ip_entry(svc: &Service, source: &str) -> bool {
    svc.ip_access_list.iter().any(|e| e.source == source)
}

async fn poll_for_ip_presence(
    client: &Client,
    org_id: &str,
    service_id: &str,
    ip: &str,
    expected_present: bool,
    timeout: std::time::Duration,
    interval: std::time::Duration,
) -> TestResult<()> {
    poll_until(
        &format!("ip visibility for {ip}"),
        timeout,
        interval,
        || {
            let client = client.clone();
            let org_id = org_id.to_string();
            let service_id = service_id.to_string();
            let ip = ip.to_string();
            async move {
                let resp = client.instance_get(&org_id, &service_id).await?;
                let svc = resp.result.ok_or("service get returned no result")?;
                if has_ip_entry(&svc, &ip) == expected_present {
                    Ok(Some(()))
                } else {
                    Ok(None)
                }
            }
        },
    )
    .await?;
    Ok(())
}

#[allow(clippy::too_many_arguments)]
async fn scale_service_and_wait(
    client: &Client,
    org_id: &str,
    service_id: &str,
    min_memory_gb: Option<f64>,
    max_memory_gb: Option<f64>,
    replicas: Option<f64>,
    description: &str,
    timeout: std::time::Duration,
    interval: std::time::Duration,
) -> TestResult<()> {
    client
        .instance_replica_scaling_update(
            org_id,
            service_id,
            &ServiceReplicaScalingPatchRequest {
                min_replica_memory_gb: min_memory_gb,
                max_replica_memory_gb: max_memory_gb,
                num_replicas: replicas,
                ..Default::default()
            },
        )
        .await?;

    poll_until(
        &format!("{description} visibility"),
        timeout,
        interval,
        || {
            let client = client.clone();
            let org_id = org_id.to_string();
            let service_id = service_id.to_string();
            async move {
                let resp = client.instance_get(&org_id, &service_id).await?;
                let svc = resp.result.ok_or("service get returned no result")?;
                if min_memory_gb.is_none_or(|v| svc.min_replica_memory_gb == v)
                    && max_memory_gb.is_none_or(|v| svc.max_replica_memory_gb == v)
                    && replicas.is_none_or(|v| svc.num_replicas == v)
                {
                    Ok(Some(()))
                } else {
                    Ok(None)
                }
            }
        },
    )
    .await?;

    Ok(())
}

/// Builds a provider-shaped but synthetic private endpoint id that embeds
/// `ctx.run_id`. The format is plausible enough for the control plane to
/// accept syntactically but the underlying cloud resource does not exist,
/// so the create call is expected to be rejected with a 4xx. The run id is
/// embedded so a leaked id in API logs can be traced back to a specific
/// test run.
fn synthetic_private_endpoint_id(ctx: &TestContext) -> String {
    // Reduce the run id to a hex-safe slug capped at 16 chars to fit inside
    // provider id formats.
    let slug: String = ctx
        .run_id
        .chars()
        .filter(|c| c.is_ascii_alphanumeric())
        .map(|c| c.to_ascii_lowercase())
        .take(16)
        .collect();
    let padded = format!("{slug:0<16}");
    match ctx.provider.as_str() {
        // AWS VPC endpoint ids look like `vpce-0123456789abcdef0` (17 hex
        // chars after the prefix).
        "aws" => format!("vpce-{}0", &padded[..16]),
        // GCP Private Service Connect endpoint ids are decimal strings. We
        // pick a 19-digit value seeded by the run id hash so different runs
        // collide neither with each other nor with real PSC endpoints.
        "gcp" => {
            let hash: u64 = ctx.run_id.bytes().fold(0u64, |acc, b| {
                acc.wrapping_mul(31).wrapping_add(b as u64)
            });
            format!("{:019}", hash % 10u64.pow(19))
        }
        // Azure private endpoint resource ids are GUIDs. Synthesize one
        // from the run id slug.
        "azure" => {
            let s = format!("{padded:0<32}");
            format!(
                "{}-{}-{}-{}-{}",
                &s[..8],
                &s[8..12],
                &s[12..16],
                &s[16..20],
                &s[20..32]
            )
        }
        // Unknown providers: pick something that contains the run id so it
        // is traceable. The API will reject it; that is the assertion.
        _ => format!("clickhousectl-it-{}", ctx.run_id),
    }
}

#[allow(deprecated)]
#[allow(clippy::too_many_arguments)]
async fn scale_service_vertical_and_wait(
    client: &Client,
    org_id: &str,
    service_id: &str,
    min_total_memory_gb: Option<f64>,
    max_total_memory_gb: Option<f64>,
    description: &str,
    timeout: std::time::Duration,
    interval: std::time::Duration,
) -> TestResult<()> {
    client
        .instance_scaling_update(
            org_id,
            service_id,
            &ServiceScalingPatchRequest {
                min_total_memory_gb,
                max_total_memory_gb,
                ..Default::default()
            },
        )
        .await?;

    poll_until(
        &format!("{description} visibility"),
        timeout,
        interval,
        || {
            let client = client.clone();
            let org_id = org_id.to_string();
            let service_id = service_id.to_string();
            async move {
                let resp = client.instance_get(&org_id, &service_id).await?;
                let svc = resp.result.ok_or("service get returned no result")?;
                if min_total_memory_gb.is_none_or(|v| svc.min_total_memory_gb == v)
                    && max_total_memory_gb.is_none_or(|v| svc.max_total_memory_gb == v)
                {
                    Ok(Some(()))
                } else {
                    Ok(None)
                }
            }
        },
    )
    .await?;

    Ok(())
}