udb 0.3.7

Universal Data Broker — a Rust gRPC broker over multiple databases (Postgres, MySQL, SQLite, MongoDB, ClickHouse, Cassandra, MSSQL, Redis, Qdrant, S3, Neo4j, …) with per-tenant RLS, 2PC, sagas, and CDC.
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
//! Native `AssetService` — proto-driven Postgres CRUD + processing-pipeline
//! orchestration over the UDB-owned `udb_asset.{assets,pipeline_definitions,
//! pipeline_instances,pipeline_steps}` tables.
//!
//! Mirrors `tenant_service`: no in-memory store, no hand-mapped schema. Table and
//! column identifiers are resolved from the embedded proto manifest via
//! [`NativeModel`] (see `runtime::native_catalog`), so the SQL here follows the
//! same single-source-of-truth rule as the rest of the native services.

use std::sync::Arc;

use sqlx::{PgPool, Row};
use tonic::{Request, Response, Status};
use uuid::Uuid;

use crate::ir::{
    ComparisonOp, ConflictStrategy, LogicalFilter, LogicalPagination, LogicalProjection,
    LogicalRead, LogicalRecord, LogicalSort, LogicalValue, SortDirection,
};
use crate::metrics::{MetricsRecorder, NoopMetrics};
use crate::proto::udb::core::asset::entity::v1 as asset_entity_pb;
use crate::proto::udb::core::asset::services::v1 as asset_pb;
use crate::proto::udb::core::asset::services::v1::asset_service_server::AssetService;
use crate::runtime::DataBrokerRuntime;
use crate::runtime::channels::{ChannelManager, ChannelPermit, OperationChannel};
use crate::runtime::native_catalog::{NativeModel, native_model};

pub use crate::proto::udb::core::asset::services::v1::asset_service_server::AssetServiceServer;

use super::DataBrokerService;
use super::native_helpers::{
    admit_on as native_admit_on, emit_payload_event, native_service_context,
    storage_object_defaults, validate_request_scope, validate_request_tenant,
};

const ASSET_MSG: &str = "udb.core.asset.entity.v1.Asset";
const PIPELINE_DEFINITION_MSG: &str = "udb.core.asset.entity.v1.PipelineDefinition";
const PIPELINE_INSTANCE_MSG: &str = "udb.core.asset.entity.v1.PipelineInstance";
const PIPELINE_STEP_MSG: &str = "udb.core.asset.entity.v1.PipelineStep";

// ── stable machine-readable error reasons ─────────────────────────────────────
// Attached to the matching pipeline failures so SDK callers can branch on a
// stable code instead of parsing human text. The gRPC Status *code* is left
// unchanged at each site. The repo has no `google.rpc.ErrorInfo` status-detail
// infrastructure, so non-OK statuses carry the reason on the `error-reason`
// metadata trailer (uniform with the storage/webrtc/notification services); the
// OK "already started" return carries it in its response `message` body field.
/// The pipeline definition is structurally invalid (e.g. its persisted step
/// list is not valid JSON).
const PIPELINE_DEFINITION_INVALID: &str = "PIPELINE_DEFINITION_INVALID";
/// A definition step declares a `type` the runtime does not support.
const STEP_TYPE_UNSUPPORTED: &str = "STEP_TYPE_UNSUPPORTED";
/// Reserved: the source asset/file required by a step is missing. No hard
/// failure site exists today (a missing asset yields empty step inputs), so this
/// is held for the future byte-step "source object not found" path.
#[allow(dead_code)]
const ASSET_FILE_MISSING: &str = "ASSET_FILE_MISSING";
/// A concurrent start with the same correlation id won the race; the existing
/// instance is returned instead of starting a new pipeline.
const PIPELINE_ALREADY_STARTED: &str = "PIPELINE_ALREADY_STARTED";

/// Attach a stable machine-readable `reason` to a non-OK gRPC `Status` via the
/// `error-reason` metadata trailer — uniform with the storage/webrtc/notification
/// services (a non-OK status is trailers-only, so the sub-code rides a trailer).
fn status_with_reason(mut status: Status, reason: &'static str) -> Status {
    status.metadata_mut().insert(
        "error-reason",
        tonic::metadata::MetadataValue::from_static(reason),
    );
    status
}

/// Vector collection EMBED-step vectors are upserted into, when not overridden by
/// `UDB_ASSET_VECTOR_COLLECTION`.
const DEFAULT_VECTOR_COLLECTION: &str = "udb_asset_embeddings";

/// Postgres-backed `AssetService` handler.
pub struct AssetServiceImpl {
    pg_pool: Option<PgPool>,
    /// Schema-qualified outbox table (`udb_system.outbox_events`) the CDC engine
    /// tails → Apache Kafka → downstream consumers. `None` = no emit.
    outbox_relation: Option<String>,
    /// Runtime handle used to push `EMBED`-step vectors into the vector backend.
    /// `None` = embeddings stay in the step result only (no vector upsert).
    runtime: Option<Arc<DataBrokerRuntime>>,
    /// Per-tenant fair-admission manager (the SAME one the data plane uses via
    /// `execute_with_channel_scoped`). Mutating/orchestration RPCs acquire a
    /// per-tenant `Object` budget through this so one tenant can't starve shared
    /// pipeline capacity. `None` only in test construction (no runtime wired).
    channels: Option<ChannelManager>,
    /// Vector collection EMBED vectors are upserted into.
    vector_collection: String,
    metrics: Arc<dyn MetricsRecorder>,
}

// ── outbox topics (dot-only per Kafka topic policy) ───────────────────────────
const ASSET_REGISTERED_TOPIC: &str = "udb.asset.asset.registered.v1";
const PIPELINE_STARTED_TOPIC: &str = "udb.asset.pipeline.started.v1";
const PIPELINE_STEP_COMPLETED_TOPIC: &str = "udb.asset.pipeline.step_completed.v1";
const PIPELINE_COMPLETED_TOPIC: &str = "udb.asset.pipeline.completed.v1";
const PIPELINE_FAILED_TOPIC: &str = "udb.asset.pipeline.failed.v1";

impl AssetServiceImpl {
    pub fn new() -> Self {
        Self {
            pg_pool: None,
            outbox_relation: None,
            runtime: None,
            channels: None,
            vector_collection: DEFAULT_VECTOR_COLLECTION.to_string(),
            metrics: Arc::new(NoopMetrics),
        }
    }

    pub fn with_postgres(mut self, pool: Option<PgPool>) -> Self {
        self.pg_pool = pool;
        self
    }

    pub(crate) fn with_metrics(mut self, metrics: Arc<dyn MetricsRecorder>) -> Self {
        self.metrics = metrics;
        self
    }

    /// Wire the runtime handle + target collection so completed `EMBED` steps
    /// upsert their vector into the vector backend (best-effort).
    pub(crate) fn with_vector(
        mut self,
        runtime: Option<Arc<DataBrokerRuntime>>,
        collection: String,
    ) -> Self {
        // Capture the shared per-tenant fair-admission manager (same path as the
        // data plane) so mutating RPCs acquire the per-tenant Object budget.
        self.channels = runtime.as_ref().map(|rt| rt.channels().clone());
        self.runtime = runtime;
        if !collection.trim().is_empty() {
            self.vector_collection = collection;
        }
        self
    }

    fn encrypt_native_json_state(&self, raw_json: &str) -> Result<String, Status> {
        match self.runtime.as_ref() {
            Some(runtime) => runtime
                .encrypt_native_json_state_at_rest(raw_json)
                .map_err(|err| {
                    Status::failed_precondition(format!("native-state encryption failed: {err}"))
                }),
            None => Ok(raw_json.to_string()),
        }
    }

    fn decrypt_native_json_state(&self, stored_json: &str) -> Result<String, Status> {
        if stored_json.trim().is_empty() {
            return Ok(String::new());
        }
        match self.runtime.as_ref() {
            Some(runtime) => runtime
                .decrypt_native_json_state_at_rest(stored_json)
                .map_err(|err| {
                    Status::failed_precondition(format!("native-state decryption failed: {err}"))
                }),
            None => Ok(stored_json.to_string()),
        }
    }

    /// Typed native entity dispatch is the P4 production path for the isolated
    /// AssetService entity CRUD/read methods. Pipeline orchestration still keeps
    /// the transitional Postgres pool for multi-table workflow state.
    fn require_runtime(&self) -> Result<&DataBrokerRuntime, Status> {
        self.runtime.as_deref().ok_or_else(|| {
            Status::failed_precondition("asset service requires runtime native entity dispatch")
        })
    }

    /// Per-tenant fair admission for a mutating/orchestration asset RPC.
    /// Acquires the shared `Object` channel budget SCOPED to the validated tenant
    /// (+ project) so a single tenant's pipeline flood cannot starve other
    /// tenants — the exact path the data plane uses via
    /// `execute_with_channel_scoped`. On exhaustion returns the same
    /// `Status::resource_exhausted` backpressure as the data plane. The returned
    /// [`ChannelPermit`] must be held for the whole RPC (drop = release). `None`
    /// channels (no runtime — test mode) admit without a permit.
    ///
    /// `tenant` MUST be the VALIDATED tenant (post `validate_request_*`).
    async fn admit(&self, tenant: &str, project: &str) -> Result<Option<ChannelPermit>, Status> {
        native_admit_on(
            self.channels.as_ref(),
            &self.metrics,
            "asset",
            OperationChannel::Object,
            tenant,
            Some(project),
        )
        .await
    }

    /// Lighter per-tenant fair admission for a READ RPC (get/list pipeline/asset).
    /// Acquires the cheap `Read` channel budget scoped to the validated tenant so
    /// one tenant cannot exhaust the shared pool with reads, without charging the
    /// heavier `Object` cost the mutating/orchestration RPCs pay.
    async fn admit_read(&self, tenant: &str) -> Result<Option<ChannelPermit>, Status> {
        native_admit_on(
            self.channels.as_ref(),
            &self.metrics,
            "asset",
            OperationChannel::Read,
            tenant,
            Some(""),
        )
        .await
    }

    /// Best-effort: push a completed EMBED step's vector into the vector backend.
    /// `point_id` is the asset id; the embedding + dim come from the step result.
    /// Never fails the pipeline — a vector-backend outage just logs.
    async fn upsert_embedding(
        &self,
        project_id: &str,
        point_id: &str,
        result: &serde_json::Value,
    ) -> Option<VectorEmbeddingTarget> {
        let Some(runtime) = self.runtime.as_ref() else {
            return None;
        };
        let Some(arr) = result.get("embedding").and_then(|e| e.as_array()) else {
            return None;
        };
        let vector: Vec<f32> = arr
            .iter()
            .filter_map(|v| v.as_f64().map(|f| f as f32))
            .collect();
        if vector.is_empty() {
            return None;
        }
        let dim = result
            .get("dim")
            .and_then(|d| d.as_i64())
            .unwrap_or(vector.len() as i64) as i32;
        let point = crate::proto::VectorPointMutation {
            id: point_id.to_string(),
            vector,
            payload: None,
        };
        let vector_instance = runtime
            .choose_instance_name_for_project("qdrant", true, project_id)
            .map(str::to_string)
            .unwrap_or_else(|| "default".to_string());
        if let Err(err) = runtime
            .vector_upsert_backend_target(
                Some(&vector_instance),
                project_id,
                &self.vector_collection,
                dim,
                vec![point],
            )
            .await
        {
            tracing::warn!(error = %err, collection = %self.vector_collection, point_id, "asset embedding vector upsert failed");
            None
        } else {
            Some(VectorEmbeddingTarget {
                project_id: project_id.to_string(),
                instance: vector_instance,
            })
        }
    }

