lenso-notification-plugin 0.1.0

Plugin-first transactional notification ledger for Lenso.
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
use chrono::{Duration, Utc};
use serde::Serialize;
use sqlx::postgres::PgPoolOptions;

use crate::contracts::{
    DispatchOutcome, EMAIL_DISPATCH_OBSERVED_EVENT, EMAIL_RECEIPT_OBSERVED_EVENT,
    EmailDispatchObserved, EmailReceiptObserved, ReceiptKind, RemoteReceiptSummary,
    SanitizedFailure,
};
use crate::domain::{DeliveryStatus, MAX_SAFE_WIRE_INTEGER};
use crate::error::ErrorCode;
use crate::events::{NotificationEventApplier, ObservationEnvelope};
use crate::operator::{NotificationOperator, NotificationOperatorError};
use crate::plugin::format_time;
use crate::public::{
    AccessRequestNotificationEvent, AccessRequestNotificationTemplateV1, AccessRequestRoleV1,
    AccessRequestScopeV1, CreateAccessRequestNotificationIntent, CreateTransactionalEmailIntent,
    EmailRecipient, IntentSource, OrganizationInvitationTemplateV1, RenderedTemplate,
    create_access_request_notification_in_tx, create_transactional_email_intent_in_tx,
    find_transactional_email_intent_replay,
};
use crate::repository::PostgresNotificationRepository;
use crate::runtime::claim_one_due;
use crate::snapshot::TestSnapshotProtector;

