rostra-client-db 0.1.0

Embedded database and projections for a Rostra client
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
mod current_state;
mod event_order;
mod events_content_missing_ops;
mod extension;
mod id_nodes_ops;
mod ids_full;
mod migration_ops;
mod models;
pub mod news;
mod paginate;
mod process_event_content_ops;
mod process_event_ops;
mod reception_order_ops;
pub mod social;
mod table_ops;
mod tables;
mod tx_ops;

use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::panic::{AssertUnwindSafe, catch_unwind, resume_unwind};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::{io, ops, result};

use event::ContentStoreRecord;
pub use ids::{IdsFolloweesRecord, IdsFollowersRecord};
use itertools::Itertools as _;
use process_event_content_ops::ProcessEventError;
use redb_bincode::{ReadTransaction, ReadableTable, WriteTransaction};
use rostra_core::event::{
    EventAuxKey, EventContentRaw, EventExt as _, EventKind, IrohNodeId, PersonasTagsSelector,
    VerifiedEvent, VerifiedEventContent, content_kind,
};
use rostra_core::id::{RostraId, ShortRostraId, ToShort as _};
use rostra_core::{ExternalEventId, ShortEventId, Timestamp};
use rostra_util_error::{BoxedError, FmtCompact as _};
use snafu::{Location, ResultExt as _, Snafu};
use tokio::sync::{Notify, broadcast, watch};
use tokio::task::JoinError;
use tracing::{debug, error, info, instrument};

pub use self::current_state::{CurrentState, CurrentStateClosed};
pub use self::extension::{
    EXTENSION_RESERVED_TABLE_PREFIXES, ExtensionReadTransaction, ExtensionTableDefinition,
    ExtensionWriteTransaction,
};
pub(crate) use self::tables::*;
pub use self::tables::{
    ContentStoreRecordOwned, EventContentResult, EventContentState, EventReceivedRecord,
    EventReceivedSource, EventRecord, EventsHeadsTableRecord, IdSocialProfileRecord,
    IdsDataUsageRecord, IrohNodeRecord, IrohNodeStats, Latest, SocialNewsRankRecord,
    SocialPostRecord, SocialPostsReactionsRecord, SocialPostsRepliesRecord, SocialVoteScore,
    SocialVoteSumRecord,
};

/// Web of Trust data - contains direct followees and extended followees.
///
/// Extended followees are the followees of your direct followees, excluding
/// those you already follow directly.
#[derive(Debug, Clone, Default)]
pub struct WotData {
    /// Direct followees with their persona selectors
    pub followees: HashMap<RostraId, ids::IdsFolloweesRecord>,
    /// Extended followees (followees of followees), excluding direct followees
    pub extended: HashSet<RostraId>,
}

impl WotData {
    /// Returns true if the given id is in our web of trust (self, direct
    /// followee, or extended)
    pub fn contains(&self, id: RostraId, self_id: RostraId) -> bool {
        id == self_id || self.followees.contains_key(&id) || self.extended.contains(&id)
    }

    /// Returns the total number of IDs in the web of trust (excluding self)
    pub fn len(&self) -> usize {
        self.followees.len() + self.extended.len()
    }

    /// Returns true if there are no followees
    pub fn is_empty(&self) -> bool {
        self.followees.is_empty()
    }

    /// Returns an iterator over all IDs in the web of trust (direct +
    /// extended), excluding self
    pub fn iter_all(&self) -> impl Iterator<Item = RostraId> + '_ {
        self.followees
            .keys()
            .copied()
            .chain(self.extended.iter().copied())
    }
}

const LOG_TARGET: &str = "rostra::db";

type CommitHook = Box<dyn FnOnce() + 'static>;

pub(crate) struct WriteTransactionCtx {
    dbtx: WriteTransaction,
    on_commit: std::sync::Mutex<Option<Vec<CommitHook>>>,
}

impl From<WriteTransaction> for WriteTransactionCtx {
    fn from(dbtx: WriteTransaction) -> Self {
        Self {
            dbtx,
            on_commit: std::sync::Mutex::new(Some(vec![])),
        }
    }
}
impl std::ops::Deref for WriteTransactionCtx {
    type Target = WriteTransaction;

    fn deref(&self) -> &Self::Target {
        &self.dbtx
    }
}

impl std::ops::DerefMut for WriteTransactionCtx {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.dbtx
    }
}

impl WriteTransactionCtx {
    /// Registers an action to run in registration order after a successful
    /// commit.
    ///
    /// A hook panic does not suppress later hooks. After every hook has been
    /// attempted, the first panic resumes.
    pub(crate) fn on_commit(&self, f: impl FnOnce() + 'static) {
        if let Some(hooks) = self.on_commit.lock().expect("Locking failed").as_mut() {
            hooks.push(Box::new(f));
        }
    }

    /// Discard existing and future commit hooks for a bulk internal rebuild.
    ///
    /// Total replay reconstructs durable state before the database is exposed
    /// to subscribers. Retaining one publication closure per source event
    /// would make an otherwise streaming rebuild consume memory
    /// proportional to database size.
    pub(crate) fn discard_commit_hooks(&self) {
        *self.on_commit.lock().expect("Locking failed") = None;
    }

    /// Return whether this transaction publishes incremental commit hooks.
    pub(crate) fn commit_hooks_enabled(&self) -> bool {
        self.on_commit.lock().expect("Locking failed").is_some()
    }

    fn commit(self) -> result::Result<(), redb::CommitError> {
        let Self { dbtx, on_commit } = self;

        dbtx.commit()?;

        let mut first_panic = None;
        if let Some(hooks) = on_commit.lock().expect("Locking failed").as_mut() {
            for hook in hooks.drain(..) {
                if let Err(payload) = catch_unwind(AssertUnwindSafe(hook)) {
                    first_panic.get_or_insert(payload);
                }
            }
        }
        if let Some(payload) = first_panic {
            resume_unwind(payload);
        }
        Ok(())
    }
}

#[derive(Debug, Snafu)]
pub enum TableDumpError {
    #[snafu(display("Unknown table `{name}`"))]
    UnknownTable { name: String },
}
pub type TableDumpResult<T> = std::result::Result<T, TableDumpError>;

