anytype 0.5.0

An ergonomic Anytype API client in rust
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
//! # Anytype Types
//!
//! This module provides a fluent builder API for working with Anytype object types.
//!
//! ## Type methods on `AnytypeClient`
//!
//! - [`types`](AnytypeClient::types) - list types in the space
//! - [`get_type`](AnytypeClient::get_type) - get type for retrieval or deletion
//! - [`new_type`](AnytypeClient::new_type) - create a new type
//! - [`update_type`](AnytypeClient::update_type) - update type properties
//! - [`lookup_type_by_key`](AnytypeClient::lookup_type_by_key) - find type using key
//!
//! ## Quick Start
//!
//! ```rust
//! use anytype::prelude::*;
//!
//! # async fn example() -> Result<(), AnytypeError> {
//! #   let client = AnytypeClient::new("doc test")?;
//! #   let space_id = anytype::test_util::example_space_id(&client).await?;
//!
//! // List all types
//! let types = client.types(&space_id).list().await?;
//! let some_type = types.iter().next().unwrap().clone();
//!
//! // Get a type by id
//! let typ = client.get_type(&space_id, &some_type.id).get().await?;
//!
//! // Get a type by key
//! let typ = client.lookup_type_by_key(&space_id, "page").await?;
//!
//! // Create a new type
//! let project = client.new_type(&space_id, "Project")
//!     .key("project")
//!     .create().await?;
//!
//! // Update a type: change its name and replace its recommended properties
//! let project = client.update_type(&space_id, &project.id)
//!     .name("My New Project")
//!     .property("Location", "location", PropertyFormat::Text)
//!     .update().await?;
//!
//! // Delete a type
//! client.get_type(&space_id, &project.id).delete().await?;
//!
//! # Ok(())
//! # }
//! ```
//!
//! ## Types
//!
//! - [`Type`] - Represents an Anytype object type
//! - [`TypePropertyClassification`] - Separates featured properties from the
//!   complete non-featured set replaceable by an update
//! - [`TypeLayout`] - Layout variants for types (Basic, Profile, Action, Note)
//! - [`TypeRequest`] - Builder for get/delete operations
//! - [`NewTypeRequest`] - Builder for creating types
//! - [`ListTypesRequest`] - Builder for listing types

use std::{
    collections::HashMap,
    future::Future,
    pin::Pin,
    sync::{
        Arc,
        atomic::{AtomicU64, Ordering},
    },
    time::Duration,
};

use anytype_rpc::anytype::rpc::object::{close as object_close, show as object_show};
use anytype_rpc::model;
use prost_types::value::Kind;
use serde::{Deserialize, Deserializer, Serialize};
use snafu::prelude::*;
use tonic::Request;

use crate::{
    Result,
    cache::AnytypeCache,
    client::AnytypeClient,
    error::{CacheDisabledSnafu, NotFoundSnafu, OtherSnafu, ValidationSnafu},
    filters::{Query, QueryWithFilters},
    grpc_util::{ensure_error_ok, grpc_status, with_token_request},
    http_client::{GetPaged, HttpClient},
    prelude::*,
    verify::{VerifyConfig, VerifyPolicy, resolve_verify, verify_available},
};

/// Longest per-RPC deadline accepted by the finite type-property classifier.
pub const MAX_TYPE_PROPERTY_RPC_TIMEOUT: Duration = Duration::from_secs(5);

/// Cumulative work counters for type-property classification RPC ownership.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct TypePropertyClassificationMetricsSnapshot {
    /// `ObjectShow` RPCs polled by the classifier.
    pub show_attempts: u64,
    /// `ObjectClose` RPCs polled by explicit cleanup or the detached fallback.
    pub close_attempts: u64,
    /// Detached cleanup fallbacks started after cancellation or failed cleanup.
    pub close_fallbacks: u64,
    /// Explicit or detached close attempts that confirmed cleanup.
    pub cleanup_successes: u64,
    /// Explicit or detached close attempts that did not confirm cleanup.
    pub cleanup_failures: u64,
}

#[derive(Debug, Default)]
pub(crate) struct TypePropertyClassificationMetrics {
    show_attempts: AtomicU64,
    close_attempts: AtomicU64,
    close_fallbacks: AtomicU64,
    cleanup_successes: AtomicU64,
    cleanup_failures: AtomicU64,
}

impl TypePropertyClassificationMetrics {
    pub(crate) fn snapshot(&self) -> TypePropertyClassificationMetricsSnapshot {
        TypePropertyClassificationMetricsSnapshot {
            show_attempts: self.show_attempts.load(Ordering::Relaxed),
            close_attempts: self.close_attempts.load(Ordering::Relaxed),
            close_fallbacks: self.close_fallbacks.load(Ordering::Relaxed),
            cleanup_successes: self.cleanup_successes.load(Ordering::Relaxed),
            cleanup_failures: self.cleanup_failures.load(Ordering::Relaxed),
        }
    }
}

/// Maximum number of featured and ordinary recommended property links
/// accepted by one exact type-property classification read.
pub const MAX_TYPE_PROPERTY_LINKS: usize = 1_000;

const RECOMMENDED_FEATURED_RELATIONS: &str = "recommendedFeaturedRelations";
const RECOMMENDED_RELATIONS: &str = "recommendedRelations";

/// Layout variants for types.
///
/// Determines the default appearance and behavior of objects of this type.
/// Note: This differs from [`ObjectLayout`] which has additional variants
/// (Bookmark, Set, Collection, Participant). Anytype's public REST create and
/// update contract accepts only the four variants below; collection-layout
/// types used by integration tests are created through the cleanup-safe helper
/// in [`crate::test_util::TestContext`].
#[derive(
    Debug, Deserialize, Serialize, Clone, Default, PartialEq, Eq, strum::Display, strum::EnumString,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum TypeLayout {
    /// Standard object layout with full editing capabilities
    #[default]
    Basic,
    /// Profile layout for user/contact information
    Profile,
    /// Action/task layout
    Action,
    /// Note layout - simplified, name is optional
    Note,
}

/// Property definition for type creation.
///
/// Defines a property to be associated with a new type.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CreateTypeProperty {
    /// The format of the property (text, number, date, etc.)
    pub format: PropertyFormat,
    /// Unique key for the property
    pub key: String,
    /// Display name for the property
    pub name: String,
}

/// Represents an Anytype object type.
///
/// Types define the structure and default behavior for objects. Each type
/// has a unique key, a display name, and a default layout. Built-in types
/// include Page, Note, Task, and Bookmark.
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Type {
    /// Data model type returned by the REST API.
    #[serde(default = "type_data_model")]
    pub object: DataModel,

    /// Whether the type is archived
    pub archived: bool,

    /// Type icon (emoji, file, or colored icon)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub icon: Option<Icon>,

    /// Unique type identifier (unique across all spaces)
    pub id: String,

    /// Key of the type (can be the same across spaces for known types, e.g., "page")
    pub key: String,

    /// Default layout for objects of this type
    #[serde(default)]
    pub layout: ObjectLayout,

    /// Display name of the type
    #[serde(default)]
    pub name: Option<String>,

    /// Plural form of the name
    #[serde(default)]
    pub plural_name: Option<String>,

    /// Properties linked to the type
    #[serde(default, deserialize_with = "deserialize_vec_properties_or_null")]
    pub properties: Vec<Property>,
}

fn type_data_model() -> DataModel {
    DataModel::Type
}

/// Source-backed classification of the properties linked to a type.
///
/// Anytype stores featured and ordinary recommended properties in separate
/// source lists, while the REST `Type.properties` field combines their visible
/// definitions and carries no classification boundary. Obtain this model with
/// [`TypeRequest::classify_properties`].
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct TypePropertyClassification {
    /// Exact ordered IDs from Anytype's featured-property source list.
    ///
    /// Some system-featured properties are intentionally omitted from the REST
    /// type representation, so not every ID necessarily has a corresponding
    /// entry in [`featured`](Self::featured).
    pub featured_ids: Vec<String>,

    /// REST-visible featured property definitions, in source-list order.
    pub featured: Vec<Property>,

    /// Complete non-featured recommended property list, in source-list order.
    ///
    /// This is the exact set replaced by [`UpdateTypeRequest::properties`] or
    /// removed by [`UpdateTypeRequest::clear_properties`].
    pub recommended: Vec<Property>,
}

/// Payload-free failure classification for the finite property-classification
/// lifecycle.
#[derive(Clone, Copy, Debug, PartialEq, Eq, strum::Display)]
#[strum(serialize_all = "snake_case")]
pub enum TypePropertyClassificationErrorKind {
    /// `ObjectShow` exceeded its caller-selected finite RPC deadline.
    RpcDeadline,
    /// The matching `ObjectClose` could not be confirmed within its deadline.
    CleanupFailed,
    /// No Tokio runtime was available to own the close fallback.
    RuntimeUnavailable,
}

