hpsvm 0.2.1

A fast and lightweight Solana VM simulator for testing solana programs
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
use std::sync::Arc;

use solana_address::Address;
use solana_transaction::InstructionError;
use solana_transaction_error::TransactionError;
use thiserror::Error;

use crate::{AccountSourceError, account_source::AccountSourceErrorKind, tx_registry::TxTag};

/// Errors related to invalid sysvar data
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum InvalidSysvarDataError {
    /// Invalid Clock sysvar data
    #[error("Invalid Clock sysvar data.")]
    Clock,
    /// Invalid EpochRewards sysvar data
    #[error("Invalid EpochRewards sysvar data.")]
    EpochRewards,
    /// Invalid EpochSchedule sysvar data
    #[error("Invalid EpochSchedule sysvar data.")]
    EpochSchedule,
    /// Invalid Fees sysvar data
    #[error("Invalid Fees sysvar data.")]
    Fees,
    /// Invalid LastRestartSlot sysvar data
    #[error("Invalid LastRestartSlot sysvar data.")]
    LastRestartSlot,
    /// Invalid RecentBlockhashes sysvar data
    #[error("Invalid RecentBlockhashes sysvar data.")]
    RecentBlockhashes,
    /// Invalid Rent sysvar data
    #[error("Invalid Rent sysvar data.")]
    Rent,
    /// Invalid SlotHashes sysvar data
    #[error("Invalid SlotHashes sysvar data.")]
    SlotHashes,
    /// Invalid StakeHistory sysvar data
    #[error("Invalid StakeHistory sysvar data.")]
    StakeHistory,
}