#[derive(Debug, Snafu)]
pub enum DbError {
    #[snafu(display("Database error"))]
    Database {
        source: redb::DatabaseError,
        #[snafu(implicit)]
        location: Location,
    },
    #[snafu(transparent)]
    Table {
        source: redb::TableError,
        #[snafu(implicit)]
        location: Location,
    },
    #[snafu(transparent)]
    Storage {
        source: redb::StorageError,
        #[snafu(implicit)]
        location: Location,
    },
    #[snafu(display("Database transaction error"))]
    Transaction {
        #[snafu(source(from(redb::TransactionError, Box::new)))]
        source: Box<redb::TransactionError>,
        #[snafu(implicit)]
        location: Location,
    },
    #[snafu(display("Database commit error"))]
    Commit {
        source: redb::CommitError,
        #[snafu(implicit)]
        location: Location,
    },
    #[snafu(transparent)]
    StoredDecode {
        source: bincode::error::DecodeError,
        #[snafu(implicit)]
        location: Location,
    },
    #[snafu(display("Database version {db_ver} is newer than supported version {code_ver}"))]
    DbVersionTooHigh {
        db_ver: u64,
        code_ver: u64,
        #[snafu(implicit)]
        location: Location,
    },
    #[snafu(display("Pending migration stash is missing required table `{table}`"))]
    MissingMigrationStashTable {
        table: String,
        #[snafu(implicit)]
        location: Location,
    },
    #[snafu(display("Database task failed"))]
    Join {
        source: JoinError,
        #[snafu(implicit)]
        location: Location,
    },
    #[snafu(transparent)]
    DbTxLogic {
        source: BoxedError,
        #[snafu(implicit)]
        location: Location,
    },
    #[snafu(visibility(pub))]
    #[snafu(display("Provided Id does not match one used previously"))]
    DbIdMismatch {
        #[snafu(implicit)]
        location: Location,
    },
    #[snafu(display("Database file-format upgrade failed"))]
    Upgrade {
        source: redb::UpgradeError,
        #[snafu(implicit)]
        location: Location,
    },
    #[snafu(display("Integer overflow"))]
    Overflow,
    #[snafu(display(
        "Reception-order key ({received_at:?}, {reception_order}) already exists in table {table}"
    ))]
    ReceptionOrderCollision {
        table: String,
        received_at: Timestamp,
        reception_order: u64,
        #[snafu(implicit)]
        location: Location,
    },
    #[snafu(display("Social post {event_id} already has a reception-order key"))]
    SocialPostReceiptAlreadyIndexed {
        event_id: ShortEventId,
        #[snafu(implicit)]
        location: Location,
    },
    #[snafu(display(
        "Reception-order key for social post {event_id} references {actual_event_id:?}"
    ))]
    SocialPostReceiptMismatch {
        event_id: ShortEventId,
        actual_event_id: Option<ShortEventId>,
        #[snafu(implicit)]
        location: Location,
    },
    #[snafu(display("Deletion attribution references missing event {event_id}"))]
    MissingDeletionAttribution {
        event_id: ShortEventId,
        #[snafu(implicit)]
        location: Location,
    },
    #[snafu(display("Extension access to built-in table `{name}` is forbidden"))]
    ReservedExtensionTable { name: String },
    #[snafu(display("Stored vote singleton {event_id} has no inline vote projection"))]
    MissingVoteSingletonProjection {
        event_id: ShortEventId,
        #[snafu(implicit)]
        location: Location,
    },
    #[snafu(display(
        "Stored vote singleton {event_id} has a cached target outside its shortened key"
    ))]
    InvalidVoteSingletonProjection {
        event_id: ShortEventId,
        #[snafu(implicit)]
        location: Location,
    },
    #[snafu(display(
        "Shortened identity prefix {prefix} maps to both {existing_id} and {incoming_id}"
    ))]
    IdentityPrefixCollision {
        prefix: ShortRostraId,
        existing_id: RostraId,
        incoming_id: RostraId,
        #[snafu(implicit)]
        location: Location,
    },
}
pub type DbResult<T> = std::result::Result<T, DbError>;

/// The authoritative event store and projection boundary for one local
/// identity.
///
/// Built-in reducers and projection tables are not part of the external API:
///
/// ```compile_fail
/// let _ = rostra_client_db::Database::process_event_content_inserted_tx;
/// ```
///
/// ```compile_fail
/// let _ = rostra_client_db::events_singletons_new::TABLE;
/// ```
///
/// ```compile_fail
/// let _ = rostra_client_db::Database::write_with::<()>;
/// ```
///
/// ```compile_fail
/// let _ = rostra_client_db::Database::write_with_inner::<()>;
/// ```
///
/// ```compile_fail
/// let _ = rostra_client_db::Database::read_with::<()>;
/// ```
///
/// ```compile_fail
/// let _: Option<rostra_client_db::WriteTransactionCtx> = None;
/// ```
///
/// ```compile_fail
/// rostra_client_db::def_table!(forbidden: u64 => u64);
/// ```
#[derive(Debug)]
pub struct Database {
    inner: redb_bincode::Database,
    self_id: RostraId,
    iroh_secret: iroh::SecretKey,

    /// Timestamp when this database was first created.
    ///
    /// Used with the current follow epoch as a notification cutoff: posts older
    /// than both are historical syncs and should not appear as newly received.
    db_init_time: Timestamp,

    /// Serializes writes through their post-commit current-state publication.
    ///
    /// Acquiring it before transaction creation keeps redb writer order and
    /// publication order identical. Commit hooks run while it is held and must
    /// not synchronously re-enter `write_with`. A hook panic propagates after
    /// commit and poisons this mutex; the next write recovers the guard because
    /// the durable transaction is still valid.
    write_and_publish_lock: std::sync::Mutex<()>,

    self_followees_updated: watch::Sender<Arc<HashMap<RostraId, IdsFolloweesRecord>>>,
    self_followers_updated: watch::Sender<Arc<HashMap<RostraId, IdsFollowersRecord>>>,
    self_wot_updated: watch::Sender<Arc<WotData>>,
    self_head_updated: watch::Sender<Option<ShortEventId>>,
    new_content_tx: broadcast::Sender<VerifiedEventContent>,
    new_posts_tx: broadcast::Sender<(VerifiedEventContent, content_kind::SocialPost)>,
    new_shoutbox_tx: broadcast::Sender<(VerifiedEventContent, content_kind::Shoutbox)>,
    new_heads_tx: broadcast::Sender<(RostraId, ShortEventId)>,
    ids_with_missing_events_tx: dedup_chan::Sender<RostraId>,
    news_score_updates_tx: dedup_chan::Sender<ExternalEventId>,

    /// Notification for when new content is added to `events_content_missing`.
    ///
    /// The `MissingEventContentFetcher` task waits on this to wake up
    /// immediately when new missing content arrives, instead of polling.
    content_missing_notify: Arc<Notify>,
}

impl Database {
    const MAX_CONTENT_LEN: u32 = 10_000_000u32;

    pub async fn mk_db_path(
        data_dir: &Path,
        self_id: RostraId,
    ) -> std::result::Result<PathBuf, io::Error> {
        tokio::fs::create_dir_all(&data_dir).await?;

        let legacy_path_unprefixed_z32 =
            data_dir.join(format!("{}.redb", self_id.to_unprefixed_z32_string()));
        if legacy_path_unprefixed_z32.exists() {
            return Ok(legacy_path_unprefixed_z32);
        }
        let legacy_path_bech32 = data_dir.join(format!("{}.redb", self_id.to_bech32_string()));
        if legacy_path_bech32.exists() {
            return Ok(legacy_path_bech32);
        }
        Ok(data_dir.join(format!("{self_id}.redb")))
    }