#[tokio::test]
async fn plugin_owned_delivery_ledger_is_atomic_append_only_and_fail_closed() {
    let database_url = std::env::var("LENSO_TEST_DATABASE_URL");
    let Ok(database_url) = database_url else {
        assert!(
            std::env::var_os("CI").is_none(),
            "CI requires LENSO_TEST_DATABASE_URL so Postgres acceptance cannot be skipped"
        );
        eprintln!("skipping Postgres acceptance: LENSO_TEST_DATABASE_URL is not configured");
        return;
    };
    let pool = PgPoolOptions::new()
        .max_connections(2)
        .connect(&database_url)
        .await
        .expect("connect test Postgres");
    let database_name: String = sqlx::query_scalar("select current_database()")
        .fetch_one(&pool)
        .await
        .expect("read test database name");
    assert!(
        database_name == "notification_test" || database_name.starts_with("notification_test_"),
        "refusing destructive test setup against non-test database {database_name}"
    );

    let expanded_year: chrono::DateTime<Utc> =
        sqlx::query_scalar("select timestamptz '10000-01-01 00:00:00+00'")
            .fetch_one(&pool)
            .await
            .expect("read PostgreSQL expanded-year timestamp");
    assert!(
        format_time(expanded_year).is_err(),
        "PostgreSQL expanded years must fail before Capability projection"
    );

    assert_legacy_ledger_tamper_rejected(
        &pool,
        &database_url,
        "delete from platform.schema_migrations where name = 'notification/0001_create_notification_schema'",
    )
    .await;
    assert_legacy_ledger_tamper_rejected(
        &pool,
        &database_url,
        "update platform.schema_migrations set name = 'notification/0001_wrong' where name = 'notification/0001_create_notification_schema'",
    )
    .await;
    assert_legacy_ledger_tamper_rejected(
        &pool,
        &database_url,
        "alter table platform.schema_migrations alter column applied_at drop default",
    )
    .await;
    assert_legacy_ledger_tamper_rejected(
        &pool,
        &database_url,
        "grant select on platform.schema_migrations to public",
    )
    .await;
    assert_legacy_ledger_tamper_rejected(
        &pool,
        &database_url,
        "revoke usage on type platform.schema_migrations from public",
    )
    .await;
    assert_legacy_ledger_tamper_rejected(
        &pool,
        &database_url,
        "comment on table platform.schema_migrations is 'unexpected provenance override'",
    )
    .await;
    assert_legacy_ledger_tamper_rejected(
        &pool,
        &database_url,
        r#"
        create function platform.unexpected_ledger_trigger() returns trigger
        language plpgsql as $$ begin return new; end $$;
        create trigger unexpected_ledger_trigger
            before insert on platform.schema_migrations
            for each row execute function platform.unexpected_ledger_trigger();
        "#,
    )
    .await;
    assert_legacy_tamper_rejected(
        &pool,
        &database_url,
        "alter default privileges in schema platform grant select on tables to public",
    )
    .await;
    assert_legacy_tamper_rejected(
        &pool,
        &database_url,
        r#"
        alter table notification.deliveries
            drop constraint notification_delivery_status;
        alter table notification.deliveries
            add constraint notification_delivery_status check (
                status in ('queued', 'attempting', 'accepted', 'retry_scheduled',
                           'delivered', 'failed', 'notification.delivery_unknown')
            );
        "#,
    )
    .await;
    assert_legacy_tamper_rejected(
        &pool,
        &database_url,
        "alter table notification.deliveries alter column max_attempts set default 9",
    )
    .await;
    assert_legacy_tamper_rejected(
        &pool,
        &database_url,
        r#"
        alter table notification.deliveries
            drop constraint notification_delivery_channel;
        alter table notification.deliveries
            add constraint notification_delivery_channel check (channel in ('email', 'sms'));
        "#,
    )
    .await;
    assert_legacy_tamper_rejected(
        &pool,
        &database_url,
        r#"
        drop index notification.notification_deliveries_due_idx;
        create index notification_deliveries_due_idx
            on notification.deliveries (next_attempt_at, id)
            where status = 'queued';
        "#,
    )
    .await;
    assert_legacy_tamper_rejected(
        &pool,
        &database_url,
        r#"
        alter table notification.intents
            add constraint notification_extra_intent_check check (length(source_module) > 0)
        "#,
    )
    .await;
    assert_legacy_tamper_rejected(
        &pool,
        &database_url,
        "create index notification_extra_intents_idx on notification.intents (id, source_module)",
    )
    .await;
    assert_legacy_tamper_rejected(
        &pool,
        &database_url,
        "comment on column notification.intents.recipient_ciphertext is 'unsafe plaintext access'",
    )
    .await;
    assert_legacy_tamper_rejected(
        &pool,
        &database_url,
        "grant select (recipient_ciphertext) on notification.intents to public",
    )
    .await;
    assert_legacy_tamper_rejected(
        &pool,
        &database_url,
        "grant select on notification.intents to public",
    )
    .await;
    assert_legacy_tamper_rejected(
        &pool,
        &database_url,
        "grant usage on schema notification to public",
    )
    .await;
    assert_legacy_tamper_rejected(
        &pool,
        &database_url,
        r#"
        create function notification.unexpected_routine() returns integer
        language sql immutable as $$ select 1 $$
        "#,
    )
    .await;
    assert_legacy_tamper_rejected(
        &pool,
        &database_url,
        "alter table notification.intents set (fillfactor = 70)",
    )
    .await;
    assert_legacy_tamper_rejected(
        &pool,
        &database_url,
        "alter default privileges in schema notification grant select on tables to public",
    )
    .await;
    assert_legacy_tamper_rejected(
        &pool,
        &database_url,
        "create text search dictionary notification.unexpected_dictionary (template = simple)",
    )
    .await;
    assert_legacy_tamper_rejected(
        &pool,
        &database_url,
        "create statistics notification.unexpected_statistics on status, revision from notification.deliveries",
    )
    .await;
    assert_global_default_acl_tamper_rejected(&pool, &database_url).await;
    assert_legacy_publication_tamper_rejected(
        &pool,
        &database_url,
        "create publication notification_schema_publication for tables in schema notification",
        "notification_schema_publication",
    )
    .await;
    assert_legacy_publication_tamper_rejected(
        &pool,
        &database_url,
        "create publication notification_all_publication for all tables",
        "notification_all_publication",
    )
    .await;

    reset_legacy_schema(&pool).await;
    sqlx::query(
        r#"
        insert into notification.template_releases (
            id, template_id, version, locale, renderer_identity, template_digest, created_at
        ) values ('legacy-proof', 'legacy-proof', 'v1', 'en', 'legacy', $1, now())
        "#,
    )
    .bind(format!("sha256:{}", "c".repeat(64)))
    .execute(&pool)
    .await
    .expect("seed legacy row before adoption");

    let mut maintenance_guard = pool
        .begin()
        .await
        .expect("begin shared maintenance lock proof");
    sqlx::query(
        "select pg_advisory_xact_lock(hashtextextended(current_database() || ':lenso-maintenance', 0))",
    )
    .execute(maintenance_guard.as_mut())
    .await
    .expect("hold shared maintenance advisory key");
    assert!(
        tokio::time::timeout(
            std::time::Duration::from_millis(250),
            NotificationOperator::adopt_legacy(&database_url),
        )
        .await
        .is_err(),
        "legacy adoption must wait for the shared maintenance protocol key",
    );
    maintenance_guard
        .rollback()
        .await
        .expect("release shared maintenance advisory key");

    let adopted = NotificationOperator::adopt_legacy(&database_url)
        .await
        .expect("adopt exact legacy schema without rewriting data");
    assert_eq!(adopted.version, 1);
    let legacy_rows: i64 = sqlx::query_scalar(
        "select count(*) from notification.template_releases where id = 'legacy-proof'",
    )
    .fetch_one(&pool)
    .await
    .expect("verify adopted legacy data");
    assert_eq!(legacy_rows, 1);
    let unrelated_legacy_rows: i64 = sqlx::query_scalar(
        "select count(*) from platform.schema_migrations where name = 'other/0001_fixture'",
    )
    .fetch_one(&pool)
    .await
    .expect("verify unrelated legacy Host ledger rows are preserved");
    assert_eq!(unrelated_legacy_rows, 1);
    NotificationOperator::upgrade(&database_url)
        .await
        .expect("upgrade adopted legacy schema to current Plugin migrations");
    let prepared = NotificationOperator::connect(&database_url)
        .await
        .expect("managed schema must pass runtime preparation");
    assert_eq!(prepared.schema(), "notification");
    sqlx::raw_sql(
        r#"
        create table notification.post_adoption_extra (id bigint primary key);
        create function notification.post_adoption_extra_function() returns integer
        language sql immutable as $$ select 1 $$;
        "#,
    )
    .execute(&pool)
    .await
    .expect("simulate schema-local DDL after adoption");
    let managed_error = NotificationOperator::connect(&database_url)
        .await
        .expect_err("managed preparation must reject later catalog additions");
    assert!(matches!(
        managed_error,
        NotificationOperatorError::ManagedSchemaMismatch
    ));
    sqlx::raw_sql(
        r#"
        drop function notification.post_adoption_extra_function();
        drop table notification.post_adoption_extra;
        "#,
    )
    .execute(&pool)
    .await
    .expect("remove post-adoption DDL fixture");
    NotificationOperator::connect(&database_url)
        .await
        .expect("managed preparation recovers after exact catalog is restored");
    assert_managed_publication_tamper_rejected(
        &pool,
        &database_url,
        "create publication notification_schema_publication for tables in schema notification",
        "notification_schema_publication",
    )
    .await;
    assert_managed_publication_tamper_rejected(
        &pool,
        &database_url,
        "create publication notification_all_publication for all tables",
        "notification_all_publication",
    )
    .await;
    assert_managed_schema_tamper_rejected(
        &pool,
        &database_url,
        "create text search dictionary notification.unexpected_dictionary (template = simple)",
        "drop text search dictionary notification.unexpected_dictionary",
    )
    .await;
    assert_managed_schema_tamper_rejected(
        &pool,
        &database_url,
        "create statistics notification.unexpected_statistics on status, revision from notification.deliveries",
        "drop statistics notification.unexpected_statistics",
    )
    .await;
    truncate_notification_ledger(&pool).await;

    let now = Utc::now();
    let mut blue_request = invitation_request(now, "shared-blue");
    blue_request.source.module_id = "organization-blue".to_owned();
    blue_request.source.entity_id = "org_invite_shared".to_owned();
    blue_request.template.invitation_id = "org_invite_shared".to_owned();
    let mut blue_tx = pool.begin().await.expect("begin blue caller intent");
    let blue = create_transactional_email_intent_in_tx(
        &mut blue_tx,
        &blue_request,
        &invitation_render(&blue_request),
        now,
        &TestSnapshotProtector,
    )
    .await
    .expect("create blue caller intent");
    blue_tx.commit().await.expect("commit blue caller intent");

    let mut red_request = invitation_request(now, "shared-red");
    red_request.source.module_id = "organization-red".to_owned();
    red_request.source.entity_id = "org_invite_shared".to_owned();
    red_request.template.invitation_id = "org_invite_shared".to_owned();
    let mut red_tx = pool.begin().await.expect("begin red caller intent");
    let red = create_transactional_email_intent_in_tx(
        &mut red_tx,
        &red_request,
        &invitation_render(&red_request),
        now,
        &TestSnapshotProtector,
    )
    .await
    .expect("create red caller intent");
    red_tx.commit().await.expect("commit red caller intent");

    let lifecycle_at = now + Duration::seconds(1);
    NotificationEventApplier::new(pool.clone())
        .apply(&ObservationEnvelope {
            id: "obs_invitation_shared_blue".to_owned(),
            event_name: crate::contracts::ORGANIZATION_INVITATION_REVOKED_EVENT.to_owned(),
            event_version: 1,
            source_module: "organization-blue".to_owned(),
            aggregate_id: "org_invite_shared".to_owned(),
            occurred_at: lifecycle_at,
            payload: serde_json::to_value(crate::contracts::OrganizationInvitationLifecycle {
                invitation_id: "org_invite_shared".to_owned(),
                organization_id: "org_test".to_owned(),
                observed_at: lifecycle_at,
            })
            .expect("encode caller-scoped lifecycle"),
        })
        .await
        .expect("apply caller-scoped lifecycle");
    let scoped_repository = PostgresNotificationRepository::from_pool(pool.clone());
    let blue_detail = scoped_repository
        .get_delivery(&blue.delivery_id)
        .await
        .expect("load blue caller delivery")
        .expect("blue caller delivery exists");
    let red_detail = scoped_repository
        .get_delivery(&red.delivery_id)
        .await
        .expect("load red caller delivery")
        .expect("red caller delivery exists");
    assert_eq!(blue_detail.delivery.status, "failed");
    assert_eq!(red_detail.delivery.status, "queued");
    let lifecycle_source: String = sqlx::query_scalar(
        "select source_module from notification.source_lifecycle_events where event_id = 'obs_invitation_shared_blue'",
    )
    .fetch_one(&pool)
    .await
    .expect("read caller-derived lifecycle source");
    assert_eq!(lifecycle_source, "organization-blue");

    NotificationEventApplier::new(pool.clone())
        .apply(&ObservationEnvelope {
            id: "obs_invitation_shared_red_expired".to_owned(),
            event_name: crate::contracts::ORGANIZATION_INVITATION_EXPIRED_EVENT.to_owned(),
            event_version: 1,
            source_module: "organization-red".to_owned(),
            aggregate_id: "org_invite_shared".to_owned(),
            occurred_at: lifecycle_at,
            payload: serde_json::to_value(crate::contracts::OrganizationInvitationLifecycle {
                invitation_id: "org_invite_shared".to_owned(),
                organization_id: "org_test".to_owned(),
                observed_at: lifecycle_at,
            })
            .expect("encode expired caller-scoped lifecycle"),
        })
        .await
        .expect("apply expired caller-scoped lifecycle");
    let red_after_expiry = scoped_repository
        .get_delivery(&red.delivery_id)
        .await
        .expect("load expired red caller delivery")
        .expect("expired red caller delivery exists");
    assert_eq!(red_after_expiry.delivery.status, "failed");
    let expired_lifecycle: String = sqlx::query_scalar(
        "select lifecycle from notification.source_lifecycle_events where event_id = 'obs_invitation_shared_red_expired'",
    )
    .fetch_one(&pool)
    .await
    .expect("read expired lifecycle");
    assert_eq!(expired_lifecycle, "expired");

    truncate_notification_ledger(&pool).await;
    let access_request =
        access_request_notification(now, AccessRequestNotificationEvent::Submitted);
    let mut access_tx = pool.begin().await.expect("begin access-request intent");
    let access_receipt = create_access_request_notification_in_tx(
        &mut access_tx,
        &access_request,
        &access_request_render(&access_request),
        now,
        &TestSnapshotProtector,
    )
    .await
    .expect("create access-request intent");
    access_tx
        .commit()
        .await
        .expect("commit access-request intent");
    assert!(!access_receipt.idempotent_replay);

    let restarted_pool = PgPoolOptions::new()
        .max_connections(2)
        .connect(&database_url)
        .await
        .expect("restart Notification connection for access-request replay");
    let mut access_replay_tx = restarted_pool
        .begin()
        .await
        .expect("begin restarted access-request replay");
    let access_replay = create_access_request_notification_in_tx(
        &mut access_replay_tx,
        &access_request,
        &access_request_render(&access_request),
        now,
        &TestSnapshotProtector,
    )
    .await
    .expect("replay access-request intent after restart");
    access_replay_tx
        .commit()
        .await
        .expect("commit restarted access-request replay");
    assert!(access_replay.idempotent_replay);
    assert_eq!(access_replay.intent_id, access_receipt.intent_id);

    let mut changed_access_request = access_request.clone();
    changed_access_request.template.role.display_name = Some("Owner".to_owned());
    let mut access_conflict_tx = restarted_pool
        .begin()
        .await
        .expect("begin access-request conflict");
    let access_conflict = create_access_request_notification_in_tx(
        &mut access_conflict_tx,
        &changed_access_request,
        &access_request_render(&changed_access_request),
        now,
        &TestSnapshotProtector,
    )
    .await
    .expect_err("same request/event with changed display input must conflict");
    assert_eq!(access_conflict.code, ErrorCode::Conflict);
    access_conflict_tx
        .rollback()
        .await
        .expect("rollback access-request conflict");

    let approved = access_request_notification(now, AccessRequestNotificationEvent::Approved);
    let mut approved_tx = restarted_pool
        .begin()
        .await
        .expect("begin approved access-request intent");
    let approved_receipt = create_access_request_notification_in_tx(
        &mut approved_tx,
        &approved,
        &access_request_render(&approved),
        now,
        &TestSnapshotProtector,
    )
    .await
    .expect("create distinct approved access-request intent");
    approved_tx
        .commit()
        .await
        .expect("commit approved access-request intent");
    assert_ne!(approved_receipt.intent_id, access_receipt.intent_id);
    let access_purposes: i64 = sqlx::query_scalar(
        "select count(*) from notification.intents where purpose='transactional.access_request' and source_entity_id='ar_notification_1'",
    )
    .fetch_one(&restarted_pool)
    .await
    .expect("count durable access-request intents");
    assert_eq!(access_purposes, 2);
    let templates: Vec<String> = sqlx::query_scalar(
        "select template_id from notification.template_releases where template_id like 'access-request-%' order by template_id",
    )
    .fetch_all(&restarted_pool)
    .await
    .expect("read access-request template releases");
    assert_eq!(
        templates,
        vec![
            "access-request-approved".to_owned(),
            "access-request-submitted".to_owned(),
        ]
    );
    restarted_pool.close().await;

    truncate_notification_ledger(&pool).await;
    let request = invitation_request(now, "primary");
    let mut first_tx = pool.begin().await.expect("begin intent transaction");
    let first = create_transactional_email_intent_in_tx(
        &mut first_tx,
        &request,
        &invitation_render(&request),
        now,
        &TestSnapshotProtector,
    )
    .await
    .expect("create intent");
    first_tx.commit().await.expect("commit intent");
    assert_eq!(first.status, DeliveryStatus::Queued);
    assert!(!first.idempotent_replay);
    let fast_replay = find_transactional_email_intent_replay(&pool, &request, now)
        .await
        .expect("read committed replay without rendering")
        .expect("committed replay exists");
    assert_eq!(fast_replay.intent_id, first.intent_id);
    assert!(fast_replay.idempotent_replay);

    let mut replay_tx = pool.begin().await.expect("begin replay transaction");
    let replay = create_transactional_email_intent_in_tx(
        &mut replay_tx,
        &request,
        &invitation_render(&request),
        now,
        &TestSnapshotProtector,
    )
    .await
    .expect("replay intent");
    replay_tx.commit().await.expect("commit replay");
    assert_eq!(replay.intent_id, first.intent_id);
    assert_eq!(replay.delivery_id, first.delivery_id);
    assert!(replay.idempotent_replay);

    let mut changed = request.clone();
    changed.recipient.address = "different@example.com".to_owned();
    let fast_conflict = find_transactional_email_intent_replay(&pool, &changed, now)
        .await
        .expect_err("changed input must conflict before rendering");
    assert_eq!(fast_conflict.code, ErrorCode::Conflict);
    let mut conflict_tx = pool.begin().await.expect("begin conflict transaction");
    let conflict = create_transactional_email_intent_in_tx(
        &mut conflict_tx,
        &changed,
        &invitation_render(&changed),
        now,
        &TestSnapshotProtector,
    )
    .await
    .expect_err("same key with changed input must conflict");
    assert_eq!(conflict.code, ErrorCode::Conflict);
    conflict_tx.rollback().await.expect("rollback conflict");

    let leaked: i64 = sqlx::query_scalar(
        r#"
        select count(*)
        from notification.intents intents
        join notification.render_snapshots snapshots on snapshots.id = intents.snapshot_id
        where intents.recipient_ciphertext like '%member@example.com%'
           or snapshots.text_ciphertext like '%secret-token%'
           or snapshots.html_ciphertext like '%secret-token%'
        "#,
    )
    .fetch_one(&pool)
    .await
    .expect("scan protected columns");
    assert_eq!(leaked, 0);

    let first_work = claim_one_due(&pool, &TestSnapshotProtector, now)
        .await
        .expect("claim first attempt")
        .expect("queued delivery is due");
    assert_eq!(first_work.claim.delivery_id, first.delivery_id);
    assert_eq!(first_work.request.recipient.address, "member@example.com");
    assert!(
        first_work
            .request
            .message
            .text
            .contains("secret-token-primary")
    );
    let applier = NotificationEventApplier::new(pool.clone());
    let first_failed_at = now + Duration::seconds(1);
    let temporary_failure = EmailDispatchObserved {
        delivery_id: first.delivery_id.clone(),
        attempt_id: first_work.claim.attempt_id.clone(),
        function_run_id: first_work.claim.run_id.clone(),
        outcome: DispatchOutcome::TemporaryFailure,
        provider: "fixture.email-dispatch".to_owned(),
        observed_at: first_failed_at,
        remote_receipt: None,
        failure: Some(SanitizedFailure {
            code: "provider_rate_limited".to_owned(),
            classification: "temporary_failure".to_owned(),
            retry_after_ms: Some(120_000),
        }),
    };
    let failed = event(
        "obs_dispatch_failed_primary",
        EMAIL_DISPATCH_OBSERVED_EVENT,
        &temporary_failure,
        first_failed_at,
    );
    applier.apply(&failed).await.expect("schedule retry");
    applier
        .apply(&failed)
        .await
        .expect("replay observation idempotently");
    assert!(
        claim_one_due(
            &pool,
            &TestSnapshotProtector,
            first_failed_at + Duration::seconds(119),
        )
        .await
        .expect("check retry-after")
        .is_none(),
        "provider retry-after must prevent an early automatic retry"
    );

    let repository = PostgresNotificationRepository::from_pool(pool.clone());
    let scheduled = repository
        .get_delivery(&first.delivery_id)
        .await
        .expect("load retry candidate")
        .expect("delivery exists");
    assert_eq!(scheduled.delivery.status, "retry_scheduled");
    let manual_retry_at = first_failed_at + Duration::seconds(2);
    let retry = repository
        .request_manual_retry(
            &first.delivery_id,
            scheduled.delivery.revision,
            "manual-retry-primary",
            "operator-fixture",
            manual_retry_at,
        )
        .await
        .expect("schedule explicit manual retry");
    assert!(!retry.idempotent_replay);
    let retry_replay = repository
        .request_manual_retry(
            &first.delivery_id,
            scheduled.delivery.revision,
            "manual-retry-primary",
            "operator-fixture",
            manual_retry_at,
        )
        .await
        .expect("replay manual retry request");
    assert!(retry_replay.idempotent_replay);

    let second_work = claim_one_due(&pool, &TestSnapshotProtector, manual_retry_at)
        .await
        .expect("claim manually scheduled attempt")
        .expect("manual retry is due");
    assert_ne!(second_work.claim.attempt_id, first_work.claim.attempt_id);
    let accepted_at = manual_retry_at + Duration::seconds(1);
    applier
        .apply(&event(
            "obs_dispatch_accepted_primary",
            EMAIL_DISPATCH_OBSERVED_EVENT,
            &EmailDispatchObserved {
                delivery_id: first.delivery_id.clone(),
                attempt_id: second_work.claim.attempt_id.clone(),
                function_run_id: second_work.claim.run_id.clone(),
                outcome: DispatchOutcome::Accepted,
                provider: "fixture.email-dispatch".to_owned(),
                observed_at: accepted_at,
                remote_receipt: Some(RemoteReceiptSummary {
                    source: "fixture.email-dispatch".to_owned(),
                    remote_id: "remote-primary".to_owned(),
                    digest: format!("sha256:{}", "b".repeat(64)),
                }),
                failure: None,
            },
            accepted_at,
        ))
        .await
        .expect("record provider acceptance");
    let delivered_at = accepted_at + Duration::seconds(1);
    applier
        .apply(&event(
            "obs_receipt_delivered_primary",
            EMAIL_RECEIPT_OBSERVED_EVENT,
            &EmailReceiptObserved {
                delivery_id: first.delivery_id.clone(),
                attempt_id: second_work.claim.attempt_id.clone(),
                function_run_id: second_work.claim.run_id.clone(),
                kind: ReceiptKind::Delivered,
                source: "fixture.email-dispatch".to_owned(),
                observed_at: delivered_at,
                remote_id: "remote-primary".to_owned(),
                digest: format!("sha256:{}", "a".repeat(64)),
            },
            delivered_at,
        ))
        .await
        .expect("record authoritative delivery receipt");
    let delivered = repository
        .get_delivery(&first.delivery_id)
        .await
        .expect("load delivered state")
        .expect("delivery exists");
    assert_eq!(delivered.delivery.status, "delivered");
    assert_eq!(delivered.attempts.len(), 2);
    assert_eq!(delivered.receipts.len(), 2);
    assert_eq!(delivered.retry_requests.len(), 2);
    let redacted = serde_json::to_string(&delivered).expect("serialize redacted projection");
    assert!(!redacted.contains("member@example.com"));
    assert!(!redacted.contains("secret-token"));

    let unknown_request = invitation_request(delivered_at + Duration::seconds(1), "unknown");
    let mut unknown_tx = pool
        .begin()
        .await
        .expect("begin unknown intent transaction");
    let unknown = create_transactional_email_intent_in_tx(
        &mut unknown_tx,
        &unknown_request,
        &invitation_render(&unknown_request),
        delivered_at + Duration::seconds(1),
        &TestSnapshotProtector,
    )
    .await
    .expect("create ambiguous-effect intent");
    unknown_tx.commit().await.expect("commit unknown intent");
    let unknown_work = claim_one_due(
        &pool,
        &TestSnapshotProtector,
        delivered_at + Duration::seconds(1),
    )
    .await
    .expect("claim ambiguous-effect attempt")
    .expect("second delivery is due");
    let unknown_at = delivered_at + Duration::seconds(2);
    applier
        .apply(&event(
            "obs_dispatch_unknown",
            EMAIL_DISPATCH_OBSERVED_EVENT,
            &EmailDispatchObserved {
                delivery_id: unknown.delivery_id.clone(),
                attempt_id: unknown_work.claim.attempt_id,
                function_run_id: unknown_work.claim.run_id,
                outcome: DispatchOutcome::DeliveryUnknown,
                provider: "fixture.email-dispatch".to_owned(),
                observed_at: unknown_at,
                remote_receipt: None,
                failure: Some(SanitizedFailure {
                    code: "provider_result_ambiguous".to_owned(),
                    classification: "delivery_unknown".to_owned(),
                    retry_after_ms: None,
                }),
            },
            unknown_at,
        ))
        .await
        .expect("record ambiguous external effect");
    let terminal = repository
        .get_delivery(&unknown.delivery_id)
        .await
        .expect("load terminal delivery")
        .expect("delivery exists");
    assert_eq!(terminal.delivery.status, "delivery_unknown");
    assert_eq!(terminal.attempts.len(), 1);
    assert!(terminal.receipts.is_empty());
    assert!(
        claim_one_due(
            &pool,
            &TestSnapshotProtector,
            unknown_at + Duration::hours(1),
        )
        .await
        .expect("check terminal eligibility")
        .is_none(),
        "delivery_unknown must never be retried automatically"
    );

    sqlx::query(
        r#"
        insert into notification.receipts (
            id, delivery_id, attempt_id, kind, source, remote_id, digest,
            observed_at, recorded_at
        )
        select 'overflow_receipt_' || sequence, $1, $2, 'accepted',
               'overflow-fixture', 'overflow-remote-' || sequence, $3, $4, $4
        from generate_series(1, 999) as sequence
        "#,
    )
    .bind(&first.delivery_id)
    .bind(&second_work.claim.attempt_id)
    .bind(format!("sha256:{}", "d".repeat(64)))
    .bind(unknown_at)
    .execute(&pool)
    .await
    .expect("seed evidence just beyond the bounded Admin projection");
    let overflow = repository
        .get_delivery(&first.delivery_id)
        .await
        .expect_err("detail projection must reject rather than truncate evidence");
    assert_eq!(overflow.code, ErrorCode::EvidenceOverflow);

    assert_revision_overflow_paths_fail_closed(&pool).await;
}

