miden-node-store 0.14.8

Miden node's state store component
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
//! Tests for the `accounts` module, specifically for account storage and historical queries.

use std::collections::BTreeMap;

use diesel::query_dsl::methods::SelectDsl;
use diesel::{
    BoolExpressionMethods,
    Connection,
    ExpressionMethods,
    OptionalExtension,
    QueryDsl,
    RunQueryDsl,
};
use diesel_migrations::MigrationHarness;
use miden_node_utils::fee::test_fee_params;
use miden_protocol::account::auth::{AuthScheme, PublicKeyCommitment};
use miden_protocol::account::component::AccountComponentMetadata;
use miden_protocol::account::delta::AccountUpdateDetails;
use miden_protocol::account::{
    Account,
    AccountBuilder,
    AccountComponent,
    AccountDelta,
    AccountId,
    AccountIdVersion,
    AccountStorage,
    AccountStorageDelta,
    AccountStorageHeader,
    AccountStorageMode,
    AccountType,
    AccountVaultDelta,
    StorageMap,
    StorageMapDelta,
    StorageMapKey,
    StorageSlot,
    StorageSlotContent,
    StorageSlotDelta,
    StorageSlotName,
    StorageSlotType,
};
use miden_protocol::block::{BlockAccountUpdate, BlockHeader, BlockNumber};
use miden_protocol::crypto::dsa::ecdsa_k256_keccak::SecretKey;
use miden_protocol::utils::serde::{Deserializable, Serializable};
use miden_protocol::{EMPTY_WORD, Felt, Word};
use miden_standards::account::auth::AuthSingleSig;
use miden_standards::code_builder::CodeBuilder;

use super::*;
use crate::db::migrations::MIGRATIONS;
use crate::db::models::conv::SqlTypeConvert;
use crate::db::schema;
use crate::errors::DatabaseError;

fn setup_test_db() -> SqliteConnection {
    let mut conn =
        SqliteConnection::establish(":memory:").expect("Failed to create in-memory database");

    conn.run_pending_migrations(MIGRATIONS).expect("Failed to run migrations");

    conn
}

/// Test helper: reconstructs account storage at a given block from DB.
///
/// Reads `accounts.storage_header` and `account_storage_map_values` to reconstruct
/// the full `AccountStorage` at the specified block.
fn reconstruct_account_storage_at_block(
    conn: &mut SqliteConnection,
    account_id: AccountId,
    block_num: BlockNumber,
) -> Result<AccountStorage, DatabaseError> {
    use schema::account_storage_map_values as t;

    let account_id_bytes = account_id.to_bytes();
    let block_num_sql = block_num.to_raw_sql();

    // Query storage header blob for this account at or before this block
    let storage_blob: Option<Vec<u8>> =
        SelectDsl::select(schema::accounts::table, schema::accounts::storage_header)
            .filter(schema::accounts::account_id.eq(&account_id_bytes))
            .filter(schema::accounts::block_num.le(block_num_sql))
            .order(schema::accounts::block_num.desc())
            .limit(1)
            .first(conn)
            .optional()?
            .flatten();

    let Some(blob) = storage_blob else {
        return Ok(AccountStorage::new(Vec::new())?);
    };

    let header = AccountStorageHeader::read_from_bytes(&blob)?;

    // Query all map values for this account up to and including this block.
    let map_values: Vec<(i64, String, Vec<u8>, Vec<u8>)> =
        SelectDsl::select(t::table, (t::block_num, t::slot_name, t::key, t::value))
            .filter(t::account_id.eq(&account_id_bytes).and(t::block_num.le(block_num_sql)))
            .order((t::slot_name.asc(), t::key.asc(), t::block_num.desc()))
            .load(conn)?;

    // For each (slot_name, key) pair, keep only the latest entry
    let mut latest_map_entries: BTreeMap<(StorageSlotName, StorageMapKey), Word> = BTreeMap::new();
    for (_, slot_name_str, key_bytes, value_bytes) in map_values {
        let slot_name: StorageSlotName = slot_name_str.parse().map_err(|_| {
            DatabaseError::DataCorrupted(format!("Invalid slot name: {slot_name_str}"))
        })?;
        let key = StorageMapKey::read_from_bytes(&key_bytes)?;
        let value = Word::read_from_bytes(&value_bytes)?;
        latest_map_entries.entry((slot_name, key)).or_insert(value);
    }

    // Group entries by slot name
    let mut map_entries_by_slot: BTreeMap<StorageSlotName, Vec<(StorageMapKey, Word)>> =
        BTreeMap::new();
    for ((slot_name, key), value) in latest_map_entries {
        map_entries_by_slot.entry(slot_name).or_default().push((key, value));
    }

    // Reconstruct StorageSlots from header slots + map entries
    let mut slots = Vec::new();
    for slot_header in header.slots() {
        let slot = match slot_header.slot_type() {
            StorageSlotType::Value => {
                StorageSlot::with_value(slot_header.name().clone(), slot_header.value())
            },
            StorageSlotType::Map => {
                let entries = map_entries_by_slot.remove(slot_header.name()).unwrap_or_default();
                let storage_map = StorageMap::with_entries(entries)?;
                StorageSlot::with_map(slot_header.name().clone(), storage_map)
            },
        };
        slots.push(slot);
    }

    Ok(AccountStorage::new(slots)?)
}

fn create_test_account_with_storage() -> (Account, AccountId) {
    // Create a simple public account with one value storage slot
    let account_id = AccountId::dummy(
        [1u8; 15],
        AccountIdVersion::Version0,
        AccountType::RegularAccountImmutableCode,
        AccountStorageMode::Public,
    );

    let storage_value = Word::from([Felt::new(1), Felt::new(2), Felt::new(3), Felt::new(4)]);
    let component_storage = vec![StorageSlot::with_value(StorageSlotName::mock(0), storage_value)];

    let account_component_code = CodeBuilder::default()
        .compile_component_code("test::interface", "pub proc foo push.1 end")
        .unwrap();

    let component = AccountComponent::new(
        account_component_code,
        component_storage,
        AccountComponentMetadata::new("test", [AccountType::RegularAccountImmutableCode]),
    )
    .unwrap();

    let account = AccountBuilder::new([1u8; 32])
        .account_type(AccountType::RegularAccountImmutableCode)
        .storage_mode(AccountStorageMode::Public)
        .with_component(component)
        .with_auth_component(AuthSingleSig::new(
            PublicKeyCommitment::from(EMPTY_WORD),
            AuthScheme::Falcon512Poseidon2,
        ))
        .build_existing()
        .unwrap();

    (account, account_id)
}