type TypePropertyCleanupFuture = Pin<Box<dyn Future<Output = Result<()>> + Send>>;
type TypePropertyCleanupAction = Arc<dyn Fn(Duration) -> TypePropertyCleanupFuture + Send + Sync>;

/// Owns the matching close for one type-property `ObjectShow` boundary.
struct TypePropertyCloseGuard {
    action: TypePropertyCleanupAction,
    runtime: tokio::runtime::Handle,
    metrics: Option<Arc<TypePropertyClassificationMetrics>>,
    armed: bool,
}

impl TypePropertyCloseGuard {
    fn new(
        grpc: anytype_rpc::client::AnytypeGrpcClient,
        space_id: String,
        type_id: String,
        metrics: Arc<TypePropertyClassificationMetrics>,
    ) -> Result<Self> {
        let runtime = classification_runtime_handle()?;
        let raw_action: TypePropertyCleanupAction = Arc::new(move |timeout| {
            let grpc = grpc.clone();
            let space_id = space_id.clone();
            let type_id = type_id.clone();
            Box::pin(
                async move { close_type_property_view(grpc, space_id, type_id, timeout).await },
            )
        });
        let action = instrument_cleanup_action(raw_action, Arc::clone(&metrics));
        Ok(Self {
            action,
            runtime,
            metrics: Some(metrics),
            armed: true,
        })
    }

    #[cfg(test)]
    fn from_action(action: TypePropertyCleanupAction) -> Self {
        Self {
            action,
            runtime: tokio::runtime::Handle::current(),
            metrics: None,
            armed: true,
        }
    }

    #[cfg(test)]
    fn from_action_with_metrics(
        action: TypePropertyCleanupAction,
        metrics: Arc<TypePropertyClassificationMetrics>,
    ) -> Self {
        Self {
            action: instrument_cleanup_action(action, Arc::clone(&metrics)),
            runtime: tokio::runtime::Handle::current(),
            metrics: Some(metrics),
            armed: true,
        }
    }

    async fn cleanup(&mut self, timeout: Duration) -> Result<()> {
        match (self.action)(timeout).await {
            Ok(()) => {
                self.armed = false;
                Ok(())
            }
            Err(_) => classification_error(TypePropertyClassificationErrorKind::CleanupFailed),
        }
    }
}

fn instrument_cleanup_action(
    action: TypePropertyCleanupAction,
    metrics: Arc<TypePropertyClassificationMetrics>,
) -> TypePropertyCleanupAction {
    Arc::new(move |timeout| {
        let action = Arc::clone(&action);
        let metrics = Arc::clone(&metrics);
        Box::pin(async move {
            metrics.close_attempts.fetch_add(1, Ordering::Relaxed);
            let result = action(timeout).await;
            if result.is_ok() {
                metrics.cleanup_successes.fetch_add(1, Ordering::Relaxed);
            } else {
                metrics.cleanup_failures.fetch_add(1, Ordering::Relaxed);
            }
            result
        })
    })
}

fn classification_runtime_handle() -> Result<tokio::runtime::Handle> {
    tokio::runtime::Handle::try_current().map_err(|_| {
        classification_error_value(TypePropertyClassificationErrorKind::RuntimeUnavailable)
    })
}

impl Drop for TypePropertyCloseGuard {
    fn drop(&mut self) {
        if !self.armed {
            return;
        }
        let action = Arc::clone(&self.action);
        let metrics = self.metrics.clone();
        self.runtime.spawn(async move {
            if let Some(metrics) = metrics.as_ref() {
                metrics.close_fallbacks.fetch_add(1, Ordering::Relaxed);
            }
            let _ = action(MAX_TYPE_PROPERTY_RPC_TIMEOUT).await;
        });
    }
}

impl TypePropertyClassification {
    /// Returns the complete property set replaceable by a type update.
    #[must_use]
    pub fn replaceable(&self) -> &[Property] {
        &self.recommended
    }
}

fn deserialize_vec_properties_or_null<'de, D>(deserializer: D) -> Result<Vec<Property>, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Option::<Vec<Property>>::deserialize(deserializer)?;
    Ok(value.unwrap_or_default())
}

impl Type {
    /// Returns true if this is a built-in system type.
    ///
    /// System types like "page" and "note" cannot be deleted.
    pub fn is_system_type(&self) -> bool {
        matches!(self.key.as_str(), "page" | "note" | "task" | "bookmark")
    }

    /// Returns the name of the type, or the key if name is not set.
    pub fn display_name(&self) -> &str {
        self.name.as_deref().unwrap_or(&self.key)
    }

    pub fn get_property_by_key(&self, property_key: &str) -> Option<&Property> {
        self.properties.iter().find(|prop| prop.key == property_key)
    }
}

// ============================================================================
// RESPONSE TYPES (internal)
// ============================================================================

/// Response wrapper for single type operations
#[derive(Debug, Deserialize)]
struct TypeResponse {
    #[serde(rename = "type")]
    type_: Type,
}

// ============================================================================
// REQUEST BODY TYPES (internal)
// ============================================================================

/// Internal request body for creating a type
#[derive(Debug, Serialize)]
struct CreateTypeRequestBody {
    name: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    key: Option<String>,

    plural_name: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    icon: Option<Icon>,

    layout: TypeLayout,

    #[serde(skip_serializing_if = "Vec::is_empty")]
    properties: Vec<CreateTypeProperty>,
}

/// Internal request body for updating a type
#[derive(Debug, Serialize, Default)]
struct UpdateTypeRequestBody {
    #[serde(skip_serializing_if = "Option::is_none")]
    name: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    key: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    plural_name: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    icon: Option<Icon>,

    #[serde(skip_serializing_if = "Option::is_none")]
    layout: Option<TypeLayout>,

    #[serde(skip_serializing_if = "Option::is_none")]
    properties: Option<Vec<CreateTypeProperty>>,
}

// ============================================================================
// BUILDER STRUCTS (public)
// ============================================================================

/// Request builder for getting or deleting a single type.
///
/// Obtained via [`AnytypeClient::get_type`].
#[derive(Debug)]
pub struct TypeRequest {
    api: AnytypeClient,
    client: Arc<HttpClient>,
    limits: ValidationLimits,
    space_id: String,
    type_id: String,
    cache: Arc<AnytypeCache>,
}

impl TypeRequest {
    /// Creates a new `TypeRequest`.
    pub(crate) fn new(
        api: AnytypeClient,
        space_id: impl Into<String>,
        type_id: impl Into<String>,
    ) -> Self {
        Self {
            client: api.client.clone(),
            limits: api.config.limits.clone(),
            space_id: space_id.into(),
            type_id: type_id.into(),
            cache: api.cache.clone(),
            api,
        }
    }

    /// Retrieves the type by ID.
    ///
    /// # Returns
    /// The type with all its metadata and properties.
    ///
    /// # Errors
    /// - [`AnytypeError::NotFound`] if the type doesn't exist
    /// - [`AnytypeError::Validation`] if IDs are invalid
    pub async fn get(self) -> Result<Type> {
        self.limits.validate_id(&self.space_id, "space_id")?;
        self.limits.validate_id(&self.type_id, "type_id")?;

        if self.cache.is_enabled() {
            if let Some(typ) = self.cache.get_type(&self.space_id, &self.type_id) {
                return Ok((*typ).clone());
            }
            // see note on locking design in cache.rs
            if !self.cache.has_types(&self.space_id) {
                prime_cache_types(&self.client, &self.cache, &self.space_id).await?;
                if let Some(type_) = self.cache.get_type(&self.space_id, &self.type_id) {
                    return Ok((*type_).clone());
                }
            }
            return NotFoundSnafu {
                obj_type: "Type".to_string(),
                key: self.type_id.clone(),
            }
            .fail();
        }
        self.fetch_direct().await
    }

    /// Retrieves the type with one cache-independent HTTP request.
    ///
    /// Unlike [`get`](Self::get), this method neither reads nor primes the
    /// in-memory type cache. It validates the scoped space and type IDs before
    /// dispatch, then rejects a successful response whose type ID differs from
    /// the requested ID. This is useful for bounded resolver and protocol
    /// paths that must not turn a single-ID lookup into an all-types scan.
    ///
    /// # Returns
    /// The type returned for the exact scoped type endpoint.
    ///
    /// # Errors
    /// - [`AnytypeError::NotFound`] if the type doesn't exist
    /// - [`AnytypeError::Validation`] if either ID is invalid
    /// - [`AnytypeError::Other`] if the upstream response identity does not
    ///   match the scoped request
    pub async fn get_direct(self) -> Result<Type> {
        self.limits.validate_id(&self.space_id, "space_id")?;
        self.limits.validate_id(&self.type_id, "type_id")?;
        self.fetch_direct().await
    }