async fn assert_revision_overflow_paths_fail_closed(pool: &sqlx::PgPool) {
    truncate_notification_ledger(pool).await;
    let now = Utc::now();

    let claim_delivery = seed_intent(pool, now, "revision-claim").await;
    sqlx::query("update notification.deliveries set revision = $2 where id = $1")
        .bind(&claim_delivery)
        .bind(MAX_SAFE_WIRE_INTEGER)
        .execute(pool)
        .await
        .expect("seed exhausted claim revision");
    let claim_error = claim_one_due(pool, &TestSnapshotProtector, now)
        .await
        .expect_err("dispatch claim must reject an exhausted portable revision");
    assert_eq!(claim_error.code, ErrorCode::Conflict);
    let claim_state: (String, i64, i64) = sqlx::query_as(
        r#"
        select deliveries.status, deliveries.revision,
               (select count(*) from notification.attempts attempts where attempts.delivery_id = deliveries.id)
        from notification.deliveries deliveries where deliveries.id = $1
        "#,
    )
    .bind(&claim_delivery)
    .fetch_one(pool)
    .await
    .expect("read fail-closed claim state");
    assert_eq!(claim_state, ("queued".to_owned(), MAX_SAFE_WIRE_INTEGER, 0));

    truncate_notification_ledger(pool).await;

    let observed_delivery = seed_intent(pool, now, "revision-observation").await;
    let work = claim_one_due(pool, &TestSnapshotProtector, now)
        .await
        .expect("claim observation fixture")
        .expect("observation fixture is due");
    assert_eq!(work.claim.delivery_id, observed_delivery);
    sqlx::query("update notification.deliveries set revision = $2 where id = $1")
        .bind(&observed_delivery)
        .bind(MAX_SAFE_WIRE_INTEGER)
        .execute(pool)
        .await
        .expect("seed exhausted observation revision");
    let applier = NotificationEventApplier::new(pool.clone());
    let dispatch_id = "obs_revision_dispatch";
    let dispatch_error = applier
        .apply(&event(
            dispatch_id,
            EMAIL_DISPATCH_OBSERVED_EVENT,
            &EmailDispatchObserved {
                delivery_id: observed_delivery.clone(),
                attempt_id: work.claim.attempt_id.clone(),
                function_run_id: work.claim.run_id.clone(),
                outcome: DispatchOutcome::Accepted,
                provider: "fixture.email-dispatch".to_owned(),
                observed_at: now,
                remote_receipt: None,
                failure: None,
            },
            now,
        ))
        .await
        .expect_err("dispatch observation must reject an exhausted portable revision");
    assert_eq!(dispatch_error.code, ErrorCode::Conflict);

    let receipt_id = "obs_revision_receipt";
    let receipt_error = applier
        .apply(&event(
            receipt_id,
            EMAIL_RECEIPT_OBSERVED_EVENT,
            &EmailReceiptObserved {
                delivery_id: observed_delivery.clone(),
                attempt_id: work.claim.attempt_id.clone(),
                function_run_id: work.claim.run_id,
                kind: ReceiptKind::Delivered,
                source: "fixture.email-dispatch".to_owned(),
                observed_at: now,
                remote_id: "remote-revision".to_owned(),
                digest: format!("sha256:{}", "a".repeat(64)),
            },
            now,
        ))
        .await
        .expect_err("receipt observation must reject an exhausted portable revision");
    assert_eq!(receipt_error.code, ErrorCode::Conflict);
    let observation_state: (String, i64, String, i64, i64) = sqlx::query_as(
        r#"
        select deliveries.status, deliveries.revision, attempts.status,
               (select count(*) from notification.receipts receipts where receipts.delivery_id = deliveries.id),
               (select count(*) from notification.consumed_events consumed where consumed.event_id in ($3, $4))
        from notification.deliveries deliveries
        join notification.attempts attempts on attempts.delivery_id = deliveries.id
        where deliveries.id = $1 and attempts.id = $2
        "#,
    )
    .bind(&observed_delivery)
    .bind(&work.claim.attempt_id)
    .bind(dispatch_id)
    .bind(receipt_id)
    .fetch_one(pool)
    .await
    .expect("read fail-closed observation state");
    assert_eq!(
        observation_state,
        (
            "attempting".to_owned(),
            MAX_SAFE_WIRE_INTEGER,
            "dispatching".to_owned(),
            0,
            0,
        )
    );

    truncate_notification_ledger(pool).await;

    let lifecycle_delivery = seed_intent(pool, now, "revision-lifecycle").await;
    sqlx::query("update notification.deliveries set revision = $2 where id = $1")
        .bind(&lifecycle_delivery)
        .bind(MAX_SAFE_WIRE_INTEGER)
        .execute(pool)
        .await
        .expect("seed exhausted lifecycle revision");
    let lifecycle_id = "obs_revision_lifecycle";
    let lifecycle_error = applier
        .apply(&ObservationEnvelope {
            id: lifecycle_id.to_owned(),
            event_name: crate::contracts::ORGANIZATION_INVITATION_REVOKED_EVENT.to_owned(),
            event_version: 1,
            source_module: "organization".to_owned(),
            aggregate_id: "org_invite_revision-lifecycle".to_owned(),
            occurred_at: now,
            payload: serde_json::to_value(crate::contracts::OrganizationInvitationLifecycle {
                invitation_id: "org_invite_revision-lifecycle".to_owned(),
                organization_id: "org_test".to_owned(),
                observed_at: now,
            })
            .expect("encode exhausted lifecycle fixture"),
        })
        .await
        .expect_err("lifecycle observation must reject an exhausted portable revision");
    assert_eq!(lifecycle_error.code, ErrorCode::Conflict);
    let lifecycle_state: (String, i64, i64, i64) = sqlx::query_as(
        r#"
        select deliveries.status, deliveries.revision,
               (select count(*) from notification.source_lifecycle_events events where events.event_id = $2),
               (select count(*) from notification.consumed_events consumed where consumed.event_id = $2)
        from notification.deliveries deliveries where deliveries.id = $1
        "#,
    )
    .bind(&lifecycle_delivery)
    .bind(lifecycle_id)
    .fetch_one(pool)
    .await
    .expect("read fail-closed lifecycle state");
    assert_eq!(
        lifecycle_state,
        ("queued".to_owned(), MAX_SAFE_WIRE_INTEGER, 0, 0)
    );

    truncate_notification_ledger(pool).await;

    let retry_delivery = seed_intent(pool, now, "revision-manual").await;
    sqlx::query(
        "update notification.deliveries set status = 'retry_scheduled', revision = $2 where id = $1",
    )
    .bind(&retry_delivery)
    .bind(MAX_SAFE_WIRE_INTEGER)
    .execute(pool)
    .await
    .expect("seed exhausted manual-retry revision");
    let retry_error = PostgresNotificationRepository::from_pool(pool.clone())
        .request_manual_retry(
            &retry_delivery,
            MAX_SAFE_WIRE_INTEGER,
            "retry-revision-overflow",
            "console-blue",
            now,
        )
        .await
        .expect_err("manual retry must reject an exhausted portable revision");
    assert_eq!(retry_error.code, ErrorCode::Conflict);
    let retry_state: (i64, i64) = sqlx::query_as(
        r#"
        select deliveries.revision,
               (select count(*) from notification.retry_requests retries where retries.delivery_id = deliveries.id)
        from notification.deliveries deliveries where deliveries.id = $1
        "#,
    )
    .bind(&retry_delivery)
    .fetch_one(pool)
    .await
    .expect("read fail-closed manual-retry state");
    assert_eq!(retry_state, (MAX_SAFE_WIRE_INTEGER, 0));
}