fn insert_block_header(conn: &mut SqliteConnection, block_num: BlockNumber) {
    use crate::db::schema::block_headers;

    let secret_key = SecretKey::new();
    let block_header = BlockHeader::new(
        1_u8.into(),
        Word::default(),
        block_num,
        Word::default(),
        Word::default(),
        Word::default(),
        Word::default(),
        Word::default(),
        Word::default(),
        secret_key.public_key(),
        test_fee_params(),
        0_u8.into(),
    );
    let signature = secret_key.sign(block_header.commitment());

    diesel::insert_into(block_headers::table)
        .values((
            block_headers::block_num.eq(i64::from(block_num.as_u32())),
            block_headers::block_header.eq(block_header.to_bytes()),
            block_headers::signature.eq(signature.to_bytes()),
            block_headers::commitment.eq(block_header.commitment().to_bytes()),
        ))
        .execute(conn)
        .expect("Failed to insert block header");
}

fn create_account_with_map_storage(
    slot_name: StorageSlotName,
    entries: Vec<(StorageMapKey, Word)>,
) -> Account {
    let storage_map = StorageMap::with_entries(entries).unwrap();
    let component_storage = vec![StorageSlot::with_map(slot_name, storage_map)];

    let account_component_code = CodeBuilder::default()
        .compile_component_code("test::interface", "pub proc map push.1 end")
        .unwrap();

    let component = AccountComponent::new(
        account_component_code,
        component_storage,
        AccountComponentMetadata::new("test", [AccountType::RegularAccountImmutableCode]),
    )
    .unwrap();

    AccountBuilder::new([9u8; 32])
        .account_type(AccountType::RegularAccountImmutableCode)
        .storage_mode(AccountStorageMode::Public)
        .with_component(component)
        .with_auth_component(AuthSingleSig::new(
            PublicKeyCommitment::from(EMPTY_WORD),
            AuthScheme::Falcon512Poseidon2,
        ))
        .build_existing()
        .unwrap()
}

fn assert_storage_map_slot_entries(
    storage: &AccountStorage,
    slot_name: &StorageSlotName,
    expected: &BTreeMap<StorageMapKey, Word>,
) {
    let slot = storage
        .slots()
        .iter()
        .find(|slot| slot.name() == slot_name)
        .expect("expected storage slot");

    let StorageSlotContent::Map(storage_map) = slot.content() else {
        panic!("expected map slot");
    };

    let entries = BTreeMap::from_iter(storage_map.entries().map(|(key, value)| (*key, *value)));
    assert_eq!(&entries, expected, "map entries mismatch");
}

// ACCOUNT HEADER AT BLOCK TESTS
// ================================================================================================

#[test]
fn test_select_account_header_at_block_returns_none_for_nonexistent() {
    let mut conn = setup_test_db();
    let block_num = BlockNumber::from_epoch(0);
    insert_block_header(&mut conn, block_num);

    let account_id = AccountId::dummy(
        [99u8; 15],
        AccountIdVersion::Version0,
        AccountType::RegularAccountImmutableCode,
        AccountStorageMode::Public,
    );

    // Query for a non-existent account
    let result =
        select_account_header_with_storage_header_at_block(&mut conn, account_id, block_num)
            .expect("Query should succeed");

    assert!(result.is_none(), "Should return None for non-existent account");
}

#[test]
fn test_select_account_header_at_block_returns_correct_header() {
    let mut conn = setup_test_db();
    let (account, _) = create_test_account_with_storage();
    let account_id = account.id();

    let block_num = BlockNumber::from_epoch(0);
    insert_block_header(&mut conn, block_num);

    // Insert the account
    let delta = AccountDelta::try_from(account.clone()).unwrap();
    let account_update = BlockAccountUpdate::new(
        account_id,
        account.to_commitment(),
        AccountUpdateDetails::Delta(delta),
    );

    upsert_accounts(&mut conn, &[account_update], block_num).expect("upsert_accounts failed");

    // Query the account header
    let (header, _storage_header) =
        select_account_header_with_storage_header_at_block(&mut conn, account_id, block_num)
            .expect("Query should succeed")
            .expect("Header should exist");

    assert_eq!(header.id(), account_id, "Account ID should match");
    assert_eq!(header.nonce(), account.nonce(), "Nonce should match");
    assert_eq!(
        header.code_commitment(),
        account.code().commitment(),
        "Code commitment should match"
    );
}

#[test]
fn test_select_account_header_at_block_historical_query() {
    let mut conn = setup_test_db();
    let (account, _) = create_test_account_with_storage();
    let account_id = account.id();

    let block_num_1 = BlockNumber::from_epoch(0);
    let block_num_2 = BlockNumber::from_epoch(1);
    insert_block_header(&mut conn, block_num_1);
    insert_block_header(&mut conn, block_num_2);

    // Insert the account at block 1
    let nonce_1 = account.nonce();
    let delta_1 = AccountDelta::try_from(account.clone()).unwrap();
    let account_update_1 = BlockAccountUpdate::new(
        account_id,
        account.to_commitment(),
        AccountUpdateDetails::Delta(delta_1),
    );

    upsert_accounts(&mut conn, &[account_update_1], block_num_1).expect("First upsert failed");

    // Query at block 1 - should return the account
    let (header_1, _) =
        select_account_header_with_storage_header_at_block(&mut conn, account_id, block_num_1)
            .expect("Query should succeed")
            .expect("Header should exist at block 1");

    assert_eq!(header_1.nonce(), nonce_1, "Nonce at block 1 should match");

    // Query at block 2 - should return the same account (most recent before block 2)
    let (header_2, _) =
        select_account_header_with_storage_header_at_block(&mut conn, account_id, block_num_2)
            .expect("Query should succeed")
            .expect("Header should exist at block 2");

    assert_eq!(header_2.nonce(), nonce_1, "Nonce at block 2 should match block 1");
}

// ACCOUNT VAULT AT BLOCK TESTS
// ================================================================================================

