File size: 62,991 Bytes
712f4ea
 
 
 
 
 
 
 
 
80df99b
03f666d
712f4ea
80df99b
712f4ea
48f60d7
712f4ea
 
 
 
 
 
 
740fcec
299d1d7
 
 
 
 
740fcec
 
 
054ee3f
48f60d7
 
 
 
 
299d1d7
712f4ea
 
 
 
075133b
740fcec
80df99b
 
 
075133b
 
 
 
 
 
 
 
 
 
78efa34
 
075133b
 
 
80df99b
 
 
 
 
 
 
 
 
 
 
 
 
712f4ea
 
 
 
77507c2
 
712f4ea
075133b
 
d018198
075133b
 
 
d018198
075133b
d018198
075133b
712f4ea
 
 
 
 
 
77507c2
 
712f4ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff746e3
 
 
 
 
0cd5796
 
 
 
 
5b56d1b
05163ad
 
0cd5796
 
 
 
 
 
712f4ea
 
 
 
21f6df4
 
 
77507c2
 
 
21f6df4
 
 
299d1d7
21f6df4
 
299d1d7
 
 
 
 
 
 
 
65ccdcd
 
48f60d7
14cdea1
075133b
14cdea1
65ccdcd
 
 
48f60d7
 
 
 
 
 
 
 
 
 
 
7088133
 
21f6df4
 
 
32bf975
 
 
21f6df4
 
 
 
 
48f60d7
21f6df4
 
48f60d7
21f6df4
075133b
48f60d7
21f6df4
48f60d7
21f6df4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48f60d7
21f6df4
48f60d7
21f6df4
 
 
 
48f60d7
21f6df4
48f60d7
21f6df4
 
 
 
 
712f4ea
 
 
 
 
 
 
740fcec
 
712f4ea
 
 
 
 
 
 
 
48f60d7
740fcec
48f60d7
712f4ea
 
48f60d7
712f4ea
 
 
 
d87b18a
 
 
 
 
 
5b56d1b
d87b18a
 
48f60d7
740fcec
48f60d7
712f4ea
 
 
5b56d1b
 
712f4ea
d87b18a
 
 
 
5b56d1b
d87b18a
 
712f4ea
48f60d7
712f4ea
 
 
 
 
d87b18a
 
 
 
 
5b56d1b
d87b18a
 
48f60d7
740fcec
48f60d7
7e6906e
 
 
 
5b56d1b
7e6906e
 
48f60d7
7e6906e
 
 
 
 
0cd5796
 
 
 
 
 
48f60d7
740fcec
48f60d7
0cd5796
 
 
 
 
 
 
48f60d7
0cd5796
 
 
 
 
712f4ea
48f60d7
740fcec
48f60d7
712f4ea
 
48f60d7
712f4ea
 
 
 
48f60d7
740fcec
48f60d7
712f4ea
 
48f60d7
 
712f4ea
48f60d7
712f4ea
 
 
 
48f60d7
740fcec
48f60d7
712f4ea
 
 
 
05163ad
712f4ea
 
48f60d7
712f4ea
 
 
 
 
 
48f60d7
740fcec
48f60d7
712f4ea
 
48f60d7
712f4ea
 
05163ad
712f4ea
 
48f60d7
712f4ea
 
 
 
05163ad
712f4ea
 
48f60d7
712f4ea
 
 
 
 
 
77507c2
740fcec
712f4ea
 
05163ad
712f4ea
 
 
 
e748eb0
 
 
 
 
740fcec
 
e748eb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
712f4ea
 
 
 
 
48f60d7
78efa34
 
 
 
740fcec
48f60d7
740fcec
712f4ea
 
 
 
 
48f60d7
712f4ea
 
 
 
 
740fcec
 
712f4ea
 
 
0cd5796
 
 
 
 
 
 
 
712f4ea
 
 
 
 
 
48f60d7
740fcec
48f60d7
712f4ea
 
 
 
48f60d7
712f4ea
 
 
 
 
 
48f60d7
740fcec
48f60d7
712f4ea
 
 
0cd5796
 
 
 
48f60d7
712f4ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48f60d7
 
740fcec
 
48f60d7
740fcec
 
 
712f4ea
 
 
 
 
 
 
48f60d7
712f4ea
 
 
 
44d1f89
 
 
 
48f60d7
 
 
 
740fcec
48f60d7
740fcec
44d1f89
 
 
 
 
 
 
48f60d7
44d1f89
 
 
712f4ea
 
48f60d7
740fcec
48f60d7
712f4ea
 
 
 
 
 
 
48f60d7
712f4ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d87b18a
 
 
 
 
 
5b56d1b
d87b18a
 
 
5b56d1b
d87b18a
 
 
 
 
 
 
5b56d1b
d87b18a
 
 
5b56d1b
d87b18a
7e6906e
0cd5796
 
 
 
 
 
 
 
 
 
712f4ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e748eb0
 
 
712f4ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44d1f89
 
 
712f4ea
 
05163ad
 
 
 
 
 
740fcec
 
 
 
48f60d7
740fcec
05163ad
48f60d7
 
05163ad
48f60d7
77507c2
48f60d7
 
 
 
 
 
05163ad
 
 
 
 
 
 
 
 
 
 
 
 
 
740fcec
 
 
 
 
 
48f60d7
 
 
 
 
 
7088133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48f60d7
740fcec
48f60d7
740fcec
 
 
48f60d7
740fcec
05163ad
 
 
 
 
740fcec
 
 
 
48f60d7
740fcec
 
 
 
 
 
48f60d7
740fcec
299d1d7
 
 
 
 
 
 
 
740fcec
 
80df99b
48f60d7
 
 
299d1d7
 
 
 
48f60d7
 
 
299d1d7
 
 
 
 
 
 
48f60d7
 
299d1d7
 
 
 
 
 
 
 
 
48f60d7
 
 
 
 
299d1d7
 
 
 
 
 
 
 
 
740fcec
 
299d1d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff746e3
 
 
 
 
 
 
 
 
740fcec
 
 
 
 
 
 
 
 
413947b
299d1d7
 
413947b
 
 
 
ff746e3
 
 
413947b
 
 
 
 
48f60d7
413947b
 
 
075133b
 
 
 
 
 
413947b
 
 
ff746e3
413947b
48f60d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
299d1d7
 
 
 
 
 
740fcec
 
299d1d7
 
 
 
 
 
 
 
740fcec
 
299d1d7
 
 
 
 
 
 
 
 
80df99b
299d1d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
740fcec
 
299d1d7
 
 
 
 
80df99b
299d1d7
 
 
 
 
 
 
 
 
 
 
 
 
740fcec
 
 
299d1d7
 
 
 
 
 
 
 
 
 
740fcec
 
299d1d7
 
48f60d7
32bf975
 
 
299d1d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
740fcec
 
299d1d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff746e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
299d1d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
740fcec
 
 
 
 
 
 
 
 
 
 
 
 
80df99b
 
 
7088133
 
 
 
 
 
 
 
 
 
 
 
 
80df99b
78efa34
 
80df99b
 
054ee3f
80df99b
 
740fcec
 
 
 
 
 
48f60d7
 
 
740fcec
 
 
 
 
 
 
78efa34
 
740fcec
78efa34
740fcec
 
 
48f60d7
740fcec
 
 
 
 
 
 
 
 
80df99b
48f60d7
78efa34
 
740fcec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78efa34
 
740fcec
 
 
78efa34
 
 
 
 
 
 
 
740fcec
 
 
 
78efa34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
054ee3f
78efa34
 
 
 
 
 
 
 
 
740fcec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78efa34
 
740fcec
 
 
 
 
 
 
78efa34
 
740fcec
 
 
 
 
 
48f60d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
PostgreSQL (Neon) connection manager and helper utilities.