    /// Best-effort: remove an asset's embedding (point id = asset_id) from the
    /// vector backend. Called on pipeline failure so a failed run leaves no orphan
    /// vector. Never fails the caller.
    async fn delete_embedding(
        &self,
        project_id: &str,
        vector_instance: Option<&str>,
        point_id: &str,
    ) {
        let Some(runtime) = self.runtime.as_ref() else {
            return;
        };
        if point_id.trim().is_empty() {
            return;
        }
        if let Err(err) = runtime
            .vector_delete_backend_target(
                vector_instance,
                project_id,
                &self.vector_collection,
                vec![point_id.to_string()],
            )
            .await
        {
            tracing::warn!(error = %err, collection = %self.vector_collection, point_id, "asset embedding vector delete failed");
        }
    }

    /// CDC trigger handler: on a finalized storage file
    /// (`udb.storage.file.finalized.v1`), auto-register the asset and start the
    /// tenant's active pipeline whose `media_type` matches the file's content type.
    /// Idempotent: the asset is reused per `file_id`, and the pipeline is deduped on
    /// `correlation_id = file_id`. Returns the started instance id, or `None` when
    /// the file is gone or no matching active pipeline definition exists (no-op).
    pub(crate) async fn handle_storage_finalized(
        &self,
        file_id: &str,
        tenant_id: &str,
    ) -> Result<Option<String>, Status> {
        let pool = self.require_pool()?;
        let tenant_uuid = parse_uuid("tenant_id", tenant_id)?;
        let file_uuid = parse_uuid("file_id", file_id)?;

        // Resolve the file's content_type + filename from storage (proto-driven).
        let fm = native_model(
            "udb.core.storage.entity.v1.File",
            &["file_id", "content_type", "filename"],
        );
        // Tenant-bound file lookup: only act on a file owned by this tenant.
        let frow = sqlx::query(&format!(
            "SELECT {ct}, {fname}, {project_id} FROM {rel} \
             WHERE {fid} = $1::UUID AND {tid} = $2::UUID AND {del} IS NULL",
            ct = fm.text_or_empty_as("content_type", "content_type"),
            fname = fm.text_or_empty_as("filename", "filename"),
            project_id = fm.text_or_empty_as("project_id", "project_id"),
            rel = fm.relation,
            fid = fm.q("file_id"),
            tid = fm.q("tenant_id"),
            del = fm.q("deleted_at"),
        ))
        .bind(file_uuid)
        .bind(tenant_uuid)
        .fetch_optional(pool)
        .await
        .map_err(|e| Status::internal(format!("resolve finalized file failed: {e}")))?;
        let Some(frow) = frow else {
            return Ok(None);
        };
        let content_type: String = frow.try_get("content_type").unwrap_or_default();
        let filename: String = frow.try_get("filename").unwrap_or_default();
        let project_id: String = frow.try_get("project_id").unwrap_or_default();
        // image/png → "image"; falls back to the whole string if no slash.
        let media_type = content_type
            .split('/')
            .next()
            .unwrap_or("")
            .trim()
            .to_string();

        // Match an active pipeline definition for this tenant + media type.
        let dm = pipeline_definition_model();
        let def_id: Option<String> = sqlx::query_scalar(&format!(
            "SELECT {did}::TEXT FROM {rel} \
             WHERE {tid} = $1::UUID AND {mt} = $2 AND {status} = 'ACTIVE' \
             ORDER BY {ver} DESC LIMIT 1",
            did = dm.q("definition_id"),
            rel = dm.relation,
            tid = dm.q("tenant_id"),
            mt = dm.q("media_type"),
            status = dm.q("status"),
            ver = dm.q("version"),
        ))
        .bind(tenant_uuid)
        .bind(&media_type)
        .fetch_optional(pool)
        .await
        .map_err(|e| Status::internal(format!("match pipeline definition failed: {e}")))?;
        let Some(definition_id) = def_id else {
            return Ok(None);
        };

        // Reuse an existing asset for this file, else register one.
        let am = asset_model();
        let existing: Option<String> = sqlx::query_scalar(&format!(
            "SELECT {aid}::TEXT FROM {rel} \
             WHERE {fid} = $1::UUID AND {tid} = $2::UUID AND {del} IS NULL LIMIT 1",
            aid = am.q("asset_id"),
            rel = am.relation,
            fid = am.q("file_id"),
            tid = am.q("tenant_id"),
            del = am.q("deleted_at"),
        ))
        .bind(file_uuid)
        .bind(tenant_uuid)
        .fetch_optional(pool)
        .await
        .map_err(|e| Status::internal(format!("lookup asset for file failed: {e}")))?;
        let asset_id = match existing {
            Some(a) => a,
            None => {
                self.register_asset(Request::new(asset_pb::RegisterAssetRequest {
                    tenant_id: tenant_id.to_string(),
                    project_id: project_id.clone(),
                    file_id: file_id.to_string(),
                    name: if filename.is_empty() {
                        file_id.to_string()
                    } else {
                        filename
                    },
                    media_type: media_type.clone(),
                    ..Default::default()
                }))
                .await?
                .into_inner()
                .asset_id
            }
        };

        // Start the pipeline, idempotent on correlation_id = file_id.
        let started = self
            .start_pipeline(Request::new(asset_pb::StartPipelineRequest {
                tenant_id: tenant_id.to_string(),
                definition_id,
                asset_id,
                correlation_id: file_id.to_string(),
                ..Default::default()
            }))
            .await?
            .into_inner();
        Ok(Some(started.instance_id))
    }

    /// Resolve a storage file's `object_key` (UDB-owned `udb_storage.files`),
    /// **tenant-bound** so a byte step can only read a file owned by its tenant.
    /// Proto-driven via the embedded manifest — no hardcoded table/columns.
    async fn resolve_object_key(
        &self,
        pool: &PgPool,
        file_id: Uuid,
        tenant_id: Uuid,
    ) -> Option<String> {
        let m = native_model(
            "udb.core.storage.entity.v1.File",
            &["file_id", "object_key"],
        );
        let rel = m.relation.clone();
        sqlx::query_scalar::<_, String>(&format!(
            "SELECT {ok}::TEXT FROM {rel} \
             WHERE {fid} = $1::UUID AND {tid} = $2::UUID AND {del} IS NULL",
            ok = m.q("object_key"),
            fid = m.q("file_id"),
            tid = m.q("tenant_id"),
            del = m.q("deleted_at"),
        ))
        .bind(file_id)
        .bind(tenant_id)
        .fetch_optional(pool)
        .await
        .ok()
        .flatten()
    }

    /// Run a byte-IO step (THUMBNAIL/RESIZE): fetch the source object bytes,
    /// transform them, and store a derived object. Image processing is behind the
    /// `asset-image` feature; without it the step fails explicitly (no fake
    /// success). Source bytes/derived objects use the same object backend+bucket
    /// as the storage service (`UDB_STORAGE_OBJECT_BACKEND` / `UDB_STORAGE_BUCKET`).
    async fn run_byte_step(
        &self,
        pool: &PgPool,
        step_type_i32: i32,
        file_id_str: &str,
        tenant_id: Uuid,
        project_id: &str,
    ) -> StepOutcome {
        let Some(runtime) = self.runtime.as_ref() else {
            return StepOutcome::Failed(
                "byte steps require a runtime object handle (none configured)".to_string(),
            );
        };
        let Ok(file_id) = Uuid::parse_str(file_id_str.trim()) else {
            return StepOutcome::Failed("asset has no valid file_id for a byte step".to_string());
        };
        let Some(object_key) = self.resolve_object_key(pool, file_id, tenant_id).await else {
            return StepOutcome::Failed("source file not found for tenant".to_string());
        };
        let (backend, bucket) = storage_object_defaults(
            std::env::var("UDB_STORAGE_OBJECT_BACKEND").ok(),
            std::env::var("UDB_STORAGE_BUCKET").ok(),
        );

        #[cfg(not(feature = "asset-image"))]
        {
            let _ = (
                runtime,
                step_type_i32,
                &object_key,
                &backend,
                &bucket,
                project_id,
            );
            StepOutcome::Failed(
                "THUMBNAIL/RESIZE require the `asset-image` feature build".to_string(),
            )
        }
        #[cfg(feature = "asset-image")]
        {
            let _ = step_type_i32;
            let get_req = crate::runtime::core::setup_data::object_request_json(
                "get",
                &bucket,
                &object_key,
                "",
            );
            let bytes = match runtime
                .get_object_backend_target_for_project(&backend, None, project_id, &get_req)
                .await
            {
                Ok(b) => b,
                Err(err) => {
                    return StepOutcome::Failed(format!("fetch source bytes failed: {err}"));
                }
            };
            let img = match image::load_from_memory(&bytes) {
                Ok(i) => i,
                Err(err) => return StepOutcome::Failed(format!("decode image failed: {err}")),
            };
            let thumb = img.thumbnail(256, 256);
            let mut out = std::io::Cursor::new(Vec::new());
            if let Err(err) = thumb.write_to(&mut out, image::ImageFormat::Png) {
                return StepOutcome::Failed(format!("encode thumbnail failed: {err}"));
            }
            let derived_key = format!("{object_key}.thumb.png");
            let put_req = crate::runtime::core::setup_data::object_request_json(
                "put",
                &bucket,
                &derived_key,
                "image/png",
            );
            if let Err(err) = runtime
                .put_object_backend_target_for_project(
                    &backend,
                    None,
                    project_id,
                    &put_req,
                    out.into_inner(),
                )
                .await
            {
                return StepOutcome::Failed(format!("store derived object failed: {err}"));
            }
            StepOutcome::Completed(serde_json::json!({
                "derived_object_key": derived_key,
                "width": thumb.width(),
                "height": thumb.height(),
                "format": "png",
            }))
        }
    }

    /// Wire the transactional outbox so asset/pipeline lifecycle events publish
    /// domain events to Kafka (via the CDC relay). `relation` is the
    /// schema-qualified table, e.g. `"udb_system"."outbox_events"`.
    pub(crate) fn with_outbox(mut self, relation: Option<String>) -> Self {
        self.outbox_relation = relation;
        self
    }

    /// Asset CRUD is durable-only: fail closed when no Postgres pool exists.
    fn require_pool(&self) -> Result<&PgPool, Status> {
        self.pg_pool.as_ref().ok_or_else(|| {
            Status::failed_precondition(
                "asset service requires a Postgres-backed store (no PG pool configured)",
            )
        })
    }
}

// ── pure-Rust step execution ──────────────────────────────────────────────────

#[derive(Debug, Clone)]
struct VectorEmbeddingTarget {
    project_id: String,
    instance: String,
}

enum StepOutcome {
    Completed(serde_json::Value),
    Failed(String),
}

/// THUMBNAIL/RESIZE are byte-IO steps run async (fetch→transform→store) outside
/// the sync metadata-step registry.
fn is_byte_step(step_type: i32) -> bool {
    use asset_entity_pb::StepType as T;
    matches!(T::try_from(step_type), Ok(T::Thumbnail) | Ok(T::Resize))
}

/// Inputs available to a step without object bytes (object-byte fetch is a
/// separate, not-yet-wired gap).
struct StepContext<'a> {
    asset_name: &'a str,
    metadata_json: &'a str,
}

/// Executes one asset-pipeline step. Implementations are pure/in-process for v1.
trait AssetStepExecutor: Send + Sync {
    /// The proto StepType enum value this executor handles.
    fn step_type(&self) -> i32;
    fn execute(&self, ctx: &StepContext) -> StepOutcome;
}