    pub async fn new_in_memory(self_id: RostraId) -> DbResult<Database> {
        debug!(target: LOG_TARGET, id = %self_id, "Opening in-memory database");
        let inner = redb::Database::builder()
            .create_with_file_format_v3(true)
            .create_with_backend(redb::backends::InMemoryBackend::new())
            .context(DatabaseSnafu)?;
        Self::open_inner(inner, self_id).await
    }

    /// Open an identity database, creating it when absent.
    ///
    /// Opening storage older than schema version 25 performs the total rebuild
    /// before returning. This can hold a long atomic write transaction and
    /// requires deployment-specific RAM and temporary disk headroom. See
    /// `specs/ARCH-client-database.md#total-rebuild`.
    pub async fn open(path: impl Into<PathBuf>, self_id: RostraId) -> DbResult<Database> {
        let path = path.into();
        debug!(target: LOG_TARGET, id = %self_id, path = %path.display(), "Opening database");

        let mut inner = tokio::task::spawn_blocking(move || {
            redb::Database::builder()
                .create_with_file_format_v3(true)
                .create(path)
        })
        .await
        .context(JoinSnafu)?
        .context(DatabaseSnafu)?;

        inner.upgrade().context(UpgradeSnafu)?;

        Self::open_inner(inner, self_id).await
    }

    #[instrument(skip_all)]
    async fn open_inner(inner: redb::Database, self_id: RostraId) -> DbResult<Database> {
        let inner = redb_bincode::Database::from(inner);

        // Run migrations (may stash tables for total migration reprocessing)
        Self::write_with_inner(&inner, |tx| {
            // Opening table definitions is raw and does not decode rows. Check
            // the schema version before reading typed identity bytes so a newer
            // database always fails with DbVersionTooHigh.
            Self::init_tables_tx(tx)?;
            Self::handle_db_ver_migrations(tx)?;
            Self::verify_self_tx(self_id, &mut tx.open_table(&ids_self::TABLE)?)?;
            Ok(())
        })
        .await?;

        // Check if there's a pending migration stash (either from this run or a
        // previous interrupted run). Using stash existence as the marker ensures
        // we retry if reprocessing fails/panics.
        let needs_reprocessing =
            Self::write_with_inner(&inner, Self::has_pending_migration_stash).await?;

        let (self_head, iroh_secret, self_followees, self_followers, self_wot, db_init_time) =
            Self::read_with_inner(&inner, |tx| {
                let ids_followees_table = tx.open_table(&ids_followees::TABLE)?;
                let self_followees = Self::read_followees_tx(self_id, &ids_followees_table)?;
                let self_wot =
                    Self::compute_wot_tx(self_id, &self_followees, &ids_followees_table)?;
                let db_init_time = tx
                    .open_table(&db_init_time::TABLE)?
                    .get(&())?
                    .map(|g| g.value())
                    .unwrap_or(Timestamp::ZERO);
                Ok((
                    Self::read_head_tx(self_id, &tx.open_table(&events_heads::TABLE)?)?,
                    Self::read_iroh_secret_tx(&tx.open_table(&ids_self::TABLE)?)?,
                    self_followees,
                    Self::read_followers_tx(self_id, &tx.open_table(&ids_followers::TABLE)?)?,
                    self_wot,
                    db_init_time,
                ))
            })
            .await?;

        let (self_followees_updated, _) = watch::channel(Arc::new(self_followees));
        let (self_followers_updated, _) = watch::channel(Arc::new(self_followers));
        let (self_wot_updated, _) = watch::channel(Arc::new(self_wot));
        let (self_head_updated, _) = watch::channel(self_head);
        let (new_content_tx, _) = broadcast::channel(100);
        let (new_posts_tx, _) = broadcast::channel(100);
        let (new_shoutbox_tx, _) = broadcast::channel(100);
        let (new_heads_tx, _) = broadcast::channel(100);

        let db = Self {
            inner,
            self_id,
            iroh_secret,
            db_init_time,
            write_and_publish_lock: std::sync::Mutex::new(()),
            self_followees_updated,
            self_followers_updated,
            self_wot_updated,
            self_head_updated,
            new_content_tx,
            new_posts_tx,
            new_shoutbox_tx,
            new_heads_tx,
            ids_with_missing_events_tx: dedup_chan::Sender::new(),
            news_score_updates_tx: dedup_chan::Sender::new(),
            content_missing_notify: Arc::new(Notify::new()),
        };

        // If total migration stashed events, reprocess them now using the real
        // Database. The stash existence check ensures we retry if this
        // fails/panics.
        if needs_reprocessing {
            db.write_with(|tx| db.reprocess_migration_stash(tx)).await?;
            db.refresh_current_state_after_replay().await?;
        }

        Ok(db)
    }

    /// Publish one coherent current-state snapshot after silent total replay.
    async fn refresh_current_state_after_replay(&self) -> DbResult<()> {
        let (self_head, self_followees, self_followers, self_wot) = self
            .read_with(|tx| {
                let followees = tx.open_table(&ids_followees::TABLE)?;
                let self_followees = Self::read_followees_tx(self.self_id, &followees)?;
                let self_wot = Self::compute_wot_tx(self.self_id, &self_followees, &followees)?;
                Ok((
                    Self::read_head_tx(self.self_id, &tx.open_table(&events_heads::TABLE)?)?,
                    self_followees,
                    Self::read_followers_tx(self.self_id, &tx.open_table(&ids_followers::TABLE)?)?,
                    self_wot,
                ))
            })
            .await?;

        self.self_head_updated.send_replace(self_head);
        self.self_followees_updated
            .send_replace(Arc::new(self_followees));
        self.self_followers_updated
            .send_replace(Arc::new(self_followers));
        self.self_wot_updated.send_replace(Arc::new(self_wot));
        Ok(())
    }

    pub async fn compact(&mut self) -> Result<bool, redb::CompactionError> {
        tokio::task::block_in_place(|| self.inner.as_raw_mut().compact())
    }

    pub async fn dump_table(&self, name: &str) -> TableDumpResult<()> {
        self.read_with(|tx| {
            match name {
                "events" => Self::dump_table_dbtx(tx, &tables::events::TABLE)?,
                "content_store" => Self::dump_table_dbtx(tx, &tables::content_store::TABLE)?,
                "events_content_state" => {
                    Self::dump_table_dbtx(tx, &tables::events_content_state::TABLE)?
                }
                "events_content_missing" => {
                    Self::dump_table_dbtx(tx, &tables::events_content_missing::TABLE)?
                }
                "social_posts" => Self::dump_table_dbtx(tx, &tables::social_posts::TABLE)?,
                "social_posts_replies" => {
                    Self::dump_table_dbtx(tx, &tables::social_posts_replies::TABLE)?
                }
                "social_posts_reactions" => {
                    Self::dump_table_dbtx(tx, &tables::social_posts_reactions::TABLE)?
                }
                "social_vote_sums" => Self::dump_table_dbtx(tx, &tables::social_vote_sums::TABLE)?,
                "social_news_rank_by_post_id" => {
                    Self::dump_table_dbtx(tx, &tables::social_news_rank_by_post_id::TABLE)?
                }
                "social_news_rank_by_score" => {
                    Self::dump_table_dbtx(tx, &tables::social_news_rank_by_score::TABLE)?
                }
                "social_news_rank_by_time" => {
                    Self::dump_table_dbtx(tx, &tables::social_news_rank_by_time::TABLE)?
                }
                _ => {
                    return Ok(Err(UnknownTableSnafu {
                        name: name.to_string(),
                    }
                    .build()));
                }
            }
            Ok(Ok(()))
        })
        .await
        .expect("Database panic")
    }