All database operations run synchronously in a thread pool via
asyncio.to_thread() called from async FastAPI routes / background tasks.
"""

import json
import logging
import math
import os
import asyncio
import threading
from contextlib import contextmanager
from datetime import datetime, timedelta, timezone
from typing import Any, Generator

import psycopg
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool

from config import DATABASE_URL
from database.memory_store import InMemoryDatabaseStore, compute_accuracy_summary_from_rows, memory_store
from database.models import (
    ALL_TABLES,
    CREATE_TRADE_JOURNAL_TABLE,
    CREATE_DAMIAN_MEMORY_TABLE,
    CREATE_JOURNAL_INDEX,
    CREATE_SIGNAL_PREDICTIONS_TABLE,
    CREATE_SIGNAL_PREDICTIONS_PENDING_INDEX,
    CREATE_SIGNAL_PREDICTIONS_EVAL_INDEX,
    CREATE_SIGNAL_PREDICTIONS_SHADOW_INDEX,
    CREATE_HL_WHALE_WALLETS_TABLE,
    CREATE_HL_WHALE_WALLETS_RELIABILITY_INDEX,
    CREATE_MICROSTRUCTURE_TAPE_TABLE,
    CREATE_MICRO_TAPE_SYM_TS_INDEX,
    CREATE_MICRO_TAPE_UNEVAL_INDEX,
)

logger = logging.getLogger(__name__)

_pool: ConnectionPool | None = None
_pool_lock = threading.Lock()
_mem = memory_store
_predictions_table_lock = threading.Lock()


_LEGACY_ALTER_COLUMNS_SQL = """
    ALTER TABLE pairs ADD COLUMN IF NOT EXISTS on_okx BOOLEAN DEFAULT FALSE;
    ALTER TABLE pairs ADD COLUMN IF NOT EXISTS on_bitget BOOLEAN DEFAULT FALSE;
    ALTER TABLE pairs ADD COLUMN IF NOT EXISTS on_hyperliquid BOOLEAN DEFAULT FALSE;
    ALTER TABLE pairs ADD COLUMN IF NOT EXISTS streak_count INTEGER DEFAULT 0;
    ALTER TABLE pairs ADD COLUMN IF NOT EXISTS streak_direction TEXT DEFAULT 'NEUTRAL';
    ALTER TABLE pairs ADD COLUMN IF NOT EXISTS last_conviction INTEGER DEFAULT 0;
    ALTER TABLE trade_journal ADD COLUMN IF NOT EXISTS failure_tag TEXT;
    ALTER TABLE trade_journal ADD COLUMN IF NOT EXISTS exit_price DOUBLE PRECISION;
    ALTER TABLE trade_journal ADD COLUMN IF NOT EXISTS holding_duration_seconds INTEGER;
    ALTER TABLE signal_predictions ADD COLUMN IF NOT EXISTS is_shadow BOOLEAN DEFAULT FALSE;
    ALTER TABLE signal_predictions ADD COLUMN IF NOT EXISTS veto_reason TEXT;