/// Signed feature-hashing embedding (the "hashing trick") — a real, deterministic,
/// dependency-free text embedding. Not a neural model, but a legitimate scheme.
fn embed_text(text: &str, dim: usize) -> Vec<f32> {
    let mut v = vec![0f32; dim];
    for token in text.split_whitespace() {
        let mut h: u64 = 0xcbf29ce484222325;
        for b in token.to_ascii_lowercase().bytes() {
            h ^= b as u64;
            h = h.wrapping_mul(0x100000001b3);
        }
        let idx = (h % dim as u64) as usize;
        v[idx] += if (h >> 1) & 1 == 0 { 1.0 } else { -1.0 };
    }
    let norm = v.iter().map(|x| x * x).sum::<f32>().sqrt();
    if norm > 0.0 {
        for x in &mut v {
            *x /= norm;
        }
    }
    v
}

/// EMBED: signed feature-hashing embedding over `asset_name + metadata`.
struct EmbedStepExecutor;
impl AssetStepExecutor for EmbedStepExecutor {
    fn step_type(&self) -> i32 {
        asset_entity_pb::StepType::Embed as i32
    }
    fn execute(&self, ctx: &StepContext) -> StepOutcome {
        let text = format!("{} {}", ctx.asset_name, ctx.metadata_json);
        let emb = embed_text(&text, 64);
        StepOutcome::Completed(serde_json::json!({ "embedding": emb, "dim": 64 }))
    }
}

/// EXTRACT: trivial text extraction from the available (non-byte) inputs.
struct ExtractStepExecutor;
impl AssetStepExecutor for ExtractStepExecutor {
    fn step_type(&self) -> i32 {
        asset_entity_pb::StepType::Extract as i32
    }
    fn execute(&self, ctx: &StepContext) -> StepOutcome {
        let text = format!("{} {}", ctx.asset_name, ctx.metadata_json);
        StepOutcome::Completed(serde_json::json!({
            "text": text.trim(),
            "chars": text.trim().chars().count(),
        }))
    }
}

/// Registry of step executors keyed by proto `StepType` enum value. Adding a new
/// step type = register an executor in [`StepRegistry::default_registry`]; the
/// pipeline orchestration (`start_pipeline`) never changes.
struct StepRegistry {
    by_type: std::collections::HashMap<i32, Box<dyn AssetStepExecutor>>,
}

impl StepRegistry {
    fn default_registry() -> Self {
        let mut by_type: std::collections::HashMap<i32, Box<dyn AssetStepExecutor>> =
            std::collections::HashMap::new();
        for executor in [
            Box::new(EmbedStepExecutor) as Box<dyn AssetStepExecutor>,
            Box::new(ExtractStepExecutor) as Box<dyn AssetStepExecutor>,
        ] {
            by_type.insert(executor.step_type(), executor);
        }
        Self { by_type }
    }

    /// Dispatch by `step_type`. Unregistered types (incl. media steps) fail
    /// EXPLICITLY with a clear "not yet implemented" message — keeping the
    /// no-capability-lies contract (no faked success).
    fn run(&self, step_type: i32, ctx: &StepContext) -> StepOutcome {
        match self.by_type.get(&step_type) {
            Some(executor) => executor.execute(ctx),
            None => {
                use asset_entity_pb::StepType as T;
                let name = T::try_from(step_type)
                    .map(|t| t.as_str_name())
                    .unwrap_or("STEP_TYPE_UNSPECIFIED");
                StepOutcome::Failed(format!(
                    "step type {name} not yet implemented \
                     (needs object-store integration + asset-media)"
                ))
            }
        }
    }
}

/// Process-wide default registry, built once. Adding a step type means editing
/// [`StepRegistry::default_registry`] only — not this accessor or `start_pipeline`.
fn step_registry() -> &'static StepRegistry {
    static REGISTRY: std::sync::OnceLock<StepRegistry> = std::sync::OnceLock::new();
    REGISTRY.get_or_init(StepRegistry::default_registry)
}

/// Roll a pipeline instance to a terminal state when all steps are accounted for,
/// or to FAILED on any failed step. Shared by `start_pipeline` (inline execution)
/// and `complete_step` (externally-driven). Emits the terminal domain event.
/// Returns the terminal status token (`"COMPLETED"`/`"FAILED"`) if one was set.
async fn advance_instance(
    svc: &AssetServiceImpl,
    pool: &PgPool,
    instance_id: Uuid,
    tenant_id: Uuid,
) -> Result<Option<&'static str>, Status> {
    let step = pipeline_step_model();
    let step_rel = step.relation.clone();
    let counts = sqlx::query(&format!(
        "SELECT \
           COUNT(*) AS total, \
           COUNT(*) FILTER (WHERE {status} IN ('COMPLETED', 'SKIPPED')) AS done, \
           COUNT(*) FILTER (WHERE {status} = 'FAILED') AS failed \
         FROM {step_rel} WHERE {instance_id} = $1::UUID AND {tenant_id} = $2::UUID",
        status = step.q("status"),
        instance_id = step.q("instance_id"),
        tenant_id = step.q("tenant_id"),
    ))
    .bind(instance_id)
    .bind(tenant_id)
    .fetch_one(pool)
    .await
    .map_err(|err| Status::internal(format!("aggregate step status failed: {err}")))?;
    let total: i64 = counts
        .try_get("total")
        .map_err(|e| Status::internal(format!("decode total failed: {e}")))?;
    let done: i64 = counts
        .try_get("done")
        .map_err(|e| Status::internal(format!("decode done failed: {e}")))?;
    let failed: i64 = counts
        .try_get("failed")
        .map_err(|e| Status::internal(format!("decode failed failed: {e}")))?;

    let new_instance_status = if failed > 0 {
        Some("FAILED")
    } else if total > 0 && done == total {
        Some("COMPLETED")
    } else {
        None
    };
    if let Some(terminal) = new_instance_status {
        let inst = pipeline_instance_model();
        let inst_rel = inst.relation.clone();
        sqlx::query(&format!(
            "UPDATE {inst_rel} SET {status} = $3, {completed_at} = CURRENT_TIMESTAMP \
             WHERE {instance_id} = $1::UUID AND {tenant_id} = $2::UUID",
            status = inst.q("status"),
            completed_at = inst.q("completed_at"),
            instance_id = inst.q("instance_id"),
            tenant_id = inst.q("tenant_id"),
        ))
        .bind(instance_id)
        .bind(tenant_id)
        .bind(terminal)
        .execute(pool)
        .await
        .map_err(|err| Status::internal(format!("advance pipeline instance failed: {err}")))?;

        let topic = if terminal == "FAILED" {
            PIPELINE_FAILED_TOPIC
        } else {
            PIPELINE_COMPLETED_TOPIC
        };
        emit_payload_event(
            pool,
            svc.outbox_relation.as_deref(),
            topic,
            &instance_id.to_string(),
            serde_json::json!({
                "instance_id": instance_id.to_string(),
                "tenant_id": tenant_id.to_string(),
                "status": terminal,
            }),
            Some(&svc.metrics),
        )
        .await;

        // On failure, remove the asset's embedding so a failed run leaves no
        // orphan vector behind (best-effort).
        if terminal == "FAILED"
            && let Ok(Some(row)) = sqlx::query(&format!(
                "SELECT i.{asset_id}::TEXT AS asset_id, COALESCE(a.{project_id}::TEXT, '') AS project_id, \
                        COALESCE(s.{result}::TEXT, '{{}}') AS vector_result \
                 FROM {inst_rel} i \
                 LEFT JOIN {asset_rel} a ON a.{asset_pk} = i.{asset_id} AND a.{asset_tenant} = i.{tenant_id} \
                 LEFT JOIN LATERAL ( \
                    SELECT {step_result} \
                    FROM {step_rel} \
                    WHERE {step_instance_id} = i.{instance_id} \
                      AND {step_tenant_id} = i.{tenant_id} \
                      AND {step_type} = 'EMBED' \
                      AND {step_status} = 'COMPLETED' \
                    ORDER BY {step_completed_at} DESC NULLS LAST \
                    LIMIT 1 \
                 ) s ON TRUE \
                 WHERE i.{instance_id} = $1::UUID AND i.{tenant_id} = $2::UUID",
                asset_id = inst.q("asset_id"),
                asset_rel = asset_model().relation,
                asset_pk = asset_model().q("asset_id"),
                asset_tenant = asset_model().q("tenant_id"),
                project_id = asset_model().q("project_id"),
                result = step.q("result"),
                step_result = step.q("result"),
                step_rel = step.relation,
                step_instance_id = step.q("instance_id"),
                step_tenant_id = step.q("tenant_id"),
                step_type = step.q("step_type"),
                step_status = step.q("status"),
                step_completed_at = step.q("completed_at"),
                instance_id = inst.q("instance_id"),
                tenant_id = inst.q("tenant_id"),
            ))
            .bind(instance_id)
            .bind(tenant_id)
            .fetch_optional(pool)
            .await
        {
            if let Ok(asset_id) = row.try_get::<String, _>("asset_id") {
                let fallback_project = row.try_get::<String, _>("project_id").unwrap_or_default();
                let vector_result = row
                    .try_get::<String, _>("vector_result")
                    .unwrap_or_else(|_| "{}".to_string());
                let decoded = svc
                    .decrypt_native_json_state(&vector_result)
                    .unwrap_or(vector_result);
                let vector_target = serde_json::from_str::<serde_json::Value>(&decoded).ok();
                let vector_project = vector_target
                    .as_ref()
                    .and_then(|value| value.get("vector_project_id"))
                    .and_then(|value| value.as_str())
                    .filter(|value| !value.trim().is_empty())
                    .unwrap_or(&fallback_project);
                let vector_instance = vector_target
                    .as_ref()
                    .and_then(|value| value.get("vector_backend_instance"))
                    .and_then(|value| value.as_str())
                    .filter(|value| !value.trim().is_empty());
                svc.delete_embedding(vector_project, vector_instance, &asset_id)
                    .await;
            }
        }
    }
    Ok(new_instance_status)
}

impl Default for AssetServiceImpl {
    fn default() -> Self {
        Self::new()
    }
}

// ── native models (table + column resolution from the embedded proto manifest) ─

fn asset_model() -> NativeModel {
    native_model(
        ASSET_MSG,
        &[
            "asset_id",
            "tenant_id",
            "project_id",
            "file_id",
            "name",
            "media_type",
            "status",
            "metadata",
        ],
    )
}

fn pipeline_definition_model() -> NativeModel {
    native_model(
        PIPELINE_DEFINITION_MSG,
        &[
            "definition_id",
            "tenant_id",
            "name",
            "description",
            "media_type",
            "steps",
            "version",
            "status",
        ],
    )
}

fn pipeline_instance_model() -> NativeModel {
    native_model(
        PIPELINE_INSTANCE_MSG,
        &[
            "instance_id",
            "definition_id",
            "asset_id",
            "tenant_id",
            "status",
            "current_step",
            "context",
            "correlation_id",
            "started_at",
            "completed_at",
        ],
    )
}

fn pipeline_step_model() -> NativeModel {
    native_model(
        PIPELINE_STEP_MSG,
        &[
            "step_id",
            "instance_id",
            "tenant_id",
            "step_name",
            "step_type",
            "status",
            "result",
            "error",
            "retry_count",
            "started_at",
            "completed_at",
        ],
    )
}

use super::native_helpers::{non_empty_json, parse_uuid};