async fn seed_intent(pool: &sqlx::PgPool, now: chrono::DateTime<Utc>, suffix: &str) -> String {
    let request = invitation_request(now, suffix);
    let mut transaction = pool.begin().await.expect("begin revision fixture intent");
    let receipt = create_transactional_email_intent_in_tx(
        &mut transaction,
        &request,
        &invitation_render(&request),
        now,
        &TestSnapshotProtector,
    )
    .await
    .expect("create revision fixture intent");
    transaction
        .commit()
        .await
        .expect("commit revision fixture intent");
    receipt.delivery_id
}

async fn assert_legacy_tamper_rejected(
    pool: &sqlx::PgPool,
    database_url: &str,
    tamper_sql: &'static str,
) {
    reset_legacy_schema(pool).await;
    sqlx::raw_sql(tamper_sql)
        .execute(pool)
        .await
        .expect("tamper legacy schema fixture");
    let error = NotificationOperator::adopt_legacy(database_url)
        .await
        .expect_err("tampered or extended legacy schema must not be adopted");
    assert!(
        matches!(error, NotificationOperatorError::LegacySchemaMismatch),
        "unexpected legacy adoption error: {error}"
    );
    let ledger_exists: bool = sqlx::query_scalar(
        r#"
        select exists (
            select 1
            from pg_class relations
            join pg_namespace namespaces on namespaces.oid = relations.relnamespace
            where namespaces.nspname = 'notification'
              and relations.relname = '_lenso_schema_migrations'
        )
        "#,
    )
    .fetch_one(pool)
    .await
    .expect("check failed adoption did not create a ledger");
    assert!(!ledger_exists);
}