    /// Reads the exact replaceable property set and its featured-property
    /// classification without reading or priming either metadata cache.
    ///
    /// One direct REST type GET supplies public property definitions. One gRPC
    /// `ObjectShow` supplies the separate source ID lists because the REST wire
    /// model flattens them. The shown view is released with a finite,
    /// cancellation-resilient owned `ObjectClose`. The combined source-list size is capped by
    /// [`MAX_TYPE_PROPERTY_LINKS`], and the read fails whole on duplicate,
    /// overlapping, missing, extra, malformed, or inconsistent evidence.
    ///
    /// These two reads are not an atomic server snapshot. A concurrent edit or
    /// eventual-consistency window can therefore produce an error; callers may
    /// retry the complete read. gRPC credentials are required.
    ///
    /// # Errors
    /// - [`AnytypeError::Validation`] if either scoped ID is invalid
    /// - [`AnytypeError::NotFound`] if the exact type is not returned
    /// - [`AnytypeError::GrpcUnavailable`] when gRPC credentials are unavailable
    /// - [`AnytypeError::Other`] for malformed, oversized, or inconsistent
    ///   upstream evidence
    pub async fn classify_properties(self) -> Result<TypePropertyClassification> {
        self.classify_properties_with_deadline(MAX_TYPE_PROPERTY_RPC_TIMEOUT)
            .await
    }

    /// Reads the exact property classification with a caller-selected finite
    /// deadline for the gRPC `ObjectShow` operation.
    ///
    /// The deadline must be nonzero and no greater than
    /// [`MAX_TYPE_PROPERTY_RPC_TIMEOUT`]. Every explicit or detached
    /// `ObjectClose` receives its own fresh [`MAX_TYPE_PROPERTY_RPC_TIMEOUT`]
    /// deadline. The close lifecycle is owned before show dispatch, so dropping
    /// this future during show or close starts one detached close fallback on
    /// the current Tokio runtime.
    ///
    /// # Errors
    /// - [`AnytypeError::Validation`] if IDs or the deadline are invalid
    /// - [`AnytypeError::TypePropertyClassification`] for an RPC deadline or
    ///   unconfirmed cleanup
    /// - the errors documented by [`Self::classify_properties`]
    pub async fn classify_properties_with_deadline(
        self,
        rpc_timeout: Duration,
    ) -> Result<TypePropertyClassification> {
        self.limits.validate_id(&self.space_id, "space_id")?;
        self.limits.validate_id(&self.type_id, "type_id")?;
        ensure!(
            !rpc_timeout.is_zero() && rpc_timeout <= MAX_TYPE_PROPERTY_RPC_TIMEOUT,
            ValidationSnafu {
                message: "type property RPC deadline must be between zero and five seconds"
                    .to_owned(),
            }
        );

        let typ = self.fetch_direct().await?;
        let (featured_ids, recommended_ids) = fetch_type_property_source_ids(
            &self.api,
            &self.limits,
            &self.space_id,
            &self.type_id,
            rpc_timeout,
        )
        .await?;
        classify_type_properties(typ.properties, featured_ids, recommended_ids)
    }

    async fn fetch_direct(&self) -> Result<Type> {
        let response: TypeResponse = self
            .client
            .get_request(
                &format!("/v1/spaces/{}/types/{}", self.space_id, self.type_id),
                QueryWithFilters::default(),
            )
            .await?;
        if response.type_.id != self.type_id {
            return OtherSnafu {
                message: "Anytype returned a mismatched type identity".to_string(),
            }
            .fail();
        }
        Ok(response.type_)
    }

    /// Deletes (archives) the type.
    ///
    /// # Returns
    /// The deleted type.
    ///
    /// # Errors
    /// - [`AnytypeError::NotFound`] if the type doesn't exist
    /// - [`AnytypeError::Forbidden`] if you don't have permission
    pub async fn delete(self) -> Result<Type> {
        self.limits.validate_id(&self.space_id, "space_id")?;
        self.limits.validate_id(&self.type_id, "type_id")?;

        let response: TypeResponse = self
            .client
            .delete_request(&format!(
                "/v1/spaces/{}/types/{}",
                self.space_id, self.type_id
            ))
            .await?;

        if self.cache.has_types(&self.space_id) {
            self.cache.delete_type(&self.space_id, &self.type_id);
        }
        Ok(response.type_)
    }
}

async fn fetch_type_property_source_ids(
    client: &AnytypeClient,
    limits: &ValidationLimits,
    space_id: &str,
    type_id: &str,
    rpc_timeout: Duration,
) -> Result<(Vec<String>, Vec<String>)> {
    let grpc = client.grpc_client().await?;
    let mut commands = grpc.client_commands();
    let request = object_show::Request {
        context_id: type_id.to_owned(),
        object_id: type_id.to_owned(),
        space_id: space_id.to_owned(),
        include_relations_as_dependent_objects: false,
        ..Default::default()
    };
    let mut request = with_token_request(Request::new(request), grpc.token())?;
    request.set_timeout(rpc_timeout);
    let metrics = Arc::clone(&client.type_property_metrics);
    let mut cleanup = TypePropertyCloseGuard::new(
        grpc,
        space_id.to_owned(),
        type_id.to_owned(),
        Arc::clone(&metrics),
    )?;
    metrics.show_attempts.fetch_add(1, Ordering::Relaxed);
    let response = match tokio::time::timeout(rpc_timeout, commands.object_show(request)).await {
        Ok(Ok(response)) => response.into_inner(),
        Ok(Err(status)) => {
            let show_error = grpc_status(status);
            cleanup.cleanup(MAX_TYPE_PROPERTY_RPC_TIMEOUT).await?;
            return Err(show_error);
        }
        Err(_) => {
            cleanup.cleanup(MAX_TYPE_PROPERTY_RPC_TIMEOUT).await?;
            return classification_error(TypePropertyClassificationErrorKind::RpcDeadline);
        }
    };
    let response_error = ensure_error_ok(response.error.as_ref(), "type property source read");
    let cleanup_result = cleanup.cleanup(MAX_TYPE_PROPERTY_RPC_TIMEOUT).await;
    finish_type_property_show(response_error, cleanup_result)?;

    let view = response.object_view.ok_or_else(|| AnytypeError::Other {
        message: "type property source read returned no object view".to_owned(),
    })?;
    type_property_source_ids_from_view(&view, limits, type_id)
}

fn finish_type_property_show(
    response_result: Result<()>,
    cleanup_result: Result<()>,
) -> Result<()> {
    cleanup_result?;
    response_result
}

async fn close_type_property_view(
    grpc: anytype_rpc::client::AnytypeGrpcClient,
    space_id: String,
    type_id: String,
    rpc_timeout: Duration,
) -> Result<()> {
    let mut commands = grpc.client_commands();
    let close = object_close::Request {
        context_id: type_id.clone(),
        object_id: type_id,
        space_id,
    };
    let mut close = with_token_request(Request::new(close), grpc.token())?;
    close.set_timeout(rpc_timeout);
    let response = tokio::time::timeout(rpc_timeout, commands.object_close(close))
        .await
        .map_err(|_| {
            classification_error_value(TypePropertyClassificationErrorKind::CleanupFailed)
        })?
        .map_err(grpc_status)?
        .into_inner();
    ensure_error_ok(response.error.as_ref(), "type property source cleanup")
}

fn classification_error<T>(kind: TypePropertyClassificationErrorKind) -> Result<T> {
    Err(classification_error_value(kind))
}

fn classification_error_value(kind: TypePropertyClassificationErrorKind) -> AnytypeError {
    AnytypeError::TypePropertyClassification { kind }
}

fn type_property_source_ids_from_view(
    view: &model::ObjectView,
    limits: &ValidationLimits,
    type_id: &str,
) -> Result<(Vec<String>, Vec<String>)> {
    let mut matching = view.details.iter().filter(|details| details.id == type_id);
    let first = matching.next().ok_or_else(|| AnytypeError::Other {
        message: "type property source read omitted the requested type details".to_owned(),
    })?;
    let source_ids = type_property_source_ids_from_details(first, limits)?;
    for duplicate in matching {
        ensure!(
            type_property_source_ids_from_details(duplicate, limits)? == source_ids,
            OtherSnafu {
                message: "type property source read returned conflicting type details".to_owned(),
            }
        );
    }
    Ok(source_ids)
}