fn logical_string(value: impl Into<String>) -> LogicalValue {
    LogicalValue::String(value.into())
}

fn logical_json_text(value: &str) -> Result<LogicalValue, Status> {
    serde_json::from_str::<serde_json::Value>(value)
        .map(LogicalValue::Json)
        .map_err(|err| Status::invalid_argument(format!("native JSON field is invalid: {err}")))
}

fn eq_filter(field: &str, value: impl Into<String>) -> LogicalFilter {
    LogicalFilter::Comparison {
        field: field.to_string(),
        op: ComparisonOp::Eq,
        value: logical_string(value),
    }
}

fn and_filter(filters: Vec<LogicalFilter>) -> LogicalFilter {
    LogicalFilter::And(filters)
}

fn asset_projection() -> LogicalProjection {
    LogicalProjection::fields([
        "asset_id".to_string(),
        "tenant_id".to_string(),
        "project_id".to_string(),
        "file_id".to_string(),
        "name".to_string(),
        "media_type".to_string(),
        "status".to_string(),
        "metadata".to_string(),
    ])
}

fn pipeline_definition_projection() -> LogicalProjection {
    LogicalProjection::fields([
        "definition_id".to_string(),
        "tenant_id".to_string(),
        "name".to_string(),
        "description".to_string(),
        "media_type".to_string(),
        "steps".to_string(),
        "version".to_string(),
        "status".to_string(),
    ])
}

fn asset_read(
    tenant_id: &str,
    asset_id: Option<&str>,
    media_type: Option<&str>,
    status: Option<&str>,
    offset: u64,
    limit: u32,
) -> LogicalRead {
    let mut filters = vec![
        eq_filter("tenant_id", tenant_id),
        LogicalFilter::IsNull("deleted_at".to_string()),
    ];
    if let Some(asset_id) = asset_id.filter(|value| !value.trim().is_empty()) {
        filters.push(eq_filter("asset_id", asset_id));
    }
    if let Some(media_type) = media_type.filter(|value| !value.trim().is_empty()) {
        filters.push(eq_filter("media_type", media_type));
    }
    if let Some(status) = status.filter(|value| !value.trim().is_empty()) {
        filters.push(eq_filter("status", status));
    }
    LogicalRead {
        message_type: ASSET_MSG.to_string(),
        filter: Some(and_filter(filters)),
        projection: Some(asset_projection()),
        sort: vec![LogicalSort {
            field: "name".to_string(),
            direction: SortDirection::Asc,
            nulls: Default::default(),
        }],
        pagination: Some(LogicalPagination::page(offset, limit)),
    }
}

fn pipeline_definition_read(tenant_id: &str, definition_id: &str) -> LogicalRead {
    LogicalRead {
        message_type: PIPELINE_DEFINITION_MSG.to_string(),
        filter: Some(and_filter(vec![
            eq_filter("definition_id", definition_id),
            eq_filter("tenant_id", tenant_id),
        ])),
        projection: Some(pipeline_definition_projection()),
        sort: Vec::new(),
        pagination: Some(LogicalPagination::limit(1)),
    }
}

fn native_json_object(row: &serde_json::Value) -> &serde_json::Map<String, serde_json::Value> {
    row.get("n")
        .and_then(serde_json::Value::as_object)
        .or_else(|| row.as_object())
        .unwrap_or_else(|| {
            static EMPTY: std::sync::OnceLock<serde_json::Map<String, serde_json::Value>> =
                std::sync::OnceLock::new();
            EMPTY.get_or_init(serde_json::Map::new)
        })
}

fn json_string_field(row: &serde_json::Map<String, serde_json::Value>, logical: &str) -> String {
    row.get(logical)
        .and_then(|value| match value {
            serde_json::Value::String(value) => Some(value.clone()),
            serde_json::Value::Number(value) => Some(value.to_string()),
            serde_json::Value::Bool(value) => Some(value.to_string()),
            serde_json::Value::Object(_) | serde_json::Value::Array(_) => Some(value.to_string()),
            serde_json::Value::Null => None,
        })
        .unwrap_or_default()
}

fn json_i32_field(row: &serde_json::Map<String, serde_json::Value>, logical: &str) -> i32 {
    row.get(logical)
        .and_then(|value| value.as_i64())
        .unwrap_or_default() as i32
}

fn asset_from_json(row: &serde_json::Value) -> asset_entity_pb::Asset {
    let row = native_json_object(row);
    asset_entity_pb::Asset {
        asset_id: json_string_field(row, "asset_id"),
        tenant_id: json_string_field(row, "tenant_id"),
        project_id: json_string_field(row, "project_id"),
        file_id: json_string_field(row, "file_id"),
        name: json_string_field(row, "name"),
        media_type: json_string_field(row, "media_type"),
        status: asset_status_from_db(&json_string_field(row, "status")),
        metadata: json_string_field(row, "metadata"),
        ..Default::default()
    }
}

fn pipeline_definition_from_json(row: &serde_json::Value) -> asset_entity_pb::PipelineDefinition {
    let row = native_json_object(row);
    asset_entity_pb::PipelineDefinition {
        definition_id: json_string_field(row, "definition_id"),
        tenant_id: json_string_field(row, "tenant_id"),
        name: json_string_field(row, "name"),
        description: json_string_field(row, "description"),
        media_type: json_string_field(row, "media_type"),
        steps: json_string_field(row, "steps"),
        version: json_i32_field(row, "version"),
        status: json_string_field(row, "status"),
        ..Default::default()
    }
}

fn asset_record(
    asset_id: &str,
    tenant_id: &str,
    project_id: &str,
    req: &asset_pb::RegisterAssetRequest,
    metadata_json: &str,
) -> Result<LogicalRecord, Status> {
    let mut record = LogicalRecord::new();
    record.insert("asset_id".to_string(), logical_string(asset_id));
    record.insert("tenant_id".to_string(), logical_string(tenant_id));
    record.insert(
        "project_id".to_string(),
        if project_id.trim().is_empty() {
            LogicalValue::Null
        } else {
            logical_string(project_id)
        },
    );
    record.insert("file_id".to_string(), logical_string(req.file_id.trim()));
    record.insert("name".to_string(), logical_string(req.name.clone()));
    record.insert(
        "media_type".to_string(),
        logical_string(req.media_type.clone()),
    );
    record.insert("status".to_string(), logical_string("PENDING"));
    record.insert("metadata".to_string(), logical_json_text(metadata_json)?);
    Ok(record)
}

fn pipeline_definition_record(
    definition_id: &str,
    tenant_id: &str,
    req: &asset_pb::CreatePipelineDefinitionRequest,
    steps_json: &str,
    version: i32,
) -> Result<LogicalRecord, Status> {
    let mut record = LogicalRecord::new();
    record.insert("definition_id".to_string(), logical_string(definition_id));
    record.insert("tenant_id".to_string(), logical_string(tenant_id));
    record.insert("name".to_string(), logical_string(req.name.clone()));
    record.insert(
        "description".to_string(),
        logical_string(req.description.clone()),
    );
    record.insert(
        "media_type".to_string(),
        logical_string(req.media_type.clone()),
    );
    record.insert("steps".to_string(), logical_json_text(steps_json)?);
    record.insert("version".to_string(), LogicalValue::Int(version as i64));
    record.insert("status".to_string(), logical_string("ACTIVE"));
    Ok(record)
}

// ── enum<->db (stored as SHORT tokens in VARCHAR(20) via the proto_enum serializer) ─

fn asset_status_from_db(value: &str) -> i32 {
    use asset_entity_pb::AssetStatus as S;
    match value {
        "PENDING" | "ASSET_STATUS_PENDING" => S::Pending as i32,
        "READY" | "ASSET_STATUS_READY" => S::Ready as i32,
        "FAILED" | "ASSET_STATUS_FAILED" => S::Failed as i32,
        _ => S::Unspecified as i32,
    }
}

fn asset_status_to_db(value: &str, default: &str) -> Result<String, Status> {
    let v = value.trim();
    if v.is_empty() {
        return Ok(default.to_string());
    }
    let short = match v.to_ascii_uppercase().as_str() {
        "PENDING" | "ASSET_STATUS_PENDING" => "PENDING",
        "READY" | "ASSET_STATUS_READY" => "READY",
        "FAILED" | "ASSET_STATUS_FAILED" => "FAILED",
        other => {
            return Err(Status::invalid_argument(format!(
                "unknown asset status: {other}"
            )));
        }
    };
    Ok(short.to_string())
}

fn pipeline_status_from_db(value: &str) -> i32 {
    use asset_entity_pb::PipelineStatus as S;
    match value {
        "PENDING" | "PIPELINE_STATUS_PENDING" => S::Pending as i32,
        "RUNNING" | "PIPELINE_STATUS_RUNNING" => S::Running as i32,
        "COMPLETED" | "PIPELINE_STATUS_COMPLETED" => S::Completed as i32,
        "FAILED" | "PIPELINE_STATUS_FAILED" => S::Failed as i32,
        _ => S::Unspecified as i32,
    }
}

fn step_status_from_db(value: &str) -> i32 {
    use asset_entity_pb::StepStatus as S;
    match value {
        "PENDING" | "STEP_STATUS_PENDING" => S::Pending as i32,
        "RUNNING" | "STEP_STATUS_RUNNING" => S::Running as i32,
        "COMPLETED" | "STEP_STATUS_COMPLETED" => S::Completed as i32,
        "SKIPPED" | "STEP_STATUS_SKIPPED" => S::Skipped as i32,
        "FAILED" | "STEP_STATUS_FAILED" => S::Failed as i32,
        _ => S::Unspecified as i32,
    }
}

/// Normalize a step-status string to the canonical SHORT stored token. Accepts
/// the short or proto-prefixed form, empty→`default`, rejects unknown input so
/// it never overflows VARCHAR(20) or reads back as Unspecified.
fn step_status_to_db(value: &str, default: &str) -> Result<String, Status> {
    let v = value.trim();
    if v.is_empty() {
        return Ok(default.to_string());
    }
    let short = match v.to_ascii_uppercase().as_str() {
        "PENDING" | "STEP_STATUS_PENDING" => "PENDING",
        "RUNNING" | "STEP_STATUS_RUNNING" => "RUNNING",
        "COMPLETED" | "STEP_STATUS_COMPLETED" => "COMPLETED",
        "SKIPPED" | "STEP_STATUS_SKIPPED" => "SKIPPED",
        "FAILED" | "STEP_STATUS_FAILED" => "FAILED",
        other => {
            return Err(Status::invalid_argument(format!(
                "unknown step status: {other}"
            )));
        }
    };
    Ok(short.to_string())
}

fn step_type_from_db(value: &str) -> i32 {
    use asset_entity_pb::StepType as T;
    match value {
        "EMBED" | "STEP_TYPE_EMBED" => T::Embed as i32,
        "THUMBNAIL" | "STEP_TYPE_THUMBNAIL" => T::Thumbnail as i32,
        "RESIZE" | "STEP_TYPE_RESIZE" => T::Resize as i32,
        "TRANSCODE" | "STEP_TYPE_TRANSCODE" => T::Transcode as i32,
        "CAPTION" | "STEP_TYPE_CAPTION" => T::Caption as i32,
        "EXTRACT" | "STEP_TYPE_EXTRACT" => T::Extract as i32,
        _ => T::Unspecified as i32,
    }
}