/// High level SVM errors
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum HPSVMError {
    /// Invalid sysvar data error
    #[error("{0}")]
    InvalidSysvarData(#[from] InvalidSysvarDataError),
    /// Sysvar serialization failure
    #[error("failed to serialize sysvar {sysvar}: {reason}")]
    SysvarSerialization { sysvar: &'static str, reason: String },
    /// Instruction error
    #[error("{0}")]
    Instruction(#[from] InstructionError),
    /// Invalid path error
    #[error("{0}")]
    InvalidPath(#[from] std::io::Error),
    /// Runtime environment refresh failure
    #[error("failed to refresh runtime environment {version}: {reason}")]
    RuntimeEnvironment { version: &'static str, reason: String },
    /// Custom syscall registration failure
    #[error("failed to register custom syscall {name} in {runtime}: {reason}")]
    CustomSyscallRegistration { name: String, runtime: &'static str, reason: String },
    /// Invalid loader error
    #[error("unsupported loader {loader_id} for program {program_id}")]
    InvalidLoader { program_id: Address, loader_id: Address },
    /// Required runtime component was not materialized.
    #[error("missing runtime component: {component}")]
    MissingRuntimeComponent { component: &'static str },
    /// External account source failure.
    #[error("account source failed while loading {pubkey}: {source}")]
    AccountSource {
        /// Account address that triggered the source read.
        pubkey: Address,
        /// Underlying account source error.
        source: AccountSourceError,
    },
    /// Program load failure.
    #[error("failed to load program: {0}")]
    ProgramLoad(String),
    /// No transaction handler was registered for the transaction's tag.
    ///
    /// This is the [`HPSVMError`] projection of
    /// [`TxRegistryError::UnknownTag`](crate::TxRegistryError::UnknownTag),
    /// used where a fallible entry point must report a dispatch failure as an
    /// error rather than an execution status.
    #[error("no transaction handler registered for tag {tag:?}")]
    UnknownTransactionTag {
        /// The tag no handler owned.
        tag: TxTag,
    },
    /// Layered database error (design §3.10).
    ///
    /// Lossless [`DbError`] projection: [`DbError::is_fatal`] and
    /// [`DbError::downcast_ref`] keep working through this variant.
    #[error(transparent)]
    Database(#[from] DbError),
    /// Layered load error (design §3.10).
    #[error(transparent)]
    Load(#[from] LoadError),
    /// Layered transaction error (design §3.10).
    #[error(transparent)]
    Transaction(#[from] TxError),
    /// Layered execution error (design §3.10).
    #[error(transparent)]
    Execution(#[from] ExecutionError),
    /// Layered host error (design §3.10).
    #[error(transparent)]
    Host(#[from] HostError),
    /// Layered handler error (design §3.10).
    #[error(transparent)]
    Handler(#[from] HandlerError),
}

impl From<Box<dyn std::error::Error>> for HPSVMError {
    fn from(err: Box<dyn std::error::Error>) -> Self {
        Self::ProgramLoad(err.to_string())
    }
}

/// Converts a dispatch failure into the fallible-entry-point error.
///
/// [`TxRegistryError::UnknownTag`](crate::TxRegistryError::UnknownTag) becomes
/// [`HPSVMError::UnknownTransactionTag`]; a handler failure already carries
/// an [`HPSVMError`] and passes through unchanged.
impl From<crate::TxRegistryError> for HPSVMError {
    fn from(error: crate::TxRegistryError) -> Self {
        match error {
            crate::TxRegistryError::UnknownTag(tag) => Self::UnknownTransactionTag { tag },
            crate::TxRegistryError::HandlerFailed(error) => error,
        }
    }
}

// ===========================================================================
// Layered error taxonomy (design §3.10).
//
// Placement: this taxonomy lives in `error.rs` (rather than a new `errors.rs`
// module) because `error.rs` is already the crate's single error home — it
// owns `HPSVMError` and `InvalidSysvarDataError` — and splitting the new
// layer across a second module would force every reader to chase conversions
// between two homes. One module, one import path (`crate::error::`).
//
// Shape of the migration (binding scope decision): the FULL taxonomy is
// introduced here, but only the DATABASE layer and the TxHandler boundary
// are migrated to it in this task. [`HPSVMError`] stays the crate's
// outer/public error, with a lossless transparent projection (`Database`,
// `Load`, `Transaction`, `Execution`, `Host`, `Handler`) and hence a
// lossless `From` conversion from every new layer. The remaining call sites
// (execution internals, registry `validate`/`execute` signatures, host entry
// points) keep surfacing `HPSVMError` directly; their migration owners are
// documented on the relevant types below.
//
// Classification rule: fatal-ness and layer identity travel in TYPES
// (`DbError::is_fatal`, exact enum variants, `downcast_ref`), never in
// message strings. `Display` impls therefore delegate to the inner error
// wherever a layer adds no context, and add a fixed prefix otherwise.
// ===========================================================================

/// Type-erased error that stays recoverable by downcast.
///
/// The inner error is held behind an `Arc`, so cloning is a pointer bump
/// and the same value can cross the registry's erased handler boundary and
/// still be recovered with [`downcast_ref`](AnyError::downcast_ref).
#[derive(Clone)]
pub struct AnyError(Arc<dyn std::error::Error + Send + Sync>);

impl AnyError {
    /// Erases a concrete error, preserving it for later downcast recovery.
    pub fn new<E>(error: E) -> Self
    where
        E: std::error::Error + Send + Sync + 'static,
    {
        Self(Arc::new(error))
    }

    /// Returns `true` when the erased error is of type `T`.
    pub fn is<T>(&self) -> bool
    where
        T: std::error::Error + 'static,
    {
        self.0.is::<T>()
    }

    /// Recovers a reference to the concrete error of type `T`, if present.
    pub fn downcast_ref<T>(&self) -> Option<&T>
    where
        T: std::error::Error + 'static,
    {
        self.0.downcast_ref::<T>()
    }

    /// Consumes the wrapper and returns the erased error.
    pub fn into_inner(self) -> Arc<dyn std::error::Error + Send + Sync> {
        self.0
    }
}

impl std::fmt::Debug for AnyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("AnyError").field(&self.0.to_string()).finish()
    }
}

impl std::fmt::Display for AnyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl std::error::Error for AnyError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(self.0.as_ref())
    }
}

impl From<HPSVMError> for AnyError {
    fn from(error: HPSVMError) -> Self {
        Self::new(error)
    }
}

impl From<AccountSourceError> for AnyError {
    fn from(error: AccountSourceError) -> Self {
        Self::new(error)
    }
}

impl From<DbError> for AnyError {
    fn from(error: DbError) -> Self {
        Self::new(error)
    }
}

/// Database-layer error: a concrete failure plus its fatal classification.
///
/// `fatal == true` means the failure is infrastructural (the source is
/// down): retrying within the same transaction is pointless. `fatal == false`
/// means the failure is deterministic for this input (bad data, missing
/// file) and must be handled, not retried, at this layer.
#[derive(Clone, Debug)]
pub struct DbError {
    error: AnyError,
    fatal: bool,
}

impl DbError {
    /// Wraps a concrete error with an explicit fatal classification.
    pub fn new<E>(error: E, fatal: bool) -> Self
    where
        E: std::error::Error + Send + Sync + 'static,
    {
        Self { error: AnyError::new(error), fatal }
    }

    /// Wraps a concrete infrastructural failure (retrying is pointless).
    pub fn fatal<E>(error: E) -> Self
    where
        E: std::error::Error + Send + Sync + 'static,
    {
        Self::new(error, true)
    }

    /// Wraps a concrete deterministic failure (handle, do not retry).
    pub fn non_fatal<E>(error: E) -> Self
    where
        E: std::error::Error + Send + Sync + 'static,
    {
        Self::new(error, false)
    }

    /// Returns the fatal classification. Survives every erased boundary
    /// because it is a plain flag on the recovered value, not a string.
    pub const fn is_fatal(&self) -> bool {
        self.fatal
    }

    /// Returns the erased concrete error.
    pub const fn error(&self) -> &AnyError {
        &self.error
    }

    /// Consumes the wrapper and returns the erased concrete error.
    pub fn into_inner(self) -> AnyError {
        self.error
    }

    /// Recovers a reference to the concrete error of type `T`, if present.
    pub fn downcast_ref<T>(&self) -> Option<&T>
    where
        T: std::error::Error + 'static,
    {
        self.error.downcast_ref::<T>()
    }

    /// Returns `true` when the wrapped error is of type `T`.
    pub fn is<T>(&self) -> bool
    where
        T: std::error::Error + 'static,
    {
        self.error.is::<T>()
    }
}

impl std::fmt::Display for DbError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.error)
    }
}

impl std::error::Error for DbError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.error)
    }
}

/// Fatal mapping for account-source failures: `AccountSourceErrorKind::Unavailable`
/// means the infrastructure is down (retrying is pointless within the
/// transaction), while `InvalidResponse`/`Other` are deterministic outcomes
/// of this request.
impl From<AccountSourceError> for DbError {
    fn from(error: AccountSourceError) -> Self {
        let fatal = matches!(error.kind(), AccountSourceErrorKind::Unavailable);
        Self::new(error, fatal)
    }
}

/// I/O failures arise loading programs and files. A missing file is
/// deterministic for this input, not infrastructure collapse, so the mapping
/// is non-fatal.
impl From<std::io::Error> for DbError {
    fn from(error: std::io::Error) -> Self {
        Self::non_fatal(error)
    }
}

/// Invalid sysvar bytes are deterministic for this input, not fatal.
impl From<InvalidSysvarDataError> for DbError {
    fn from(error: InvalidSysvarDataError) -> Self {
        Self::non_fatal(error)
    }
}

/// Program-cache load failures (`InvalidAccountData`, `IncorrectProgramId`,
/// `MissingAccount`) are deterministic for this input, not fatal.
impl From<InstructionError> for DbError {
    fn from(error: InstructionError) -> Self {
        Self::non_fatal(error)
    }
}

/// Fallible database result. Returned by the migrated database layer
/// (`Accounts::prewarm` in `crate::accounts_db`); other
/// database entry points keep their current signatures until their owning
/// tasks migrate them (see the module docs above).
pub type DbResult<T> = Result<T, DbError>;

/// Load-layer error: which load site produced the [`DbError`].
///
/// Deferred wiring: `add_account`/`sync_accounts` (sysvar validation) and
/// `load_program`/`rebuild_program_cache` (program validation) still surface
/// [`HPSVMError`] directly; their migration to `LoadError::Sysvar` /
/// `LoadError::Program` belongs to a future database-layer task. Account
/// reads migrate through the [`DbError`] conversions first.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum LoadError {
    /// An account read failed at the source.
    Account(DbError),
    /// A program load failed validation.
    Program(DbError),
    /// A managed sysvar failed validation.
    Sysvar(DbError),
}

impl LoadError {
    /// Wraps an account-read failure.
    pub const fn account(error: DbError) -> Self {
        Self::Account(error)
    }

    /// Wraps a program-load failure.
    pub const fn program(error: DbError) -> Self {
        Self::Program(error)
    }

    /// Wraps a sysvar-validation failure.
    pub const fn sysvar(error: DbError) -> Self {
        Self::Sysvar(error)
    }

    /// Returns the underlying database error, whatever the load site.
    pub const fn db_error(&self) -> &DbError {
        match self {
            Self::Account(error) | Self::Program(error) | Self::Sysvar(error) => error,
        }
    }

    /// Delegates to the underlying database error's fatal classification.
    pub const fn is_fatal(&self) -> bool {
        self.db_error().is_fatal()
    }
}

impl std::fmt::Display for LoadError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Account(error) => write!(f, "failed to load account: {error}"),
            Self::Program(error) => write!(f, "failed to load program: {error}"),
            Self::Sysvar(error) => write!(f, "failed to load sysvar: {error}"),
        }
    }
}