fn type_property_source_ids_from_details(
    details: &model::object_view::DetailsSet,
    limits: &ValidationLimits,
) -> Result<(Vec<String>, Vec<String>)> {
    let details = details
        .details
        .as_ref()
        .ok_or_else(|| AnytypeError::Other {
            message: "type property source read returned empty type details".to_owned(),
        })?;

    let featured = property_source_ids(details, RECOMMENDED_FEATURED_RELATIONS, limits)?;
    let recommended = property_source_ids(details, RECOMMENDED_RELATIONS, limits)?;
    let count = featured
        .len()
        .checked_add(recommended.len())
        .ok_or_else(|| AnytypeError::Other {
            message: "type property source link count overflowed".to_owned(),
        })?;
    ensure!(
        count <= MAX_TYPE_PROPERTY_LINKS,
        OtherSnafu {
            message: "type property source exceeded the 1,000-link limit".to_owned(),
        }
    );
    Ok((featured, recommended))
}

fn property_source_ids(
    details: &prost_types::Struct,
    key: &str,
    limits: &ValidationLimits,
) -> Result<Vec<String>> {
    let Some(value) = details.fields.get(key) else {
        return Ok(Vec::new());
    };
    let Some(Kind::ListValue(list)) = value.kind.as_ref() else {
        return OtherSnafu {
            message: "type property source field was not a list".to_owned(),
        }
        .fail();
    };
    ensure!(
        list.values.len() <= MAX_TYPE_PROPERTY_LINKS,
        OtherSnafu {
            message: "type property source exceeded the 1,000-link limit".to_owned(),
        }
    );

    let mut ids = Vec::with_capacity(list.values.len());
    for value in &list.values {
        let Some(Kind::StringValue(id)) = value.kind.as_ref() else {
            return OtherSnafu {
                message: "type property source list contained a non-string ID".to_owned(),
            }
            .fail();
        };
        if limits.validate_id(id, "property_id").is_err() {
            return OtherSnafu {
                message: "type property source list contained an invalid ID".to_owned(),
            }
            .fail();
        }
        ids.push(id.clone());
    }
    Ok(ids)
}

fn classify_type_properties(
    properties: Vec<Property>,
    featured_ids: Vec<String>,
    recommended_ids: Vec<String>,
) -> Result<TypePropertyClassification> {
    let mut classes =
        HashMap::with_capacity(featured_ids.len().saturating_add(recommended_ids.len()));
    for id in &featured_ids {
        ensure!(
            classes.insert(id.as_str(), true).is_none(),
            OtherSnafu {
                message: "type property source lists contained duplicate IDs".to_owned(),
            }
        );
    }
    for id in &recommended_ids {
        ensure!(
            classes.insert(id.as_str(), false).is_none(),
            OtherSnafu {
                message: "type property source lists overlapped or contained duplicate IDs"
                    .to_owned(),
            }
        );
    }

    let mut definitions = HashMap::with_capacity(properties.len());
    for property in properties {
        ensure!(
            classes.contains_key(property.id.as_str()),
            OtherSnafu {
                message: "REST type properties contained an unclassified property".to_owned(),
            }
        );
        let id = property.id.clone();
        ensure!(
            definitions.insert(id, property).is_none(),
            OtherSnafu {
                message: "REST type properties contained a duplicate property".to_owned(),
            }
        );
    }

    let mut featured = Vec::with_capacity(featured_ids.len());
    for id in &featured_ids {
        if let Some(property) = definitions.remove(id) {
            featured.push(property);
        }
    }

    let mut recommended = Vec::with_capacity(recommended_ids.len());
    for id in &recommended_ids {
        let property = definitions.remove(id).ok_or_else(|| AnytypeError::Other {
            message: "REST type properties omitted a replaceable property definition".to_owned(),
        })?;
        recommended.push(property);
    }
    ensure!(
        definitions.is_empty(),
        OtherSnafu {
            message: "REST type properties could not be fully classified".to_owned(),
        }
    );

    Ok(TypePropertyClassification {
        featured_ids,
        featured,
        recommended,
    })
}

/// Request builder for creating a new type.
///
/// Obtained via [`AnytypeClient::new_type`].
///
#[derive(Debug)]
pub struct NewTypeRequest {
    client: Arc<HttpClient>,
    limits: ValidationLimits,
    space_id: String,
    name: String,
    key: Option<String>,
    plural_name: String,
    icon: Option<Icon>,
    layout: TypeLayout,
    properties: Vec<CreateTypeProperty>,
    cache: Arc<AnytypeCache>,
    verify_policy: VerifyPolicy,
    verify_config: Option<VerifyConfig>,
}

impl NewTypeRequest {
    /// Creates a new `NewTypeRequest`. You must specify the name and `plural_name`.
    /// Defaults to Basic Layout
    pub(crate) fn new(
        client: Arc<HttpClient>,
        limits: ValidationLimits,
        space_id: impl Into<String>,
        name: String,
        plural_name: String,
        cache: Arc<AnytypeCache>,
        verify_config: Option<VerifyConfig>,
    ) -> Self {
        Self {
            client,
            limits,
            space_id: space_id.into(),
            name,
            key: None,
            plural_name,
            icon: None,
            layout: TypeLayout::Basic,
            properties: Vec::new(),
            cache,
            verify_policy: VerifyPolicy::Default,
            verify_config,
        }
    }

    /// Sets the plural name.
    ///
    /// Default plural name is the name + 's'.
    ///
    /// # Arguments
    /// * `plural_name` - plural display name for the type
    #[must_use]
    pub fn plural_name(mut self, plural_name: impl Into<String>) -> Self {
        self.plural_name = plural_name.into();
        self
    }

    /// Sets the type key.
    ///
    /// The key is a unique identifier for the type, typically lowercase
    /// with underscores (e.g., `project`, `meeting_note`).
    ///
    /// # Arguments
    /// * `key` - Unique key for the type
    #[must_use]
    pub fn key(mut self, key: impl Into<String>) -> Self {
        self.key = Some(key.into());
        self
    }

    /// Sets the type icon.
    ///
    /// # Arguments
    /// * `icon` - Icon for the type
    #[must_use]
    pub fn icon(mut self, icon: Icon) -> Self {
        self.icon = Some(icon);
        self
    }

    /// Sets the default layout for objects of this type.
    ///
    /// # Arguments
    /// * `layout` - Default layout for new objects
    #[must_use]
    pub fn layout(mut self, layout: TypeLayout) -> Self {
        self.layout = layout;
        self
    }

    /// Enables read-after-write verification for this request.
    #[must_use]
    pub fn ensure_available(mut self) -> Self {
        self.verify_policy = VerifyPolicy::Enabled;
        self
    }

    /// Enables verification using a custom config for this request.
    #[must_use]
    pub fn ensure_available_with(mut self, config: VerifyConfig) -> Self {
        self.verify_policy = VerifyPolicy::Enabled;
        self.verify_config = Some(config);
        self
    }

    /// Disables verification for this request.
    #[must_use]
    pub fn no_verify(mut self) -> Self {
        self.verify_policy = VerifyPolicy::Disabled;
        self
    }

    /// Adds a property definition to the type.
    ///
    /// # Arguments
    /// * `name` - name of property to add
    /// * `key` - property key
    /// * `format` - property format
    #[must_use]
    pub fn property(
        mut self,
        name: impl Into<String>,
        key: impl Into<String>,
        format: PropertyFormat,
    ) -> Self {
        self.properties.push({
            CreateTypeProperty {
                name: name.into(),
                key: key.into(),
                format,
            }
        });
        self
    }

    /// Adds multiple property definitions to the type.
    ///
    /// # Arguments
    /// * `properties` - Iterator of property definitions
    #[must_use]
    pub fn properties(mut self, properties: impl IntoIterator<Item = CreateTypeProperty>) -> Self {
        self.properties.extend(properties);
        self
    }

    /// Creates the type with the configured settings.
    ///
    /// # Returns
    /// The newly created type.
    ///
    /// # Errors
    /// - [`AnytypeError::Validation`] if name is not provided or invalid
    pub async fn create(self) -> Result<Type> {
        self.limits.validate_id(&self.space_id, "space_id")?;
        self.limits.validate_name(&self.name, "type name")?;

        let request_body = CreateTypeRequestBody {
            name: self.name,
            key: self.key,
            plural_name: self.plural_name,
            icon: self.icon,
            layout: self.layout,
            properties: self.properties,
        };

        let response: TypeResponse = self
            .client
            .post_request(
                &format!("/v1/spaces/{}/types", self.space_id),
                &request_body,
                QueryWithFilters::default(),
            )
            .await?;

        if self.cache.has_types(&self.space_id) {
            self.cache.set_type(&self.space_id, response.type_.clone());
        }
        let typ = response.type_;
        if let Some(config) = resolve_verify(self.verify_policy, self.verify_config.as_ref()) {
            return verify_available(&config, "Type", &typ.id, || async {
                let response: TypeResponse = self
                    .client
                    .get_request(
                        &format!("/v1/spaces/{}/types/{}", self.space_id, typ.id),
                        QueryWithFilters::default(),
                    )
                    .await?;
                Ok(response.type_)
            })
            .await;
        }
        Ok(typ)
    }
}