/// Normalize a step-type string to the canonical SHORT stored token. Same
/// accept-both-forms / reject-unknown / empty→default contract as
/// [`step_status_to_db`].
fn step_type_to_db(value: &str, default: &str) -> Result<String, Status> {
    let v = value.trim();
    if v.is_empty() {
        return Ok(default.to_string());
    }
    let short = match v.to_ascii_uppercase().as_str() {
        "EMBED" | "STEP_TYPE_EMBED" => "EMBED",
        "THUMBNAIL" | "STEP_TYPE_THUMBNAIL" => "THUMBNAIL",
        "RESIZE" | "STEP_TYPE_RESIZE" => "RESIZE",
        "TRANSCODE" | "STEP_TYPE_TRANSCODE" => "TRANSCODE",
        "CAPTION" | "STEP_TYPE_CAPTION" => "CAPTION",
        "EXTRACT" | "STEP_TYPE_EXTRACT" => "EXTRACT",
        other => {
            return Err(Status::invalid_argument(format!(
                "unknown step type: {other}"
            )));
        }
    };
    Ok(short.to_string())
}

fn pipeline_instance_select_projection(m: &NativeModel) -> String {
    [
        m.text("instance_id"),
        m.text("definition_id"),
        m.text("asset_id"),
        m.text("tenant_id"),
        m.text_or_empty("status"),
        m.text_or_empty("current_step"),
        m.text_or_empty("context"),
        m.text_or_empty("correlation_id"),
    ]
    .join(", ")
}

fn pipeline_instance_from_row(
    row: &sqlx::postgres::PgRow,
) -> Result<asset_entity_pb::PipelineInstance, Status> {
    let map = |e: sqlx::Error| Status::internal(format!("decode pipeline instance failed: {e}"));
    Ok(asset_entity_pb::PipelineInstance {
        instance_id: row.try_get("instance_id").map_err(map)?,
        definition_id: row.try_get("definition_id").map_err(map)?,
        asset_id: row.try_get("asset_id").map_err(map)?,
        tenant_id: row.try_get("tenant_id").map_err(map)?,
        status: pipeline_status_from_db(&row.try_get::<String, _>("status").map_err(map)?),
        current_step: row.try_get("current_step").map_err(map)?,
        context: row.try_get("context").map_err(map)?,
        correlation_id: row.try_get("correlation_id").map_err(map)?,
        ..Default::default()
    })
}

fn pipeline_step_select_projection(m: &NativeModel) -> String {
    [
        m.text("step_id"),
        m.text("instance_id"),
        m.text("tenant_id"),
        m.text_or_empty("step_name"),
        m.text_or_empty("step_type"),
        m.text_or_empty("status"),
        m.text_or_empty("result"),
        m.text_or_empty("error"),
        m.select("retry_count"),
    ]
    .join(", ")
}

fn pipeline_step_from_row(
    row: &sqlx::postgres::PgRow,
) -> Result<asset_entity_pb::PipelineStep, Status> {
    let map = |e: sqlx::Error| Status::internal(format!("decode pipeline step failed: {e}"));
    Ok(asset_entity_pb::PipelineStep {
        step_id: row.try_get("step_id").map_err(map)?,
        instance_id: row.try_get("instance_id").map_err(map)?,
        tenant_id: row.try_get("tenant_id").map_err(map)?,
        step_name: row.try_get("step_name").map_err(map)?,
        step_type: step_type_from_db(&row.try_get::<String, _>("step_type").map_err(map)?),
        status: step_status_from_db(&row.try_get::<String, _>("status").map_err(map)?),
        result: row.try_get("result").map_err(map)?,
        error: row.try_get("error").map_err(map)?,
        retry_count: row.try_get::<i32, _>("retry_count").map_err(map)?,
        ..Default::default()
    })
}

#[tonic::async_trait]
impl AssetService for AssetServiceImpl {
    async fn create_pipeline_definition(
        &self,
        request: Request<asset_pb::CreatePipelineDefinitionRequest>,
    ) -> Result<Response<asset_pb::CreatePipelineDefinitionResponse>, Status> {
        let metadata = request.metadata().clone();
        let req = request.into_inner();
        validate_request_tenant(&metadata, &req.tenant_id)?;
        // Per-tenant fair admission (Write budget) so one tenant's definition
        // writes can't starve the shared pool.
        let _admit = native_admit_on(
            self.channels.as_ref(),
            &self.metrics,
            "asset",
            OperationChannel::Write,
            &req.tenant_id,
            Some(""),
        )
        .await?;
        let tenant_id = parse_uuid("tenant_id", &req.tenant_id)?;
        if req.name.trim().is_empty() {
            return Err(Status::invalid_argument("name is required"));
        }
        let steps = {
            let s = req.steps.trim();
            if s.is_empty() {
                "[]".to_string()
            } else {
                serde_json::from_str::<serde_json::Value>(s).map_err(|e| {
                    Status::invalid_argument(format!("steps must be valid JSON: {e}"))
                })?;
                s.to_string()
            }
        };
        let version = if req.version > 0 { req.version } else { 1 };
        let definition_id = Uuid::new_v4().to_string();
        let context = native_service_context(&metadata, &req.tenant_id, "");
        self.require_runtime()?
            .native_entity_write_for_service(
                "asset",
                &context,
                PIPELINE_DEFINITION_MSG,
                pipeline_definition_record(
                    &definition_id,
                    &tenant_id.to_string(),
                    &req,
                    &steps,
                    version,
                )?,
                ConflictStrategy::Error,
            )
            .await
            .map_err(|err| {
                crate::runtime::executor_utils::prefix_status(
                    "create pipeline definition failed",
                    err,
                )
            })?;
        Ok(Response::new(asset_pb::CreatePipelineDefinitionResponse {
            definition_id,
            message: "pipeline definition created".to_string(),
            error: None,
        }))
    }

    async fn get_pipeline_definition(
        &self,
        request: Request<asset_pb::GetPipelineDefinitionRequest>,
    ) -> Result<Response<asset_pb::GetPipelineDefinitionResponse>, Status> {
        let metadata = request.metadata().clone();
        let req = request.into_inner();
        validate_request_tenant(&metadata, &req.tenant_id)?;
        // Per-tenant fair admission (lighter Read budget) so reads can't starve the pool.
        let _admit = self.admit_read(&req.tenant_id).await?;
        let tenant_id = parse_uuid("tenant_id", &req.tenant_id)?;
        let definition_id = parse_uuid("definition_id", &req.definition_id)?;
        let context = native_service_context(&metadata, &req.tenant_id, "");
        let rows = self
            .require_runtime()?
            .native_entity_read_for_service(
                "asset",
                &context,
                pipeline_definition_read(&tenant_id.to_string(), &definition_id.to_string()),
            )
            .await?;
        let definition = rows.first().map(pipeline_definition_from_json);
        if definition.is_none() {
            return Err(Status::not_found("pipeline definition not found"));
        }
        Ok(Response::new(asset_pb::GetPipelineDefinitionResponse {
            definition,
            error: None,
        }))
    }

    async fn register_asset(
        &self,
        request: Request<asset_pb::RegisterAssetRequest>,
    ) -> Result<Response<asset_pb::RegisterAssetResponse>, Status> {
        let metadata = request.metadata().clone();
        let req = request.into_inner();
        validate_request_scope(&metadata, &req.tenant_id, &req.project_id)?;
        // Per-tenant fair admission (held for the whole RPC).
        let _admit = self.admit(&req.tenant_id, &req.project_id).await?;
        let tenant_id = parse_uuid("tenant_id", &req.tenant_id)?;
        if req.file_id.trim().is_empty() {
            return Err(Status::invalid_argument("file_id is required"));
        }
        let pool = self.require_pool()?;
        // Tenant-bind the referenced storage file: refuse to wrap a file that
        // isn't an active file owned by this tenant (prevents cross-tenant
        // file references via a forged file_id).
        let file_uuid = parse_uuid("file_id", &req.file_id)?;
        if self
            .resolve_object_key(pool, file_uuid, tenant_id)
            .await
            .is_none()
        {
            return Err(Status::invalid_argument(
                "file_id does not reference an active storage file owned by this tenant",
            ));
        }
        let asset_id = Uuid::new_v4().to_string();
        let asset_metadata = self.encrypt_native_json_state(&non_empty_json(&req.metadata))?;
        let context = native_service_context(&metadata, &req.tenant_id, req.project_id.trim());
        self.require_runtime()?
            .native_entity_write_for_service(
                "asset",
                &context,
                ASSET_MSG,
                asset_record(
                    &asset_id,
                    &tenant_id.to_string(),
                    req.project_id.trim(),
                    &req,
                    &asset_metadata,
                )?,
                ConflictStrategy::Error,
            )
            .await
            .map_err(|err| {
                crate::runtime::executor_utils::prefix_status("register asset failed", err)
            })?;
        emit_payload_event(
            pool,
            self.outbox_relation.as_deref(),
            ASSET_REGISTERED_TOPIC,
            &asset_id,
            serde_json::json!({
                "asset_id": asset_id,
                "tenant_id": req.tenant_id,
                "project_id": req.project_id,
                "file_id": req.file_id.trim(),
                "name": req.name,
                "media_type": req.media_type,
            }),
            Some(&self.metrics),
        )
        .await;
        Ok(Response::new(asset_pb::RegisterAssetResponse {
            asset_id,
            message: "asset registered".to_string(),
            error: None,
        }))
    }