async fn assert_legacy_ledger_tamper_rejected(
    pool: &sqlx::PgPool,
    database_url: &str,
    tamper_sql: &'static str,
) {
    reset_legacy_schema(pool).await;
    sqlx::raw_sql(tamper_sql)
        .execute(pool)
        .await
        .expect("tamper legacy Host migration ledger fixture");
    let error = NotificationOperator::adopt_legacy(database_url)
        .await
        .expect_err("missing, wrong, or malformed legacy Host evidence must not be adopted");
    assert!(
        matches!(error, NotificationOperatorError::LegacyHostLedgerMismatch),
        "unexpected legacy adoption error: {error}"
    );
}

async fn assert_global_default_acl_tamper_rejected(pool: &sqlx::PgPool, database_url: &str) {
    reset_legacy_schema(pool).await;
    sqlx::query("alter default privileges revoke execute on functions from public")
        .execute(pool)
        .await
        .expect("tamper global function default privileges");
    let error = NotificationOperator::adopt_legacy(database_url)
        .await
        .expect_err("global default privileges must prevent legacy adoption");
    assert!(
        matches!(error, NotificationOperatorError::LegacySchemaMismatch),
        "unexpected legacy adoption error: {error}"
    );
    sqlx::query("alter default privileges grant execute on functions to public")
        .execute(pool)
        .await
        .expect("restore global function default privileges");
}