/// Request builder for updating an existing type.
///
/// Obtained via [`AnytypeClient::update_type`].
///
#[derive(Debug)]
pub struct UpdateTypeRequest {
    client: Arc<HttpClient>,
    limits: ValidationLimits,
    space_id: String,
    type_id: String,
    name: Option<String>,
    key: Option<String>,
    plural_name: Option<String>,
    icon: Option<Icon>,
    layout: Option<TypeLayout>,
    properties: Option<Vec<CreateTypeProperty>>,
    cache: Arc<AnytypeCache>,
    verify_policy: VerifyPolicy,
    verify_config: Option<VerifyConfig>,
}

impl UpdateTypeRequest {
    /// Creates a new `UpdateTypeRequest`.
    pub(crate) fn new(
        client: Arc<HttpClient>,
        limits: ValidationLimits,
        space_id: impl Into<String>,
        type_id: impl Into<String>,
        cache: Arc<AnytypeCache>,
        verify_config: Option<VerifyConfig>,
    ) -> Self {
        Self {
            client,
            limits,
            space_id: space_id.into(),
            type_id: type_id.into(),
            name: None,
            key: None,
            plural_name: None,
            icon: None,
            layout: None,
            properties: None,
            cache,
            verify_policy: VerifyPolicy::Default,
            verify_config,
        }
    }

    /// Updates the type name.
    ///
    /// # Arguments
    /// * `name` - New display name for the type
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Updates the type key.
    ///
    /// # Arguments
    /// * `key` - New key for the type
    #[must_use]
    pub fn key(mut self, key: impl Into<String>) -> Self {
        self.key = Some(key.into());
        self
    }

    /// Updates the plural name.
    ///
    /// # Arguments
    /// * `plural_name` - New plural form of the type name
    #[must_use]
    pub fn plural_name(mut self, plural_name: impl Into<String>) -> Self {
        self.plural_name = Some(plural_name.into());
        self
    }

    /// Updates the type icon.
    ///
    /// # Arguments
    /// * `icon` - New icon for the type
    #[must_use]
    pub fn icon(mut self, icon: Icon) -> Self {
        self.icon = Some(icon);
        self
    }

    /// Updates the default layout.
    ///
    /// # Arguments
    /// * `layout` - New default layout for objects of this type
    #[must_use]
    pub fn layout(mut self, layout: TypeLayout) -> Self {
        self.layout = Some(layout);
        self
    }

    /// Enables read-after-write verification for this request.
    #[must_use]
    pub fn ensure_available(mut self) -> Self {
        self.verify_policy = VerifyPolicy::Enabled;
        self
    }

    /// Enables verification using a custom config for this request.
    #[must_use]
    pub fn ensure_available_with(mut self, config: VerifyConfig) -> Self {
        self.verify_policy = VerifyPolicy::Enabled;
        self.verify_config = Some(config);
        self
    }

    /// Disables verification for this request.
    #[must_use]
    pub fn no_verify(mut self) -> Self {
        self.verify_policy = VerifyPolicy::Disabled;
        self
    }

    /// Adds a property definition to the replacement property list.
    ///
    /// When this method is used, the REST API replaces all existing
    /// non-featured recommended properties with the properties supplied to
    /// this update. It does not append to the type's current properties.
    ///
    /// # Arguments
    /// * `name` - name of property to add
    /// * `key` - property key
    /// * `format` - property format
    #[must_use]
    pub fn property(
        mut self,
        name: impl Into<String>,
        key: impl Into<String>,
        format: PropertyFormat,
    ) -> Self {
        self.properties.get_or_insert_default().push({
            CreateTypeProperty {
                name: name.into(),
                key: key.into(),
                format,
            }
        });
        self
    }

    /// Replaces all non-featured recommended properties on the type.
    ///
    /// The provided collection is the complete replacement, not a set of
    /// additions. Pass an empty collection or use [`Self::clear_properties`]
    /// to remove all non-featured recommended properties.
    #[must_use]
    pub fn properties(mut self, properties: impl IntoIterator<Item = CreateTypeProperty>) -> Self {
        self.properties = Some(properties.into_iter().collect());
        self
    }

    /// Removes all non-featured recommended properties from the type.
    ///
    /// Featured properties managed by Anytype are not affected.
    #[must_use]
    pub fn clear_properties(mut self) -> Self {
        self.properties = Some(Vec::new());
        self
    }

    /// Applies the update to the type.
    ///
    /// # Returns
    /// The updated type.
    ///
    /// # Errors
    /// - [`AnytypeError::Validation`] if called without setting any fields
    /// - [`AnytypeError::NotFound`] if the type doesn't exist
    pub async fn update(self) -> Result<Type> {
        self.limits.validate_id(&self.space_id, "space_id")?;
        self.limits.validate_id(&self.type_id, "type_id")?;

        // Check that at least one field is being updated
        ensure!(
            self.name.is_some()
                || self.key.is_some()
                || self.plural_name.is_some()
                || self.icon.is_some()
                || self.layout.is_some()
                || self.properties.is_some(),
            ValidationSnafu {
                message: "update_type: must set at least one field to update".to_string(),
            }
        );

        if let Some(ref name) = self.name {
            self.limits.validate_name(name, "type")?;
        }

        let request_body = UpdateTypeRequestBody {
            name: self.name,
            key: self.key,
            plural_name: self.plural_name,
            icon: self.icon,
            layout: self.layout,
            properties: self.properties,
        };

        let response: TypeResponse = self
            .client
            .patch_request(
                &format!("/v1/spaces/{}/types/{}", self.space_id, self.type_id),
                &request_body,
            )
            .await?;

        if self.cache.has_types(&self.space_id) {
            self.cache.set_type(&self.space_id, response.type_.clone());
        }

        let typ = response.type_;
        if let Some(config) = resolve_verify(self.verify_policy, self.verify_config.as_ref()) {
            return verify_available(&config, "Type", &typ.id, || async {
                let response: TypeResponse = self
                    .client
                    .get_request(
                        &format!("/v1/spaces/{}/types/{}", self.space_id, typ.id),
                        QueryWithFilters::default(),
                    )
                    .await?;
                Ok(response.type_)
            })
            .await;
        }
        Ok(typ)
    }
}

/// Request builder for listing types in a space.
///
/// Obtained via [`AnytypeClient::types`].
///
#[derive(Debug)]
pub struct ListTypesRequest {
    client: Arc<HttpClient>,
    limits: ValidationLimits,
    space_id: String,
    limit: Option<u32>,
    offset: Option<u32>,
    filters: Vec<Filter>,
    cache: Arc<AnytypeCache>,
}

impl ListTypesRequest {
    /// Creates a new `ListTypesRequest`.
    pub(crate) fn new(
        client: Arc<HttpClient>,
        limits: ValidationLimits,
        space_id: impl Into<String>,
        cache: Arc<AnytypeCache>,
    ) -> Self {
        Self {
            client,
            limits,
            space_id: space_id.into(),
            limit: None,
            offset: None,
            filters: Vec::new(),
            cache,
        }
    }

    /// Sets the pagination limit (max items per page).
    ///
    /// Default is 100, maximum is 1000.
    ///
    /// # Arguments
    /// * `limit` - Number of items to return per page
    #[must_use]
    pub fn limit(mut self, limit: u32) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Sets the pagination offset (starting position).
    ///
    /// # Arguments
    /// * `offset` - Number of items to skip
    #[must_use]
    pub fn offset(mut self, offset: u32) -> Self {
        self.offset = Some(offset);
        self
    }

    /// Adds a filter condition.
    ///
    /// Multiple filters are combined with AND logic.
    ///
    /// # Arguments
    /// * `filter` - Filter condition to add
    #[must_use]
    pub fn filter(mut self, filter: Filter) -> Self {
        self.filters.push(filter);
        self
    }

    /// Adds multiple filter conditions.
    ///
    /// # Arguments
    /// * `filters` - Iterator of filters to add
    #[must_use]
    pub fn filters(mut self, filters: impl IntoIterator<Item = Filter>) -> Self {
        self.filters.extend(filters);
        self
    }