    async fn start_pipeline(
        &self,
        request: Request<asset_pb::StartPipelineRequest>,
    ) -> Result<Response<asset_pb::StartPipelineResponse>, Status> {
        let metadata = request.metadata().clone();
        let req = request.into_inner();
        validate_request_tenant(&metadata, &req.tenant_id)?;
        // Per-tenant fair admission (held for the whole RPC) — starting a
        // pipeline schedules heavy step work, so it's gated per tenant.
        let _admit = self.admit(&req.tenant_id, "").await?;
        let tenant_id = parse_uuid("tenant_id", &req.tenant_id)?;
        let definition_id = parse_uuid("definition_id", &req.definition_id)?;
        let asset_id = parse_uuid("asset_id", &req.asset_id)?;
        let pool = self.require_pool()?;
        let inst = pipeline_instance_model();
        let inst_rel = inst.relation.clone();
        let def = pipeline_definition_model();
        let def_rel = def.relation.clone();
        let step = pipeline_step_model();
        let step_rel = step.relation.clone();

        let correlation_id = req.correlation_id.trim().to_string();

        // IDEMPOTENCY: if a correlation id is supplied and an instance already
        // exists for it, return that instance without re-triggering.
        if !correlation_id.is_empty() {
            if let Some(existing) = sqlx::query(&format!(
                "SELECT {instance_id}::TEXT AS instance_id FROM {inst_rel} \
                 WHERE {tenant_id} = $1::UUID AND {correlation_id} = $2",
                instance_id = inst.q("instance_id"),
                tenant_id = inst.q("tenant_id"),
                correlation_id = inst.q("correlation_id"),
            ))
            .bind(tenant_id)
            .bind(&correlation_id)
            .fetch_optional(pool)
            .await
            .map_err(|err| Status::internal(format!("start pipeline lookup failed: {err}")))?
            {
                let instance_id: String = existing
                    .try_get("instance_id")
                    .map_err(|e| Status::internal(format!("decode instance id failed: {e}")))?;
                return Ok(Response::new(asset_pb::StartPipelineResponse {
                    instance_id,
                    message: format!("pipeline already started [{PIPELINE_ALREADY_STARTED}]"),
                    error: None,
                    // Idempotent hit: only the existing instance id is in scope.
                    // Steps are left empty to avoid an extra round-trip; callers
                    // wanting them for an already-running instance call GetPipeline.
                    steps: Vec::new(),
                }));
            }
        }

        // Load the definition's step list.
        let steps_json: Option<String> = sqlx::query_scalar(&format!(
            "SELECT {steps}::TEXT FROM {def_rel} \
             WHERE {definition_id} = $1::UUID AND {tenant_id} = $2::UUID",
            steps = def.q("steps"),
            definition_id = def.q("definition_id"),
            tenant_id = def.q("tenant_id"),
        ))
        .bind(definition_id)
        .bind(tenant_id)
        .fetch_optional(pool)
        .await
        .map_err(|err| Status::internal(format!("load pipeline definition failed: {err}")))?;
        let steps_json = match steps_json {
            Some(s) => s,
            None => return Err(Status::not_found("pipeline definition not found")),
        };
        let parsed: serde_json::Value = serde_json::from_str(&steps_json).map_err(|e| {
            status_with_reason(
                Status::internal(format!("pipeline definition steps not JSON: {e}")),
                PIPELINE_DEFINITION_INVALID,
            )
        })?;
        let step_array: Vec<serde_json::Value> = match parsed {
            serde_json::Value::Array(a) => a,
            _ => Vec::new(),
        };
        let first_step_name = step_array
            .first()
            .and_then(|el| el.get("name"))
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();

        let instance_id = Uuid::new_v4().to_string();
        let context = self.encrypt_native_json_state(&non_empty_json(&req.context))?;
        let insert_result = sqlx::query(&format!(
            "INSERT INTO {inst_rel} \
             ({instance_id}, {definition_id}, {asset_id}, {tenant_id}, {status}, {current_step}, {context}, {correlation_id}, {started_at}) \
             VALUES ($1::UUID, $2::UUID, $3::UUID, $4::UUID, 'RUNNING', $5, $6::JSONB, NULLIF($7, ''), CURRENT_TIMESTAMP)",
            instance_id = inst.q("instance_id"),
            definition_id = inst.q("definition_id"),
            asset_id = inst.q("asset_id"),
            tenant_id = inst.q("tenant_id"),
            status = inst.q("status"),
            current_step = inst.q("current_step"),
            context = inst.q("context"),
            correlation_id = inst.q("correlation_id"),
            started_at = inst.q("started_at"),
        ))
        .bind(&instance_id)
        .bind(definition_id)
        .bind(asset_id)
        .bind(tenant_id)
        .bind(&first_step_name)
        .bind(&context)
        .bind(&correlation_id)
        .execute(pool)
        .await;

        if let Err(err) = insert_result {
            let is_unique = err
                .as_database_error()
                .map(|e| e.is_unique_violation())
                .unwrap_or(false);
            if is_unique && !correlation_id.is_empty() {
                // Concurrent start with the same correlation id won the race;
                // return the existing instance instead of failing.
                let existing = sqlx::query(&format!(
                    "SELECT {instance_id}::TEXT AS instance_id FROM {inst_rel} \
                     WHERE {tenant_id} = $1::UUID AND {correlation_id} = $2",
                    instance_id = inst.q("instance_id"),
                    tenant_id = inst.q("tenant_id"),
                    correlation_id = inst.q("correlation_id"),
                ))
                .bind(tenant_id)
                .bind(&correlation_id)
                .fetch_optional(pool)
                .await
                .map_err(|e| Status::internal(format!("start pipeline re-lookup failed: {e}")))?;
                if let Some(row) = existing {
                    let id: String = row
                        .try_get("instance_id")
                        .map_err(|e| Status::internal(format!("decode instance id failed: {e}")))?;
                    return Ok(Response::new(asset_pb::StartPipelineResponse {
                        instance_id: id,
                        message: format!("pipeline already started [{PIPELINE_ALREADY_STARTED}]"),
                        error: None,
                        // Race branch: only the existing instance id is in scope.
                        // Reading its steps would cost an extra round-trip, so the
                        // step list is left empty here; callers wanting steps for an
                        // already-running instance call GetPipeline.
                        steps: Vec::new(),
                    }));
                }
            }
            return Err(crate::runtime::executor_utils::sqlx_error_to_status(
                "start pipeline failed",
                &err,
            ));
        }

        // Pipeline started → emit the lifecycle event.
        emit_payload_event(
            pool,
            self.outbox_relation.as_deref(),
            PIPELINE_STARTED_TOPIC,
            &instance_id,
            serde_json::json!({
                "instance_id": instance_id,
                "definition_id": req.definition_id,
                "asset_id": req.asset_id,
                "tenant_id": req.tenant_id,
            }),
            Some(&self.metrics),
        )
        .await;

        // Load the asset's name + metadata once: these are the inputs available
        // to in-process steps without object bytes. Missing asset → empty inputs.
        let am = asset_model();
        let am_rel = am.relation.clone();
        let asset_inputs: Option<(String, String, String, String)> = sqlx::query(&format!(
            "SELECT {name}, {metadata}, {file_id}, {project_id} FROM {am_rel} \
             WHERE {asset_id} = $1::UUID AND {tenant_id} = $2::UUID",
            name = am.text_or_empty_as("name", "asset_name"),
            metadata = am.text_or_empty_as("metadata", "asset_metadata"),
            file_id = am.text_or_empty_as("file_id", "file_id"),
            project_id = am.text_or_empty_as("project_id", "project_id"),
            asset_id = am.q("asset_id"),
            tenant_id = am.q("tenant_id"),
        ))
        .bind(asset_id)
        .bind(tenant_id)
        .fetch_optional(pool)
        .await
        .map_err(|err| Status::internal(format!("load asset for pipeline failed: {err}")))?
        .map(|row| {
            let name: String = row.try_get("asset_name").unwrap_or_default();
            let metadata: String = row.try_get("asset_metadata").unwrap_or_default();
            let file_id: String = row.try_get("file_id").unwrap_or_default();
            let project_id: String = row.try_get("project_id").unwrap_or_default();
            (name, metadata, file_id, project_id)
        });
        let (asset_name, asset_metadata, asset_file_id, asset_project_id) =
            asset_inputs.unwrap_or_default();
        let asset_metadata = self.decrypt_native_json_state(&asset_metadata)?;

        // Accumulate the materialized steps so the response can return them
        // inline (mirrors GetPipelineResponse.steps) without a follow-up read.
        let mut response_steps: Vec<asset_entity_pb::PipelineStep> =
            Vec::with_capacity(step_array.len());

        // Materialize each step, RUN it in-process, and record the outcome.
        for el in &step_array {
            let step_name = el.get("name").and_then(|v| v.as_str()).unwrap_or("");
            let step_type_str = el.get("type").and_then(|v| v.as_str()).unwrap_or("");
            let step_type = step_type_to_db(step_type_str, "EMBED").map_err(|e| {
                // Same Status code; only add the stable reason for SDK branching.
                status_with_reason(e, STEP_TYPE_UNSUPPORTED)
            })?;
            let step_type_i32 = step_type_from_db(&step_type);
            let step_id = Uuid::new_v4().to_string();

            // Pure-CPU metadata steps (EMBED/EXTRACT) run via the sync registry.
            // Byte-IO steps (THUMBNAIL/RESIZE) fetch the source object, transform,
            // and store a derived object — inherently async, so they take a
            // separate path (still no registry edit to add metadata step types).
            let outcome = if is_byte_step(step_type_i32) {
                self.run_byte_step(
                    pool,
                    step_type_i32,
                    &asset_file_id,
                    tenant_id,
                    &asset_project_id,
                )
                .await
            } else {
                step_registry().run(
                    step_type_i32,
                    &StepContext {
                        asset_name: &asset_name,
                        metadata_json: &asset_metadata,
                    },
                )
            };
            let outcome = if step_type == "EMBED" {
                match outcome {
                    StepOutcome::Completed(mut value) => {
                        if let Some(target) = self
                            .upsert_embedding(&asset_project_id, &req.asset_id, &value)
                            .await
                        {
                            if let Some(object) = value.as_object_mut() {
                                object.insert(
                                    "vector_backend".to_string(),
                                    serde_json::Value::String("qdrant".to_string()),
                                );
                                object.insert(
                                    "vector_backend_instance".to_string(),
                                    serde_json::Value::String(target.instance),
                                );
                                object.insert(
                                    "vector_project_id".to_string(),
                                    serde_json::Value::String(target.project_id),
                                );
                            }
                        }
                        StepOutcome::Completed(value)
                    }
                    other => other,
                }
            } else {
                outcome
            };
            let (status_token, result_json, error_text) = match &outcome {
                StepOutcome::Completed(v) => ("COMPLETED", v.to_string(), String::new()),
                StepOutcome::Failed(msg) => ("FAILED", "{}".to_string(), msg.clone()),
            };
            let result_json = self.encrypt_native_json_state(&result_json)?;

            sqlx::query(&format!(
                "INSERT INTO {step_rel} \
                 ({step_id}, {instance_id}, {tenant_id}, {step_name}, {step_type}, {status}, {result}, {error}, {completed_at}) \
                 VALUES ($1::UUID, $2::UUID, $3::UUID, $4, $5, $6, $7::JSONB, NULLIF($8, ''), CURRENT_TIMESTAMP)",
                step_id = step.q("step_id"),
                instance_id = step.q("instance_id"),
                tenant_id = step.q("tenant_id"),
                step_name = step.q("step_name"),
                step_type = step.q("step_type"),
                status = step.q("status"),
                result = step.q("result"),
                error = step.q("error"),
                completed_at = step.q("completed_at"),
            ))
            .bind(&step_id)
            .bind(&instance_id)
            .bind(tenant_id)
            .bind(step_name)
            .bind(&step_type)
            .bind(status_token)
            .bind(&result_json)
            .bind(&error_text)
            .execute(pool)
            .await
            .map_err(|err| {
                crate::runtime::executor_utils::sqlx_error_to_status(
                    "create pipeline step failed",
                    &err,
                )
            })?;

            // Mirror the persisted row into the response. The plaintext result /
            // error come straight from `outcome` (the same values the row holds,
            // pre-encryption), matching what GetPipeline returns after decrypt.
            let (step_result_plain, step_error_plain) = match &outcome {
                StepOutcome::Completed(v) => (v.to_string(), String::new()),
                StepOutcome::Failed(msg) => ("{}".to_string(), msg.clone()),
            };
            response_steps.push(asset_entity_pb::PipelineStep {
                step_id: step_id.clone(),
                instance_id: instance_id.clone(),
                tenant_id: req.tenant_id.clone(),
                step_name: step_name.to_string(),
                step_type: step_type_i32,
                status: step_status_from_db(status_token),
                result: step_result_plain,
                error: step_error_plain,
                ..Default::default()
            });

            emit_payload_event(
                pool,
                self.outbox_relation.as_deref(),
                PIPELINE_STEP_COMPLETED_TOPIC,
                &instance_id,
                serde_json::json!({
                    "instance_id": instance_id,
                    "tenant_id": req.tenant_id,
                    "step_id": step_id,
                    "step_name": step_name,
                    "step_type": step_type,
                    "status": status_token,
                }),
                Some(&self.metrics),
            )
            .await;
        }

        // Advance the instance to a terminal state (emits completed/failed).
        let instance_uuid = parse_uuid("instance_id", &instance_id)?;
        advance_instance(self, pool, instance_uuid, tenant_id).await?;

        Ok(Response::new(asset_pb::StartPipelineResponse {
            instance_id,
            message: "pipeline started".to_string(),
            error: None,
            steps: response_steps,
        }))
    }