impl std::error::Error for LoadError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(self.db_error())
    }
}

/// Transaction-validation failure.
///
/// Deferred wiring: [`TxHandler::validate`](crate::TxHandler::validate)
/// still binds to [`HPSVMError`]; migrating that signature to
/// `TxValidationError` belongs to a future registry task. The conversion
/// here is what that task will use at the boundary.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum TxValidationError {
    /// The transaction envelope failed validation.
    Invalid(TransactionError),
}

impl TxValidationError {
    /// Returns the underlying transaction error.
    pub fn transaction_error(&self) -> TransactionError {
        match self {
            Self::Invalid(error) => error.clone(),
        }
    }
}

impl From<TransactionError> for TxValidationError {
    fn from(error: TransactionError) -> Self {
        Self::Invalid(error)
    }
}

impl std::fmt::Display for TxValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Invalid(error) => write!(f, "transaction validation failed: {error}"),
        }
    }
}

impl std::error::Error for TxValidationError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Invalid(error) => Some(error),
        }
    }
}

/// Machine halt reason, without stringly-typed payloads.
///
/// Only real halts observed in this codebase are represented:
/// [`AlreadyProcessed`](HaltReason::AlreadyProcessed) (duplicate transaction,
/// see history and execution paths) and a [`Transaction`](HaltReason::Transaction) wrapper for
/// every other `TransactionError` halt.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum HaltReason {
    /// The transaction was already processed (duplicate).
    AlreadyProcessed,
    /// Any other halt, carrying the exact transaction error.
    Transaction(TransactionError),
}

impl HaltReason {
    /// Returns the transaction error this halt reports on chain.
    pub fn transaction_error(&self) -> TransactionError {
        match self {
            Self::AlreadyProcessed => TransactionError::AlreadyProcessed,
            Self::Transaction(error) => error.clone(),
        }
    }
}

impl From<TransactionError> for HaltReason {
    fn from(error: TransactionError) -> Self {
        match error {
            TransactionError::AlreadyProcessed => Self::AlreadyProcessed,
            other => Self::Transaction(other),
        }
    }
}

impl std::fmt::Display for HaltReason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::AlreadyProcessed => write!(f, "transaction already processed"),
            Self::Transaction(error) => write!(f, "halted: {error}"),
        }
    }
}

impl std::error::Error for HaltReason {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::AlreadyProcessed => None,
            Self::Transaction(error) => Some(error),
        }
    }
}

/// Execution-layer error: database failure, erased fatal, or machine halt.
///
/// Deferred wiring: the `process_transaction` internals still report through
/// `ExecutionResult` (in `crate::types`) with an
/// [`HPSVMError`] fatal transport; migrating them to `ExecutionError`
/// belongs to a future execution task. The account-source failure path is
/// wired through
/// `AccountSourceLoadFailure::into_execution_error` (in `crate::accounts_db`).
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum ExecutionError {
    /// The database layer failed; fatal-ness comes from the inner error.
    Database(DbError),
    /// An erased fatal failure; recover the concrete error by downcast.
    Fatal(Box<AnyError>),
    /// The machine halted; the reason carries no strings.
    Halt(HaltReason),
}