    /// Executes the list request.
    ///
    /// # Returns
    /// A paginated result containing the matching types.
    ///
    /// To take advantage of cached properties for the `list()` method,
    /// the cache must be enabled, and  the query
    /// parameter must not contain filters or pagination limits or offsets.
    ///
    /// The response may include archived types,
    /// To exclude, filter returned values with `.filter(|typ| !typ.archived)`
    ///
    /// # Errors
    /// - [`AnytypeError::Validation`] if `space_id` is invalid
    pub async fn list(self) -> Result<PagedResult<Type>> {
        self.limits.validate_id(&self.space_id, "space_id")?;

        if self.cache.is_enabled()
            && self.limit.is_none()
            && self.offset.unwrap_or_default() == 0
            && self.filters.is_empty()
        {
            // see note on locking design in cache.rs
            if !self.cache.has_types(&self.space_id) {
                prime_cache_types(&self.client, &self.cache, &self.space_id).await?;
            }
            return Ok(PagedResult::from_items(
                self.cache
                    .types_for_space(&self.space_id)
                    .unwrap_or_default(),
            ));
        }

        // cache disabled, or query has limits or filters that need to be evaluated on the server
        let query = Query::default()
            .set_limit_opt(self.limit)
            .set_offset_opt(self.offset)
            .add_filters(&self.filters);

        self.client
            .get_request_paged(&format!("/v1/spaces/{}/types", self.space_id), query)
            .await
    }
}

/// Load all space types into cache.
async fn prime_cache_types(
    client: &Arc<HttpClient>,
    cache: &Arc<AnytypeCache>,
    space_id: &str,
) -> Result<()> {
    let types: Vec<Type> = client
        .get_request_paged(
            &format!("/v1/spaces/{space_id}/types"),
            QueryWithFilters::default(),
        )
        .await?
        .collect_all()
        .await?
        .into_iter()
        .filter(|typ: &Type| !typ.archived)
        .collect();
    cache.set_types(space_id, types);
    Ok(())
}

// ============================================================================
// ANYTYPECLIENT METHODS
// ============================================================================

impl AnytypeClient {
    /// Creates a request builder for getting or deleting a single type by id.
    /// To get by key, use [`lookup_type_by_key`](AnytypeClient::lookup_type_by_key)
    ///
    /// # Arguments
    /// * `space_id` - ID of the space containing the type
    /// * `type_id` - ID of the type
    ///
    /// # Example
    ///
    /// ```rust
    /// # use anytype::prelude::*;
    /// # async fn example() -> Result<(), AnytypeError> {
    /// #   let client = AnytypeClient::new("doc test")?;
    /// #   let space_id = anytype::test_util::example_space_id(&client).await?;
    /// #   let typ = client.lookup_type_by_key(&space_id, "page").await?;
    /// #   let type_id = &typ.id;
    /// let typ = client.get_type(&space_id, type_id).get().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_type(&self, space_id: impl Into<String>, type_id: impl Into<String>) -> TypeRequest {
        TypeRequest::new(self.clone(), space_id, type_id)
    }

    /// Creates a request builder for creating a new type.
    /// - default plural name is name + 's'. Override with .`plural_name()`
    /// - default layout is Basic. Override with `.layout(`)
    ///
    /// # Arguments
    /// * `space_id` - ID of the space to create the type in
    /// * `name` - type name
    ///
    /// # Example
    ///
    /// ```rust
    /// # use anytype::prelude::*;
    /// # async fn example() -> Result<(), AnytypeError> {
    /// #   let client = AnytypeClient::new("doc test")?;
    /// #   let space_id = anytype::test_util::example_space_id(&client).await?;
    ///
    /// let project = client.new_type(&space_id, "My Project")
    ///     .key("my_project")
    ///     .create().await?;
    ///
    /// # client.get_type(&space_id, &project.id).delete().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn new_type(&self, space_id: impl Into<String>, name: impl Into<String>) -> NewTypeRequest {
        let name = name.into();
        let plural_name = format!("{name}s");
        NewTypeRequest::new(
            self.client.clone(),
            self.config.limits.clone(),
            space_id,
            name,
            plural_name,
            self.cache.clone(),
            self.config.verify.clone(),
        )
    }

    /// Creates a request builder for updating an existing type.
    ///
    /// # Arguments
    /// * `space_id` - ID of the space containing the type
    /// * `type_id` - ID of the type to update
    ///
    /// # Example
    ///
    /// ```rust
    /// # use anytype::prelude::*;
    /// # async fn example() -> Result<(), AnytypeError> {
    /// #   let client = AnytypeClient::new("doc test")?;
    /// #   let space_id = anytype::test_util::example_space_id(&client).await?;
    ///
    /// let project = client.new_type(&space_id, "My Project")
    ///     .key("my_project")
    ///     .create().await?;
    ///
    /// // Change the name and replace all non-featured recommended properties
    /// // with a single text field named "Location".
    /// let typ = client.update_type(&space_id, &project.id)
    ///     .name("My New Project")
    ///     .property("Location", "location", PropertyFormat::Text)
    ///     .update().await?;
    ///
    /// # client.get_type(&space_id, &project.id).delete().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn update_type(
        &self,
        space_id: impl Into<String>,
        type_id: impl Into<String>,
    ) -> UpdateTypeRequest {
        UpdateTypeRequest::new(
            self.client.clone(),
            self.config.limits.clone(),
            space_id,
            type_id,
            self.cache.clone(),
            self.config.verify.clone(),
        )
    }

    /// Creates a request builder for listing types in a space.
    ///
    /// # Arguments
    /// * `space_id` - ID of the space to list types from
    ///
    /// # Example
    ///
    /// ```rust
    /// use anytype::prelude::*;
    /// # async fn example() -> Result<(), AnytypeError> {
    /// #   let client = AnytypeClient::new("doc test")?;
    /// #   let space_id = anytype::test_util::example_space_id(&client).await?;
    ///
    /// let types = client.types(&space_id)
    ///     .limit(50)
    ///     .list().await?.collect_all().await?;
    /// for typ in types.iter() {
    ///     println!("{:20} {:20} {}", &typ.display_name(), &typ.key, &typ.id);
    /// }
    ///
    /// # Ok(())
    /// # }
    /// ```
    pub fn types(&self, space_id: impl Into<String>) -> ListTypesRequest {
        ListTypesRequest::new(
            self.client.clone(),
            self.config.limits.clone(),
            space_id,
            self.cache.clone(),
        )
    }

    /// Searches for type in space by id, key, or name using case-insensitive match
    /// Excludes archived types.
    ///
    /// # Example
    ///
    /// ```rust
    /// use anytype::prelude::*;
    /// # async fn example() -> Result<(), AnytypeError> {
    /// #   let client = AnytypeClient::new("doc test")?;
    /// #   let space_id = anytype::test_util::example_space_id(&client).await?;
    ///
    /// let types = client.lookup_types(&space_id, "page").await?;
    /// for typ in types.iter() {
    ///     println!("Type {}", &typ.display_name());
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Errors:
    /// - `AnytypeError::NotFound` if no type in the space matched
    /// - `AnytypeError::CacheDisabled` if cache is disabled
    /// - `AnytypeError::*` any other error (likely server connection error)
    pub async fn lookup_types(&self, space_id: &str, text: impl AsRef<str>) -> Result<Vec<Type>> {
        ensure!(self.cache.is_enabled(), CacheDisabledSnafu);
        // see note on locking design in cache.rs
        if !self.cache.has_types(space_id) {
            prime_cache_types(&self.client, &self.cache, space_id).await?;
        }
        match self.cache.lookup_types(space_id, text.as_ref()) {
            Some(types) if !types.is_empty() => {
                Ok(types.into_iter().map(|arc| (*arc).clone()).collect())
            }
            _ => NotFoundSnafu {
                obj_type: "Type".to_string(),
                key: text.as_ref().to_string(),
            }
            .fail(),
        }
    }

    /// Searches for type in space by key.
    /// Excludes archived types.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use anytype::prelude::*;
    /// # async fn example() -> Result<(), AnytypeError> {
    /// #   let client = AnytypeClient::new("doc test")?;
    /// #   let space_id = anytype::test_util::example_space_id(&client).await?;
    ///
    /// let typ = client.lookup_type_by_key(&space_id, "page").await?;
    /// println!("Type {} key:{} id:{}", &typ.display_name(), &typ.key, &typ.id);
    ///
    /// # Ok(())
    /// # }
    /// ```
    /// Errors:
    /// - `AnytypeError::NotFound` if no type in the space matched
    /// - `AnytypeError::CacheDisabled` if cache is disabled
    /// - `AnytypeError::*` any other error (likely server connection error)
    ///
    pub async fn lookup_type_by_key(&self, space_id: &str, text: impl AsRef<str>) -> Result<Type> {
        ensure!(self.cache.is_enabled(), CacheDisabledSnafu);
        // see note on locking design in cache.rs
        if !self.cache.has_types(space_id) {
            prime_cache_types(&self.client, &self.cache, space_id).await?;
        }
        self.cache
            .lookup_type_by_key(space_id, text.as_ref())
            .map_or_else(
                || {
                    NotFoundSnafu {
                        obj_type: "Type".to_string(),
                        key: text.as_ref().to_string(),
                    }
                    .fail()
                },
                |typ| Ok((*typ).clone()),
            )
    }
}