#[test]
fn test_select_account_vault_at_block_empty() {
    let mut conn = setup_test_db();
    let (account, _) = create_test_account_with_storage();
    let account_id = account.id();

    let block_num = BlockNumber::from_epoch(0);
    insert_block_header(&mut conn, block_num);

    // Insert account without vault assets
    let delta = AccountDelta::try_from(account.clone()).unwrap();
    let account_update = BlockAccountUpdate::new(
        account_id,
        account.to_commitment(),
        AccountUpdateDetails::Delta(delta),
    );

    upsert_accounts(&mut conn, &[account_update], block_num).expect("upsert_accounts failed");

    // Query vault - should return empty (the test account has no assets)
    let assets = select_account_vault_at_block(&mut conn, account_id, block_num)
        .expect("Query should succeed");

    assert!(assets.is_empty(), "Account should have no assets");
}

// ACCOUNT STORAGE AT BLOCK TESTS
// ================================================================================================

#[test]
fn test_upsert_accounts_inserts_storage_header() {
    let mut conn = setup_test_db();
    let (account, account_id) = create_test_account_with_storage();

    // Block 1
    let block_num = BlockNumber::from_epoch(0);
    insert_block_header(&mut conn, block_num);

    let storage_commitment_original = account.storage().to_commitment();
    let storage_slots_len = account.storage().slots().len();
    let account_commitment = account.to_commitment();

    // Create full state delta from the account
    let delta = AccountDelta::try_from(account).unwrap();
    assert!(delta.is_full_state(), "Delta should be full state");

    let account_update =
        BlockAccountUpdate::new(account_id, account_commitment, AccountUpdateDetails::Delta(delta));

    // Upsert account
    let result = upsert_accounts(&mut conn, &[account_update], block_num);
    assert!(result.is_ok(), "upsert_accounts failed: {:?}", result.err());
    assert_eq!(result.unwrap(), 1, "Expected 1 account to be inserted");

    // Query storage header back
    let queried_storage = select_latest_account_storage(&mut conn, account_id)
        .expect("Failed to query storage header");

    // Verify storage commitment matches
    assert_eq!(
        queried_storage.to_commitment(),
        storage_commitment_original,
        "Storage commitment mismatch"
    );

    // Verify number of slots matches
    assert_eq!(queried_storage.slots().len(), storage_slots_len, "Storage slots count mismatch");

    // Verify exactly 1 latest account with storage exists
    let header_count: i64 = schema::accounts::table
        .filter(schema::accounts::account_id.eq(account_id.to_bytes()))
        .filter(schema::accounts::is_latest.eq(true))
        .filter(schema::accounts::storage_header.is_not_null())
        .count()
        .get_result(&mut conn)
        .expect("Failed to count accounts with storage");

    assert_eq!(header_count, 1, "Expected exactly 1 latest account with storage");
}

#[test]
fn test_upsert_accounts_updates_is_latest_flag() {
    let mut conn = setup_test_db();
    let (account, account_id) = create_test_account_with_storage();

    // Block 1 and 2
    let block_num_1 = BlockNumber::from_epoch(0);
    let block_num_2 = BlockNumber::from_epoch(1);

    insert_block_header(&mut conn, block_num_1);
    insert_block_header(&mut conn, block_num_2);

    // Save storage commitment before moving account
    let storage_commitment_1 = account.storage().to_commitment();
    let account_commitment_1 = account.to_commitment();

    // First update with original account - full state delta
    let delta_1 = AccountDelta::try_from(account).unwrap();

    let account_update_1 = BlockAccountUpdate::new(
        account_id,
        account_commitment_1,
        AccountUpdateDetails::Delta(delta_1),
    );

    upsert_accounts(&mut conn, &[account_update_1], block_num_1).expect("First upsert failed");

    // Create modified account with different storage value
    let storage_value_modified =
        Word::from([Felt::new(10), Felt::new(20), Felt::new(30), Felt::new(40)]);
    let component_storage_modified =
        vec![StorageSlot::with_value(StorageSlotName::mock(0), storage_value_modified)];

    let account_component_code = CodeBuilder::default()
        .compile_component_code("test::interface", "pub proc foo push.1 end")
        .unwrap();

    let component_2 = AccountComponent::new(
        account_component_code,
        component_storage_modified,
        AccountComponentMetadata::new("test", [AccountType::RegularAccountImmutableCode]),
    )
    .unwrap();

    let account_2 = AccountBuilder::new([1u8; 32])
        .account_type(AccountType::RegularAccountImmutableCode)
        .storage_mode(AccountStorageMode::Public)
        .with_component(component_2)
        .with_auth_component(AuthSingleSig::new(
            PublicKeyCommitment::from(EMPTY_WORD),
            AuthScheme::Falcon512Poseidon2,
        ))
        .build_existing()
        .unwrap();

    let storage_commitment_2 = account_2.storage().to_commitment();
    let account_commitment_2 = account_2.to_commitment();

    // Second update with modified account - full state delta
    let delta_2 = AccountDelta::try_from(account_2).unwrap();

    let account_update_2 = BlockAccountUpdate::new(
        account_id,
        account_commitment_2,
        AccountUpdateDetails::Delta(delta_2),
    );

    upsert_accounts(&mut conn, &[account_update_2], block_num_2).expect("Second upsert failed");

    // Verify 2 total account rows exist (both historical records)
    let total_accounts: i64 = schema::accounts::table
        .filter(schema::accounts::account_id.eq(account_id.to_bytes()))
        .count()
        .get_result(&mut conn)
        .expect("Failed to count total accounts");

    assert_eq!(total_accounts, 2, "Expected 2 total account records");

    // Verify only 1 is marked as latest
    let latest_accounts: i64 = schema::accounts::table
        .filter(schema::accounts::account_id.eq(account_id.to_bytes()))
        .filter(schema::accounts::is_latest.eq(true))
        .count()
        .get_result(&mut conn)
        .expect("Failed to count latest accounts");

    assert_eq!(latest_accounts, 1, "Expected exactly 1 latest account");

    // Verify latest storage matches second update
    let latest_storage = select_latest_account_storage(&mut conn, account_id)
        .expect("Failed to query latest storage");

    assert_eq!(
        latest_storage.to_commitment(),
        storage_commitment_2,
        "Latest storage should match second update"
    );

    // Verify historical query returns first update
    let storage_at_block_1 =
        reconstruct_account_storage_at_block(&mut conn, account_id, block_num_1)
            .expect("Failed to query storage at block 1");

    assert_eq!(
        storage_at_block_1.to_commitment(),
        storage_commitment_1,
        "Storage at block 1 should match first update"
    );
}