impl ExecutionError {
    /// Returns `true` for halts and erased fatals, and delegates to the
    /// inner database error otherwise.
    pub fn is_fatal(&self) -> bool {
        match self {
            Self::Database(error) => error.is_fatal(),
            Self::Fatal(_) | Self::Halt(_) => true,
        }
    }

    /// Returns the database error for the `Database` variant, if present.
    pub const fn db_error(&self) -> Option<&DbError> {
        match self {
            Self::Database(error) => Some(error),
            Self::Fatal(_) | Self::Halt(_) => None,
        }
    }
}

impl From<DbError> for ExecutionError {
    fn from(error: DbError) -> Self {
        Self::Database(error)
    }
}

impl From<HaltReason> for ExecutionError {
    fn from(reason: HaltReason) -> Self {
        Self::Halt(reason)
    }
}

impl From<AnyError> for ExecutionError {
    fn from(error: AnyError) -> Self {
        Self::Fatal(Box::new(error))
    }
}

impl std::fmt::Display for ExecutionError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Database(error) => write!(f, "{error}"),
            Self::Fatal(error) => write!(f, "{error}"),
            Self::Halt(reason) => write!(f, "execution halted: {reason}"),
        }
    }
}

impl std::error::Error for ExecutionError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Database(error) => Some(error),
            Self::Fatal(error) => Some(error.as_ref()),
            Self::Halt(reason) => Some(reason),
        }
    }
}

/// Transaction-layer error: validation, execution, or database.
///
/// Deferred wiring: [`TxRegistry::dispatch`](crate::TxRegistry::dispatch)
/// still reports [`TxRegistryError`](crate::TxRegistryError);
/// [`TxRegistryError::into_tx_error`](crate::TxRegistryError::into_tx_error)
/// maps that boundary onto this type without changing the signature, and a
/// future registry task will switch the signature itself.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum TxError {
    /// The transaction failed validation (deterministic, never fatal).
    Validation(TxValidationError),
    /// The transaction failed during execution.
    Execution(ExecutionError),
    /// The database layer failed; fatal-ness comes from the inner error.
    Database(DbError),
}

impl TxError {
    /// Validation rejections are deterministic, never fatal. Execution and
    /// database failures delegate to their inner classification.
    pub fn is_fatal(&self) -> bool {
        match self {
            Self::Validation(_) => false,
            Self::Execution(error) => error.is_fatal(),
            Self::Database(error) => error.is_fatal(),
        }
    }
}

impl From<TxValidationError> for TxError {
    fn from(error: TxValidationError) -> Self {
        Self::Validation(error)
    }
}

impl From<ExecutionError> for TxError {
    fn from(error: ExecutionError) -> Self {
        Self::Execution(error)
    }
}

impl From<DbError> for TxError {
    fn from(error: DbError) -> Self {
        Self::Database(error)
    }
}

impl std::fmt::Display for TxError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Validation(error) => write!(f, "{error}"),
            Self::Execution(error) => write!(f, "{error}"),
            Self::Database(error) => write!(f, "{error}"),
        }
    }
}

impl std::error::Error for TxError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Validation(error) => Some(error),
            Self::Execution(error) => Some(error),
            Self::Database(error) => Some(error),
        }
    }
}

/// Host-layer error: a machine halt or an execution failure.
///
/// Deferred wiring: the host entry points (`try_transact`, `transact_core`)
/// still surface [`HPSVMError`]; switching them to `HostError` belongs to a
/// future host-boundary task.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum HostError {
    /// The machine halted.
    Halt(HaltReason),
    /// Execution failed.
    Execution(ExecutionError),
}

impl HostError {
    /// Halts are always fatal; execution failures delegate inward.
    pub fn is_fatal(&self) -> bool {
        match self {
            Self::Halt(_) => true,
            Self::Execution(error) => error.is_fatal(),
        }
    }
}

impl From<HaltReason> for HostError {
    fn from(reason: HaltReason) -> Self {
        Self::Halt(reason)
    }
}

impl From<ExecutionError> for HostError {
    fn from(error: ExecutionError) -> Self {
        Self::Execution(error)
    }
}

impl std::fmt::Display for HostError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Halt(reason) => write!(f, "{reason}"),
            Self::Execution(error) => write!(f, "{error}"),
        }
    }
}

impl std::error::Error for HostError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Halt(reason) => Some(reason),
            Self::Execution(error) => Some(error),
        }
    }
}

/// Handler-layer error: the erased failure of one `TxHandler`.
///
/// This is the boundary type the registry's erased dispatch will use: a
/// handler's concrete [`HPSVMError`] is erased here and recovered later by
/// [`downcast_ref`](HandlerError::downcast_ref). The `TxHandler` trait still
/// binds to [`HPSVMError`] directly; migrating it belongs to a future
/// registry task.
#[derive(Clone)]
pub struct HandlerError(AnyError);

impl HandlerError {
    /// Erases a handler failure, preserving it for later downcast recovery.
    pub fn new<E>(error: E) -> Self
    where
        E: std::error::Error + Send + Sync + 'static,
    {
        Self(AnyError::new(error))
    }

    /// Consumes the wrapper and returns the erased error.
    pub fn into_inner(self) -> AnyError {
        self.0
    }