// ============================================================================
// TESTS
// ============================================================================

#[cfg(test)]
mod tests {
    use std::{
        future::pending,
        sync::{
            Arc, Mutex,
            atomic::{AtomicUsize, Ordering},
        },
        time::Duration,
    };

    use tokio::sync::Notify;

    use super::*;

    fn valid_id(suffix: char) -> String {
        format!("bafyrei{}{}", "a".repeat(51), suffix)
    }

    fn property(id: &str, key: &str) -> Property {
        serde_json::from_value(serde_json::json!({
            "object": "property",
            "name": key,
            "key": key,
            "id": id,
            "format": "text"
        }))
        .expect("property fixture")
    }

    #[test]
    fn type_schema_preserves_discriminator() {
        let response: TypeResponse = serde_json::from_value(serde_json::json!({
            "type": {
                "object": "type",
                "archived": false,
                "id": "type-id",
                "key": "page",
                "layout": "basic",
                "name": "Page",
                "plural_name": "Pages",
                "properties": []
            }
        }))
        .expect("type response schema");

        assert_eq!(response.type_.object, DataModel::Type);
        let serialized = serde_json::to_value(response.type_).expect("serialize type");
        assert_eq!(serialized["object"], "type");
    }

    #[test]
    fn type_discriminator_defaults_when_omitted_and_preserves_present_value() {
        let type_without_discriminator: Type = serde_json::from_value(serde_json::json!({
            "archived": false,
            "id": "type-id",
            "key": "page"
        }))
        .expect("type without discriminator");
        assert_eq!(type_without_discriminator.object, DataModel::Type);

        let type_with_observed_member: Type = serde_json::from_value(serde_json::json!({
            "object": "member",
            "archived": false,
            "id": "type-id",
            "key": "page"
        }))
        .expect("type with observed discriminator");
        assert_eq!(type_with_observed_member.object, DataModel::Member);
    }

    fn string_list(ids: &[String]) -> prost_types::Value {
        prost_types::Value {
            kind: Some(Kind::ListValue(prost_types::ListValue {
                values: ids
                    .iter()
                    .map(|id| prost_types::Value {
                        kind: Some(Kind::StringValue(id.clone())),
                    })
                    .collect(),
            })),
        }
    }

    fn update_property(name: &str, key: &str) -> CreateTypeProperty {
        CreateTypeProperty {
            name: name.to_string(),
            key: key.to_string(),
            format: PropertyFormat::Text,
        }
    }

    #[test]
    fn type_property_cleanup_requires_an_owning_runtime() {
        let error = classification_runtime_handle().expect_err("missing Tokio runtime");
        assert!(matches!(
            error,
            AnytypeError::TypePropertyClassification {
                kind: TypePropertyClassificationErrorKind::RuntimeUnavailable
            }
        ));
    }

    #[tokio::test]
    async fn type_property_deadline_is_validated_before_transport() {
        let client = AnytypeClient::with_config(crate::client::ClientConfig {
            base_url: Some("http://127.0.0.1:1".to_owned()),
            keystore: Some(crate::test_util::test_keystore_spec()),
            disable_cache: true,
            ..crate::client::ClientConfig::default()
        })
        .expect("deadline test client");
        for deadline in [
            Duration::ZERO,
            MAX_TYPE_PROPERTY_RPC_TIMEOUT + Duration::from_nanos(1),
        ] {
            let error = client
                .get_type(valid_id('b'), valid_id('c'))
                .classify_properties_with_deadline(deadline)
                .await
                .expect_err("invalid deadline");
            assert!(matches!(error, AnytypeError::Validation { .. }));
        }
        assert_eq!(client.http_metrics().logical_operations, 0);
    }

    fn successful_cleanup_action(
        calls: Arc<AtomicUsize>,
        cleaned: Arc<Notify>,
    ) -> TypePropertyCleanupAction {
        Arc::new(move |_| {
            let calls = Arc::clone(&calls);
            let cleaned = Arc::clone(&cleaned);
            Box::pin(async move {
                calls.fetch_add(1, Ordering::SeqCst);
                cleaned.notify_one();
                Ok(())
            })
        })
    }