    /// Subscribe to owned snapshots of the retained current self-followee
    /// projection.
    pub fn self_followees_subscribe(
        &self,
    ) -> CurrentState<Arc<HashMap<RostraId, IdsFolloweesRecord>>> {
        CurrentState::new(self.self_followees_updated.subscribe())
    }

    /// Subscribe to owned snapshots of the retained current self-follower
    /// projection.
    pub fn self_followers_subscribe(
        &self,
    ) -> CurrentState<Arc<HashMap<RostraId, IdsFollowersRecord>>> {
        CurrentState::new(self.self_followers_updated.subscribe())
    }

    /// Subscribe to owned snapshots of the retained current Web-of-Trust
    /// projection.
    pub fn self_wot_subscribe(&self) -> CurrentState<Arc<WotData>> {
        CurrentState::new(self.self_wot_updated.subscribe())
    }

    /// Subscribe to owned snapshots of the retained deterministic self-head
    /// representative.
    ///
    /// The value is the minimum current `ShortEventId`. It is a stable default,
    /// not a claim that the current head set is a singleton. Every committed
    /// self-event insertion publishes, even when the representative is
    /// unchanged.
    pub fn self_head_subscribe(&self) -> CurrentState<Option<ShortEventId>> {
        CurrentState::new(self.self_head_updated.subscribe())
    }

    pub fn new_content_subscribe(&self) -> broadcast::Receiver<VerifiedEventContent> {
        self.new_content_tx.subscribe()
    }
    pub fn new_posts_subscribe(
        &self,
    ) -> broadcast::Receiver<(VerifiedEventContent, content_kind::SocialPost)> {
        self.new_posts_tx.subscribe()
    }

    pub fn new_shoutbox_subscribe(
        &self,
    ) -> broadcast::Receiver<(VerifiedEventContent, content_kind::Shoutbox)> {
        self.new_shoutbox_tx.subscribe()
    }

    /// Subscribe to incremental exact new-head signals.
    ///
    /// This lossy channel carries the event that became a head. Consumers that
    /// lag must recover from the durable complete head set.
    pub fn new_heads_subscribe(&self) -> broadcast::Receiver<(RostraId, ShortEventId)> {
        self.new_heads_tx.subscribe()
    }

    pub fn ids_with_missing_events_subscribe(
        &self,
        capacity: usize,
    ) -> dedup_chan::Receiver<RostraId> {
        self.ids_with_missing_events_tx.subscribe(capacity)
    }

    pub fn news_score_updates_subscribe(
        &self,
        capacity: usize,
    ) -> dedup_chan::Receiver<ExternalEventId> {
        self.news_score_updates_tx.subscribe(capacity)
    }

    /// Get a handle to the content-missing notification.
    ///
    /// The `MissingEventContentFetcher` calls `notified()` on this to wake up
    /// when new missing content is inserted into the database.
    pub fn content_missing_notify(&self) -> Arc<Notify> {
        self.content_missing_notify.clone()
    }

    pub async fn has_event(&self, event_id: impl Into<ShortEventId>) -> bool {
        let event_id = event_id.into();
        self.read_with(|tx| {
            let events_table = tx.open_table(&events::TABLE).expect("Storage error");
            Database::has_event_tx(event_id, &events_table)
        })
        .await
        .expect("Database panic")
    }

    pub async fn get_missing_events_for_id(&self, id: RostraId) -> Vec<ShortEventId> {
        self.read_with(|tx| {
            let events_missing_tbl = tx.open_table(&events_missing::TABLE)?;
            Ok(
                Database::get_missing_events_for_id_tx(id, &events_missing_tbl)?
                    .into_iter()
                    .collect(),
            )
        })
        .await
        .expect("Database panic")
    }

    pub async fn get_heads_events_for_id(&self, id: RostraId) -> Vec<ShortEventId> {
        self.read_with(|tx| {
            let events_heads_tbl = tx.open_table(&events_heads::TABLE)?;
            Ok(Database::get_heads_events_tx(id, &events_heads_tbl)?
                .into_iter()
                .collect())
        })
        .await
        .expect("Database panic")
    }

    pub async fn count_missing_events_for_id(&self, id: RostraId) -> usize {
        self.read_with(|tx| {
            let events_missing_tbl = tx.open_table(&events_missing::TABLE)?;
            Database::count_missing_events_for_id_tx(id, &events_missing_tbl)
        })
        .await
        .expect("Database panic")
    }

    pub async fn count_heads_events_for_id(&self, id: RostraId) -> usize {
        self.read_with(|tx| {
            let events_heads_tbl = tx.open_table(&events_heads::TABLE)?;
            Database::count_heads_events_tx(id, &events_heads_tbl)
        })
        .await
        .expect("Database panic")
    }

    pub async fn get_data_usage(&self, id: RostraId) -> IdsDataUsageRecord {
        self.read_with(|tx| {
            let ids_data_usage_tbl = tx.open_table(&ids_data_usage::TABLE)?;
            Database::get_data_usage_tx(id, &ids_data_usage_tbl)
        })
        .await
        .expect("Database panic")
    }

    pub async fn get_self_followees(&self) -> Vec<(RostraId, PersonasTagsSelector)> {
        self.get_followees(self.self_id).await
    }

    pub async fn get_followees(&self, id: RostraId) -> Vec<(RostraId, PersonasTagsSelector)> {
        self.read_with(|tx| {
            let ids_followees_table = tx.open_table(&ids_followees::TABLE)?;
            Ok(Database::read_followees_tx(id, &ids_followees_table)?
                .into_iter()
                .map(|(id, record)| (id, record.effective_tags_selector()))
                .collect())
        })
        .await
        .expect("Database panic")
    }

    pub async fn get_followees_extended(
        &self,
        id: RostraId,
    ) -> (HashMap<RostraId, PersonasTagsSelector>, HashSet<RostraId>) {
        self.read_with(|tx| {
            let ids_followees_table = tx.open_table(&ids_followees::TABLE)?;
            let followees: HashMap<RostraId, PersonasTagsSelector> =
                Database::read_followees_tx_iter(id, &ids_followees_table)?
                    .map_ok(|(id, record)| (id, record.effective_tags_selector()))
                    .collect::<Result<_, _>>()?;

            let mut extended = HashSet::new();

            for followee in followees.keys() {
                for extended_followee in
                    Database::read_followees_tx_iter(*followee, &ids_followees_table)?
                        .map_ok(|(id, _record)| id)
                {
                    let extended_followee = extended_followee?;
                    if !followees.contains_key(&extended_followee) {
                        extended.insert(extended_followee);
                    }
                }
            }
            Ok((followees, extended))
        })
        .await
        .expect("Database panic")
    }