    /// Recovers a reference to the concrete error of type `T`, if present.
    pub fn downcast_ref<T>(&self) -> Option<&T>
    where
        T: std::error::Error + 'static,
    {
        self.0.downcast_ref::<T>()
    }

    /// Returns `true` when the wrapped error is of type `T`.
    pub fn is<T>(&self) -> bool
    where
        T: std::error::Error + 'static,
    {
        self.0.is::<T>()
    }
}

impl std::fmt::Debug for HandlerError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("HandlerError").field(&self.0.to_string()).finish()
    }
}

impl std::fmt::Display for HandlerError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl std::error::Error for HandlerError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.0)
    }
}

impl From<HPSVMError> for HandlerError {
    fn from(error: HPSVMError) -> Self {
        Self::new(error)
    }
}

impl From<AnyError> for HandlerError {
    fn from(error: AnyError) -> Self {
        Self(error)
    }
}

impl From<crate::TxRegistryError> for HandlerError {
    fn from(error: crate::TxRegistryError) -> Self {
        Self::new(error)
    }
}

#[cfg(test)]
mod tests {
    use solana_transaction::InstructionError;

    use super::*;
    use crate::account_source::AccountSourceErrorKind;

    /// Every `InvalidSysvarDataError` variant must render a message that names
    /// the offending sysvar, and the `#[from]` conversion must preserve it.
    #[test]
    fn invalid_sysvar_data_error_variants_render_and_convert() {
        let cases: [(InvalidSysvarDataError, &str); 9] = [
            (InvalidSysvarDataError::Clock, "Invalid Clock sysvar data."),
            (InvalidSysvarDataError::EpochRewards, "Invalid EpochRewards sysvar data."),
            (InvalidSysvarDataError::EpochSchedule, "Invalid EpochSchedule sysvar data."),
            (InvalidSysvarDataError::Fees, "Invalid Fees sysvar data."),
            (InvalidSysvarDataError::LastRestartSlot, "Invalid LastRestartSlot sysvar data."),
            (InvalidSysvarDataError::RecentBlockhashes, "Invalid RecentBlockhashes sysvar data."),
            (InvalidSysvarDataError::Rent, "Invalid Rent sysvar data."),
            (InvalidSysvarDataError::SlotHashes, "Invalid SlotHashes sysvar data."),
            (InvalidSysvarDataError::StakeHistory, "Invalid StakeHistory sysvar data."),
        ];

        for (error, expected) in cases {
            assert_eq!(error.to_string(), expected);
            // `HPSVMError::InvalidSysvarData` delegates rendering to the inner error.
            let wrapped = HPSVMError::from(error);
            assert!(matches!(wrapped, HPSVMError::InvalidSysvarData(_)));
            assert_eq!(wrapped.to_string(), expected);
        }
    }

    #[test]
    fn sysvar_serialization_error_renders_sysvar_and_reason() {
        let error = HPSVMError::SysvarSerialization {
            sysvar: "EpochSchedule",
            reason: "slot index out of range".to_string(),
        };
        assert_eq!(
            error.to_string(),
            "failed to serialize sysvar EpochSchedule: slot index out of range"
        );
    }

    #[test]
    fn instruction_error_conversion_preserves_payload() {
        let error = HPSVMError::from(InstructionError::InvalidArgument);
        match &error {
            HPSVMError::Instruction(InstructionError::InvalidArgument) => {}
            other => panic!("expected HPSVMError::Instruction, got {other:?}"),
        }
        assert_eq!(error.to_string(), InstructionError::InvalidArgument.to_string());
    }

    #[test]
    fn invalid_path_error_converts_from_io_error() {
        let io_error = std::io::Error::new(std::io::ErrorKind::NotFound, "missing program.so");
        let error = HPSVMError::from(io_error);
        match &error {
            HPSVMError::InvalidPath(io) => assert_eq!(io.kind(), std::io::ErrorKind::NotFound),
            other => panic!("expected HPSVMError::InvalidPath, got {other:?}"),
        }
        assert_eq!(error.to_string(), "missing program.so");
    }

    #[test]
    fn runtime_environment_error_renders_version_and_reason() {
        let error = HPSVMError::RuntimeEnvironment {
            version: "v1",
            reason: "custom syscall replay failed".to_string(),
        };
        assert_eq!(
            error.to_string(),
            "failed to refresh runtime environment v1: custom syscall replay failed"
        );
    }

    #[test]
    fn custom_syscall_registration_error_renders_name_runtime_and_reason() {
        let error = HPSVMError::CustomSyscallRegistration {
            name: "sol_alloc_free_".to_string(),
            runtime: "runtime",
            reason: "duplicate registration".to_string(),
        };
        assert_eq!(
            error.to_string(),
            "failed to register custom syscall sol_alloc_free_ in runtime: duplicate registration"
        );
    }

    #[test]
    fn invalid_loader_error_renders_program_and_loader_ids() {
        let program_id = Address::new_unique();
        let loader_id = Address::new_unique();
        let error = HPSVMError::InvalidLoader { program_id, loader_id };
        assert_eq!(
            error.to_string(),
            format!("unsupported loader {loader_id} for program {program_id}")
        );
    }

    #[test]
    fn missing_runtime_component_error_renders_component() {
        let error = HPSVMError::MissingRuntimeComponent { component: "loader_cache" };
        assert_eq!(error.to_string(), "missing runtime component: loader_cache");
    }

    #[test]
    fn account_source_error_renders_pubkey_and_underlying_source() {
        let pubkey = Address::new_unique();
        let source = AccountSourceError::new("rpc endpoint unreachable");
        let error = HPSVMError::AccountSource { pubkey, source };

        assert_eq!(
            error.to_string(),
            format!(
                "account source failed while loading {pubkey}: Unavailable: rpc endpoint unreachable"
            )
        );
    }