    async fn get_pipeline(
        &self,
        request: Request<asset_pb::GetPipelineRequest>,
    ) -> Result<Response<asset_pb::GetPipelineResponse>, Status> {
        let metadata = request.metadata().clone();
        let req = request.into_inner();
        validate_request_tenant(&metadata, &req.tenant_id)?;
        // Per-tenant fair admission (lighter Read budget) so reads can't starve the pool.
        let _admit = self.admit_read(&req.tenant_id).await?;
        let tenant_id = parse_uuid("tenant_id", &req.tenant_id)?;
        let instance_id = parse_uuid("instance_id", &req.instance_id)?;
        let pool = self.require_pool()?;
        let inst = pipeline_instance_model();
        let inst_rel = inst.relation.clone();
        let inst_projection = pipeline_instance_select_projection(&inst);
        let row = sqlx::query(&format!(
            "SELECT {inst_projection} FROM {inst_rel} \
             WHERE {instance_id} = $1::UUID AND {tenant_id} = $2::UUID",
            instance_id = inst.q("instance_id"),
            tenant_id = inst.q("tenant_id"),
        ))
        .bind(instance_id)
        .bind(tenant_id)
        .fetch_optional(pool)
        .await
        .map_err(|err| Status::internal(format!("get pipeline failed: {err}")))?;
        let instance = match row {
            Some(row) => {
                let mut instance = pipeline_instance_from_row(&row)?;
                instance.context = self.decrypt_native_json_state(&instance.context)?;
                Some(instance)
            }
            None => return Err(Status::not_found("pipeline instance not found")),
        };

        let step = pipeline_step_model();
        let step_rel = step.relation.clone();
        let step_projection = pipeline_step_select_projection(&step);
        let step_rows = sqlx::query(&format!(
            "SELECT {step_projection} FROM {step_rel} \
             WHERE {instance_id} = $1::UUID AND {tenant_id} = $2::UUID ORDER BY {step_name}",
            instance_id = step.q("instance_id"),
            tenant_id = step.q("tenant_id"),
            step_name = step.q("step_name"),
        ))
        .bind(instance_id)
        .bind(tenant_id)
        .fetch_all(pool)
        .await
        .map_err(|err| Status::internal(format!("get pipeline steps failed: {err}")))?;
        let mut steps = Vec::with_capacity(step_rows.len());
        for r in &step_rows {
            let mut step = pipeline_step_from_row(r)?;
            step.result = self.decrypt_native_json_state(&step.result)?;
            steps.push(step);
        }

        Ok(Response::new(asset_pb::GetPipelineResponse {
            instance,
            steps,
            error: None,
        }))
    }

    async fn complete_step(
        &self,
        request: Request<asset_pb::CompleteStepRequest>,
    ) -> Result<Response<asset_pb::CompleteStepResponse>, Status> {
        let metadata = request.metadata().clone();
        let req = request.into_inner();
        validate_request_tenant(&metadata, &req.tenant_id)?;
        // Per-tenant fair admission (held for the whole RPC) — completing a step
        // can trigger the next step + vector upserts, so it's gated per tenant.
        let _admit = self.admit(&req.tenant_id, "").await?;
        let tenant_id = parse_uuid("tenant_id", &req.tenant_id)?;
        let step_id = parse_uuid("step_id", &req.step_id)?;
        let pool = self.require_pool()?;
        let step = pipeline_step_model();
        let step_rel = step.relation.clone();
        let status = step_status_to_db(&req.status, "COMPLETED")?;
        let result_json = if req.result.trim().is_empty() {
            String::new()
        } else {
            self.encrypt_native_json_state(req.result.trim())?
        };

        let result = sqlx::query(&format!(
            "UPDATE {step_rel} SET \
               {status} = $3, \
               {result} = CASE WHEN $4 = '' THEN {result} ELSE $4::JSONB END, \
               {error} = NULLIF($5, ''), \
               {completed_at} = CURRENT_TIMESTAMP \
             WHERE {step_id} = $1::UUID AND {tenant_id} = $2::UUID",
            status = step.q("status"),
            result = step.q("result"),
            error = step.q("error"),
            completed_at = step.q("completed_at"),
            step_id = step.q("step_id"),
            tenant_id = step.q("tenant_id"),
        ))
        .bind(step_id)
        .bind(tenant_id)
        .bind(&status)
        .bind(&result_json)
        .bind(req.error_message.trim())
        .execute(pool)
        .await
        .map_err(|err| Status::internal(format!("complete step failed: {err}")))?;
        if result.rows_affected() == 0 {
            return Err(Status::not_found("pipeline step not found"));
        }

        // Resolve the owning instance for advance.
        let instance_id: Uuid = sqlx::query_scalar(&format!(
            "SELECT {instance_id} FROM {step_rel} \
             WHERE {step_id} = $1::UUID AND {tenant_id} = $2::UUID",
            instance_id = step.q("instance_id"),
            step_id = step.q("step_id"),
            tenant_id = step.q("tenant_id"),
        ))
        .bind(step_id)
        .bind(tenant_id)
        .fetch_one(pool)
        .await
        .map_err(|err| Status::internal(format!("resolve step instance failed: {err}")))?;

        // Per-step completion event (externally-driven step).
        emit_payload_event(
            pool,
            self.outbox_relation.as_deref(),
            PIPELINE_STEP_COMPLETED_TOPIC,
            &instance_id.to_string(),
            serde_json::json!({
                "instance_id": instance_id.to_string(),
                "tenant_id": req.tenant_id,
                "step_id": req.step_id,
                "status": status,
            }),
            Some(&self.metrics),
        )
        .await;

        // Roll the instance to a terminal state when all steps are accounted for,
        // or to FAILED on any failed step (shared with start_pipeline).
        advance_instance(self, pool, instance_id, tenant_id).await?;

        Ok(Response::new(asset_pb::CompleteStepResponse {
            message: "step completed".to_string(),
            error: None,
        }))
    }

    async fn list_assets(
        &self,
        request: Request<asset_pb::ListAssetsRequest>,
    ) -> Result<Response<asset_pb::ListAssetsResponse>, Status> {
        let metadata = request.metadata().clone();
        let req = request.into_inner();
        validate_request_tenant(&metadata, &req.tenant_id)?;
        // Per-tenant fair admission (lighter Read budget) so list scans can't starve the pool.
        let _admit = self.admit_read(&req.tenant_id).await?;
        let tenant_id = parse_uuid("tenant_id", &req.tenant_id)?;
        let m = asset_model();
        let rel = m.relation.clone();
        let media_filter = req.media_type.trim().to_string();
        let status_filter = asset_status_to_db(&req.status, "")?;
        let page_size = if req.page_size > 0 { req.page_size } else { 50 }.min(500);
        let page = if req.page > 0 { req.page } else { 1 };
        let offset = (page - 1) * page_size;
        let pool = self.require_pool()?;
        let where_clause = format!(
            "WHERE {tenant_id} = $1::UUID AND {deleted} IS NULL \
             AND ($2 = '' OR {media_type} = $2) AND ($3 = '' OR {status} = $3)",
            tenant_id = m.q("tenant_id"),
            deleted = m.q("deleted_at"),
            media_type = m.q("media_type"),
            status = m.q("status"),
        );
        let total: i64 = sqlx::query_scalar(&format!("SELECT COUNT(*) FROM {rel} {where_clause}"))
            .bind(tenant_id)
            .bind(&media_filter)
            .bind(&status_filter)
            .fetch_one(pool)
            .await
            .map_err(|err| Status::internal(format!("count assets failed: {err}")))?;
        let context = native_service_context(&metadata, &req.tenant_id, "");
        let rows = self
            .require_runtime()?
            .native_entity_read_for_service(
                "asset",
                &context,
                asset_read(
                    &tenant_id.to_string(),
                    None,
                    Some(&media_filter),
                    Some(&status_filter),
                    offset as u64,
                    page_size as u32,
                ),
            )
            .await?;
        let mut assets = Vec::with_capacity(rows.len());
        for row in &rows {
            let mut asset = asset_from_json(row);
            asset.metadata = self.decrypt_native_json_state(&asset.metadata)?;
            assets.push(asset);
        }
        Ok(Response::new(asset_pb::ListAssetsResponse {
            assets,
            total_count: total as i32,
            error: None,
        }))
    }

    async fn get_asset(
        &self,
        request: Request<asset_pb::GetAssetRequest>,
    ) -> Result<Response<asset_pb::GetAssetResponse>, Status> {
        let metadata = request.metadata().clone();
        let req = request.into_inner();
        validate_request_tenant(&metadata, &req.tenant_id)?;
        // Per-tenant fair admission (lighter Read budget) so reads can't starve the pool.
        let _admit = self.admit_read(&req.tenant_id).await?;
        let tenant_id = parse_uuid("tenant_id", &req.tenant_id)?;
        let asset_id = parse_uuid("asset_id", &req.asset_id)?;
        let context = native_service_context(&metadata, &req.tenant_id, "");
        let rows = self
            .require_runtime()?
            .native_entity_read_for_service(
                "asset",
                &context,
                asset_read(
                    &tenant_id.to_string(),
                    Some(&asset_id.to_string()),
                    None,
                    None,
                    0,
                    1,
                ),
            )
            .await?;
        let asset = match rows.first() {
            Some(row) => {
                let mut asset = asset_from_json(row);
                asset.metadata = self.decrypt_native_json_state(&asset.metadata)?;
                Some(asset)
            }
            None => return Err(Status::not_found("asset not found")),
        };
        Ok(Response::new(asset_pb::GetAssetResponse {
            asset,
            error: None,
        }))
    }
}

#[cfg(test)]
mod step_executor_tests {
    use super::*;
    use asset_entity_pb::StepType as T;

    #[test]
    fn registry_dispatches_embed_extract_and_fails_media() {
        let registry = StepRegistry::default_registry();
        let ctx = StepContext {
            asset_name: "report",
            metadata_json: "{\"k\":\"v\"}",
        };

        match registry.run(T::Embed as i32, &ctx) {
            StepOutcome::Completed(v) => {
                assert!(
                    v.get("embedding").and_then(|e| e.as_array()).is_some(),
                    "EMBED must produce an `embedding` array, got {v}"
                );
            }
            StepOutcome::Failed(msg) => panic!("EMBED should complete, failed with: {msg}"),
        }

        assert!(
            matches!(
                registry.run(T::Extract as i32, &ctx),
                StepOutcome::Completed(_)
            ),
            "EXTRACT should complete"
        );

        match registry.run(T::Transcode as i32, &ctx) {
            StepOutcome::Failed(msg) => {
                assert!(
                    msg.contains("not yet implemented"),
                    "TRANSCODE failure message should explain it is unimplemented, got: {msg}"
                );
            }
            StepOutcome::Completed(_) => panic!("TRANSCODE must fail (no capability lie)"),
        }
    }
}

#[cfg(test)]
mod tenant_scope_tests {
    use super::*;
    use tonic::metadata::MetadataValue;

    /// A caller scoped to tenant-a must not read another tenant's asset by putting
    /// a foreign tenant_id in the request BODY; the scope guard rejects this before
    /// any pool/DB access (no Postgres needed).
    #[tokio::test]
    async fn get_asset_rejects_cross_tenant_body() {
        let svc = AssetServiceImpl::new(); // no pool, no channels (admit no-op)
        let mut request = Request::new(asset_pb::GetAssetRequest {
            tenant_id: "tenant-b".to_string(),
            asset_id: "00000000-0000-0000-0000-000000000001".to_string(),
            ..Default::default()
        });
        request
            .metadata_mut()
            .insert("x-tenant-id", MetadataValue::from_static("tenant-a"));
        let err = svc
            .get_asset(request)
            .await
            .expect_err("cross-tenant body must be rejected");
        assert_eq!(err.code(), tonic::Code::PermissionDenied);
    }
}