#[test]
fn test_upsert_accounts_with_multiple_storage_slots() {
    let mut conn = setup_test_db();

    // Create account with 3 storage slots
    let account_id = AccountId::dummy(
        [2u8; 15],
        AccountIdVersion::Version0,
        AccountType::RegularAccountImmutableCode,
        AccountStorageMode::Public,
    );

    let slot_value_1 = Word::from([Felt::new(1), Felt::new(2), Felt::new(3), Felt::new(4)]);
    let slot_value_2 = Word::from([Felt::new(5), Felt::new(6), Felt::new(7), Felt::new(8)]);
    let slot_value_3 = Word::from([Felt::new(9), Felt::new(10), Felt::new(11), Felt::new(12)]);

    let component_storage = vec![
        StorageSlot::with_value(StorageSlotName::mock(0), slot_value_1),
        StorageSlot::with_value(StorageSlotName::mock(1), slot_value_2),
        StorageSlot::with_value(StorageSlotName::mock(2), slot_value_3),
    ];

    let account_component_code = CodeBuilder::default()
        .compile_component_code("test::interface", "pub proc foo push.1 end")
        .unwrap();

    let component = AccountComponent::new(
        account_component_code,
        component_storage,
        AccountComponentMetadata::new("test", [AccountType::RegularAccountImmutableCode]),
    )
    .unwrap();

    let account = AccountBuilder::new([2u8; 32])
        .account_type(AccountType::RegularAccountImmutableCode)
        .storage_mode(AccountStorageMode::Public)
        .with_component(component)
        .with_auth_component(AuthSingleSig::new(
            PublicKeyCommitment::from(EMPTY_WORD),
            AuthScheme::Falcon512Poseidon2,
        ))
        .build_existing()
        .unwrap();

    let block_num = BlockNumber::from_epoch(0);
    insert_block_header(&mut conn, block_num);

    let storage_commitment = account.storage().to_commitment();
    let account_commitment = account.to_commitment();
    let delta = AccountDelta::try_from(account).unwrap();

    let account_update =
        BlockAccountUpdate::new(account_id, account_commitment, AccountUpdateDetails::Delta(delta));

    upsert_accounts(&mut conn, &[account_update], block_num)
        .expect("Upsert with multiple storage slots failed");

    // Query back and verify
    let queried_storage =
        select_latest_account_storage(&mut conn, account_id).expect("Failed to query storage");

    assert_eq!(
        queried_storage.to_commitment(),
        storage_commitment,
        "Storage commitment mismatch"
    );

    // Note: AuthSingleSig adds 2 storage slots (pub key + scheme id), so 3 component slots + 2 auth
    // = 5 total
    assert_eq!(
        queried_storage.slots().len(),
        5,
        "Expected 5 storage slots (3 component + 2 auth)"
    );

    // The storage commitment matching proves that all values are correctly preserved.
    // We don't check individual slot values by index since slot ordering may vary.
}

#[test]
fn test_upsert_accounts_with_empty_storage() {
    let mut conn = setup_test_db();

    // Create account with no component storage slots (only auth slot)
    let account_id = AccountId::dummy(
        [3u8; 15],
        AccountIdVersion::Version0,
        AccountType::RegularAccountImmutableCode,
        AccountStorageMode::Public,
    );

    let account_component_code = CodeBuilder::default()
        .compile_component_code("test::interface", "pub proc foo push.1 end")
        .unwrap();

    let component = AccountComponent::new(
        account_component_code,
        vec![],
        AccountComponentMetadata::new("test", [AccountType::RegularAccountImmutableCode]),
    )
    .unwrap();

    let account = AccountBuilder::new([3u8; 32])
        .account_type(AccountType::RegularAccountImmutableCode)
        .storage_mode(AccountStorageMode::Public)
        .with_component(component)
        .with_auth_component(AuthSingleSig::new(
            PublicKeyCommitment::from(EMPTY_WORD),
            AuthScheme::Falcon512Poseidon2,
        ))
        .build_existing()
        .unwrap();

    let block_num = BlockNumber::from_epoch(0);
    insert_block_header(&mut conn, block_num);

    let storage_commitment = account.storage().to_commitment();
    let account_commitment = account.to_commitment();
    let delta = AccountDelta::try_from(account).unwrap();

    let account_update =
        BlockAccountUpdate::new(account_id, account_commitment, AccountUpdateDetails::Delta(delta));

    upsert_accounts(&mut conn, &[account_update], block_num)
        .expect("Upsert with empty storage failed");

    // Query back and verify
    let queried_storage =
        select_latest_account_storage(&mut conn, account_id).expect("Failed to query storage");

    assert_eq!(
        queried_storage.to_commitment(),
        storage_commitment,
        "Storage commitment mismatch for empty storage"
    );

    // Note: AuthSingleSig adds 2 storage slots (pub key + scheme id)
    assert_eq!(queried_storage.slots().len(), 2, "Expected 2 storage slots (auth component)");

    // Verify the storage header blob exists in database
    let storage_header_exists: Option<bool> = SelectDsl::select(
        schema::accounts::table
            .filter(schema::accounts::account_id.eq(account_id.to_bytes()))
            .filter(schema::accounts::is_latest.eq(true)),
        schema::accounts::storage_header.is_not_null(),
    )
    .first(&mut conn)
    .optional()
    .expect("Failed to check storage header existence");

    assert_eq!(
        storage_header_exists,
        Some(true),
        "Storage header blob should exist even for empty storage"
    );
}

// STORAGE MAP LATEST ACCOUNT QUERY TESTS
// ================================================================================================