    #[test]
    fn program_load_error_renders_message() {
        let error = HPSVMError::ProgramLoad("ELF header is truncated".to_string());
        assert_eq!(error.to_string(), "failed to load program: ELF header is truncated");
    }

    #[test]
    fn boxed_error_converts_to_program_load() {
        let boxed: Box<dyn std::error::Error> = Box::new(std::io::Error::other("bad magic"));
        let error = HPSVMError::from(boxed);
        match &error {
            HPSVMError::ProgramLoad(message) => assert_eq!(message, "bad magic"),
            other => panic!("expected HPSVMError::ProgramLoad, got {other:?}"),
        }
    }

    #[test]
    fn account_source_error_is_classifiable_through_hpsvm_error() {
        // `HPSVMError::AccountSource` must not erase the source error's kind.
        let source = AccountSourceError::with_kind(
            AccountSourceErrorKind::InvalidResponse,
            "malformed json",
        );
        let error = HPSVMError::AccountSource { pubkey: Address::new_unique(), source };

        match error {
            HPSVMError::AccountSource { source, .. } => {
                assert_eq!(source.kind(), AccountSourceErrorKind::InvalidResponse);
            }
            other => panic!("expected HPSVMError::AccountSource, got {other:?}"),
        }
    }

    #[test]
    fn unknown_transaction_tag_error_renders_tag() {
        use crate::tx_registry::TxTag;
        let error = HPSVMError::UnknownTransactionTag { tag: TxTag::Custom(9) };
        assert_eq!(error.to_string(), "no transaction handler registered for tag Custom(9)");
    }

    #[test]
    fn registry_unknown_tag_converts_into_hpsvm_error() {
        use crate::{TxRegistryError, tx_registry::TxTag};
        let error = HPSVMError::from(TxRegistryError::UnknownTag(TxTag::V0));
        match &error {
            HPSVMError::UnknownTransactionTag { tag } => assert_eq!(*tag, TxTag::V0),
            other => panic!("expected HPSVMError::UnknownTransactionTag, got {other:?}"),
        }
    }

    #[test]
    fn registry_handler_failure_passes_the_hpsvm_error_through() {
        use crate::TxRegistryError;
        let error = HPSVMError::from(TxRegistryError::HandlerFailed(HPSVMError::ProgramLoad(
            "boom".to_string(),
        )));
        match &error {
            HPSVMError::ProgramLoad(message) => assert_eq!(message, "boom"),
            other => panic!("expected HPSVMError::ProgramLoad, got {other:?}"),
        }
    }
}

// ---------------------------------------------------------------------------
// Task 7.1 (TDD RED): layered error taxonomy (§3.10).
//
// These tests name the taxonomy types before they exist, so this module fails
// to compile until the taxonomy is added below the `HPSVMError` section.
// Every assertion matches an exact variant (never `is_err`) and every
// classification travels in types, never in strings.
// ---------------------------------------------------------------------------
#[cfg(test)]
mod task71_taxonomy_tests {
    use solana_transaction_error::TransactionError;

    use super::*;
    use crate::account_source::{AccountSourceError, AccountSourceErrorKind};

    #[test]
    fn any_error_downcast_round_trip_recovers_the_concrete_type() {
        let original =
            AccountSourceError::with_kind(AccountSourceErrorKind::InvalidResponse, "bad body");
        let erased = AnyError::new(original.clone());

        assert!(erased.is::<AccountSourceError>());
        assert!(!erased.is::<std::io::Error>());
        let recovered = erased
            .downcast_ref::<AccountSourceError>()
            .expect("AnyError must recover the concrete source error");
        assert_eq!(recovered, &original);
        assert_eq!(recovered.kind(), AccountSourceErrorKind::InvalidResponse);
        assert!(erased.downcast_ref::<std::io::Error>().is_none());
    }

    #[test]
    fn any_error_survives_a_boxed_erased_boundary() {
        let erased = AnyError::new(AccountSourceError::new("rpc down"));
        let boxed: Box<dyn std::error::Error + Send + Sync> = Box::new(erased);
        let outer = boxed
            .downcast_ref::<AnyError>()
            .expect("AnyError must survive a boxed erased boundary");
        let recovered = outer
            .downcast_ref::<AccountSourceError>()
            .expect("concrete error must be recoverable after double erasure");
        assert_eq!(recovered.kind(), AccountSourceErrorKind::Unavailable);
        assert_eq!(recovered.message(), "rpc down");
    }

    #[test]
    fn db_error_from_io_error_is_non_fatal_and_recoverable() {
        let db_error =
            DbError::from(std::io::Error::new(std::io::ErrorKind::NotFound, "missing program.so"));
        assert!(!db_error.is_fatal());
        let io =
            db_error.downcast_ref::<std::io::Error>().expect("DbError must recover the io error");
        assert_eq!(io.kind(), std::io::ErrorKind::NotFound);
    }