impl DataBrokerService {
    /// Build the native `AssetService`, wired to the broker's Postgres pool.
    pub(crate) fn build_asset_service(&self) -> AssetServiceImpl {
        let runtime = self.runtime.load_full();
        // Native-service persistence resolves through the discovery seam (extend_udb.md):
        // the backend is read from this service's proto `native_service` binding, then a
        // health/weight-routed instance is chosen — not the process-global pool.
        let pg_pool = runtime
            .native_store_pool_for_service("asset", true, "")
            .ok();
        let outbox = runtime.config().cdc.outbox_relation();
        let collection = std::env::var("UDB_ASSET_VECTOR_COLLECTION")
            .unwrap_or_else(|_| DEFAULT_VECTOR_COLLECTION.to_string());
        AssetServiceImpl::new()
            .with_postgres(pg_pool)
            .with_outbox(Some(outbox))
            .with_metrics(self.metrics.clone())
            .with_vector(Some(runtime.clone()), collection)
    }
}

/// Topic the storage service emits on finalize; the auto-trigger consumes it.
#[cfg(feature = "kafka")]
const STORAGE_FINALIZED_TOPIC: &str = "udb.storage.file.finalized.v1";

#[cfg(feature = "kafka")]
fn storage_finalized_consumer_config(brokers: &str) -> rdkafka::ClientConfig {
    let mut config = rdkafka::ClientConfig::new();
    config
        .set("bootstrap.servers", brokers)
        .set("group.id", "udb-asset-storage-finalized-trigger")
        .set("enable.auto.commit", "false")
        .set("auto.offset.reset", "earliest");
    config
}

#[cfg(feature = "kafka")]
async fn ensure_storage_finalized_topic(brokers: &str) -> Result<(), String> {
    use rdkafka::ClientConfig;
    use rdkafka::admin::{AdminClient, AdminOptions, NewTopic, TopicReplication};
    use rdkafka::client::DefaultClientContext;

    let admin: AdminClient<DefaultClientContext> = ClientConfig::new()
        .set("bootstrap.servers", brokers)
        .create()
        .map_err(|err| format!("create Kafka admin client failed: {err}"))?;
    match admin
        .create_topics(
            &[NewTopic::new(
                STORAGE_FINALIZED_TOPIC,
                1,
                TopicReplication::Fixed(1),
            )],
            &AdminOptions::new(),
        )
        .await
    {
        Ok(results) => {
            for result in results {
                if let Err((name, code)) = result
                    && !format!("{code:?}").contains("TopicAlreadyExists")
                {
                    return Err(format!("create Kafka topic {name} failed: {code:?}"));
                }
            }
        }
        Err(err) => return Err(format!("create Kafka topic request failed: {err}")),
    }
    admin
        .inner()
        .fetch_metadata(
            Some(STORAGE_FINALIZED_TOPIC),
            std::time::Duration::from_secs(10),
        )
        .map_err(|err| {
            format!("Kafka topic {STORAGE_FINALIZED_TOPIC} metadata was not visible: {err}")
        })?;
    Ok(())
}

#[cfg(feature = "kafka")]
fn storage_finalized_payload_ids(bytes: &[u8]) -> Option<(String, String)> {
    let env = serde_json::from_slice::<serde_json::Value>(bytes).ok()?;
    // Canonical envelope: tenant_id at top level; file_id in the payload
    // (document_id is the partition key = file_id too).
    let tenant_id = env.get("tenant_id").and_then(|v| v.as_str())?.trim();
    let file_id = env
        .get("payload")
        .and_then(|p| p.get("file_id"))
        .and_then(|v| v.as_str())
        .or_else(|| env.get("document_id").and_then(|v| v.as_str()))?
        .trim();
    if tenant_id.is_empty() || file_id.is_empty() {
        return None;
    }
    Some((tenant_id.to_string(), file_id.to_string()))
}

#[cfg(feature = "kafka")]
fn storage_finalized_commit_offsets(
    topic: &str,
    partition: i32,
    message_offset: i64,
) -> rdkafka::error::KafkaResult<rdkafka::TopicPartitionList> {
    let mut offsets = rdkafka::TopicPartitionList::new();
    offsets.add_partition_offset(
        topic,
        partition,
        rdkafka::Offset::Offset(message_offset.saturating_add(1)),
    )?;
    Ok(offsets)
}

#[cfg(feature = "kafka")]
fn should_commit_storage_finalized_offset(result: &Result<Option<String>, Status>) -> bool {
    result.is_ok()
}

#[cfg(feature = "kafka")]
fn is_storage_finalized_topic_missing_error(err: &rdkafka::error::KafkaError) -> bool {
    let text = err.to_string();
    text.contains("UnknownTopicOrPartition")
        || text.contains("Broker: Unknown topic or partition")
        || text.contains("unknown topic or partition")
}

#[cfg(feature = "kafka")]
impl AssetServiceImpl {
    /// Spawn the storage→asset auto-trigger: a background Kafka consumer on
    /// `udb.storage.file.finalized.v1` that, per finalized file, registers the
    /// asset and starts the matching pipeline via [`handle_storage_finalized`]
    /// (idempotent). Offsets are committed only after successful handling, so
    /// backlog is replayed at-least-once across restarts. Best-effort — a
    /// consumer error logs; the broker keeps running.
    ///
    /// Lifecycle (P6.4 decision): this runs **per node**, intentionally — every
    /// replica joins the **shared** Kafka consumer group
    /// `udb-asset-storage-finalized-trigger`, so the group coordinator
    /// distributes partitions across replicas and each message is delivered to
    /// exactly one consumer. This is NOT the leader-elected `NativeWorkerHost`
    /// pattern and must NOT be converted to it: a singleton lease would collapse
    /// every partition onto one node and forfeit horizontal consume throughput.
    /// At-least-once redelivery on rebalance is made safe by
    /// [`handle_storage_finalized`]'s idempotency, not by single-ownership.
    pub(crate) fn spawn_storage_finalized_consumer(self: std::sync::Arc<Self>, brokers: String) {
        tokio::spawn(async move {
            use rdkafka::Message;
            use rdkafka::consumer::{CommitMode, Consumer, StreamConsumer};
            if let Err(err) = ensure_storage_finalized_topic(&brokers).await {
                tracing::warn!(
                    error = %err,
                    topic = STORAGE_FINALIZED_TOPIC,
                    "asset storage-finalized consumer: topic preflight failed; consumer will retry metadata"
                );
            }
            let config = storage_finalized_consumer_config(&brokers);
            let consumer: StreamConsumer = match config.create() {
                Ok(c) => c,
                Err(err) => {
                    tracing::error!(
                        error = %err,
                        "asset storage-finalized consumer: create failed"
                    );
                    return;
                }
            };
            if let Err(err) = consumer.subscribe(&[STORAGE_FINALIZED_TOPIC]) {
                tracing::error!(error = %err, "asset storage-finalized consumer: subscribe failed");
                return;
            }
            tracing::info!(
                topic = STORAGE_FINALIZED_TOPIC,
                "storage→asset auto-trigger consumer started"
            );
            loop {
                match consumer.recv().await {
                    Ok(msg) => {
                        let Some(bytes) = msg.payload() else {
                            tracing::warn!(
                                "asset storage-finalized consumer: message missing payload"
                            );
                            continue;
                        };
                        let Some((tenant_id, file_id)) = storage_finalized_payload_ids(bytes)
                        else {
                            tracing::warn!(
                                topic = msg.topic(),
                                partition = msg.partition(),
                                offset = msg.offset(),
                                "asset storage-finalized consumer: invalid envelope"
                            );
                            continue;
                        };
                        let topic = msg.topic().to_string();
                        let partition = msg.partition();
                        let offset = msg.offset();
                        let result = self.handle_storage_finalized(&file_id, &tenant_id).await;
                        if should_commit_storage_finalized_offset(&result) {
                            match storage_finalized_commit_offsets(&topic, partition, offset) {
                                Ok(offsets) => {
                                    if let Err(err) = consumer.commit(&offsets, CommitMode::Async) {
                                        tracing::warn!(
                                            error = %err,
                                            file_id = %file_id,
                                            topic = %topic,
                                            partition,
                                            offset,
                                            "asset storage-finalized consumer commit failed"
                                        );
                                    }
                                }
                                Err(err) => {
                                    tracing::warn!(
                                        error = %err,
                                        file_id = %file_id,
                                        topic = %topic,
                                        partition,
                                        offset,
                                        "asset storage-finalized consumer commit offset build failed"
                                    );
                                }
                            }
                        }
                        if let Err(err) = result {
                            tracing::warn!(
                                error = %err,
                                file_id = %file_id,
                                "storage→asset trigger failed"
                            );
                        }
                    }
                    Err(err) => {
                        if is_storage_finalized_topic_missing_error(&err) {
                            tracing::debug!(
                                error = %err,
                                topic = STORAGE_FINALIZED_TOPIC,
                                "asset storage-finalized consumer: topic not visible yet"
                            );
                            tokio::time::sleep(std::time::Duration::from_secs(2)).await;
                            continue;
                        }
                        tracing::warn!(error = %err, "asset storage-finalized consumer recv error");
                    }
                }
            }
        });
    }
}

#[cfg(all(test, feature = "kafka"))]
mod storage_finalized_consumer_tests {
    use super::*;

    #[test]
    fn consumer_config_replays_backlog_and_disables_auto_commit() {
        let config = storage_finalized_consumer_config("broker-a:9092");

        assert_eq!(config.get("bootstrap.servers"), Some("broker-a:9092"));
        assert_eq!(
            config.get("group.id"),
            Some("udb-asset-storage-finalized-trigger")
        );
        assert_eq!(config.get("auto.offset.reset"), Some("earliest"));
        assert_eq!(config.get("enable.auto.commit"), Some("false"));
    }

    #[test]
    fn commit_offset_advances_only_the_processed_message() {
        let offsets = storage_finalized_commit_offsets(STORAGE_FINALIZED_TOPIC, 2, 41).unwrap();
        let elem = offsets
            .find_partition(STORAGE_FINALIZED_TOPIC, 2)
            .expect("topic partition offset should be present");

        assert_eq!(elem.offset(), rdkafka::Offset::Offset(42));
    }

    #[test]
    fn commit_decision_follows_handler_success() {
        assert!(should_commit_storage_finalized_offset(&Ok(Some(
            "instance-1".to_string()
        ))));
        assert!(should_commit_storage_finalized_offset(&Ok(None)));
        assert!(!should_commit_storage_finalized_offset(&Err(
            Status::internal("handler failed")
        )));
    }

    #[test]
    fn finalized_payload_extracts_payload_file_id_then_document_id() {
        let direct = br#"{
            "tenant_id": "tenant-a",
            "document_id": "fallback",
            "payload": { "file_id": "file-a" }
        }"#;
        assert_eq!(
            storage_finalized_payload_ids(direct),
            Some(("tenant-a".to_string(), "file-a".to_string()))
        );

        let fallback = br#"{
            "tenant_id": "tenant-a",
            "document_id": "file-b",
            "payload": {}
        }"#;
        assert_eq!(
            storage_finalized_payload_ids(fallback),
            Some(("tenant-a".to_string(), "file-b".to_string()))
        );

        assert_eq!(
            storage_finalized_payload_ids(br#"{"tenant_id":"tenant-a"}"#),
            None
        );
    }
}