    pub async fn get_self_followers(&self) -> Vec<RostraId> {
        self.get_followers(self.self_id).await
    }

    pub async fn get_followers(&self, id: RostraId) -> Vec<RostraId> {
        self.read_with(|tx| {
            let ids_followers_table = tx.open_table(&ids_followers::TABLE)?;
            Ok(Database::read_followers_tx(id, &ids_followers_table)?
                .into_keys()
                .collect())
        })
        .await
        .expect("Database panic")
    }

    pub async fn get_event(
        &self,
        event_id: impl Into<ShortEventId>,
    ) -> Option<crate::event::EventRecord> {
        let event_id = event_id.into();
        self.read_with(|tx| {
            let events_table = tx.open_table(&events::TABLE)?;
            Database::get_event_tx(event_id, &events_table)
        })
        .await
        .expect("Database panic")
    }

    pub async fn get_event_content(
        &self,
        event_id: impl Into<ShortEventId>,
    ) -> Option<EventContentRaw> {
        let event_id = event_id.into();
        self.read_with(|tx| {
            let events_table = tx.open_table(&events::TABLE)?;
            let events_content_state_table = tx.open_table(&events_content_state::TABLE)?;
            let content_store_table = tx.open_table(&content_store::TABLE)?;

            // Get the event to find its content hash
            let Some(event_record) = Database::get_event_tx(event_id, &events_table)? else {
                return Ok(None);
            };
            let content_hash = event_record.content_hash();

            Ok(Database::get_event_content_full_tx(
                event_id,
                content_hash,
                &events_content_state_table,
                &content_store_table,
            )?
            .and_then(|result| result.content().cloned()))
        })
        .await
        .expect("Database panic")
    }

    /// Return the lifecycle state for event content that is not currently
    /// stored.
    ///
    /// For an existing event, `None` normally means the content was processed.
    /// A terminal state such as `Deleted`, `Pruned`, or `Invalid` means callers
    /// must not wait for payload availability.
    pub async fn get_event_content_state(
        &self,
        event_id: impl Into<ShortEventId>,
    ) -> Option<EventContentState> {
        let event_id = event_id.into();
        self.read_with(|tx| {
            Self::get_event_content_state_tx(
                event_id,
                &tx.open_table(&events_content_state::TABLE)?,
            )
        })
        .await
        .expect("Database panic")
    }

    /// Return the minimum current self-head as a deterministic representative.
    ///
    /// Use [`Self::get_heads_self`] when the complete set is required.
    pub async fn get_self_current_head(&self) -> Option<ShortEventId> {
        self.read_with(|tx| {
            let events_heads_table = tx.open_table(&events_heads::TABLE)?;

            Database::read_head_tx(self.self_id, &events_heads_table)
        })
        .await
        .expect("Storage error")
    }

    pub async fn get_self_random_eventid(&self) -> Option<ShortEventId> {
        self.read_with(|tx| {
            let events_self_table = tx.open_table(&events_self::TABLE)?;

            Database::get_random_self_event(&events_self_table)
        })
        .await
        .expect("Storage error")
    }

    /// Fallibly process a verified event envelope.
    ///
    /// # Errors
    ///
    /// Returns storage and transaction errors, including
    /// [`DbError::IdentityPrefixCollision`]. An error leaves the ingestion
    /// transaction uncommitted.
    pub async fn try_process_event(
        &self,
        event: &VerifiedEvent,
    ) -> DbResult<(InsertEventOutcome, ProcessEventState)> {
        let now = Timestamp::now();
        self.write_with(|tx| self.process_event_tx(event, now, tx))
            .await
    }

    /// Process a verified event envelope, panicking on storage failure.
    ///
    /// # Panics
    ///
    /// Panics after rolling back if storage fails or the event author's
    /// shortened identity prefix is already mapped to a different full
    /// identity.
    pub async fn process_event(
        &self,
        event: &VerifiedEvent,
    ) -> (InsertEventOutcome, ProcessEventState) {
        self.try_process_event(event).await.expect("Storage error")
    }

    /// Fallibly process a verified envelope and its verified content
    /// atomically.
    ///
    /// This operation is idempotent whether or not the envelope or content was
    /// processed previously.
    ///
    /// # Errors
    ///
    /// Returns storage and transaction errors, including
    /// [`DbError::IdentityPrefixCollision`]. An error rolls back the envelope,
    /// content, lifecycle, and projection changes together.
    pub async fn try_process_event_with_content(
        &self,
        content: &VerifiedEventContent,
    ) -> DbResult<(InsertEventOutcome, ProcessEventState)> {
        let now = Timestamp::now();
        self.write_with(|tx| {
            let res = self.process_event_tx(&content.event, now, tx)?;
            self.process_event_content_tx(content, now, tx)?;
            Ok(res)
        })
        .await
    }

    /// Process a verified envelope and its verified content, panicking on
    /// storage failure.
    ///
    /// This operation is idempotent whether or not the envelope or content was
    /// processed previously.
    ///
    /// # Panics
    ///
    /// Panics after rolling back if storage fails or a stored invariant is
    /// violated, including a vote winner with a missing or invalid inline
    /// projection or a shortened identity prefix mapped to a different full
    /// identity.
    pub async fn process_event_with_content(
        &self,
        content: &VerifiedEventContent,
    ) -> (InsertEventOutcome, ProcessEventState) {
        self.try_process_event_with_content(content)
            .await
            .expect("Storage error")
    }

    /// Fallibly process verified content and its carried envelope atomically.
    ///
    /// This is the safe public content-ingestion boundary. If the envelope is
    /// absent, it is inserted before content processing in the same
    /// transaction. If the envelope is already present, normal
    /// lifecycle-state checks make the operation idempotent and prevent
    /// repeated accounting or projections.
    ///
    /// # Errors
    ///
    /// Returns errors under the same conditions as
    /// [`Database::try_process_event_with_content`].
    pub async fn try_process_event_content(
        &self,
        event_content: &VerifiedEventContent,
    ) -> DbResult<()> {
        self.try_process_event_with_content(event_content)
            .await
            .map(|_| ())
    }

    /// Process verified content and its carried envelope, panicking on storage
    /// failure.
    ///
    /// # Panics
    ///
    /// Panics under the same conditions as
    /// [`Database::process_event_with_content`].
    pub async fn process_event_content(&self, event_content: &VerifiedEventContent) {
        self.try_process_event_content(event_content)
            .await
            .expect("Storage error");
    }