    #[test]
    fn db_error_fatal_matrix_over_account_source_kinds() {
        for (kind, fatal) in [
            (AccountSourceErrorKind::Unavailable, true),
            (AccountSourceErrorKind::InvalidResponse, false),
            (AccountSourceErrorKind::Other, false),
        ] {
            let db_error = DbError::from(AccountSourceError::with_kind(kind, "boom"));
            assert_eq!(db_error.is_fatal(), fatal, "kind {kind:?} must map to fatal={fatal}");
            // The mapping must survive an erased boundary: erase into
            // `AnyError`, recover the `DbError`, and the flag is intact.
            let erased = AnyError::new(db_error);
            let recovered = erased
                .downcast_ref::<DbError>()
                .expect("DbError must be recoverable from AnyError");
            assert_eq!(recovered.is_fatal(), fatal, "kind {kind:?} must stay fatal={fatal}");
            let source = recovered
                .downcast_ref::<AccountSourceError>()
                .expect("AccountSourceError must be recoverable through DbError");
            assert_eq!(source.kind(), kind);
        }
    }

    #[test]
    fn db_result_alias_carries_db_error() {
        let ok: DbResult<u32> = Ok(7);
        match ok {
            Ok(value) => assert_eq!(value, 7),
            Err(error) => panic!("expected DbResult::Ok, got {error:?}"),
        }
        let err: DbResult<u32> = Err(DbError::non_fatal(AccountSourceError::with_kind(
            AccountSourceErrorKind::Other,
            "x",
        )));
        match err {
            Err(error) => assert!(!error.is_fatal()),
            Ok(_) => panic!("expected DbResult::Err, got Ok"),
        }
    }

    #[test]
    fn load_error_variants_carry_their_db_error_and_fatal_flag() {
        let fatal_db = DbError::from(AccountSourceError::new("rpc down"));
        let non_fatal_db =
            DbError::from(AccountSourceError::with_kind(AccountSourceErrorKind::Other, "custom"));

        let account = LoadError::account(fatal_db);
        let program = LoadError::program(non_fatal_db.clone());
        let sysvar = LoadError::sysvar(non_fatal_db);

        match &account {
            LoadError::Account(inner) => assert!(inner.is_fatal()),
            other => panic!("expected LoadError::Account, got {other:?}"),
        }
        match &program {
            LoadError::Program(inner) => assert!(!inner.is_fatal()),
            other => panic!("expected LoadError::Program, got {other:?}"),
        }
        match &sysvar {
            LoadError::Sysvar(inner) => assert!(!inner.is_fatal()),
            other => panic!("expected LoadError::Sysvar, got {other:?}"),
        }
        assert!(account.db_error().is_fatal());
        assert!(!program.db_error().is_fatal());
        assert_eq!(account.to_string(), "failed to load account: Unavailable: rpc down");
        assert_eq!(program.to_string(), "failed to load program: Other: custom");
        assert_eq!(sysvar.to_string(), "failed to load sysvar: Other: custom");
    }

    #[test]
    fn tx_validation_error_wraps_the_transaction_error() {
        let validation = TxValidationError::from(TransactionError::BlockhashNotFound);
        match &validation {
            TxValidationError::Invalid(TransactionError::BlockhashNotFound) => {}
            other => panic!("expected TxValidationError::Invalid, got {other:?}"),
        }
        assert_eq!(validation.to_string(), "transaction validation failed: Blockhash not found");
    }

    #[test]
    fn tx_error_variants_and_from_conversions_cover_every_layer() {
        let validation =
            TxError::from(TxValidationError::Invalid(TransactionError::BlockhashNotFound));
        match &validation {
            TxError::Validation(TxValidationError::Invalid(
                TransactionError::BlockhashNotFound,
            )) => {}
            other => panic!("expected TxError::Validation, got {other:?}"),
        }
        assert!(!validation.is_fatal());

        let execution = TxError::from(ExecutionError::from(HaltReason::AlreadyProcessed));
        match &execution {
            TxError::Execution(ExecutionError::Halt(HaltReason::AlreadyProcessed)) => {}
            other => panic!("expected TxError::Execution(Halt), got {other:?}"),
        }
        assert!(execution.is_fatal());

        let fatal_db = DbError::from(AccountSourceError::new("rpc down"));
        let database = TxError::from(fatal_db);
        match &database {
            TxError::Database(inner) => assert!(inner.is_fatal()),
            other => panic!("expected TxError::Database, got {other:?}"),
        }
        assert!(database.is_fatal());
    }

    #[test]
    fn execution_error_variants_distinguish_database_fatal_and_halt() {
        let non_fatal_db =
            DbError::from(AccountSourceError::with_kind(AccountSourceErrorKind::Other, "custom"));
        let database = ExecutionError::from(non_fatal_db);
        match &database {
            ExecutionError::Database(inner) => assert!(!inner.is_fatal()),
            other => panic!("expected ExecutionError::Database, got {other:?}"),
        }
        assert!(!database.is_fatal());

        let fatal =
            ExecutionError::Fatal(Box::new(AnyError::new(AccountSourceError::new("rpc down"))));
        match &fatal {
            ExecutionError::Fatal(_) => {}
            other => panic!("expected ExecutionError::Fatal, got {other:?}"),
        }
        assert!(fatal.is_fatal());
        match fatal.db_error() {
            // A `Fatal` erasure carries no `DbError` classification.
            None => {}
            Some(_) => panic!("expected no DbError inside ExecutionError::Fatal"),
        }

        let halt = ExecutionError::from(HaltReason::Transaction(TransactionError::AccountInUse));
        match &halt {
            ExecutionError::Halt(HaltReason::Transaction(TransactionError::AccountInUse)) => {}
            other => panic!("expected ExecutionError::Halt, got {other:?}"),
        }
        assert!(halt.is_fatal());
    }