#[test]
fn test_select_latest_account_storage_ordering_semantics() {
    let mut conn = setup_test_db();
    let block_num = BlockNumber::from_epoch(0);
    insert_block_header(&mut conn, block_num);

    let slot_name = StorageSlotName::mock(0);
    let key_1 = StorageMapKey::from_index(1);
    let key_2 = StorageMapKey::from_index(2);
    let key_3 = StorageMapKey::from_index(3);

    let value_1 = Word::from([Felt::new(10), Felt::ZERO, Felt::ZERO, Felt::ZERO]);
    let value_2 = Word::from([Felt::new(20), Felt::ZERO, Felt::ZERO, Felt::ZERO]);
    let value_3 = Word::from([Felt::new(30), Felt::ZERO, Felt::ZERO, Felt::ZERO]);

    let mut entries = vec![(key_2, value_2), (key_1, value_1), (key_3, value_3)];
    entries.reverse();

    let account = create_account_with_map_storage(slot_name.clone(), entries.clone());
    let account_id = account.id();
    let account_commitment = account.to_commitment();

    let mut reversed_entries = entries.clone();
    reversed_entries.reverse();
    let reordered_account = create_account_with_map_storage(slot_name.clone(), reversed_entries);
    assert_eq!(
        account.storage().to_commitment(),
        reordered_account.storage().to_commitment(),
        "storage commitments should be order-independent"
    );

    let delta = AccountDelta::try_from(account).unwrap();
    let account_update =
        BlockAccountUpdate::new(account_id, account_commitment, AccountUpdateDetails::Delta(delta));

    upsert_accounts(&mut conn, &[account_update], block_num).expect("upsert_accounts failed");

    let storage =
        select_latest_account_storage(&mut conn, account_id).expect("Failed to query storage");

    let expected = BTreeMap::from_iter(entries);
    assert_storage_map_slot_entries(&storage, &slot_name, &expected);
}

#[test]
fn test_select_latest_account_storage_multiple_slots() {
    let mut conn = setup_test_db();
    let block_num = BlockNumber::from_epoch(0);
    insert_block_header(&mut conn, block_num);

    let slot_name_1 = StorageSlotName::mock(0);
    let slot_name_2 = StorageSlotName::mock(1);

    let key_a = StorageMapKey::from_index(1);
    let key_b = StorageMapKey::from_index(2);

    let value_a = Word::from([Felt::new(11), Felt::ZERO, Felt::ZERO, Felt::ZERO]);
    let value_b = Word::from([Felt::new(22), Felt::ZERO, Felt::ZERO, Felt::ZERO]);

    let map_a = StorageMap::with_entries(vec![(key_a, value_a)]).unwrap();
    let map_b = StorageMap::with_entries(vec![(key_b, value_b)]).unwrap();

    let component_storage = vec![
        StorageSlot::with_map(slot_name_2.clone(), map_b),
        StorageSlot::with_map(slot_name_1.clone(), map_a),
    ];

    let account_component_code = CodeBuilder::default()
        .compile_component_code("test::interface", "pub proc map push.1 end")
        .unwrap();

    let component = AccountComponent::new(
        account_component_code,
        component_storage,
        AccountComponentMetadata::new("test", [AccountType::RegularAccountImmutableCode]),
    )
    .unwrap();

    let account = AccountBuilder::new([9u8; 32])
        .account_type(AccountType::RegularAccountImmutableCode)
        .storage_mode(AccountStorageMode::Public)
        .with_component(component)
        .with_auth_component(AuthSingleSig::new(
            PublicKeyCommitment::from(EMPTY_WORD),
            AuthScheme::Falcon512Poseidon2,
        ))
        .build_existing()
        .unwrap();

    let account_id = account.id();
    let account_commitment = account.to_commitment();
    let delta = AccountDelta::try_from(account).unwrap();
    let account_update =
        BlockAccountUpdate::new(account_id, account_commitment, AccountUpdateDetails::Delta(delta));

    upsert_accounts(&mut conn, &[account_update], block_num).expect("upsert_accounts failed");

    let storage =
        select_latest_account_storage(&mut conn, account_id).expect("Failed to query storage");

    let expected_slot_1 = BTreeMap::from_iter([(key_a, value_a)]);
    let expected_slot_2 = BTreeMap::from_iter([(key_b, value_b)]);

    assert_storage_map_slot_entries(&storage, &slot_name_1, &expected_slot_1);
    assert_storage_map_slot_entries(&storage, &slot_name_2, &expected_slot_2);
}

#[test]
fn test_select_latest_account_storage_slot_updates() {
    let mut conn = setup_test_db();
    let block_1 = BlockNumber::from_epoch(0);
    let block_2 = BlockNumber::from_epoch(1);
    insert_block_header(&mut conn, block_1);
    insert_block_header(&mut conn, block_2);

    let slot_name = StorageSlotName::mock(0);
    let key_1 = StorageMapKey::from_index(1);
    let key_2 = StorageMapKey::from_index(2);

    let value_1 = Word::from([Felt::new(10), Felt::ZERO, Felt::ZERO, Felt::ZERO]);
    let value_2 = Word::from([Felt::new(20), Felt::ZERO, Felt::ZERO, Felt::ZERO]);
    let value_3 = Word::from([Felt::new(30), Felt::ZERO, Felt::ZERO, Felt::ZERO]);

    let account = create_account_with_map_storage(slot_name.clone(), vec![(key_1, value_1)]);
    let account_id = account.id();
    let account_commitment = account.to_commitment();

    let delta = AccountDelta::try_from(account.clone()).unwrap();
    let account_update =
        BlockAccountUpdate::new(account_id, account_commitment, AccountUpdateDetails::Delta(delta));

    upsert_accounts(&mut conn, &[account_update], block_1).expect("upsert_accounts failed");

    let mut map_delta = StorageMapDelta::default();
    map_delta.insert(key_1, value_2);
    map_delta.insert(key_2, value_3);
    let storage_delta = AccountStorageDelta::from_raw(BTreeMap::from_iter([(
        slot_name.clone(),
        StorageSlotDelta::Map(map_delta),
    )]));

    let partial_delta =
        AccountDelta::new(account_id, storage_delta, AccountVaultDelta::default(), Felt::new(1))
            .unwrap();

    let mut expected_account = account.clone();
    expected_account.apply_delta(&partial_delta).unwrap();
    let expected_commitment = expected_account.to_commitment();

    let account_update = BlockAccountUpdate::new(
        account_id,
        expected_commitment,
        AccountUpdateDetails::Delta(partial_delta),
    );

    upsert_accounts(&mut conn, &[account_update], block_2).expect("upsert_accounts failed");

    let storage =
        select_latest_account_storage(&mut conn, account_id).expect("Failed to query storage");

    let expected = BTreeMap::from_iter([(key_1, value_2), (key_2, value_3)]);
    assert_storage_map_slot_entries(&storage, &slot_name, &expected);
}