"""


def _sanitize_json_payload(obj: Any) -> Any:
    """Replace non-finite floats (NaN/Inf) with None so PostgreSQL JSONB never fails on NaN."""
    if isinstance(obj, float):
        return obj if math.isfinite(obj) else None
    if isinstance(obj, dict):
        return {k: _sanitize_json_payload(v) for k, v in obj.items()}
    if isinstance(obj, (list, tuple)):
        return [_sanitize_json_payload(v) for v in obj]
    return obj


def _safe_json_dumps(obj: Any) -> str:
    return json.dumps(_sanitize_json_payload(obj), allow_nan=False)


def get_pool() -> ConnectionPool:
    global _pool
    if not DATABASE_URL:
        raise RuntimeError("DATABASE_URL is not configured.")
    if _pool is None:
        with _pool_lock:
            if _pool is None:
                max_pool = max(1, int(os.getenv("DB_POOL_MAX_SIZE", "4") or "4"))
                _pool = ConnectionPool(
                    conninfo=DATABASE_URL,
                    min_size=1,
                    max_size=max_pool,
                    timeout=15.0,
                    kwargs={"row_factory": dict_row, "prepare_threshold": None},
                )
    return _pool


@contextmanager
def get_connection() -> Generator[psycopg.Connection, None, None]:
    """Yield a connection from the pool; commit or roll back on exit."""
    if not DATABASE_URL:
        raise RuntimeError("DATABASE_URL is not configured.")
    pool = get_pool()
    with pool.connection() as conn:
        try:
            yield conn
            conn.commit()
        except Exception:
            conn.rollback()
            raise


def _format_row(row: dict | None) -> dict | None:
    if not row:
        return None
    d = dict(row)
    for k, v in d.items():
        if hasattr(v, "isoformat"):
            d[k] = v.isoformat()
    if "signal_data" in d and isinstance(d["signal_data"], str):
        try:
            d["signal_data"] = json.loads(d["signal_data"])
        except Exception:
            pass
    if "snapshot_data" in d and isinstance(d["snapshot_data"], str):
        try:
            d["snapshot_data"] = json.loads(d["snapshot_data"])
        except Exception:
            pass
    if isinstance(d.get("signal_data"), dict):
        if "streak" not in d["signal_data"] or d["signal_data"].get("streak") is None:
            d["signal_data"]["streak"] = int(d.get("streak_count") or 0)
        if "streak_direction" not in d["signal_data"] or not d["signal_data"].get("streak_direction"):
            d["signal_data"]["streak_direction"] = str(d.get("streak_direction") or "NEUTRAL")
    for bool_col in ("on_binance", "on_bybit", "on_okx", "on_bitget", "on_hyperliquid", "is_active"):
        if bool_col in d and d[bool_col] is not None:
            d[bool_col] = bool(d[bool_col])
    if "streak_count" in d and d["streak_count"] is not None:
        d["streak_count"] = int(d["streak_count"])
    if "last_conviction" in d and d["last_conviction"] is not None:
        d["last_conviction"] = int(d["last_conviction"])
    if "streak_direction" in d and d["streak_direction"] is not None:
        d["streak_direction"] = str(d["streak_direction"])
    return d


def init_db() -> None:
    """Create all tables in Neon PostgreSQL if they do not exist yet, and run schema migrations.
    Protected by PostgreSQL advisory lock and schema existence check to prevent concurrent DDL deadlocks.
    """
    if not DATABASE_URL:
        logger.info("DATABASE_URL not set; skipping database initialization (running in stateless mode).")
        return
    try:
        with get_connection() as conn:
            with conn.cursor() as cur:
                # 1. Quick check: if 'pairs' table already exists, ensure trade_journal & damian_memory exist
                cur.execute("SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'pairs';")
                if cur.fetchone():
                    # Ensure trade_journal and damian_memory tables exist
                    cur.execute("SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'trade_journal';")
                    if not cur.fetchone():
                        cur.execute(CREATE_TRADE_JOURNAL_TABLE)
                        cur.execute(CREATE_DAMIAN_MEMORY_TABLE)
                        cur.execute(CREATE_JOURNAL_INDEX)
                        conn.commit()
                        logger.info("Created trade_journal and damian_memory tables.")
                    cur.execute(CREATE_SIGNAL_PREDICTIONS_TABLE)
                    conn.commit()
                    # Run legacy ALTER ADD COLUMN statements BEFORE creating new column indexes (e.g. is_shadow)
                    try:
                        cur.execute(_LEGACY_ALTER_COLUMNS_SQL)
                        conn.commit()
                    except Exception as e:
                        conn.rollback()
                        logger.warning("Postgres schema add column to existing tables note: %s", e)
                    cur.execute(CREATE_SIGNAL_PREDICTIONS_PENDING_INDEX)
                    cur.execute(CREATE_SIGNAL_PREDICTIONS_EVAL_INDEX)
                    cur.execute(CREATE_SIGNAL_PREDICTIONS_SHADOW_INDEX)
                    cur.execute(CREATE_HL_WHALE_WALLETS_TABLE)
                    cur.execute(CREATE_HL_WHALE_WALLETS_RELIABILITY_INDEX)
                    cur.execute(CREATE_MICROSTRUCTURE_TAPE_TABLE)
                    cur.execute(CREATE_MICRO_TAPE_SYM_TS_INDEX)
                    cur.execute(CREATE_MICRO_TAPE_UNEVAL_INDEX)
                    cur.execute("CREATE INDEX IF NOT EXISTS idx_signals_symbol_created ON signals (symbol, created_at DESC);")
                    cur.execute("CREATE INDEX IF NOT EXISTS idx_pairs_active ON pairs (is_active);")
                    conn.commit()
                    global _predictions_table_ensured
                    _predictions_table_ensured = True
                    return

                # 2. Schema does not exist: acquire advisory lock so only 1 worker creates tables
                cur.execute("SELECT pg_try_advisory_lock(72817001) AS got_lock;")
                lock_row = cur.fetchone() or {}
                got_lock = bool(lock_row.get("got_lock", False)) if isinstance(lock_row, dict) else bool(lock_row[0])
                if not got_lock:
                    logger.info("Another worker is currently initializing the database. Skipping.")
                    return

                try:
                    cur.execute("SET LOCAL lock_timeout = '5s';")
                    for ddl in ALL_TABLES:
                        cur.execute(ddl)
                    conn.commit()
                    try:
                        cur.execute(_LEGACY_ALTER_COLUMNS_SQL)
                        conn.commit()
                    except Exception as e:
                        conn.rollback()
                        logger.warning("Postgres schema add column note: %s", e)
                    try:
                        cur.execute("""
                            DO $$
                            BEGIN
                                IF EXISTS (
                                    SELECT 1 FROM information_schema.columns 
                                    WHERE table_name = 'pairs' AND column_name = 'is_active' AND data_type = 'integer'
                                ) THEN
                                    ALTER TABLE pairs ALTER COLUMN on_binance DROP DEFAULT;
                                    ALTER TABLE pairs ALTER COLUMN on_bybit DROP DEFAULT;
                                    ALTER TABLE pairs ALTER COLUMN is_active DROP DEFAULT;

                                    ALTER TABLE pairs ALTER COLUMN on_binance TYPE BOOLEAN USING (on_binance != 0);
                                    ALTER TABLE pairs ALTER COLUMN on_bybit TYPE BOOLEAN USING (on_bybit != 0);
                                    ALTER TABLE pairs ALTER COLUMN is_active TYPE BOOLEAN USING (is_active != 0);

                                    ALTER TABLE pairs ALTER COLUMN on_binance SET DEFAULT FALSE;
                                    ALTER TABLE pairs ALTER COLUMN on_bybit SET DEFAULT FALSE;
                                    ALTER TABLE pairs ALTER COLUMN is_active SET DEFAULT TRUE;
                                END IF;
                            END $$;
                        """)
                        conn.commit()
                    except Exception as e:
                        conn.rollback()
                        logger.warning("Postgres schema migration note: %s", e)
                    logger.info("Neon PostgreSQL database initialized successfully.")
                finally:
                    try:
                        conn.rollback()
                        cur.execute("SELECT pg_advisory_unlock(72817001);")
                        conn.commit()
                    except Exception:
                        pass
    except Exception as exc:
        # Non-fatal: never crash serverless cold starts due to DDL race condition
        logger.warning("init_db non-fatal notice (schema already created or lock skipped): %s", exc)


# ---------------------------------------------------------------------------
# Pairs helpers
# ---------------------------------------------------------------------------

def db_get_all_pairs() -> list[dict]:
    if not DATABASE_URL:
        return _mem.get_all_pairs()
    with get_connection() as conn:
        with conn.cursor() as cur:
            cur.execute("SELECT * FROM pairs ORDER BY created_at DESC")
            rows = cur.fetchall()
            return [_format_row(r) for r in rows]


def db_get_pair(symbol: str) -> dict | None:
    sym = symbol.upper().strip()
    if not DATABASE_URL:
        return _mem.get_pair(sym)
    with get_connection() as conn:
        with conn.cursor() as cur:
            cur.execute("SELECT * FROM pairs WHERE symbol = %s", (sym,))
            row = cur.fetchone()
            return _format_row(row)


def db_insert_pair(
    symbol: str,
    display_name: str,
    on_binance: bool = False,
    on_bybit: bool = False,
    on_okx: bool = False,
    on_bitget: bool = False,
    on_hyperliquid: bool = False,
) -> dict:
    sym = symbol.upper().strip()
    if not DATABASE_URL:
        return _mem.insert_pair(sym, display_name, on_binance, on_bybit, on_okx, on_bitget, on_hyperliquid)
    with get_connection() as conn:
        with conn.cursor() as cur:
            cur.execute(
                """INSERT INTO pairs (symbol, display_name, on_binance, on_bybit, on_okx, on_bitget, on_hyperliquid, is_active)
                   VALUES (%s, %s, %s, %s, %s, %s, %s, TRUE)
                   ON CONFLICT (symbol) DO UPDATE SET
                       display_name   = EXCLUDED.display_name,
                       on_binance     = EXCLUDED.on_binance,
                       on_bybit       = EXCLUDED.on_bybit,
                       on_okx         = EXCLUDED.on_okx,
                       on_bitget      = EXCLUDED.on_bitget,
                       on_hyperliquid = EXCLUDED.on_hyperliquid,
                       is_active      = TRUE
                   RETURNING *""",
                (sym, display_name, bool(on_binance), bool(on_bybit), bool(on_okx), bool(on_bitget), bool(on_hyperliquid)),
            )
            row = cur.fetchone()
            return _format_row(row)


def db_update_pair_exchanges(
    symbol: str,
    on_binance: bool,
    on_bybit: bool,
    on_okx: bool = False,
    on_bitget: bool = False,
    on_hyperliquid: bool = False,
) -> dict | None:
    sym = symbol.upper().strip()
    if not DATABASE_URL:
        return _mem.update_pair_exchanges(sym, on_binance, on_bybit, on_okx, on_bitget, on_hyperliquid)
    with get_connection() as conn:
        with conn.cursor() as cur:
            cur.execute(
                """UPDATE pairs
                   SET on_binance = %s, on_bybit = %s, on_okx = %s, on_bitget = %s, on_hyperliquid = %s
                   WHERE symbol = %s
                   RETURNING *""",
                (bool(on_binance), bool(on_bybit), bool(on_okx), bool(on_bitget), bool(on_hyperliquid), sym),
            )
            row = cur.fetchone()
            return _format_row(row)


def db_update_pair_streak(
    symbol: str,
    streak_count: int,
    streak_direction: str,
    last_conviction: int,
) -> dict | None:
    sym = symbol.upper().strip()
    if not DATABASE_URL:
        return _mem.update_pair_streak(sym, streak_count, streak_direction, last_conviction)
    with get_connection() as conn:
        with conn.cursor() as cur:
            cur.execute(
                """UPDATE pairs
                   SET streak_count = %s, streak_direction = %s, last_conviction = %s
                   WHERE symbol = %s
                   RETURNING *""",
                (int(streak_count), str(streak_direction), int(last_conviction), sym),
            )
            row = cur.fetchone()
            return _format_row(row)


def db_delete_pair(symbol: str) -> bool:
    sym = symbol.upper().strip()
    if not DATABASE_URL:
        return _mem.delete_pair(sym)
    with get_connection() as conn:
        with conn.cursor() as cur:
            cur.execute("DELETE FROM pairs WHERE symbol = %s", (sym,))
            return cur.rowcount > 0


def db_delete_pair_by_identifier(identifier: str) -> bool:
    ident = identifier.strip()
    if not DATABASE_URL:
        return _mem.delete_pair_by_identifier(ident)
    with get_connection() as conn:
        with conn.cursor() as cur:
            if ident.isdigit():
                cur.execute("DELETE FROM pairs WHERE id = %s", (int(ident),))
            else:
                cur.execute("DELETE FROM pairs WHERE symbol = %s", (ident.upper(),))
            return cur.rowcount > 0


def db_toggle_pair(symbol: str) -> dict | None:
    sym = symbol.upper().strip()
    if not DATABASE_URL:
        return _mem.toggle_pair(sym)
    with get_connection() as conn:
        with conn.cursor() as cur:
            cur.execute(
                """UPDATE pairs
                   SET is_active = NOT is_active
                   WHERE symbol = %s
                   RETURNING *""",
                (sym,),
            )
            row = cur.fetchone()
            return _format_row(row)


def db_toggle_pair_by_identifier(identifier: str) -> dict | None:
    ident = identifier.strip()
    if not DATABASE_URL:
        return _mem.toggle_pair_by_identifier(ident)
    with get_connection() as conn:
        with conn.cursor() as cur:
            if ident.isdigit():
                cur.execute(
                    """UPDATE pairs
                       SET is_active = NOT is_active
                       WHERE id = %s
                       RETURNING *""",
                    (int(ident),),
                )
            else:
                cur.execute(
                    """UPDATE pairs
                       SET is_active = NOT is_active
                       WHERE symbol = %s
                       RETURNING *""",
                    (ident.upper(),),
                )
            row = cur.fetchone()
            return _format_row(row)


def db_get_active_pairs() -> list[dict]:
    if not DATABASE_URL:
        return _mem.get_active_pairs()
    with get_connection() as conn:
        with conn.cursor() as cur:
            cur.execute("SELECT * FROM pairs WHERE is_active = TRUE ORDER BY symbol")
            rows = cur.fetchall()
            return [_format_row(r) for r in rows]


def db_get_stale_active_pairs(limit: int | None = None) -> list[dict]:
    """
    Get active pairs sorted by least-recently-computed signal first (starvation-free round-robin).
    Pairs with no signal or oldest created_at are returned first to ensure all pairs refresh equally.
    """
    if not DATABASE_URL:
        return _mem.get_stale_active_pairs(limit=limit)
    with get_connection() as conn:
        with conn.cursor() as cur:
            query = """
                SELECT p.*
                FROM pairs p
                LEFT JOIN (
                    SELECT symbol, MAX(created_at) as last_signal_time
                    FROM signals
                    GROUP BY symbol
                ) s ON s.symbol = p.symbol
                WHERE p.is_active = TRUE
                ORDER BY s.last_signal_time ASC NULLS FIRST, p.symbol ASC
            """
            if limit:
                query += " LIMIT %s"
                cur.execute(query, (limit,))
            else:
                cur.execute(query)
            rows = cur.fetchall()
            return [_format_row(r) for r in rows]


# ---------------------------------------------------------------------------
# Signal helpers
# ---------------------------------------------------------------------------

def db_save_signal(symbol: str, timeframe: str, direction: str, conviction: int, signal_data: dict) -> None:
    sym = symbol.upper().strip()
    clean_signal_data = signal_data
    if isinstance(signal_data, dict) and "_shadow_trade_levels" in signal_data:
        clean_signal_data = dict(signal_data)
        clean_signal_data.pop("_shadow_trade_levels", None)
    if not DATABASE_URL:
        _mem.save_signal(sym, timeframe, direction, conviction, clean_signal_data)
        return
    with get_connection() as conn:
        with conn.cursor() as cur:
            cur.execute(
                """INSERT INTO signals (symbol, timeframe, direction, conviction, signal_data)
                   VALUES (%s, %s, %s, %s, %s)""",
                (sym, timeframe, direction, conviction, _safe_json_dumps(clean_signal_data)),
            )


def db_get_latest_signals() -> list[dict]:
    """Latest signal per pair using Postgres DISTINCT ON (symbol)."""
    if not DATABASE_URL:
        return _mem.get_latest_signals()
    with get_connection() as conn:
        with conn.cursor() as cur:
            cur.execute(
                """SELECT DISTINCT ON (s.symbol) 
                       s.*, 
                       p.streak_count, 
                       p.streak_direction, 
                       p.last_conviction
                   FROM signals s
                   LEFT JOIN pairs p ON p.symbol = s.symbol
                   ORDER BY s.symbol, s.id DESC"""
            )
            rows = cur.fetchall()
            return [_format_row(r) for r in rows]


def db_get_signal_history(symbol: str, limit: int = 50) -> list[dict]:
    sym = symbol.upper().strip()
    if not DATABASE_URL:
        return _mem.get_signal_history(sym, limit=limit)
    with get_connection() as conn:
        with conn.cursor() as cur:
            cur.execute(
                "SELECT * FROM signals WHERE symbol = %s ORDER BY created_at DESC LIMIT %s",
                (sym, limit),
            )
            rows = cur.fetchall()
            return [_format_row(r) for r in rows]


def db_get_latest_signal(symbol: str) -> dict | None:
    sym = symbol.upper().strip()
    if not DATABASE_URL:
        return _mem.get_latest_signal(sym)
    with get_connection() as conn:
        with conn.cursor() as cur:
            cur.execute(
                """SELECT s.*, p.streak_count, p.streak_direction, p.last_conviction
                   FROM signals s
                   LEFT JOIN pairs p ON p.symbol = s.symbol
                   WHERE s.symbol = %s ORDER BY s.id DESC LIMIT 1""",
                (sym,),
            )
            row = cur.fetchone()
            return _format_row(row)


# ---------------------------------------------------------------------------
# Market snapshot helpers
# ---------------------------------------------------------------------------

def db_save_snapshot(
    symbol: str,
    exchange: str,
    funding_rate: float | None,
    open_interest: float | None,
    long_ratio: float | None,
    short_ratio: float | None,
    mark_price: float | None,
    index_price: float | None,
    basis_pct: float | None,
) -> None:
    sym = symbol.upper().strip()
    ex = exchange.lower().strip()
    if not DATABASE_URL:
        _mem.save_snapshot(
            sym, ex, funding_rate, open_interest,
            long_ratio, short_ratio, mark_price, index_price, basis_pct,
        )
        return
    with get_connection() as conn:
        with conn.cursor() as cur:
            cur.execute(
                """INSERT INTO market_snapshots
                   (symbol, exchange, funding_rate, open_interest, long_ratio,
                    short_ratio, mark_price, index_price, basis_pct)
                   VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)""",
                (sym, ex, funding_rate, open_interest, long_ratio,
                 short_ratio, mark_price, index_price, basis_pct),
            )


def db_save_snapshots_batch(snapshots: list[tuple]) -> None:
    """Save multiple exchange market snapshots in a single high-efficiency DB roundtrip."""
    if not snapshots:
        return
    norm_snapshots = [
        (str(s[0]).upper().strip(), str(s[1]).lower().strip(), *s[2:])
        for s in snapshots
    ]
    if not DATABASE_URL:
        _mem.save_snapshots_batch(norm_snapshots)
        return
    with get_connection() as conn:
        with conn.cursor() as cur:
            cur.executemany(
                """INSERT INTO market_snapshots
                   (symbol, exchange, funding_rate, open_interest, long_ratio,
                    short_ratio, mark_price, index_price, basis_pct)
                   VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)""",
                norm_snapshots,
            )


def db_get_latest_snapshot(symbol: str) -> list[dict]:
    """Return latest snapshot per exchange using Postgres DISTINCT ON (exchange)."""
    sym = symbol.upper().strip()
    if not DATABASE_URL:
        return _mem.get_latest_snapshot(sym)
    with get_connection() as conn:
        with conn.cursor() as cur:
            cur.execute(
                """SELECT DISTINCT ON (exchange) *
                   FROM market_snapshots
                   WHERE symbol = %s
                   ORDER BY exchange, id DESC""",
                (sym,),
            )
            rows = cur.fetchall()
            return [_format_row(r) for r in rows]


# ---------------------------------------------------------------------------
# Async wrappers (run blocking DB calls in thread pool)
# ---------------------------------------------------------------------------

async def async_get_all_pairs() -> list[dict]:
    return await asyncio.to_thread(db_get_all_pairs)

async def async_get_pair(symbol: str) -> dict | None:
    return await asyncio.to_thread(db_get_pair, symbol)

async def async_insert_pair(
    symbol: str,
    display_name: str,
    on_binance: bool = False,
    on_bybit: bool = False,
    on_okx: bool = False,
    on_bitget: bool = False,
    on_hyperliquid: bool = False,
) -> dict:
    return await asyncio.to_thread(
        db_insert_pair, symbol, display_name, on_binance, on_bybit, on_okx, on_bitget, on_hyperliquid
    )

async def async_update_pair_exchanges(
    symbol: str,
    on_binance: bool,
    on_bybit: bool,
    on_okx: bool = False,
    on_bitget: bool = False,
    on_hyperliquid: bool = False,
) -> dict | None:
    return await asyncio.to_thread(
        db_update_pair_exchanges, symbol, on_binance, on_bybit, on_okx, on_bitget, on_hyperliquid
    )

async def async_update_pair_streak(
    symbol: str,
    streak_count: int,
    streak_direction: str,
    last_conviction: int,
) -> dict | None:
    return await asyncio.to_thread(
        db_update_pair_streak, symbol, streak_count, streak_direction, last_conviction
    )

async def async_delete_pair(symbol: str) -> bool:
    return await asyncio.to_thread(db_delete_pair, symbol)

async def async_delete_pair_by_identifier(identifier: str) -> bool:
    return await asyncio.to_thread(db_delete_pair_by_identifier, identifier)

async def async_toggle_pair(symbol: str) -> dict | None:
    return await asyncio.to_thread(db_toggle_pair, symbol)

async def async_toggle_pair_by_identifier(identifier: str) -> dict | None:
    return await asyncio.to_thread(db_toggle_pair_by_identifier, identifier)

async def async_get_active_pairs() -> list[dict]:
    return await asyncio.to_thread(db_get_active_pairs)

async def async_get_stale_active_pairs(limit: int | None = None) -> list[dict]:
    return await asyncio.to_thread(db_get_stale_active_pairs, limit)

async def async_save_signal(symbol, timeframe, direction, conviction, signal_data) -> None:
    return await asyncio.to_thread(db_save_signal, symbol, timeframe, direction, conviction, signal_data)

async def async_get_latest_signals() -> list[dict]:
    return await asyncio.to_thread(db_get_latest_signals)

async def async_get_signal_history(symbol: str, limit: int = 50) -> list[dict]:
    return await asyncio.to_thread(db_get_signal_history, symbol, limit)

async def async_get_latest_signal(symbol: str) -> dict | None:
    return await asyncio.to_thread(db_get_latest_signal, symbol)

async def async_save_snapshot(symbol, exchange, funding_rate, open_interest,
                               long_ratio, short_ratio, mark_price, index_price, basis_pct) -> None:
    return await asyncio.to_thread(
        db_save_snapshot, symbol, exchange, funding_rate, open_interest,
        long_ratio, short_ratio, mark_price, index_price, basis_pct,
    )

async def async_save_snapshots_batch(snapshots: list[tuple]) -> None:
    return await asyncio.to_thread(db_save_snapshots_batch, snapshots)

async def async_get_latest_snapshot(symbol: str) -> list[dict]:
    return await asyncio.to_thread(db_get_latest_snapshot, symbol)


# ---------------------------------------------------------------------------
# Retention Pruning
# ---------------------------------------------------------------------------

def db_prune_old_records(
    retention_hours_snapshots: int = 2,
    retention_days_signals: int = 2,
    retention_days_predictions: int = 30,
    retention_days_tape: int = 14,
) -> dict[str, int]:
    """
    Prune old market_snapshots, signals, evaluated signal_predictions, and microstructure_tape to prevent database bloat on Neon free tier.
    Default: snapshots older than 2h, signals older than 2 days, evaluated predictions older than 30 days, tape older than 14 days.
    """
    pruned = {"snapshots": 0, "signals": 0, "predictions": 0, "microstructure_tape": 0}
    if not DATABASE_URL:
        return _mem.prune_old_records(
            retention_hours_snapshots=retention_hours_snapshots,
            retention_days_signals=retention_days_signals,
            retention_days_predictions=retention_days_predictions,
            retention_days_tape=retention_days_tape,
        )
    try:
        with get_connection() as conn:
            with conn.cursor() as cur:
                cur.execute(
                    "DELETE FROM market_snapshots WHERE snapshot_at < NOW() - (%s * INTERVAL '1 hour')",
                    (retention_hours_snapshots,),
                )
                pruned["snapshots"] = cur.rowcount

                cur.execute(
                    "DELETE FROM signals WHERE created_at < NOW() - (%s * INTERVAL '1 day')",
                    (retention_days_signals,),
                )
                pruned["signals"] = cur.rowcount

                cur.execute(
                    "DELETE FROM signal_predictions WHERE outcome != 'PENDING' AND created_at < NOW() - (%s * INTERVAL '1 day')",
                    (retention_days_predictions,),
                )
                pruned["predictions"] = cur.rowcount

                cur.execute(
                    "DELETE FROM microstructure_tape WHERE recorded_at < NOW() - (%s * INTERVAL '1 day')",
                    (retention_days_tape,),
                )
                pruned["microstructure_tape"] = cur.rowcount

                # Prune stale non-SMART_WHALE wallets inactive > 14 days and cap table at top 250 wallets
                cur.execute(
                    """
                    DELETE FROM hl_whale_wallets
                    WHERE COALESCE(tier, 'UNPROVEN') != 'SMART_WHALE'
                      AND updated_at < NOW() - (%s * INTERVAL '1 day');
                    """,
                    (retention_days_tape,),
                )
                pruned_wallets = cur.rowcount
                cur.execute(
                    """
                    DELETE FROM hl_whale_wallets
                    WHERE address IN (
                        SELECT address FROM hl_whale_wallets
                        ORDER BY (CASE WHEN tier = 'SMART_WHALE' THEN 1 ELSE 0 END) DESC,
                                 reliability_score DESC,
                                 account_value_usd DESC,
                                 updated_at DESC
                        OFFSET 250
                    );
                    """
                )
                pruned["hl_whale_wallets"] = pruned_wallets + cur.rowcount
        if pruned["snapshots"] > 0 or pruned["signals"] > 0 or pruned["predictions"] > 0 or pruned["microstructure_tape"] > 0:
            logger.info(
                "[DB Retention] Pruned %d snapshots, %d signals, %d predictions, and %d tape records.",
                pruned["snapshots"],
                pruned["signals"],
                pruned["predictions"],
                pruned["microstructure_tape"],
            )
    except Exception as exc:
        logger.warning("[DB Retention] Pruning failed: %s", exc)
    return pruned


async def async_prune_old_records(
    retention_hours_snapshots: int = 2,
    retention_days_signals: int = 2,
    retention_days_predictions: int = 30,
    retention_days_tape: int = 14,
) -> dict[str, int]:
    return await asyncio.to_thread(
        db_prune_old_records,
        retention_hours_snapshots,
        retention_days_signals,
        retention_days_predictions,
        retention_days_tape,
    )


# ---------------------------------------------------------------------------
# Trade Journal & Damian Memory
# ---------------------------------------------------------------------------

def db_create_journal_entry(data: dict) -> dict:
    """Insert a new trade record into trade_journal."""
    if not DATABASE_URL:
        return _mem.create_journal_entry(data)
    snapshot_json = _safe_json_dumps(data.get("snapshot_data") or {})
    sym = str(data.get("symbol") or "").upper().strip()
    bias = str(data.get("bias") or "ANALYZED")
    status = str(data.get("status") or "PENDING").upper().strip()
    query = """
    INSERT INTO trade_journal (
        symbol, bias, entry_zone, stop_loss, take_profit, risk_reward,
        leverage, invalidation, summary_tldr, full_analysis, model_used,
        status, outcome_note, failure_tag, exit_price, holding_duration_seconds,
        snapshot_data
    ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
    RETURNING *;
    """
    with get_connection() as conn:
        with conn.cursor() as cur:
            cur.execute(
                query,
                (
                    sym,
                    bias,
                    data.get("entry_zone"),
                    data.get("stop_loss"),
                    data.get("take_profit"),
                    data.get("risk_reward"),
                    data.get("leverage"),
                    data.get("invalidation"),
                    data.get("summary_tldr"),
                    data.get("full_analysis"),
                    data.get("model_used"),
                    status,
                    data.get("outcome_note"),
                    data.get("failure_tag"),
                    data.get("exit_price"),
                    data.get("holding_duration_seconds"),
                    snapshot_json,
                ),
            )
            row = cur.fetchone()
            return _format_row(row) or {}


def db_get_journal_entries(status: str | None = None, limit: int = 50, offset: int = 0) -> list[dict]:
    """Fetch trade journal entries with optional status filter."""
    if not DATABASE_URL:
        return _mem.get_journal_entries(status=status, limit=limit, offset=offset)
    with get_connection() as conn:
        with conn.cursor() as cur:
            if status and status.upper() != "ALL":
                cur.execute(
                    "SELECT * FROM trade_journal WHERE status = %s ORDER BY created_at DESC LIMIT %s OFFSET %s;",
                    (status.upper(), limit, offset),
                )
            else:
                cur.execute(
                    "SELECT * FROM trade_journal ORDER BY created_at DESC LIMIT %s OFFSET %s;",
                    (limit, offset),
                )
            rows = cur.fetchall()
            return [_format_row(r) for r in rows if r]


def db_update_journal_status(
    journal_id: int,
    status: str,
    note: str | None = None,
    failure_tag: str | None = None,
    exit_price: float | None = None,
    holding_duration_seconds: int | None = None,
) -> dict | None:
    """Update trade outcome status (HIT_TP, HIT_SL, CANCELLED, PENDING) with rich post-mortem metadata."""
    if not DATABASE_URL:
        return _mem.update_journal_status(
            journal_id=journal_id,
            status=status,
            note=note,
            failure_tag=failure_tag,
            exit_price=exit_price,
            holding_duration_seconds=holding_duration_seconds,
        )
    st = status.upper().strip()
    with get_connection() as conn:
        with conn.cursor() as cur:
            if st == "PENDING":
                cur.execute(
                    """
                    UPDATE trade_journal
                    SET status = 'PENDING', outcome_note = NULL, outcome_at = NULL,
                        failure_tag = NULL, exit_price = NULL, holding_duration_seconds = NULL,
                        audited = FALSE
                    WHERE id = %s
                    RETURNING *;
                    """,
                    (journal_id,),
                )
            elif st == "HIT_SL":
                cur.execute(
                    """
                    UPDATE trade_journal
                    SET status = %s,
                        outcome_note = %s,
                        outcome_at = NOW(),
                        failure_tag = COALESCE(%s, failure_tag),
                        exit_price = COALESCE(%s, exit_price),
                        holding_duration_seconds = COALESCE(%s, holding_duration_seconds)
                    WHERE id = %s
                    RETURNING *;
                    """,
                    (st, note, failure_tag, exit_price, holding_duration_seconds, journal_id),
                )
            else:
                cur.execute(
                    """
                    UPDATE trade_journal
                    SET status = %s,
                        outcome_note = %s,
                        outcome_at = NOW(),
                        failure_tag = NULL,
                        audited = FALSE,
                        exit_price = COALESCE(%s, exit_price),
                        holding_duration_seconds = COALESCE(%s, holding_duration_seconds)
                    WHERE id = %s
                    RETURNING *;
                    """,
                    (st, note, exit_price, holding_duration_seconds, journal_id),
                )
            row = cur.fetchone()
            return _format_row(row)


def db_delete_journal_entry(journal_id: int) -> bool:
    """Delete a trade journal entry."""
    if not DATABASE_URL:
        return _mem.delete_journal_entry(journal_id)
    with get_connection() as conn:
        with conn.cursor() as cur:
            cur.execute("DELETE FROM trade_journal WHERE id = %s;", (journal_id,))
            return cur.rowcount > 0


def db_get_journal_stats() -> dict:
    """Calculate Win Rate, total counts, and unaudited SL count."""
    if not DATABASE_URL:
        return _mem.get_journal_stats()
    with get_connection() as conn:
        with conn.cursor() as cur:
            cur.execute("""
                SELECT
                    COUNT(*) as total,
                    COUNT(*) FILTER (WHERE status = 'HIT_TP') as hit_tp,
                    COUNT(*) FILTER (WHERE status = 'HIT_SL') as hit_sl,
                    COUNT(*) FILTER (WHERE status = 'PENDING') as pending,
                    COUNT(*) FILTER (WHERE status = 'CANCELLED') as cancelled,
                    COUNT(*) FILTER (WHERE status = 'HIT_SL' AND COALESCE(audited, FALSE) = FALSE) as unaudited_sl
                FROM trade_journal;
            """)
            row = cur.fetchone() or {}
            total = int(row.get("total") or 0)
            hit_tp = int(row.get("hit_tp") or 0)
            hit_sl = int(row.get("hit_sl") or 0)
            pending = int(row.get("pending") or 0)
            cancelled = int(row.get("cancelled") or 0)
            unaudited_sl = int(row.get("unaudited_sl") or 0)

            completed = hit_tp + hit_sl
            win_rate = round((hit_tp / completed * 100), 1) if completed > 0 else 0.0

            return {
                "total": total,
                "hit_tp": hit_tp,
                "hit_sl": hit_sl,
                "pending": pending,
                "cancelled": cancelled,
                "completed": completed,
                "win_rate_pct": win_rate,
                "unaudited_sl_count": unaudited_sl,
            }


def db_get_unaudited_failed_trades(limit: int = 10) -> list[dict]:
    """Retrieve up to 10 unaudited HIT_SL trades for Damian audit synthesis."""
    if not DATABASE_URL:
        return _mem.get_unaudited_failed_trades(limit=limit)
    with get_connection() as conn:
        with conn.cursor() as cur:
            cur.execute(
                """
                SELECT * FROM trade_journal
                WHERE status = 'HIT_SL' AND COALESCE(audited, FALSE) = FALSE
                ORDER BY created_at ASC
                LIMIT %s;
                """,
                (limit,),
            )
            rows = cur.fetchall()
            return [_format_row(r) for r in rows if r]


def db_mark_trades_as_audited(trade_ids: list[int]) -> None:
    """Mark failed trades as audited."""
    if not trade_ids:
        return
    if not DATABASE_URL:
        _mem.mark_trades_as_audited(trade_ids)
        return
    with get_connection() as conn:
        with conn.cursor() as cur:
            cur.execute(
                "UPDATE trade_journal SET audited = TRUE WHERE id = ANY(%s);",
                (trade_ids,),
            )


def db_save_damian_memory(audit_summary: str, model_used: str, failed_count: int = 10) -> dict:
    """Save synthesized lessons and golden rules into damian_memory."""
    if not DATABASE_URL:
        return _mem.save_damian_memory(audit_summary=audit_summary, model_used=model_used, failed_count=failed_count)
    with get_connection() as conn:
        with conn.cursor() as cur:
            cur.execute("SELECT pg_advisory_xact_lock(72817002);")
            cur.execute("SELECT COALESCE(MAX(batch_index), 0) + 1 AS next_batch FROM damian_memory;")
            batch_row = cur.fetchone() or {}
            next_batch = int(batch_row.get("next_batch", 1)) if isinstance(batch_row, dict) else int(batch_row[0])

            cur.execute(
                """
                INSERT INTO damian_memory (batch_index, failed_count, model_used, audit_summary, is_active)
                VALUES (%s, %s, %s, %s, TRUE)
                RETURNING *;
                """,
                (next_batch, failed_count, model_used, audit_summary),
            )
            row = cur.fetchone()
            return _format_row(row) or {}


def db_get_active_damian_memory(limit: int = 3) -> list[dict]:
    """Retrieve active Damian memory audit summaries."""
    if not DATABASE_URL:
        return _mem.get_active_damian_memory(limit=limit)
    with get_connection() as conn:
        with conn.cursor() as cur:
            cur.execute(
                "SELECT * FROM damian_memory WHERE is_active = TRUE ORDER BY created_at DESC LIMIT %s;",
                (limit,),
            )
            rows = cur.fetchall()
            return [_format_row(r) for r in rows if r]


async def async_create_journal_entry(data: dict) -> dict:
    return await asyncio.to_thread(db_create_journal_entry, data)

async def async_get_journal_entries(status: str | None = None, limit: int = 50, offset: int = 0) -> list[dict]:
    return await asyncio.to_thread(db_get_journal_entries, status, limit, offset)

async def async_update_journal_status(
    journal_id: int,
    status: str,
    note: str | None = None,
    failure_tag: str | None = None,
    exit_price: float | None = None,
    holding_duration_seconds: int | None = None,
) -> dict | None:
    return await asyncio.to_thread(
        db_update_journal_status,
        journal_id,
        status,
        note,
        failure_tag,
        exit_price,
        holding_duration_seconds,
    )

async def async_delete_journal_entry(journal_id: int) -> bool:
    return await asyncio.to_thread(db_delete_journal_entry, journal_id)

async def async_get_journal_stats() -> dict:
    return await asyncio.to_thread(db_get_journal_stats)

async def async_get_unaudited_failed_trades(limit: int = 10) -> list[dict]:
    return await asyncio.to_thread(db_get_unaudited_failed_trades, limit)

async def async_mark_trades_as_audited(trade_ids: list[int]) -> None:
    return await asyncio.to_thread(db_mark_trades_as_audited, trade_ids)

async def async_save_damian_memory(audit_summary: str, model_used: str, failed_count: int = 10) -> dict:
    return await asyncio.to_thread(db_save_damian_memory, audit_summary, model_used, failed_count)

async def async_get_active_damian_memory(limit: int = 3) -> list[dict]:
    return await asyncio.to_thread(db_get_active_damian_memory, limit)


# ---------------------------------------------------------------------------
# Signal Predictions (Forward Accuracy Tracker)
# ---------------------------------------------------------------------------

_predictions_table_ensured = False


def _ensure_predictions_table(cur: Any, conn: Any) -> None:
    global _predictions_table_ensured
    if _predictions_table_ensured:
        return
    with _predictions_table_lock:
        if _predictions_table_ensured:
            return
        # Fast non-locking catalog check: if signal_predictions.is_shadow already exists, skip DDL completely
        cur.execute(
            """
            SELECT 1 FROM information_schema.columns
            WHERE table_schema = 'public'
              AND table_name = 'signal_predictions'
              AND column_name = 'is_shadow'
            LIMIT 1;
            """
        )
        if cur.fetchone():
            _predictions_table_ensured = True
            return
        cur.execute(CREATE_SIGNAL_PREDICTIONS_TABLE)
        cur.execute("ALTER TABLE signal_predictions ADD COLUMN IF NOT EXISTS is_shadow BOOLEAN DEFAULT FALSE;")
        cur.execute("ALTER TABLE signal_predictions ADD COLUMN IF NOT EXISTS veto_reason TEXT;")
        cur.execute(CREATE_SIGNAL_PREDICTIONS_PENDING_INDEX)
        cur.execute(CREATE_SIGNAL_PREDICTIONS_EVAL_INDEX)
        cur.execute(CREATE_SIGNAL_PREDICTIONS_SHADOW_INDEX)
        conn.commit()
        _predictions_table_ensured = True


def db_insert_signal_prediction(data: dict) -> dict:
    """Insert a new forward signal prediction row."""
    if not DATABASE_URL:
        return _mem.insert_signal_prediction(data)
    default_expires = data.get("expires_at")
    if default_expires is None:
        default_expires = datetime.now(timezone.utc) + timedelta(hours=24)
    with get_connection() as conn:
        with conn.cursor() as cur:
            _ensure_predictions_table(cur, conn)
            cur.execute(
                """
                INSERT INTO signal_predictions (
                    symbol, horizon, direction, conviction, regime, sniper_grade,
                    entry_price, stop_loss, tp1, tp2, factor_scores, outcome, expires_at,
                    is_shadow, veto_reason
                )
                VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s::jsonb, 'PENDING', %s, %s, %s)
                RETURNING *;
                """,
                (
                    str(data.get("symbol", "")).upper().strip(),
                    str(data.get("horizon", "intraday")),
                    str(data.get("direction", "NEUTRAL")),
                    int(data.get("conviction", 0)),
                    str(data.get("regime", "ranging")),
                    str(data.get("sniper_grade", "WAIT")),
                    float(data.get("entry_price", 0.0)),
                    float(data.get("stop_loss", 0.0)),
                    float(data.get("tp1", 0.0)),
                    float(data.get("tp2", 0.0)),
                    _safe_json_dumps(data.get("factor_scores") or {}),
                    default_expires,
                    bool(data.get("is_shadow", False)),
                    data.get("veto_reason"),
                ),
            )
            row = cur.fetchone()
            return _format_row(row) or {}


def db_get_pending_predictions(limit: int = 200) -> list[dict]:
    """Fetch pending predictions ordered by expires_at ASC."""
    if not DATABASE_URL:
        return _mem.get_pending_predictions(limit=limit)
    with get_connection() as conn:
        with conn.cursor() as cur:
            _ensure_predictions_table(cur, conn)
            cur.execute(
                """
                SELECT * FROM signal_predictions
                WHERE outcome = 'PENDING'
                ORDER BY expires_at ASC, id ASC
                LIMIT %s;
                """,
                (limit,),
            )
            rows = cur.fetchall()
            return [_format_row(r) for r in rows if r]


def db_update_signal_prediction_outcome(
    pred_id: int,
    outcome: str,
    outcome_price: float,
    r_multiple: float,
) -> dict | None:
    """Update outcome, outcome_price, r_multiple, and evaluated_at for a prediction."""
    if not DATABASE_URL:
        return _mem.update_signal_prediction_outcome(pred_id, outcome, outcome_price, r_multiple)
    with get_connection() as conn:
        with conn.cursor() as cur:
            _ensure_predictions_table(cur, conn)
            cur.execute(
                """
                UPDATE signal_predictions
                SET outcome = %s,
                    outcome_price = %s,
                    r_multiple = %s,
                    evaluated_at = CURRENT_TIMESTAMP
                WHERE id = %s
                RETURNING *;
                """,
                (outcome, float(outcome_price), float(r_multiple), int(pred_id)),
            )
            row = cur.fetchone()
            return _format_row(row) if row else None


def db_get_recent_prediction(
    symbol: str,
    horizon: str,
    direction: str,
    cooldown_hours: int,
    is_shadow: bool = False,
    veto_reason: str | None = None,
) -> dict | None:
    """Return an active PENDING prediction or a same-direction prediction within cooldown_hours."""
    if not DATABASE_URL:
        return _mem.get_recent_prediction(
            symbol,
            horizon,
            direction,
            cooldown_hours,
            is_shadow=is_shadow,
            veto_reason=veto_reason,
        )
    sym = symbol.upper()
    with get_connection() as conn:
        with conn.cursor() as cur:
            _ensure_predictions_table(cur, conn)
            if not is_shadow:
                cur.execute(
                    """
                    SELECT * FROM signal_predictions
                    WHERE symbol = %s
                      AND horizon = %s
                      AND COALESCE(is_shadow, FALSE) = FALSE
                      AND (
                          outcome = 'PENDING'
                          OR (direction = %s AND created_at >= NOW() - (%s * INTERVAL '1 hour'))
                      )
                    ORDER BY id DESC
                    LIMIT 1;
                    """,
                    (sym, horizon, direction, int(cooldown_hours)),
                )
            else:
                cur.execute(
                    """
                    SELECT * FROM signal_predictions
                    WHERE symbol = %s
                      AND horizon = %s
                      AND is_shadow = TRUE
                      AND veto_reason IS NOT DISTINCT FROM %s
                      AND (
                          outcome = 'PENDING'
                          OR (direction = %s AND created_at >= NOW() - (%s * INTERVAL '1 hour'))
                      )
                    ORDER BY id DESC
                    LIMIT 1;
                    """,
                    (sym, horizon, veto_reason, direction, int(cooldown_hours)),
                )
            row = cur.fetchone()
            return _format_row(row) if row else None


def db_get_accuracy_summary(days: int = 30, symbol: str | None = None) -> dict:
    """Compute rolling forward accuracy summary across evaluated predictions."""
    if not DATABASE_URL:
        return _mem.get_accuracy_summary(days=days, symbol=symbol)
    with get_connection() as conn:
        with conn.cursor() as cur:
            _ensure_predictions_table(cur, conn)
            if symbol:
                cur.execute(
                    """
                    SELECT * FROM signal_predictions
                    WHERE symbol = %s
                      AND created_at >= NOW() - (%s * INTERVAL '1 day')
                    ORDER BY created_at DESC;
                    """,
                    (symbol.upper(), int(days)),
                )
            else:
                cur.execute(
                    """
                    SELECT * FROM signal_predictions
                    WHERE created_at >= NOW() - (%s * INTERVAL '1 day')
                    ORDER BY created_at DESC;
                    """,
                    (int(days),),
                )
            rows = [_format_row(r) for r in cur.fetchall() if r]
    return compute_accuracy_summary_from_rows(rows, days=days)


async def async_insert_signal_prediction(data: dict) -> dict:
    return await asyncio.to_thread(db_insert_signal_prediction, data)


async def async_get_pending_predictions(limit: int = 200) -> list[dict]:
    return await asyncio.to_thread(db_get_pending_predictions, limit)


async def async_update_signal_prediction_outcome(
    pred_id: int,
    outcome: str,
    outcome_price: float,
    r_multiple: float,
) -> dict | None:
    return await asyncio.to_thread(
        db_update_signal_prediction_outcome,
        pred_id,
        outcome,
        outcome_price,
        r_multiple,
    )


async def async_get_recent_prediction(
    symbol: str,
    horizon: str,
    direction: str,
    cooldown_hours: int,
    is_shadow: bool = False,
    veto_reason: str | None = None,
) -> dict | None:
    return await asyncio.to_thread(
        db_get_recent_prediction,
        symbol,
        horizon,
        direction,
        cooldown_hours,
        is_shadow,
        veto_reason,
    )


async def async_get_accuracy_summary(days: int = 30, symbol: str | None = None) -> dict:
    return await asyncio.to_thread(db_get_accuracy_summary, days, symbol)


# ---------------------------------------------------------------------------
# Hyperliquid Whale Wallets
# ---------------------------------------------------------------------------

def db_upsert_hl_wallet(wallet: dict) -> dict:
    if not DATABASE_URL:
        return _mem.upsert_hl_wallet(wallet)
    addr = str(wallet.get("address", "")).lower()
    if not addr:
        return {}
    sql = """
    INSERT INTO hl_whale_wallets (
        address, label, account_value_usd, total_notional_usd, cumulative_pnl_usd,
        win_count, loss_count, reliability_score, tier, positions_json, recent_events_json, updated_at
    ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NOW())
    ON CONFLICT (address) DO UPDATE SET
        label = COALESCE(EXCLUDED.label, hl_whale_wallets.label),
        account_value_usd = EXCLUDED.account_value_usd,
        total_notional_usd = EXCLUDED.total_notional_usd,
        cumulative_pnl_usd = EXCLUDED.cumulative_pnl_usd,
        win_count = EXCLUDED.win_count,
        loss_count = EXCLUDED.loss_count,
        reliability_score = EXCLUDED.reliability_score,
        tier = EXCLUDED.tier,
        positions_json = EXCLUDED.positions_json,
        recent_events_json = EXCLUDED.recent_events_json,
        updated_at = NOW()
    RETURNING *;
    """
    try:
        with get_connection() as conn:
            with conn.cursor() as cur:
                cur.execute(
                    sql,
                    (
                        addr,
                        wallet.get("label"),
                        float(wallet.get("account_value_usd", 0.0) or 0.0),
                        float(wallet.get("total_notional_usd", 0.0) or 0.0),
                        float(wallet.get("cumulative_pnl_usd", 0.0) or 0.0),
                        int(wallet.get("win_count", 0) or 0),
                        int(wallet.get("loss_count", 0) or 0),
                        float(wallet.get("reliability_score", 1.0) or 1.0),
                        wallet.get("tier", "UNPROVEN"),
                        _safe_json_dumps(wallet.get("positions_json", {})),
                        _safe_json_dumps(wallet.get("recent_events_json", [])),
                    ),
                )
                row = cur.fetchone()
                return _format_row(row) or wallet
    except Exception as exc:
        logger.warning("[DB] db_upsert_hl_wallet error: %s", exc)
        return _mem.upsert_hl_wallet(wallet)


def db_get_hl_wallets(limit: int = 100) -> list[dict]:
    if not DATABASE_URL:
        return _mem.get_hl_wallets(limit)
    sql = """
    SELECT * FROM hl_whale_wallets
    ORDER BY reliability_score DESC, account_value_usd DESC
    LIMIT %s;
    """
    try:
        with get_connection() as conn:
            with conn.cursor() as cur:
                cur.execute(sql, (limit,))
                rows = cur.fetchall()
                return [_format_row(r) for r in rows if r]
    except Exception as exc:
        logger.warning("[DB] db_get_hl_wallets error: %s", exc)
        return _mem.get_hl_wallets(limit)


def db_get_hl_wallet(address: str) -> dict | None:
    if not DATABASE_URL:
        return _mem.get_hl_wallet(address)
    sql = "SELECT * FROM hl_whale_wallets WHERE LOWER(address) = LOWER(%s);"
    try:
        with get_connection() as conn:
            with conn.cursor() as cur:
                cur.execute(sql, (address,))
                row = cur.fetchone()
                return _format_row(row)
    except Exception as exc:
        logger.warning("[DB] db_get_hl_wallet error: %s", exc)
        return _mem.get_hl_wallet(address)


# ---------------------------------------------------------------------------
# Microstructure Tape
# ---------------------------------------------------------------------------

def db_insert_microstructure_tape(tape_row: dict) -> dict:
    if not DATABASE_URL:
        return _mem.insert_microstructure_tape(tape_row)
    sql = """
    INSERT INTO microstructure_tape (
        symbol, timestamp_ms, mark_price, adv_24h_usd, horizon_scores,
        factor_scores, whale_sub_metrics, raw_replay_slice,
        ret_15m_pct, ret_1h_pct, ret_4h_pct, recorded_at
    ) VALUES (
        %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NOW()
    )
    RETURNING *;
    """
    try:
        with get_connection() as conn:
            with conn.cursor() as cur:
                cur.execute(
                    sql,
                    (
                        str(tape_row.get("symbol", "")).upper(),
                        int(tape_row.get("timestamp_ms") or int(datetime.now(timezone.utc).timestamp() * 1000)),
                        float(tape_row.get("mark_price", 0.0) or 0.0),
                        float(tape_row.get("adv_24h_usd", 0.0) or 0.0),
                        _safe_json_dumps(tape_row.get("horizon_scores", {})),
                        _safe_json_dumps(tape_row.get("factor_scores", {})),
                        _safe_json_dumps(tape_row.get("whale_sub_metrics", {})),
                        _safe_json_dumps(tape_row.get("raw_replay_slice", {})),
                        tape_row.get("ret_15m_pct"),
                        tape_row.get("ret_1h_pct"),
                        tape_row.get("ret_4h_pct"),
                    ),
                )
                row = cur.fetchone()
                return _format_row(row) or tape_row
    except Exception as exc:
        logger.warning("[DB] db_insert_microstructure_tape error: %s", exc)
        return _mem.insert_microstructure_tape(tape_row)


def db_get_microstructure_tape(symbol: str | None = None, limit: int = 500, days: int = 14) -> list[dict]:
    if not DATABASE_URL:
        return _mem.get_microstructure_tape(symbol, limit, days)
    try:
        with get_connection() as conn:
            with conn.cursor() as cur:
                if symbol:
                    sql = """
                    SELECT * FROM microstructure_tape
                    WHERE symbol = %s AND recorded_at >= NOW() - (%s * INTERVAL '1 day')
                    ORDER BY timestamp_ms DESC
                    LIMIT %s;
                    """
                    cur.execute(sql, (symbol.upper(), days, limit))
                else:
                    sql = """
                    SELECT * FROM microstructure_tape
                    WHERE recorded_at >= NOW() - (%s * INTERVAL '1 day')
                    ORDER BY timestamp_ms DESC
                    LIMIT %s;
                    """
                    cur.execute(sql, (days, limit))
                rows = cur.fetchall()
                return [_format_row(r) for r in rows if r]
    except Exception as exc:
        logger.warning("[DB] db_get_microstructure_tape error: %s", exc)
        return _mem.get_microstructure_tape(symbol, limit, days)


def db_get_unevaluated_microstructure_tape(limit: int = 200) -> list[dict]:
    if not DATABASE_URL:
        return _mem.get_unevaluated_microstructure_tape(limit)
    sql = """
    SELECT * FROM microstructure_tape
    WHERE ret_4h_pct IS NULL OR evaluated_at IS NULL
    ORDER BY timestamp_ms ASC
    LIMIT %s;
    """
    try:
        with get_connection() as conn:
            with conn.cursor() as cur:
                cur.execute(sql, (limit,))
                rows = cur.fetchall()
                return [_format_row(r) for r in rows if r]
    except Exception as exc:
        logger.warning("[DB] db_get_unevaluated_microstructure_tape error: %s", exc)
        return _mem.get_unevaluated_microstructure_tape(limit)


def db_update_microstructure_tape_returns(
    tape_id: int,
    ret_15m: float | None,
    ret_1h: float | None,
    ret_4h: float | None,
) -> bool:
    if not DATABASE_URL:
        return _mem.update_microstructure_tape_returns(tape_id, ret_15m, ret_1h, ret_4h)
    sql = """
    UPDATE microstructure_tape
    SET ret_15m_pct = COALESCE(%s, ret_15m_pct),
        ret_1h_pct = COALESCE(%s, ret_1h_pct),
        ret_4h_pct = COALESCE(%s, ret_4h_pct),
        evaluated_at = NOW()
    WHERE id = %s;
    """
    try:
        with get_connection() as conn:
            with conn.cursor() as cur:
                cur.execute(sql, (ret_15m, ret_1h, ret_4h, tape_id))
                return cur.rowcount > 0
    except Exception as exc:
        logger.warning("[DB] db_update_microstructure_tape_returns error: %s", exc)
        return _mem.update_microstructure_tape_returns(tape_id, ret_15m, ret_1h, ret_4h)


async def async_upsert_hl_wallet(wallet: dict) -> dict:
    return await asyncio.to_thread(db_upsert_hl_wallet, wallet)


async def async_get_hl_wallets(limit: int = 100) -> list[dict]:
    return await asyncio.to_thread(db_get_hl_wallets, limit)


async def async_get_hl_wallet(address: str) -> dict | None:
    return await asyncio.to_thread(db_get_hl_wallet, address)


async def async_insert_microstructure_tape(tape_row: dict) -> dict:
    return await asyncio.to_thread(db_insert_microstructure_tape, tape_row)


async def async_get_microstructure_tape(symbol: str | None = None, limit: int = 500, days: int = 14) -> list[dict]:
    return await asyncio.to_thread(db_get_microstructure_tape, symbol, limit, days)


async def async_get_unevaluated_microstructure_tape(limit: int = 200) -> list[dict]:
    return await asyncio.to_thread(db_get_unevaluated_microstructure_tape, limit)


async def async_update_microstructure_tape_returns(
    tape_id: int,
    ret_15m: float | None,
    ret_1h: float | None,
    ret_4h: float | None,
) -> bool:
    return await asyncio.to_thread(db_update_microstructure_tape_returns, tape_id, ret_15m, ret_1h, ret_4h)