    #[test]
    fn halt_reason_covers_real_halts_without_stringly_typed_reasons() {
        let already = HaltReason::AlreadyProcessed;
        assert_eq!(already.transaction_error(), TransactionError::AlreadyProcessed);
        assert_eq!(already.to_string(), "transaction already processed");

        let wrapped = HaltReason::Transaction(TransactionError::InsufficientFundsForFee);
        assert_eq!(wrapped.transaction_error(), TransactionError::InsufficientFundsForFee);
        match &wrapped {
            HaltReason::Transaction(TransactionError::InsufficientFundsForFee) => {}
            other => panic!("expected HaltReason::Transaction, got {other:?}"),
        }
    }

    #[test]
    fn host_error_variants_and_from_conversions() {
        let halt = HostError::from(HaltReason::AlreadyProcessed);
        match &halt {
            HostError::Halt(HaltReason::AlreadyProcessed) => {}
            other => panic!("expected HostError::Halt, got {other:?}"),
        }
        assert!(halt.is_fatal());

        let execution = HostError::from(ExecutionError::from(DbError::from(
            AccountSourceError::with_kind(AccountSourceErrorKind::Other, "custom"),
        )));
        match &execution {
            HostError::Execution(ExecutionError::Database(_)) => {}
            other => panic!("expected HostError::Execution(Database), got {other:?}"),
        }
        assert!(!execution.is_fatal());
    }

    #[test]
    fn handler_error_round_trip_recovers_the_hpsvm_error() {
        let handler = HandlerError::from(HPSVMError::ProgramLoad("boom".to_string()));
        let recovered =
            handler.downcast_ref::<HPSVMError>().expect("HandlerError must recover the HPSVMError");
        match recovered {
            HPSVMError::ProgramLoad(message) => assert_eq!(message, "boom"),
            other => panic!("expected HPSVMError::ProgramLoad, got {other:?}"),
        }
        assert_eq!(handler.to_string(), "failed to load program: boom");
    }

    #[test]
    fn hpsvm_error_outer_variants_preserve_every_layer_losslessly() {
        let db_error = DbError::from(AccountSourceError::new("rpc down"));
        let error = HPSVMError::from(db_error);
        match &error {
            HPSVMError::Database(inner) => {
                assert!(inner.is_fatal());
                let source = inner
                    .downcast_ref::<AccountSourceError>()
                    .expect("AccountSourceError must survive the HPSVMError boundary");
                assert_eq!(source.kind(), AccountSourceErrorKind::Unavailable);
            }
            other => panic!("expected HPSVMError::Database, got {other:?}"),
        }

        let error = HPSVMError::from(LoadError::account(DbError::from(AccountSourceError::new(
            "rpc down",
        ))));
        assert!(
            matches!(error, HPSVMError::Load(LoadError::Account(_))),
            "expected HPSVMError::Load(Account), got {error:?}"
        );

        let error = HPSVMError::from(TxError::from(TxValidationError::Invalid(
            TransactionError::BlockhashNotFound,
        )));
        assert!(
            matches!(error, HPSVMError::Transaction(TxError::Validation(_))),
            "expected HPSVMError::Transaction(Validation), got {error:?}"
        );

        let error = HPSVMError::from(ExecutionError::from(HaltReason::AlreadyProcessed));
        assert!(
            matches!(error, HPSVMError::Execution(ExecutionError::Halt(_))),
            "expected HPSVMError::Execution(Halt), got {error:?}"
        );

        let error = HPSVMError::from(HostError::from(HaltReason::AlreadyProcessed));
        assert!(
            matches!(error, HPSVMError::Host(HostError::Halt(_))),
            "expected HPSVMError::Host(Halt), got {error:?}"
        );

        let error =
            HPSVMError::from(HandlerError::from(HPSVMError::ProgramLoad("boom".to_string())));
        assert!(
            matches!(error, HPSVMError::Handler(_)),
            "expected HPSVMError::Handler, got {error:?}"
        );
    }

    #[test]
    fn fatal_at_db_is_still_fatal_after_host_crossing() {
        // A fatal database error (infrastructure down) must remain
        // distinguishable as fatal after crossing the erased `AnyError`
        // boundary and the public `HPSVMError` boundary.
        let db_error = DbError::from(AccountSourceError::new("rpc down"));
        assert!(db_error.is_fatal());

        let erased = AnyError::new(db_error);
        let recovered =
            erased.downcast_ref::<DbError>().expect("DbError must be recoverable from AnyError");
        assert!(recovered.is_fatal());

        let host = HPSVMError::from(HostError::from(ExecutionError::Database(
            erased
                .downcast_ref::<DbError>()
                .expect("DbError must be recoverable a second time")
                .clone(),
        )));
        match &host {
            HPSVMError::Host(HostError::Execution(ExecutionError::Database(inner))) => {
                assert!(inner.is_fatal(), "fatal-at-DB must still be fatal after host");
            }
            other => panic!("expected HPSVMError::Host(Execution(Database)), got {other:?}"),
        }
    }

    #[test]
    fn taxonomy_types_are_send_sync_and_static_for_handler_erasure() {
        fn assert_send_sync_static<T: Send + Sync + 'static>() {}
        assert_send_sync_static::<AnyError>();
        assert_send_sync_static::<DbError>();
        assert_send_sync_static::<LoadError>();
        assert_send_sync_static::<TxValidationError>();
        assert_send_sync_static::<HaltReason>();
        assert_send_sync_static::<ExecutionError>();
        assert_send_sync_static::<TxError>();
        assert_send_sync_static::<HostError>();
        assert_send_sync_static::<HandlerError>();
        assert_send_sync_static::<HPSVMError>();
    }
}