// VAULT AT BLOCK HISTORICAL QUERY TESTS
// ================================================================================================

/// Tests that querying vault at an older block returns the correct historical state,
/// even when the same `vault_key` has been updated in later blocks.
///
/// Focuses on deduplication logic that relies on ordering by (`vault_key` ASC and `block_num`
/// DESC).
#[test]
fn test_select_account_vault_at_block_historical_with_updates() {
    use assert_matches::assert_matches;
    use miden_protocol::asset::FungibleAsset;
    use miden_protocol::testing::account_id::{
        ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET,
        ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET_1,
    };

    let mut conn = setup_test_db();
    let (account, _) = create_test_account_with_storage();
    let account_id = account.id();

    // Faucet ID is needed for creating FungibleAssets
    let faucet_id = AccountId::try_from(ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET).unwrap();

    let block_1 = BlockNumber::from_epoch(0);
    let block_2 = BlockNumber::from_epoch(1);
    let block_3 = BlockNumber::from_epoch(2);

    insert_block_header(&mut conn, block_1);
    insert_block_header(&mut conn, block_2);
    insert_block_header(&mut conn, block_3);

    // Insert account at block 1
    let delta = AccountDelta::try_from(account.clone()).unwrap();
    let account_update = BlockAccountUpdate::new(
        account_id,
        account.to_commitment(),
        AccountUpdateDetails::Delta(delta),
    );

    for block in [block_1, block_2, block_3] {
        upsert_accounts(&mut conn, std::slice::from_ref(&account_update), block)
            .expect("upsert_accounts failed");
    }

    // Insert vault asset at block 1: vault_key_1 = 1000 tokens
    let asset_v1 = Asset::Fungible(FungibleAsset::new(faucet_id, 1000).unwrap());
    let vault_key_1 = asset_v1.vault_key();

    insert_account_vault_asset(&mut conn, account_id, block_1, vault_key_1, Some(asset_v1))
        .expect("insert vault asset failed");

    // Update vault asset at block 2: vault_key_1 = 2000 tokens (updated value)
    let asset_v2 = Asset::Fungible(FungibleAsset::new(faucet_id, 2000).unwrap());
    insert_account_vault_asset(&mut conn, account_id, block_2, vault_key_1, Some(asset_v2))
        .expect("insert vault asset update failed");

    // Add a second vault_key at block 2 (different faucet for different vault key)
    let faucet_id_2 = AccountId::try_from(ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET_1).unwrap();
    let asset_key2 = Asset::Fungible(FungibleAsset::new(faucet_id_2, 500).unwrap());
    let vault_key_2 = asset_key2.vault_key();
    insert_account_vault_asset(&mut conn, account_id, block_2, vault_key_2, Some(asset_key2))
        .expect("insert second vault asset failed");

    // Update vault_key_1 again at block 3: vault_key_1 = 3000 tokens
    let asset_v3 = Asset::Fungible(FungibleAsset::new(faucet_id, 3000).unwrap());
    insert_account_vault_asset(&mut conn, account_id, block_3, vault_key_1, Some(asset_v3))
        .expect("insert vault asset update 2 failed");

    // Query at block 1: should only see vault_key_1 with 1000 tokens
    let assets_at_block_1 = select_account_vault_at_block(&mut conn, account_id, block_1)
        .expect("Query at block 1 should succeed");

    assert_eq!(assets_at_block_1.len(), 1, "Should have 1 asset at block 1");
    assert_matches!(&assets_at_block_1[0], Asset::Fungible(f) if f.amount() == 1000);

    // Query at block 2: should see vault_key_1 with 2000 tokens AND vault_key_2 with 500 tokens
    let assets_at_block_2 = select_account_vault_at_block(&mut conn, account_id, block_2)
        .expect("Query at block 2 should succeed");

    assert_eq!(assets_at_block_2.len(), 2, "Should have 2 assets at block 2");

    // Find the amounts (order may vary)
    let amounts: Vec<u64> = assets_at_block_2
        .iter()
        .map(|a| assert_matches!(a, Asset::Fungible(f) => f.amount()))
        .collect();

    assert!(amounts.contains(&2000), "Block 2 should have vault_key_1 with 2000 tokens");
    assert!(amounts.contains(&500), "Block 2 should have vault_key_2 with 500 tokens");

    // Query at block 3: should see vault_key_1 with 3000 tokens AND vault_key_2 with 500 tokens
    let assets_at_block_3 = select_account_vault_at_block(&mut conn, account_id, block_3)
        .expect("Query at block 3 should succeed");

    assert_eq!(assets_at_block_3.len(), 2, "Should have 2 assets at block 3");

    let amounts: Vec<u64> = assets_at_block_3
        .iter()
        .map(|a| assert_matches!(a, Asset::Fungible(f) => f.amount()))
        .collect();

    assert!(amounts.contains(&3000), "Block 3 should have vault_key_1 with 3000 tokens");
    assert!(amounts.contains(&500), "Block 3 should have vault_key_2 with 500 tokens");
}

/// Tests that a 5-block history returns the correct asset per block.
#[test]
fn test_select_account_vault_at_block_exponential_updates() {
    const BLOCK_COUNT: u32 = 5;

    use assert_matches::assert_matches;
    use miden_protocol::asset::{AssetVaultKey, FungibleAsset};
    use miden_protocol::testing::account_id::ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET;

    let mut conn = setup_test_db();
    let (account, _) = create_test_account_with_storage();
    let account_id = account.id();

    let faucet_id = AccountId::try_from(ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET).unwrap();

    let blocks: Vec<BlockNumber> = (0..BLOCK_COUNT).map(BlockNumber::from).collect();

    for block in &blocks {
        insert_block_header(&mut conn, *block);
    }

    let delta = AccountDelta::try_from(account.clone()).unwrap();
    let account_update = BlockAccountUpdate::new(
        account_id,
        account.to_commitment(),
        AccountUpdateDetails::Delta(delta),
    );

    for block in &blocks {
        upsert_accounts(&mut conn, std::slice::from_ref(&account_update), *block)
            .expect("upsert_accounts failed");
    }

    let vault_key = AssetVaultKey::new_fungible(faucet_id).unwrap();

    for (index, block) in blocks.iter().enumerate() {
        let amount = 1u64 << index;
        let asset = Asset::Fungible(FungibleAsset::new(faucet_id, amount).unwrap());
        insert_account_vault_asset(&mut conn, account_id, *block, vault_key, Some(asset))
            .expect("insert vault asset failed");
    }

    for (index, block) in blocks.iter().enumerate() {
        let assets_at_block = select_account_vault_at_block(&mut conn, account_id, *block)
            .expect("Query at block should succeed");

        assert_eq!(assets_at_block.len(), 1, "Should have 1 asset at block");
        let expected_amount = 1u64 << index;
        assert_matches!(
            &assets_at_block[0],
            Asset::Fungible(f) if f.amount() == expected_amount
        );
    }
}