    /// Process event content.
    ///
    /// Ordinary processing requires Missing state, applies kind-specific side
    /// effects, stores the content, removes fetch scheduling, and transitions
    /// to Processed. RC was already incremented at event insertion.
    ///
    /// A verified, below-limit Deleted social-post edit is the sole
    /// terminal-state exception. It may add only immutable forward and reverse
    /// replacement rows; it does not store the supplied bytes or change
    /// lifecycle bookkeeping or other projections.
    ///
    /// The `now` parameter should be `Timestamp::now()` for normal operation,
    /// but can be set to a specific value for testing or migration.
    pub(crate) fn process_event_content_tx(
        &self,
        event_content: &VerifiedEventContent,
        now: Timestamp,
        tx: &WriteTransactionCtx,
    ) -> DbResult<()> {
        {
            let events_table = tx.open_table(&events::TABLE)?;
            let has_event = Database::has_event_tx(event_content.event.event_id, &events_table)?;
            if !has_event {
                // Event doesn't exist - this shouldn't happen in normal operation.
                // It means process_event_content_tx was called without first inserting the
                // event.
                debug_assert!(false, "Processing content for non-existent event");
                error!(
                    target: LOG_TARGET,
                    event_id = %event_content.event.event_id,
                    "Processing content for non-existent event - possible bug"
                );
                return Ok(());
            }
        }

        // Check if content should be processed (not deleted/pruned, is Missing)
        let (can_insert, is_deleted) = if u32::from(event_content.event.event.content_len)
            < Self::MAX_CONTENT_LEN
        {
            let events_content_state_table = tx.open_table(&events_content_state::TABLE)?;
            let state = events_content_state_table
                .get(&event_content.event_id().to_short())?
                .map(|state| state.value());
            (
                Database::can_insert_event_content_tx(event_content, &events_content_state_table)?,
                matches!(state, Some(EventContentState::Deleted { .. })),
            )
        } else {
            (false, false)
        };

        if can_insert {
            // Remove eligible content from the missing list.
            {
                let event_short_id = event_content.event_id().to_short();
                let events_content_state_table = tx.open_table(&events_content_state::TABLE)?;
                let mut events_content_missing_table =
                    tx.open_table(&tables::events_content_missing::TABLE)?;
                let state = events_content_state_table
                    .get(&event_short_id)?
                    .map(|g| g.value());
                if let Some(EventContentState::Missing {
                    next_fetch_attempt, ..
                }) = state
                {
                    events_content_missing_table.remove(&(next_fetch_attempt, event_short_id))?;
                }
            }

            if let Some(content) = event_content.content.as_ref() {
                let content_hash = event_content.content_hash();
                let event_short_id = event_content.event_id().to_short();

                // Process side effects
                let is_valid = match self.process_event_content_inserted_tx(event_content, now, tx)
                {
                    Ok(()) => {
                        if tx.commit_hooks_enabled() {
                            info!(target: LOG_TARGET,
                                kind = %event_content.kind(),
                                event_id = %event_short_id,
                                author = %event_content.author().to_short(),
                                len = %event_content.content_len(),
                                "New event content inserted"
                            );
                        }
                        true
                    }
                    Err(ProcessEventError::Invalid { source, location }) => {
                        if tx.commit_hooks_enabled() {
                            info!(
                                target: LOG_TARGET,
                                err = %source.as_ref().fmt_compact(),
                                %location,
                                "Invalid event content"
                            );
                        }
                        false
                    }
                    Err(ProcessEventError::Db { source }) => {
                        return Err(source);
                    }
                };

                if is_valid {
                    // Store content in content_store if not already there
                    {
                        let mut content_store_table = tx.open_table(&content_store::TABLE)?;
                        if content_store_table.get(&content_hash)?.is_none() {
                            content_store_table.insert(
                                &content_hash,
                                &ContentStoreRecord(Cow::Owned(content.clone())),
                            )?;
                        }
                    }

                    // Remove the Missing marker now that content is processed
                    {
                        let mut events_content_state_table =
                            tx.open_table(&events_content_state::TABLE)?;
                        events_content_state_table.remove(&event_short_id)?;
                    }

                    // Track payload as processed (missing → current)
                    {
                        let mut ids_data_usage_table =
                            tx.open_table(&tables::ids_data_usage::TABLE)?;
                        Database::track_payload_processed_tx(
                            event_content.author(),
                            event_content.content_len(),
                            &mut ids_data_usage_table,
                        )?;
                    }

                    // Notify about new content
                    if tx.commit_hooks_enabled() {
                        tx.on_commit({
                            let new_content_tx = self.new_content_tx.clone();
                            let event_content = event_content.clone();
                            move || {
                                let _ = new_content_tx.send(event_content);
                            }
                        });
                    }
                } else {
                    // Content failed validation — mark as Invalid, decrement RC,
                    // discard content bytes
                    {
                        let mut events_content_state_table =
                            tx.open_table(&events_content_state::TABLE)?;
                        events_content_state_table
                            .insert(&event_short_id, &EventContentState::Invalid)?;
                    }
                    {
                        let mut content_rc_table = tx.open_table(&tables::content_rc::TABLE)?;
                        Database::decrement_content_rc_tx(content_hash, &mut content_rc_table)?;
                    }

                    // Track payload as invalid (missing → invalid)
                    {
                        let mut ids_data_usage_table =
                            tx.open_table(&tables::ids_data_usage::TABLE)?;
                        Database::track_payload_invalid_tx(
                            event_content.author(),
                            event_content.content_len(),
                            &mut ids_data_usage_table,
                        )?;
                    }
                }
            }
        } else if is_deleted && event_content.content.is_some() {
            match Self::process_deleted_social_post_replacement_tx(event_content, tx) {
                Ok(_) => {}
                Err(ProcessEventError::Invalid { source, location }) => {
                    debug!(
                        target: LOG_TARGET,
                        err = %source.as_ref().fmt_compact(),
                        %location,
                        "Ignoring malformed Deleted social-post content"
                    );
                }
                Err(ProcessEventError::Db { source }) => return Err(source),
            }
        }
        Ok(())
    }

    pub async fn wants_content(
        &self,
        event_id: impl Into<ShortEventId>,
        process_state: ProcessEventState,
    ) -> bool {
        match process_state.wants_content() {
            ContentWantState::DoesNotWant => {
                return false;
            }
            ContentWantState::Wants => {
                return true;
            }
            ContentWantState::MaybeWants => {}
        }

        let event_id = event_id.into();
        self.read_with(|tx| {
            let events_table = tx.open_table(&events::TABLE)?;
            let events_content_state_table = tx.open_table(&events_content_state::TABLE)?;
            let content_store_table = tx.open_table(&content_store::TABLE)?;

            // Get event to find content_hash
            let Some(event) = Database::get_event_tx(event_id, &events_table)? else {
                return Ok(false);
            };
            let content_hash = event.content_hash();

            // We want content if we DON'T have it yet
            Ok(!Database::has_event_content_tx(
                event_id,
                content_hash,
                &events_content_state_table,
                &content_store_table,
            )?)
        })
        .await
        .expect("Storage error")
    }