async fn assert_legacy_publication_tamper_rejected(
    pool: &sqlx::PgPool,
    database_url: &str,
    tamper_sql: &'static str,
    publication: &'static str,
) {
    reset_legacy_schema(pool).await;
    sqlx::query(tamper_sql)
        .execute(pool)
        .await
        .expect("publish legacy Notification schema fixture");
    let error = NotificationOperator::adopt_legacy(database_url)
        .await
        .expect_err("implicit publication scope must prevent legacy adoption");
    assert!(
        matches!(error, NotificationOperatorError::LegacySchemaMismatch),
        "unexpected legacy publication error: {error}"
    );
    sqlx::query(publication_drop_sql(publication))
        .execute(pool)
        .await
        .expect("remove legacy publication fixture");
}

async fn assert_managed_publication_tamper_rejected(
    pool: &sqlx::PgPool,
    database_url: &str,
    tamper_sql: &'static str,
    publication: &'static str,
) {
    sqlx::query(tamper_sql)
        .execute(pool)
        .await
        .expect("publish managed Notification schema fixture");
    let error = NotificationOperator::connect(database_url)
        .await
        .expect_err("implicit publication scope must prevent managed preparation");
    assert!(matches!(
        error,
        NotificationOperatorError::ManagedSchemaMismatch
    ));
    sqlx::query(publication_drop_sql(publication))
        .execute(pool)
        .await
        .expect("remove managed publication fixture");
    NotificationOperator::connect(database_url)
        .await
        .expect("managed preparation recovers after publication removal");
}