/// Tests that deleted vault assets (asset = None) are correctly excluded from results,
/// and that the deduplication handles deletion entries properly.
#[test]
fn test_select_account_vault_at_block_with_deletion() {
    use assert_matches::assert_matches;
    use miden_protocol::asset::FungibleAsset;
    use miden_protocol::testing::account_id::ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET;

    let mut conn = setup_test_db();
    let (account, _) = create_test_account_with_storage();
    let account_id = account.id();

    // Faucet ID is needed for creating FungibleAssets
    let faucet_id = AccountId::try_from(ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET).unwrap();

    let block_1 = BlockNumber::from_epoch(0);
    let block_2 = BlockNumber::from_epoch(1);
    let block_3 = BlockNumber::from_epoch(2);

    insert_block_header(&mut conn, block_1);
    insert_block_header(&mut conn, block_2);
    insert_block_header(&mut conn, block_3);

    // Insert account at block 1
    let delta = AccountDelta::try_from(account.clone()).unwrap();
    let account_update = BlockAccountUpdate::new(
        account_id,
        account.to_commitment(),
        AccountUpdateDetails::Delta(delta),
    );

    for block in [block_1, block_2, block_3] {
        upsert_accounts(&mut conn, std::slice::from_ref(&account_update), block)
            .expect("upsert_accounts failed");
    }

    // Insert vault asset at block 1
    let asset = Asset::Fungible(FungibleAsset::new(faucet_id, 1000).unwrap());
    let vault_key = asset.vault_key();

    insert_account_vault_asset(&mut conn, account_id, block_1, vault_key, Some(asset))
        .expect("insert vault asset failed");

    // Delete the vault asset at block 2 (insert with asset = None)
    insert_account_vault_asset(&mut conn, account_id, block_2, vault_key, None)
        .expect("delete vault asset failed");

    // Re-add the vault asset at block 3 with different amount
    let asset_v3 = Asset::Fungible(FungibleAsset::new(faucet_id, 2000).unwrap());
    insert_account_vault_asset(&mut conn, account_id, block_3, vault_key, Some(asset_v3))
        .expect("re-add vault asset failed");

    // Query at block 1: should see the asset
    let assets_at_block_1 = select_account_vault_at_block(&mut conn, account_id, block_1)
        .expect("Query at block 1 should succeed");
    assert_eq!(assets_at_block_1.len(), 1, "Should have 1 asset at block 1");

    // Query at block 2: should NOT see the asset (it was deleted)
    let assets_at_block_2 = select_account_vault_at_block(&mut conn, account_id, block_2)
        .expect("Query at block 2 should succeed");
    assert!(assets_at_block_2.is_empty(), "Should have no assets at block 2 (deleted)");

    // Query at block 3: should see the re-added asset with new amount
    let assets_at_block_3 = select_account_vault_at_block(&mut conn, account_id, block_3)
        .expect("Query at block 3 should succeed");
    assert_eq!(assets_at_block_3.len(), 1, "Should have 1 asset at block 3");
    assert_matches!(&assets_at_block_3[0], Asset::Fungible(f) if f.amount() == 2000);
}

// ACCOUNT CODE PRUNING TESTS
// ================================================================================================

/// Counts the number of rows in `account_codes`.
fn count_account_codes(conn: &mut SqliteConnection) -> usize {
    use schema::account_codes;

    let val =
        SelectDsl::select(account_codes::table, diesel::dsl::count(account_codes::code_commitment))
            .get_result::<i64>(conn)
            .expect("Failed to count account_codes");
    usize::try_from(u64::try_from(val).unwrap()).unwrap()
}

/// Returns whether a specific code commitment exists in `account_codes`.
fn account_code_exists(conn: &mut SqliteConnection, code_commitment: Word) -> bool {
    use schema::account_codes;

    let n =
        SelectDsl::select(account_codes::table, diesel::dsl::count(account_codes::code_commitment))
            .filter(account_codes::code_commitment.eq(code_commitment.to_bytes()))
            .get_result::<i64>(conn)
            .expect("Failed to query account_codes");

    n == 1
}

/// Creates a full-state [`BlockAccountUpdate`] for the given account.
fn make_full_state_update(account: &Account) -> BlockAccountUpdate {
    let delta = AccountDelta::try_from(account.clone()).unwrap();
    assert!(delta.is_full_state(), "expected full-state delta");
    BlockAccountUpdate::new(
        account.id(),
        account.to_commitment(),
        AccountUpdateDetails::Delta(delta),
    )
}

/// Builds a public account using a fixed account ID seed but a different component code.
///
/// All accounts produced here share the same [`AccountId`] because the same seed is used.
/// The `push_value` must be different for each variant to produce a distinct MAST root and thus a
/// distinct [`AccountCode::commitment`].
fn build_account_with_code(push_value: u32) -> Account {
    let code_src = format!("pub proc variant push.{push_value} end");
    let component_code = CodeBuilder::default()
        .compile_component_code("test::code_prune", &code_src)
        .unwrap();
    let component = AccountComponent::new(
        component_code,
        vec![StorageSlot::with_value(
            StorageSlotName::mock(0),
            Word::from([Felt::new(1), Felt::ZERO, Felt::ZERO, Felt::ZERO]),
        )],
        AccountComponentMetadata::new(
            "code_prune_test",
            [AccountType::RegularAccountUpdatableCode],
        ),
    )
    .unwrap();

    // Seed [2u8; 32] keeps the account ID distinct from the other test helpers.
    AccountBuilder::new([2u8; 32])
        .account_type(AccountType::RegularAccountUpdatableCode)
        .storage_mode(AccountStorageMode::Public)
        .with_component(component)
        .with_auth_component(AuthSingleSig::new(
            PublicKeyCommitment::from(EMPTY_WORD),
            AuthScheme::Falcon512Poseidon2,
        ))
        .build_existing()
        .unwrap()
}