    pub fn db_init_time(&self) -> Timestamp {
        self.db_init_time
    }

    pub fn iroh_secret(&self) -> iroh::SecretKey {
        self.iroh_secret.clone()
    }
}

impl Database {
    fn write_with_inner_blocking<T>(
        inner: &redb_bincode::Database,
        f: impl FnOnce(&'_ WriteTransactionCtx) -> DbResult<T>,
    ) -> DbResult<T> {
        let mut dbtx = WriteTransactionCtx::from(inner.begin_write().context(TransactionSnafu)?);
        let res = f(&mut dbtx)?;

        dbtx.commit().context(CommitSnafu)?;

        Ok(res)
    }

    /// Runs a low-level write transaction without a `Database` publication
    /// boundary.
    ///
    /// The synchronous transaction closure must not start another write.
    pub(crate) async fn write_with_inner<T>(
        inner: &redb_bincode::Database,
        f: impl FnOnce(&'_ WriteTransactionCtx) -> DbResult<T>,
    ) -> DbResult<T> {
        tokio::task::block_in_place(|| Self::write_with_inner_blocking(inner, f))
    }

    /// Runs a serialized write transaction and its internal post-commit
    /// actions.
    ///
    /// The mutex spans transaction creation, durable commit, and all
    /// post-commit actions so their publication order matches writer order.
    /// The synchronous transaction closure and post-commit actions must not
    /// re-enter database writes.
    ///
    /// A post-commit action panic propagates to the caller after the
    /// transaction has committed. Every registered action is attempted, then
    /// the first panic resumes. A later write recovers the poisoned
    /// serialization mutex and proceeds.
    pub(crate) async fn write_with<T>(
        &self,
        f: impl FnOnce(&'_ WriteTransactionCtx) -> DbResult<T>,
    ) -> DbResult<T> {
        tokio::task::block_in_place(|| {
            let _write_and_publish_guard = self
                .write_and_publish_lock
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            Self::write_with_inner_blocking(&self.inner, f)
        })
    }

    /// Runs a serialized transaction over caller-owned extension tables.
    ///
    /// The closure cannot access built-in graph, lifecycle, or projection
    /// tables. It must not re-enter database writes. This trusted persistence
    /// boundary does not include extension data in core replay or convergence;
    /// callers own their schema, invariants, and compatibility. Total database
    /// migrations preserve extension tables byte-for-byte.
    ///
    /// Returning `Ok` commits all extension-table mutations atomically.
    /// Returning `Err`, panicking, or failing a reserved-name/table
    /// operation leaves the transaction uncommitted. Post-commit built-in
    /// projection hooks are not available at this boundary.
    ///
    /// # Errors
    ///
    /// Returns the closure's error and propagates transaction, table, and
    /// commit errors. Opening a reserved table returns
    /// [`DbError::ReservedExtensionTable`].
    pub async fn extension_write<T>(
        &self,
        f: impl FnOnce(&ExtensionWriteTransaction<'_>) -> DbResult<T>,
    ) -> DbResult<T> {
        self.write_with(|tx| f(&ExtensionWriteTransaction::new(tx)))
            .await
    }

    pub(crate) async fn read_with_inner<T>(
        inner: &redb_bincode::Database,
        f: impl FnOnce(&'_ ReadTransaction) -> DbResult<T>,
    ) -> DbResult<T> {
        tokio::task::block_in_place(|| {
            let mut dbtx = inner.begin_read().context(TransactionSnafu)?;

            f(&mut dbtx)
        })
    }

    pub(crate) async fn read_with<T>(
        &self,
        f: impl FnOnce(&'_ ReadTransaction) -> DbResult<T>,
    ) -> DbResult<T> {
        Self::read_with_inner(&self.inner, f).await
    }

    /// Runs a read transaction over trusted, caller-owned extension tables.
    ///
    /// Callers own extension schemas, invariants, and compatibility; core event
    /// replay does not validate or rebuild their contents.
    ///
    /// # Errors
    ///
    /// Returns the closure's error and propagates transaction and table errors.
    /// Opening a reserved table returns [`DbError::ReservedExtensionTable`].
    pub async fn extension_read<T>(
        &self,
        f: impl FnOnce(&ExtensionReadTransaction<'_>) -> DbResult<T>,
    ) -> DbResult<T> {
        self.read_with(|tx| f(&ExtensionReadTransaction::new(tx)))
            .await
    }

    pub(crate) fn verify_self_tx(
        self_id: RostraId,
        ids_self_t: &mut ids_self::Table,
    ) -> DbResult<()> {
        match Self::read_self_id_tx(ids_self_t)? {
            Some(existing_self_id_record) => {
                if existing_self_id_record.rostra_id != self_id {
                    return DbIdMismatchSnafu.fail();
                }
            }
            _ => {
                Self::write_self_id_tx(self_id, ids_self_t)?;
            }
        };
        Ok(())
    }

    /// Return the minimum current head as a deterministic representative.
    ///
    /// Use [`Self::get_heads`] when the complete set is required.
    pub async fn get_head(&self, id: RostraId) -> Option<ShortEventId> {
        self.read_with(|tx| {
            let events_heads = tx.open_table(&events_heads::TABLE)?;

            Self::read_head_tx(id, &events_heads)
        })
        .await
        .expect("Database panic")
    }

    /// Return the complete current head set for an identity.
    pub async fn get_heads(&self, id: RostraId) -> HashSet<ShortEventId> {
        self.read_with(|tx| {
            let events_heads = tx.open_table(&events_heads::TABLE)?;

            Self::get_heads_tx(id, &events_heads)
        })
        .await
        .expect("Database panic")
    }

    /// Return the complete current head set for the local identity.
    pub async fn get_heads_self(&self) -> HashSet<ShortEventId> {
        self.read_with(|tx| {
            let events_heads = tx.open_table(&events_heads::TABLE)?;

            Self::get_heads_tx(self.self_id, &events_heads)
        })
        .await
        .expect("Database panic")
    }

    pub async fn get_social_profile(&self, id: RostraId) -> Option<IdSocialProfileRecord> {
        self.read_with(|tx| {
            let events_heads = tx.open_table(&social_profiles::TABLE)?;

            Self::get_social_profile_tx(id, &events_heads)
        })
        .await
        .expect("Database panic")
    }

    pub async fn get_latest_singleton_event(
        &self,
        rostra_id: RostraId,
        kind: EventKind,
        aux_key: EventAuxKey,
    ) -> Option<ShortEventId> {
        self.read_with(|tx| {
            let singletons_table = tx.open_table(&events_singletons_new::TABLE)?;

            Ok(singletons_table
                .get(&(rostra_id, kind, aux_key))?
                .map(|record| record.value().inner.event_id))
        })
        .await
        .expect("Database panic")
    }

    /// Returns an identity's singleton winners for one event kind in descending
    /// `(timestamp, ShortEventId)` order.
    pub async fn get_latest_singleton_events(
        &self,
        rostra_id: RostraId,
        kind: EventKind,
    ) -> Vec<ShortEventId> {
        self.read_with(|tx| {
            let singletons = tx.open_table(&events_singletons_new::TABLE)?;
            let start = (rostra_id, kind, EventAuxKey::ZERO);
            let end = (rostra_id, kind, EventAuxKey::MAX);
            let mut events = singletons
                .range(start..=end)?
                .map(|entry| {
                    let (_, value) = entry?;
                    let value = value.value();
                    Ok((value.ts, value.inner.event_id))
                })
                .collect::<DbResult<Vec<_>>>()?;
            events.sort_unstable_by_key(|event| std::cmp::Reverse(*event));
            Ok(events.into_iter().map(|(_, event_id)| event_id).collect())
        })
        .await
        .expect("Database panic")
    }

    pub async fn get_id_endpoints(
        &self,
        id: RostraId,
    ) -> BTreeMap<(Timestamp, IrohNodeId), IrohNodeRecord> {
        self.write_with(|tx| {
            let mut table = tx.open_table(&ids_nodes::TABLE)?;

            Self::get_id_endpoints_tx(id, &mut table)
        })
        .await
        .expect("Database panic")
    }

    /// Register an iroh node endpoint for an identity.
    ///
    /// Useful for test setups where peer node addresses need to be manually
    /// registered.
    pub async fn insert_id_node(&self, id: RostraId, node_id: IrohNodeId, ts: Timestamp) {
        self.write_with(|tx| {
            let mut table = tx.open_table(&ids_nodes::TABLE)?;
            table.insert(
                &(id, node_id),
                &IrohNodeRecord {
                    announcement_ts: ts,
                    stats: Default::default(),
                },
            )?;
            Ok(())
        })
        .await
        .expect("Database panic")
    }

    /// Get events for an identity, sorted by timestamp (most recent first).
    ///
    /// Returns a vector of (EventRecord, Timestamp, EventContentState
    /// option) limited to the specified count.
    pub async fn get_events_for_id(
        &self,
        id: RostraId,
        limit: usize,
    ) -> Vec<(event::EventRecord, Timestamp, Option<EventContentState>)> {
        self.read_with(|tx| {
            let events_table = tx.open_table(&events::TABLE)?;
            let events_by_time_table = tx.open_table(&events_by_time::TABLE)?;
            let events_content_state_table = tx.open_table(&events_content_state::TABLE)?;

            let mut results = Vec::new();

            // Iterate events_by_time in reverse (newest first)
            for entry in events_by_time_table.range(..)?.rev() {
                if limit <= results.len() {
                    break;
                }

                let entry = entry?;
                let (ts, event_id) = entry.0.value();

                // Get the event record
                let Some(event_record) = events_table.get(&event_id)?.map(|g| g.value()) else {
                    continue;
                };

                // Check if this event belongs to the requested identity
                if event_record.signed.event.author != id {
                    continue;
                }

                // Get content state if available
                let content_state = events_content_state_table
                    .get(&event_id)?
                    .map(|g| g.value());

                results.push((event_record, ts, content_state));
            }

            Ok(results)
        })
        .await
        .expect("Database panic")
    }

    /// Get all identities that have authored retained events.
    pub async fn get_known_identities(&self) -> Vec<RostraId> {
        self.read_with(ids_full::read_all)
            .await
            .expect("Database panic")
    }
}

fn get_first_in_range<K, V>(
    events_table: &impl ReadableTable<K, V>,
    range: impl ops::RangeBounds<K>,
) -> Result<Option<K>, DbError>
where
    K: bincode::Decode<()> + bincode::Encode,
    V: bincode::Decode<()> + bincode::Encode,
{
    Ok(events_table
        .range(range)?
        .next()
        .transpose()?
        .map(|(k, _)| k.value()))
}

fn get_last_in_range<K, V>(
    events_table: &impl ReadableTable<K, V>,
    range: impl ops::RangeBounds<K>,
) -> Result<Option<K>, DbError>
where
    K: bincode::Decode<()> + bincode::Encode,
    V: bincode::Decode<()> + bincode::Encode,
{
    Ok(events_table
        .range(range)?
        .next_back()
        .transpose()?
        .map(|(k, _)| k.value()))
}

#[derive(Debug, Clone)]
pub enum InsertEventOutcome {
    /// The event already existed, so graph, lifecycle, and projection state did
    /// not change.
    ///
    /// Identity registration is still validated and may restore an absent
    /// shortened/full mapping.
    AlreadyPresent,
    Inserted {
        /// An event already had a child reporting its existence.
        ///
        /// This also implies that the event can't be a "head event"
        /// as we already have a child of it.
        was_missing: bool,
        /// This event was already marked as deleted by some processed children
        /// event.
        ///
        /// This also implies that the event can't be a "head event"
        /// as we already have a child of it.
        is_deleted: bool,
        /// An existing parent event had its content marked as deleted by this
        /// event.
        ///
        /// Note, if the parent event was marked for deletion, but it was not
        /// processed yet, this will not be set, and instead `is_deleted` will
        /// be set to true, when the deleted parent is processed.
        deleted_parent: Option<ShortEventId>,
        /// Parent content to be reverted.
        ///
        /// If Some - deletion of the `deleted_parent` is cusing revertion of
        /// this content, which should be processed.
        reverted_parent_content: Option<EventContentRaw>,

        /// Ids of parents we don't have yet, so they are now marked
        /// as "missing".
        missing_parents: Vec<ShortEventId>,
    },
}

impl InsertEventOutcome {
    fn validate(self) -> Self {
        if let InsertEventOutcome::Inserted {
            deleted_parent,
            reverted_parent_content,
            ..
        } = &self
        {
            if reverted_parent_content.is_some() {
                assert!(deleted_parent.is_some());
            }
        }
        self
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ProcessEventState {
    New,
    Existing,
    Pruned,
    Deleted,
}

pub enum ContentWantState {
    Wants,
    MaybeWants,
    DoesNotWant,
}

impl ProcessEventState {
    pub fn wants_content(self) -> ContentWantState {
        match self {
            ProcessEventState::New => ContentWantState::Wants,
            ProcessEventState::Existing => ContentWantState::MaybeWants,
            ProcessEventState::Pruned => ContentWantState::DoesNotWant,
            ProcessEventState::Deleted => ContentWantState::DoesNotWant,
        }
    }
}
#[cfg(test)]
mod content_ingestion_tests;
#[cfg(test)]
mod deleted_replacement_tests;
#[cfg(test)]
mod follow_epoch_tests;
#[cfg(test)]
mod identity_collision_tests;
#[cfg(test)]
mod reception_order_tests;
#[cfg(test)]
mod social_post_projection_tests;
#[cfg(test)]
mod social_post_receipt_tests;
#[cfg(test)]
mod tests;