async fn assert_managed_schema_tamper_rejected(
    pool: &sqlx::PgPool,
    database_url: &str,
    tamper_sql: &'static str,
    restore_sql: &'static str,
) {
    sqlx::query(tamper_sql)
        .execute(pool)
        .await
        .expect("add unsupported managed schema object");
    let error = NotificationOperator::connect(database_url)
        .await
        .expect_err("unsupported schema object must prevent managed preparation");
    assert!(matches!(
        error,
        NotificationOperatorError::ManagedSchemaMismatch
    ));
    sqlx::query(restore_sql)
        .execute(pool)
        .await
        .expect("remove unsupported managed schema object");
    NotificationOperator::connect(database_url)
        .await
        .expect("managed preparation recovers after unsupported object removal");
}

fn publication_drop_sql(publication: &str) -> &'static str {
    match publication {
        "notification_schema_publication" => "drop publication notification_schema_publication",
        "notification_all_publication" => "drop publication notification_all_publication",
        _ => panic!("unknown fixed publication fixture"),
    }
}

async fn reset_legacy_schema(pool: &sqlx::PgPool) {
    sqlx::raw_sql(
        "drop publication if exists notification_schema_publication; drop publication if exists notification_all_publication;",
    )
    .execute(pool)
    .await
    .expect("remove stale publication fixtures");
    sqlx::query("drop schema if exists notification cascade")
        .execute(pool)
        .await
        .expect("reset dedicated Notification test schema");
    sqlx::raw_sql(include_str!(
        "../migrations/0001_create_notification_schema.sql"
    ))
    .execute(pool)
    .await
    .expect("apply immutable Notification migration");
    sqlx::raw_sql(
        r#"
        drop schema if exists platform cascade;
        create schema platform;
        create table platform.schema_migrations (
            name text primary key,
            applied_at timestamptz not null default now()
        );
        insert into platform.schema_migrations (name) values
            ('notification/0001_create_notification_schema'),
            ('other/0001_fixture');
        "#,
    )
    .execute(pool)
    .await
    .expect("create legacy Host migration ledger fixture");
}