/// Prune test 2: when an account's code changes, the old code must be pruned after the retention
/// window, while the new (latest) code is retained.
#[test]
fn test_prune_account_code_retains_latest_after_code_change() {
    let mut conn = setup_test_db();

    // Block 0: account created with code A.
    // Block RETENTION+1 (=51): account updated to code B — within the retention window at prune
    //   time.
    // Block 2*RETENTION+1 (=101): prune → cutoff is block 51; code A (last at block 0) is outside
    //   the window → pruned; code B (last at block 51) is within the window → retained.
    let block_0 = BlockNumber::from(0u32);
    let block_code_b = BlockNumber::from(HISTORICAL_BLOCK_RETENTION + 1);
    let block_prunable = BlockNumber::from(2 * HISTORICAL_BLOCK_RETENTION + 1);

    insert_block_header(&mut conn, block_0);
    insert_block_header(&mut conn, block_code_b);
    insert_block_header(&mut conn, block_prunable);

    let account_a = build_account_with_code(1);
    let account_b = build_account_with_code(2);

    // Both accounts must have the same ID for this to test code replacement.
    assert_eq!(account_a.id(), account_b.id(), "accounts must share the same ID");
    assert_ne!(
        account_a.code().commitment(),
        account_b.code().commitment(),
        "accounts must have different codes"
    );

    let account_id = account_a.id();
    let code_commitment_a = account_a.code().commitment();
    let code_commitment_b = account_b.code().commitment();

    // Block 0: insert account with code A.
    upsert_accounts(&mut conn, &[make_full_state_update(&account_a)], block_0)
        .expect("initial upsert failed");

    // Block RETENTION+1: update the same account ID to code B via a full-state delta.
    upsert_accounts(&mut conn, &[make_full_state_update(&account_b)], block_code_b)
        .expect("code-change upsert failed");

    assert_eq!(count_account_codes(&mut conn), 2, "both codes must exist before pruning");

    // Advance past retention window and prune.
    // cutoff = block_prunable - RETENTION = 2*RETENTION+1 - RETENTION = RETENTION+1 = block_code_b
    let (_, _, codes_deleted) =
        prune_history(&mut conn, block_prunable).expect("prune_history failed");

    // Only code A was dropped; code B is still referenced by the latest accounts row.
    assert_eq!(codes_deleted, 1, "exactly one code (A) must be pruned");
    assert!(!account_code_exists(&mut conn, code_commitment_a), "old code A must be pruned");
    assert!(
        account_code_exists(&mut conn, code_commitment_b),
        "current code B must be retained"
    );

    // Confirm the latest account row still points to code B.
    let (latest_header, _) =
        select_account_header_with_storage_header_at_block(&mut conn, account_id, block_prunable)
            .expect("query failed")
            .expect("account must still exist");
    assert_eq!(
        latest_header.code_commitment(),
        account_b.code().commitment(),
        "latest account must reference code B"
    );
}

/// Prune test 3: code A → code B → code A; after the retention window, code B must be pruned
/// but code A must be retained because it is still the latest.
#[test]
fn test_prune_account_code_retains_revisited_code() {
    let mut conn = setup_test_db();

    // Block 0:           code A.
    // Block RETENTION+1: code B (will be outside retention window at prune time).
    // Block RETENTION+2: back to code A (within the retention window at prune time).
    // Block 2*RETENTION+2: prune.
    //   cutoff = 2*RETENTION+2 - RETENTION = RETENTION+2.
    //   Code A: last referenced at block RETENTION+2 >= cutoff → retained.
    //   Code B: last referenced at block RETENTION+1 < cutoff → pruned.
    let block_0 = BlockNumber::from(0u32);
    let block_code_b = BlockNumber::from(HISTORICAL_BLOCK_RETENTION + 1);
    let block_code_a_again = BlockNumber::from(HISTORICAL_BLOCK_RETENTION + 2);
    let block_prunable = BlockNumber::from(2 * HISTORICAL_BLOCK_RETENTION + 2);

    insert_block_header(&mut conn, block_0);
    insert_block_header(&mut conn, block_code_b);
    insert_block_header(&mut conn, block_code_a_again);
    insert_block_header(&mut conn, block_prunable);

    let account_a = build_account_with_code(1);
    let account_b = build_account_with_code(2);

    assert_eq!(account_a.id(), account_b.id(), "accounts must share the same ID");
    assert_ne!(
        account_a.code().commitment(),
        account_b.code().commitment(),
        "accounts must have different codes"
    );

    let account_id = account_a.id();
    let code_commitment_a = account_a.code().commitment();
    let code_commitment_b = account_b.code().commitment();

    // Block 0: code A.
    upsert_accounts(&mut conn, &[make_full_state_update(&account_a)], block_0)
        .expect("block 0 upsert failed");
    // Block RETENTION+1: code B.
    upsert_accounts(&mut conn, &[make_full_state_update(&account_b)], block_code_b)
        .expect("block code_b upsert failed");
    // Block RETENTION+2: back to code A.
    upsert_accounts(&mut conn, &[make_full_state_update(&account_a)], block_code_a_again)
        .expect("block code_a_again upsert failed");

    // Before pruning: both codes must be in account_codes (code A inserted once via ON CONFLICT DO
    // NOTHING, code B inserted once).
    assert_eq!(count_account_codes(&mut conn), 2, "both codes must exist before pruning");

    // Advance past retention window and prune.
    let (_, _, codes_deleted) =
        prune_history(&mut conn, block_prunable).expect("prune_history failed");

    // Code B is no longer referenced by any account row within the retention window → pruned.
    // Code A is still referenced by the block_code_a_again accounts row (within cutoff) → retained.
    assert_eq!(codes_deleted, 1, "exactly one code (B) must be pruned");
    assert!(account_code_exists(&mut conn, code_commitment_a), "code A must be retained");
    assert!(!account_code_exists(&mut conn, code_commitment_b), "code B must be pruned");

    // Confirm the latest account row still points to code A.
    let (latest_header, _) =
        select_account_header_with_storage_header_at_block(&mut conn, account_id, block_prunable)
            .expect("query failed")
            .expect("account must still exist");
    assert_eq!(
        latest_header.code_commitment(),
        account_a.code().commitment(),
        "latest account must reference code A"
    );
}