    #[tokio::test]
    async fn type_property_guard_closes_when_show_boundary_is_cancelled() {
        let armed = Arc::new(Notify::new());
        let cleaned = Arc::new(Notify::new());
        let calls = Arc::new(AtomicUsize::new(0));
        let action = successful_cleanup_action(Arc::clone(&calls), Arc::clone(&cleaned));
        let task = tokio::spawn({
            let armed = Arc::clone(&armed);
            async move {
                let _guard = TypePropertyCloseGuard::from_action(action);
                armed.notify_one();
                pending::<()>().await;
            }
        });
        armed.notified().await;
        task.abort();
        let _ = task.await;
        tokio::time::timeout(Duration::from_secs(1), cleaned.notified())
            .await
            .expect("cancelled show guard cleanup");
        assert_eq!(calls.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn type_property_guard_uses_one_fallback_when_close_is_cancelled() {
        let started = Arc::new(Notify::new());
        let recovered = Arc::new(Notify::new());
        let calls = Arc::new(AtomicUsize::new(0));
        let action: TypePropertyCleanupAction = Arc::new({
            let calls = Arc::clone(&calls);
            let started = Arc::clone(&started);
            let recovered = Arc::clone(&recovered);
            move |_| {
                let attempt = calls.fetch_add(1, Ordering::SeqCst);
                let started = Arc::clone(&started);
                let recovered = Arc::clone(&recovered);
                Box::pin(async move {
                    if attempt == 0 {
                        started.notify_one();
                        pending::<()>().await;
                    }
                    recovered.notify_one();
                    Ok(())
                })
            }
        });
        let task = tokio::spawn(async move {
            let mut guard = TypePropertyCloseGuard::from_action(action);
            let _ = guard.cleanup(Duration::from_secs(1)).await;
        });
        started.notified().await;
        task.abort();
        let _ = task.await;
        tokio::time::timeout(Duration::from_secs(1), recovered.notified())
            .await
            .expect("cancelled close guard fallback");
        assert_eq!(calls.load(Ordering::SeqCst), 2);
    }

    #[tokio::test]
    async fn confirmed_type_property_close_disarms_guard() {
        let cleaned = Arc::new(Notify::new());
        let calls = Arc::new(AtomicUsize::new(0));
        let action = successful_cleanup_action(Arc::clone(&calls), Arc::clone(&cleaned));
        {
            let mut guard = TypePropertyCloseGuard::from_action(action);
            guard
                .cleanup(Duration::from_secs(1))
                .await
                .expect("explicit close");
        }
        cleaned.notified().await;
        tokio::task::yield_now().await;
        assert_eq!(calls.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn type_property_close_failure_is_typed_and_payload_free() {
        let calls = Arc::new(AtomicUsize::new(0));
        let durations = Arc::new(Mutex::new(Vec::new()));
        let action: TypePropertyCleanupAction = Arc::new({
            let calls = Arc::clone(&calls);
            let durations = Arc::clone(&durations);
            move |duration| {
                let calls = Arc::clone(&calls);
                durations.lock().expect("duration lock").push(duration);
                Box::pin(async move {
                    calls.fetch_add(1, Ordering::SeqCst);
                    Err(AnytypeError::Other {
                        message: "secret upstream payload".to_owned(),
                    })
                })
            }
        });
        let metrics = Arc::new(TypePropertyClassificationMetrics::default());
        let mut guard =
            TypePropertyCloseGuard::from_action_with_metrics(action, Arc::clone(&metrics));
        let error = guard
            .cleanup(Duration::from_millis(1))
            .await
            .expect_err("cleanup failure");
        assert!(matches!(
            error,
            AnytypeError::TypePropertyClassification {
                kind: TypePropertyClassificationErrorKind::CleanupFailed
            }
        ));
        assert!(!format!("{error:?}").contains("secret upstream payload"));
        drop(guard);
        tokio::time::timeout(Duration::from_secs(1), async {
            while metrics.snapshot().close_attempts < 2 {
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("fallback exhaustion metrics");
        assert_eq!(calls.load(Ordering::SeqCst), 2);
        assert_eq!(
            metrics.snapshot(),
            TypePropertyClassificationMetricsSnapshot {
                show_attempts: 0,
                close_attempts: 2,
                close_fallbacks: 1,
                cleanup_successes: 0,
                cleanup_failures: 2,
            }
        );
        assert_eq!(
            *durations.lock().expect("duration lock"),
            vec![Duration::from_millis(1), MAX_TYPE_PROPERTY_RPC_TIMEOUT]
        );
    }

    #[test]
    fn type_property_cleanup_failure_precedes_show_application_error() {
        let response = Err(AnytypeError::Other {
            message: "show application payload".to_owned(),
        });
        let cleanup = Err(classification_error_value(
            TypePropertyClassificationErrorKind::CleanupFailed,
        ));
        let error = finish_type_property_show(response, cleanup).expect_err("cleanup precedence");
        assert!(matches!(
            error,
            AnytypeError::TypePropertyClassification {
                kind: TypePropertyClassificationErrorKind::CleanupFailed
            }
        ));
        assert!(!format!("{error:?}").contains("show application payload"));
    }

    #[test]
    fn update_type_omits_unchanged_properties() {
        let body = UpdateTypeRequestBody::default();
        assert_eq!(serde_json::to_value(body).unwrap(), serde_json::json!({}));
    }

    #[test]
    fn update_type_serializes_property_replacement() {
        let body = UpdateTypeRequestBody {
            properties: Some(vec![update_property("Location", "location")]),
            ..UpdateTypeRequestBody::default()
        };

        assert_eq!(
            serde_json::to_value(body).unwrap(),
            serde_json::json!({
                "properties": [{
                    "format": "text",
                    "key": "location",
                    "name": "Location"
                }]
            })
        );
    }

    #[test]
    fn update_type_serializes_explicit_property_clear() {
        let body = UpdateTypeRequestBody {
            properties: Some(Vec::new()),
            ..UpdateTypeRequestBody::default()
        };
        assert_eq!(
            serde_json::to_value(body).unwrap(),
            serde_json::json!({ "properties": [] })
        );
    }

    #[test]
    fn type_property_classification_preserves_source_order_and_hidden_featured_ids() {
        let hidden_featured_id = valid_id('b');
        let visible_featured_id = valid_id('c');
        let first_id = valid_id('d');
        let second_id = valid_id('e');

        let classified = classify_type_properties(
            vec![
                property(&visible_featured_id, "tag"),
                property(&first_id, "first"),
                property(&second_id, "second"),
            ],
            vec![hidden_featured_id.clone(), visible_featured_id.clone()],
            vec![first_id.clone(), second_id.clone()],
        )
        .expect("classification");

        assert_eq!(
            classified.featured_ids,
            vec![hidden_featured_id, visible_featured_id]
        );
        assert_eq!(
            classified
                .featured
                .iter()
                .map(|property| property.id.as_str())
                .collect::<Vec<_>>(),
            vec![classified.featured_ids[1].as_str()]
        );
        assert_eq!(
            classified
                .replaceable()
                .iter()
                .map(|property| property.id.as_str())
                .collect::<Vec<_>>(),
            vec![first_id.as_str(), second_id.as_str()]
        );
    }

    #[test]
    fn type_property_classification_rejects_incomplete_or_ambiguous_evidence() {
        let featured_id = valid_id('b');
        let recommended_id = valid_id('c');

        assert!(
            classify_type_properties(
                vec![property(&featured_id, "tag")],
                vec![featured_id.clone()],
                vec![recommended_id],
            )
            .is_err()
        );
        assert!(
            classify_type_properties(
                vec![property(&featured_id, "tag")],
                vec![featured_id.clone()],
                vec![featured_id],
            )
            .is_err()
        );
    }

    #[test]
    fn type_property_source_view_reads_separate_lists() {
        let type_id = valid_id('b');
        let featured_id = valid_id('c');
        let recommended_id = valid_id('d');
        let details = prost_types::Struct {
            fields: [
                (
                    RECOMMENDED_FEATURED_RELATIONS.to_owned(),
                    string_list(std::slice::from_ref(&featured_id)),
                ),
                (
                    RECOMMENDED_RELATIONS.to_owned(),
                    string_list(std::slice::from_ref(&recommended_id)),
                ),
            ]
            .into_iter()
            .collect(),
        };
        let view = model::ObjectView {
            details: vec![model::object_view::DetailsSet {
                id: type_id.clone(),
                details: Some(details),
                sub_ids: Vec::new(),
            }],
            ..Default::default()
        };

        let ids = type_property_source_ids_from_view(&view, &ValidationLimits::default(), &type_id)
            .expect("source IDs");
        assert_eq!(ids, (vec![featured_id], vec![recommended_id]));
    }

    #[test]
    fn type_property_source_view_rejects_malformed_and_oversized_lists() {
        let type_id = valid_id('b');
        let mut fields = std::collections::BTreeMap::new();
        fields.insert(
            RECOMMENDED_RELATIONS.to_owned(),
            prost_types::Value {
                kind: Some(Kind::StringValue("not-a-list".to_owned())),
            },
        );
        let malformed = model::ObjectView {
            details: vec![model::object_view::DetailsSet {
                id: type_id.clone(),
                details: Some(prost_types::Struct { fields }),
                sub_ids: Vec::new(),
            }],
            ..Default::default()
        };
        assert!(
            type_property_source_ids_from_view(&malformed, &ValidationLimits::default(), &type_id,)
                .is_err()
        );

        let ids = (0..=MAX_TYPE_PROPERTY_LINKS)
            .map(|index| valid_id(char::from(b'b' + u8::try_from(index % 25).unwrap())))
            .collect::<Vec<_>>();
        let oversized = model::ObjectView {
            details: vec![model::object_view::DetailsSet {
                id: type_id.clone(),
                details: Some(prost_types::Struct {
                    fields: [(RECOMMENDED_RELATIONS.to_owned(), string_list(&ids))]
                        .into_iter()
                        .collect(),
                }),
                sub_ids: Vec::new(),
            }],
            ..Default::default()
        };
        assert!(
            type_property_source_ids_from_view(&oversized, &ValidationLimits::default(), &type_id,)
                .is_err()
        );
    }

    #[test]
    fn test_type_layout_default() {
        let layout = TypeLayout::default();
        assert_eq!(layout, TypeLayout::Basic);
    }

    #[test]
    fn test_type_layout_display() {
        assert_eq!(TypeLayout::Basic.to_string(), "basic");
        assert_eq!(TypeLayout::Note.to_string(), "note");
        assert_eq!(TypeLayout::Action.to_string(), "action");
    }

    #[test]
    fn test_type_layout_from_string() {
        use std::str::FromStr;
        assert_eq!(TypeLayout::from_str("basic").unwrap(), TypeLayout::Basic);
        assert_eq!(TypeLayout::from_str("note").unwrap(), TypeLayout::Note);
    }

    #[test]
    fn test_type_is_system_type() {
        let page_type = Type {
            object: DataModel::Type,
            archived: false,
            id: "id".to_string(),
            key: "page".to_string(),
            name: Some("Page".to_string()),
            plural_name: None,
            icon: None,
            layout: ObjectLayout::Basic,
            properties: vec![],
        };
        assert!(page_type.is_system_type());

        let custom_type = Type {
            object: DataModel::Type,
            archived: false,
            id: "id".to_string(),
            key: "project".to_string(),
            name: Some("Project".to_string()),
            plural_name: None,
            icon: None,
            layout: ObjectLayout::Basic,
            properties: vec![],
        };
        assert!(!custom_type.is_system_type());
    }

    #[test]
    fn test_type_display_name() {
        let with_name = Type {
            object: DataModel::Type,
            archived: false,
            id: "id".to_string(),
            key: "page".to_string(),
            name: Some("Page".to_string()),
            plural_name: None,
            icon: None,
            layout: ObjectLayout::Basic,
            properties: vec![],
        };
        assert_eq!(with_name.display_name(), "Page");

        let without_name = Type {
            object: DataModel::Type,
            archived: false,
            id: "id".to_string(),
            key: "custom_type".to_string(),
            name: None,
            plural_name: None,
            icon: None,
            layout: ObjectLayout::Basic,
            properties: vec![],
        };
        assert_eq!(without_name.display_name(), "custom_type");
    }
}