async fn truncate_notification_ledger(pool: &sqlx::PgPool) {
    sqlx::raw_sql(
        r#"
        truncate table notification.source_lifecycle_events, notification.consumed_events,
            notification.retry_requests, notification.receipts, notification.attempts,
            notification.deliveries, notification.intents, notification.render_snapshots,
            notification.template_releases restart identity cascade
        "#,
    )
    .execute(pool)
    .await
    .expect("clean Notification schema");
}

fn event(
    id: &str,
    name: &str,
    payload: &impl Serialize,
    occurred_at: chrono::DateTime<Utc>,
) -> ObservationEnvelope {
    ObservationEnvelope {
        id: id.to_owned(),
        event_name: name.to_owned(),
        event_version: 1,
        source_module: "fixture.email-dispatch".to_owned(),
        aggregate_id: "notification-test".to_owned(),
        occurred_at,
        payload: serde_json::to_value(payload).expect("encode observation fixture"),
    }
}

fn invitation_request(now: chrono::DateTime<Utc>, suffix: &str) -> CreateTransactionalEmailIntent {
    CreateTransactionalEmailIntent {
        source: IntentSource {
            module_id: "organization".to_owned(),
            entity_type: "organization_invitation".to_owned(),
            entity_id: format!("org_invite_{suffix}"),
        },
        recipient: EmailRecipient {
            address: "member@example.com".to_owned(),
            display_name: None,
            locale: "en".to_owned(),
        },
        template: OrganizationInvitationTemplateV1 {
            organization_id: "org_test".to_owned(),
            organization_name: "Test Organization".to_owned(),
            invitation_id: format!("org_invite_{suffix}"),
            invitation_url: format!("https://example.test/invitations/secret-token-{suffix}"),
            inviter_display_name: Some("Operator".to_owned()),
            role_name: Some("Member".to_owned()),
            expires_at: now + Duration::days(1),
        },
        idempotency_key: format!("organization-invitation:org_invite_{suffix}"),
        correlation_id: format!("corr_notification_{suffix}"),
        causation_id: Some(format!("obs_invitation_{suffix}")),
        requested_by: Some("usr_test".to_owned()),
    }
}

fn access_request_notification(
    now: chrono::DateTime<Utc>,
    event: AccessRequestNotificationEvent,
) -> CreateAccessRequestNotificationIntent {
    let event_name = match event {
        AccessRequestNotificationEvent::Submitted => "submitted",
        AccessRequestNotificationEvent::Approved => "approved",
        AccessRequestNotificationEvent::Denied => "denied",
        AccessRequestNotificationEvent::Expiring => "expiring",
    };
    CreateAccessRequestNotificationIntent {
        source: IntentSource {
            module_id: "access-requests".to_owned(),
            entity_type: "access_request".to_owned(),
            entity_id: "ar_notification_1".to_owned(),
        },
        recipient: EmailRecipient {
            address: "requester@example.com".to_owned(),
            display_name: Some("Requester".to_owned()),
            locale: "en".to_owned(),
        },
        template: AccessRequestNotificationTemplateV1 {
            request_id: "ar_notification_1".to_owned(),
            organization_id: "org_test".to_owned(),
            event,
            role: AccessRequestRoleV1 {
                role_id: "role_member".to_owned(),
                display_name: Some("Member".to_owned()),
            },
            scope: AccessRequestScopeV1 {
                kind: "organization".to_owned(),
                id: "org_test".to_owned(),
                display_name: Some("Test Organization".to_owned()),
            },
            expires_at: Some(now + Duration::days(1)),
        },
        idempotency_key: format!("access-request:ar_notification_1:{event_name}"),
        correlation_id: "corr_access_request_notification_1".to_owned(),
        causation_id: Some(format!("access_request_notification_1:{event_name}")),
        requested_by: Some("usr_requester".to_owned()),
    }
}

fn invitation_render(request: &CreateTransactionalEmailIntent) -> RenderedTemplate {
    let subject = format!("Invitation to join {}", request.template.organization_name);
    let text = format!(
        "Accept invitation: {}\nExpires: {}",
        request.template.invitation_url,
        request.template.expires_at.to_rfc3339()
    );
    let html = format!(
        "<p><a href=\"{}\">Accept invitation</a></p>",
        request.template.invitation_url
    );
    RenderedTemplate {
        template_id: "organization-invitation".to_owned(),
        template_version: "v1".to_owned(),
        requested_locale: request.recipient.locale.clone(),
        resolved_locale: request.recipient.locale.clone(),
        fallback_used: false,
        renderer_identity: "lenso.notification-template.renderer/safe-sections@1".to_owned(),
        template_digest: format!("sha256:{}", "a".repeat(64)),
        content_digest: crate::snapshot::content_digest(&subject, &text, &html),
        subject,
        text,
        html,
    }
}

fn access_request_render(request: &CreateAccessRequestNotificationIntent) -> RenderedTemplate {
    let template_id = crate::public::access_request_template_id(request.template.event);
    let event = match request.template.event {
        AccessRequestNotificationEvent::Submitted => "submitted",
        AccessRequestNotificationEvent::Approved => "approved",
        AccessRequestNotificationEvent::Denied => "denied",
        AccessRequestNotificationEvent::Expiring => "expiring",
    };
    let subject = format!("Access request {event}");
    let text = format!("Request: {}", request.template.request_id);
    let html = format!("<p>Request: {}</p>", request.template.request_id);
    RenderedTemplate {
        template_id: template_id.to_owned(),
        template_version: "v1".to_owned(),
        requested_locale: request.recipient.locale.clone(),
        resolved_locale: request.recipient.locale.clone(),
        fallback_used: false,
        renderer_identity: "lenso.notification-template.renderer/safe-sections@1".to_owned(),
        template_digest: format!("sha256:{}", "b".repeat(64)),
        content_digest: crate::snapshot::content_digest(&subject, &text, &html),
        subject,
        text,
        html,
    }
}