hfim-cli 1.15.6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (288) hide show
  1. fim/__init__.py +42 -0
  2. fim/analysis/__init__.py +53 -0
  3. fim/analysis/burst_sdc.py +160 -0
  4. fim/analysis/classifier.py +924 -0
  5. fim/analysis/comparator.py +738 -0
  6. fim/analysis/consolidate.py +625 -0
  7. fim/analysis/csv_io.py +28 -0
  8. fim/analysis/ecc_quartet.py +167 -0
  9. fim/analysis/nvm_endurance_matrix.py +170 -0
  10. fim/analysis/observable_state.py +945 -0
  11. fim/analysis/reporter.py +712 -0
  12. fim/analysis/results_txt.py +229 -0
  13. fim/campaigns/__init__.py +28 -0
  14. fim/campaigns/base_campaign.py +5151 -0
  15. fim/campaigns/cache_campaign.py +233 -0
  16. fim/campaigns/campaign_view.py +135 -0
  17. fim/campaigns/csr_campaign.py +31 -0
  18. fim/campaigns/fault_plan.py +105 -0
  19. fim/campaigns/faultlist_builder.py +503 -0
  20. fim/campaigns/gem5_parallel_runner.py +210 -0
  21. fim/campaigns/golden_gate.py +158 -0
  22. fim/campaigns/injection_point_selector.py +473 -0
  23. fim/campaigns/memory_campaign.py +686 -0
  24. fim/campaigns/parallel_runner.py +510 -0
  25. fim/campaigns/register_campaign.py +617 -0
  26. fim/campaigns/serial_feeder.py +169 -0
  27. fim/cli.py +2652 -0
  28. fim/configs/benchmarks/bitcount.yaml +11 -0
  29. fim/configs/benchmarks/checksum.yaml +11 -0
  30. fim/configs/benchmarks/dotprod_f64.yaml +12 -0
  31. fim/configs/benchmarks/fibonacci.yaml +10 -0
  32. fim/configs/boards/board_spec_schema.yaml +216 -0
  33. fim/configs/boards/raspberry_pi_5.yaml +122 -0
  34. fim/configs/boards/xuantie_c906.yaml +127 -0
  35. fim/configs/boards/xuantie_c906_ruby_nvmain.yaml +85 -0
  36. fim/configs/dramsim3/DDR3_1Gb_x8_1333.ini +69 -0
  37. fim/configs/dramsim3/DDR3_4Gb_x16_1600.ini +67 -0
  38. fim/configs/dramsim3/DDR3_4Gb_x16_1866.ini +67 -0
  39. fim/configs/dramsim3/DDR3_4Gb_x4_1600.ini +67 -0
  40. fim/configs/dramsim3/DDR3_4Gb_x4_1866.ini +67 -0
  41. fim/configs/dramsim3/DDR3_4Gb_x8_1600.ini +67 -0
  42. fim/configs/dramsim3/DDR3_4Gb_x8_1866.ini +67 -0
  43. fim/configs/dramsim3/DDR3_8Gb_x16_1600.ini +67 -0
  44. fim/configs/dramsim3/DDR3_8Gb_x16_1866.ini +67 -0
  45. fim/configs/dramsim3/DDR3_8Gb_x4_1600.ini +67 -0
  46. fim/configs/dramsim3/DDR3_8Gb_x4_1866.ini +67 -0
  47. fim/configs/dramsim3/DDR3_8Gb_x8_1600.ini +67 -0
  48. fim/configs/dramsim3/DDR3_8Gb_x8_1866.ini +67 -0
  49. fim/configs/dramsim3/DDR4_4Gb_x16_1866.ini +67 -0
  50. fim/configs/dramsim3/DDR4_4Gb_x16_2133.ini +67 -0
  51. fim/configs/dramsim3/DDR4_4Gb_x16_2133_2.ini +67 -0
  52. fim/configs/dramsim3/DDR4_4Gb_x16_2400.ini +67 -0
  53. fim/configs/dramsim3/DDR4_4Gb_x16_2400_2.ini +67 -0
  54. fim/configs/dramsim3/DDR4_4Gb_x16_2666.ini +67 -0
  55. fim/configs/dramsim3/DDR4_4Gb_x16_2666_2.ini +67 -0
  56. fim/configs/dramsim3/DDR4_4Gb_x4_1866.ini +67 -0
  57. fim/configs/dramsim3/DDR4_4Gb_x4_2133.ini +67 -0
  58. fim/configs/dramsim3/DDR4_4Gb_x4_2133_2.ini +67 -0
  59. fim/configs/dramsim3/DDR4_4Gb_x4_2400.ini +67 -0
  60. fim/configs/dramsim3/DDR4_4Gb_x4_2400_2.ini +67 -0
  61. fim/configs/dramsim3/DDR4_4Gb_x4_2666.ini +67 -0
  62. fim/configs/dramsim3/DDR4_4Gb_x4_2666_2.ini +67 -0
  63. fim/configs/dramsim3/DDR4_4Gb_x8_1866.ini +67 -0
  64. fim/configs/dramsim3/DDR4_4Gb_x8_2133.ini +67 -0
  65. fim/configs/dramsim3/DDR4_4Gb_x8_2133_2.ini +67 -0
  66. fim/configs/dramsim3/DDR4_4Gb_x8_2400.ini +67 -0
  67. fim/configs/dramsim3/DDR4_4Gb_x8_2400_2.ini +67 -0
  68. fim/configs/dramsim3/DDR4_4Gb_x8_2666.ini +67 -0
  69. fim/configs/dramsim3/DDR4_4Gb_x8_2666_2.ini +67 -0
  70. fim/configs/dramsim3/DDR4_8Gb_x16_1866.ini +67 -0
  71. fim/configs/dramsim3/DDR4_8Gb_x16_2133.ini +67 -0
  72. fim/configs/dramsim3/DDR4_8Gb_x16_2133_2.ini +67 -0
  73. fim/configs/dramsim3/DDR4_8Gb_x16_2400.ini +67 -0
  74. fim/configs/dramsim3/DDR4_8Gb_x16_2400_2.ini +67 -0
  75. fim/configs/dramsim3/DDR4_8Gb_x16_2666.ini +67 -0
  76. fim/configs/dramsim3/DDR4_8Gb_x16_2666_2.ini +67 -0
  77. fim/configs/dramsim3/DDR4_8Gb_x16_2933.ini +67 -0
  78. fim/configs/dramsim3/DDR4_8Gb_x16_2933_2.ini +67 -0
  79. fim/configs/dramsim3/DDR4_8Gb_x16_3200.ini +67 -0
  80. fim/configs/dramsim3/DDR4_8Gb_x4_1866.ini +67 -0
  81. fim/configs/dramsim3/DDR4_8Gb_x4_2133.ini +67 -0
  82. fim/configs/dramsim3/DDR4_8Gb_x4_2133_2.ini +67 -0
  83. fim/configs/dramsim3/DDR4_8Gb_x4_2400.ini +67 -0
  84. fim/configs/dramsim3/DDR4_8Gb_x4_2400_2.ini +67 -0
  85. fim/configs/dramsim3/DDR4_8Gb_x4_2666.ini +67 -0
  86. fim/configs/dramsim3/DDR4_8Gb_x4_2666_2.ini +67 -0
  87. fim/configs/dramsim3/DDR4_8Gb_x4_2933.ini +67 -0
  88. fim/configs/dramsim3/DDR4_8Gb_x4_2933_2.ini +67 -0
  89. fim/configs/dramsim3/DDR4_8Gb_x4_3200.ini +67 -0
  90. fim/configs/dramsim3/DDR4_8Gb_x8_1866.ini +67 -0
  91. fim/configs/dramsim3/DDR4_8Gb_x8_2133.ini +67 -0
  92. fim/configs/dramsim3/DDR4_8Gb_x8_2133_2.ini +67 -0
  93. fim/configs/dramsim3/DDR4_8Gb_x8_2400.ini +77 -0
  94. fim/configs/dramsim3/DDR4_8Gb_x8_2400_2.ini +67 -0
  95. fim/configs/dramsim3/DDR4_8Gb_x8_2666.ini +67 -0
  96. fim/configs/dramsim3/DDR4_8Gb_x8_2666_2.ini +67 -0
  97. fim/configs/dramsim3/DDR4_8Gb_x8_2933.ini +67 -0
  98. fim/configs/dramsim3/DDR4_8Gb_x8_2933_2.ini +67 -0
  99. fim/configs/dramsim3/DDR4_8Gb_x8_3200.ini +67 -0
  100. fim/configs/ecc_policies/c906.yaml +26 -0
  101. fim/configs/matmul_aarch64.yaml +62 -0
  102. fim/configs/mcpat/c906.xml +481 -0
  103. fim/configs/mcpat/raspberry_pi_5.xml +405 -0
  104. fim/configs/mcpat/sTemplate.xml +444 -0
  105. fim/configs/mcpat/template.xml +405 -0
  106. fim/configs/mmult.yaml +140 -0
  107. fim/configs/mmult_memory_gem5.yaml +23 -0
  108. fim/configs/nvmain/2D_DRAM_example.config +249 -0
  109. fim/configs/nvmain/3D_DRAMCache_OffChipMemory_example.config +154 -0
  110. fim/configs/nvmain/3D_DRAMCache_example.config +275 -0
  111. fim/configs/nvmain/3D_DRAM_example.config +237 -0
  112. fim/configs/nvmain/3D_PredictorDRC_example.config +277 -0
  113. fim/configs/nvmain/3D_VariableDRC_example.config +278 -0
  114. fim/configs/nvmain/Hybrid_DRAM_channel.config +249 -0
  115. fim/configs/nvmain/Hybrid_NVM_channel.config +208 -0
  116. fim/configs/nvmain/Hybrid_NVM_channel_BitModel.config +208 -0
  117. fim/configs/nvmain/Hybrid_example.config +72 -0
  118. fim/configs/nvmain/Hybrid_example_BitModel.config +72 -0
  119. fim/configs/nvmain/PCM_ISSCC_2012_4GB.config +217 -0
  120. fim/configs/nvmain/PCM_ISSCC_2012_4GB_BitModel.config +217 -0
  121. fim/configs/nvmain/PCM_ISSCC_2012_4GB_BitModel_ECP.config +222 -0
  122. fim/configs/nvmain/PCM_ISSCC_2012_4GB_ByteModel.config +217 -0
  123. fim/configs/nvmain/PCM_ISSCC_2012_4GB_RowModel.config +217 -0
  124. fim/configs/nvmain/PCM_ISSCC_2012_4GB_WordModel.config +217 -0
  125. fim/configs/nvmain/PCM_MLC_estimated.config +233 -0
  126. fim/configs/nvmain/PCM_MLC_example.config +232 -0
  127. fim/configs/nvmain/PCM_MLC_example_BitModel.config +232 -0
  128. fim/configs/nvmain/PerfectMemory.config +229 -0
  129. fim/configs/nvmain/RRAM_ISSCC_2012_4GB.config +218 -0
  130. fim/configs/nvmain/STTRAM_Everspin_4GB.config +217 -0
  131. fim/configs/nvmain/STTRAM_Everspin_4GB_BitModel.config +217 -0
  132. fim/configs/nvmain/printtrace.config +145 -0
  133. fim/configs/nvmain/printtrace_bitflip.config +146 -0
  134. fim/configs/quicksort_dmr.yaml +225 -0
  135. fim/configs/rust_sort_array.yaml +28 -0
  136. fim/configs/rust_sort_bss.yaml +38 -0
  137. fim/configs/sum.yaml +149 -0
  138. fim/configs/template.yaml +418 -0
  139. fim/configs/toolchains.remote.json +14 -0
  140. fim/core/__init__.py +161 -0
  141. fim/core/artifacts/__init__.py +25 -0
  142. fim/core/artifacts/adapters/__init__.py +146 -0
  143. fim/core/artifacts/adapters/board.py +38 -0
  144. fim/core/artifacts/adapters/config.py +115 -0
  145. fim/core/artifacts/adapters/sdk.py +435 -0
  146. fim/core/artifacts/adapters/simulator.py +139 -0
  147. fim/core/artifacts/adapters/template.py +107 -0
  148. fim/core/artifacts/classification.py +95 -0
  149. fim/core/artifacts/hashing.py +265 -0
  150. fim/core/artifacts/inputs.py +179 -0
  151. fim/core/artifacts/records.py +238 -0
  152. fim/core/artifacts/retention.py +504 -0
  153. fim/core/artifacts/staleness.py +486 -0
  154. fim/core/artifacts/store.py +202 -0
  155. fim/core/artifacts/workspace.py +108 -0
  156. fim/core/checkpoint.py +338 -0
  157. fim/core/checkpoint_policy.py +171 -0
  158. fim/core/classifier_view.py +96 -0
  159. fim/core/clock_view.py +99 -0
  160. fim/core/configuration/__init__.py +13 -0
  161. fim/core/configuration/frozen.py +85 -0
  162. fim/core/configuration/groups.py +41 -0
  163. fim/core/configuration/includes.py +249 -0
  164. fim/core/configuration/lifecycle_rules.py +83 -0
  165. fim/core/configuration/reference.py +200 -0
  166. fim/core/configuration/reference_docs.py +344 -0
  167. fim/core/configuration/resolver.py +495 -0
  168. fim/core/configuration/run_context.py +51 -0
  169. fim/core/configuration/schema.py +784 -0
  170. fim/core/configuration/sources.py +121 -0
  171. fim/core/configuration/template_pins.py +79 -0
  172. fim/core/fault_models.py +261 -0
  173. fim/core/fim.py +452 -0
  174. fim/core/gdb_controller.py +2053 -0
  175. fim/core/gem5_controller.py +1226 -0
  176. fim/core/gem5_launch.py +489 -0
  177. fim/core/gem5_observable.py +202 -0
  178. fim/core/gem5_producers.py +684 -0
  179. fim/core/gem5_simulator.py +724 -0
  180. fim/core/golden_view.py +94 -0
  181. fim/core/hardware_cluster.py +236 -0
  182. fim/core/hardware_simulator.py +992 -0
  183. fim/core/hardware_spec.py +352 -0
  184. fim/core/hardware_station.py +374 -0
  185. fim/core/hardware_view.py +64 -0
  186. fim/core/hardware_window.py +102 -0
  187. fim/core/hook_view.py +52 -0
  188. fim/core/lifecycle.py +433 -0
  189. fim/core/machine_binding.py +317 -0
  190. fim/core/ovp_plan.py +419 -0
  191. fim/core/ovp_protocol.py +647 -0
  192. fim/core/ovp_simulator.py +1201 -0
  193. fim/core/ovp_view.py +99 -0
  194. fim/core/qemu_controller.py +1396 -0
  195. fim/core/qemu_launch.py +179 -0
  196. fim/core/qemu_simulator.py +329 -0
  197. fim/core/results_store.py +218 -0
  198. fim/core/results_view.py +94 -0
  199. fim/core/simulator_controller.py +298 -0
  200. fim/core/simulator_manifest.py +739 -0
  201. fim/core/station_host.py +277 -0
  202. fim/install/__init__.py +16 -0
  203. fim/install/ensure.py +182 -0
  204. fim/install/home.py +126 -0
  205. fim/install/index.py +122 -0
  206. fim/install/index.yaml +59 -0
  207. fim/install/prebuilt.py +120 -0
  208. fim/install/probes.py +182 -0
  209. fim/install/remote.py +165 -0
  210. fim/install/sdk.py +178 -0
  211. fim/install/setup.py +184 -0
  212. fim/install/simulators.py +323 -0
  213. fim/install/template.py +147 -0
  214. fim/install/uninstall.py +149 -0
  215. fim/provision/__init__.py +48 -0
  216. fim/provision/catalog.py +278 -0
  217. fim/provision/commands.py +1051 -0
  218. fim/provision/doctor.py +291 -0
  219. fim/provision/drain.py +117 -0
  220. fim/provision/forms/__init__.py +4 -0
  221. fim/provision/forms/docker.py +469 -0
  222. fim/provision/forms/fake.py +281 -0
  223. fim/provision/forms/native.py +438 -0
  224. fim/provision/fresh_layout.py +66 -0
  225. fim/provision/hostdeps.py +229 -0
  226. fim/provision/layout_units.py +148 -0
  227. fim/provision/lock.py +100 -0
  228. fim/provision/package.py +110 -0
  229. fim/provision/plan.py +356 -0
  230. fim/provision/privilege.py +259 -0
  231. fim/provision/probe.py +117 -0
  232. fim/provision/release.py +188 -0
  233. fim/provision/sdk.py +102 -0
  234. fim/provision/steps.py +324 -0
  235. fim/provision/switch.py +80 -0
  236. fim/provision/switch_recovery.py +165 -0
  237. fim/remote/__init__.py +15 -0
  238. fim/remote/access/__init__.py +203 -0
  239. fim/remote/access/credential.py +46 -0
  240. fim/remote/access/credentials/__init__.py +4 -0
  241. fim/remote/access/credentials/command.py +50 -0
  242. fim/remote/access/credentials/keychain.py +50 -0
  243. fim/remote/access/credentials/none.py +16 -0
  244. fim/remote/access/credentials/peer.py +25 -0
  245. fim/remote/access/credentials/token.py +50 -0
  246. fim/remote/access/spec.py +34 -0
  247. fim/remote/access/transport.py +66 -0
  248. fim/remote/access/transports/__init__.py +4 -0
  249. fim/remote/access/transports/command.py +222 -0
  250. fim/remote/access/transports/direct.py +39 -0
  251. fim/remote/access/transports/ssh_tunnel.py +74 -0
  252. fim/remote/api.py +245 -0
  253. fim/remote/commands.py +625 -0
  254. fim/remote/fetch.py +155 -0
  255. fim/remote/follow.py +157 -0
  256. fim/remote/journal.py +150 -0
  257. fim/remote/location.py +108 -0
  258. fim/remote/preflight.py +350 -0
  259. fim/remote/servers.py +159 -0
  260. fim/remote/snapshot.py +249 -0
  261. fim/remote/submit.py +302 -0
  262. fim/scripts/__init__.py +2 -0
  263. fim/scripts/generate_report.py +108 -0
  264. fim/scripts/run_campaign.py +1447 -0
  265. fim/scripts/run_ecc_quartet.py +94 -0
  266. fim/scripts/run_golden.py +2256 -0
  267. fim/scripts/verify_provenance.py +61 -0
  268. fim/utils/__init__.py +74 -0
  269. fim/utils/board.py +378 -0
  270. fim/utils/board_view.py +39 -0
  271. fim/utils/config.py +1714 -0
  272. fim/utils/coredump.py +28 -0
  273. fim/utils/elf_parser.py +1118 -0
  274. fim/utils/elf_provenance.py +140 -0
  275. fim/utils/injection_file_writer.py +309 -0
  276. fim/utils/logger.py +362 -0
  277. fim/utils/picker.py +195 -0
  278. fim/utils/prng.py +207 -0
  279. fim/utils/provenance.py +873 -0
  280. fim/utils/register_width.py +52 -0
  281. hfim_cli-1.15.6.data/data/share/hfim/gem5_to_mcpat.py +508 -0
  282. hfim_cli-1.15.6.dist-info/METADATA +131 -0
  283. hfim_cli-1.15.6.dist-info/RECORD +288 -0
  284. hfim_cli-1.15.6.dist-info/WHEEL +5 -0
  285. hfim_cli-1.15.6.dist-info/entry_points.txt +2 -0
  286. hfim_cli-1.15.6.dist-info/licenses/LICENSE +21 -0
  287. hfim_cli-1.15.6.dist-info/licenses/THIRD_PARTY_NOTICES +166 -0
  288. hfim_cli-1.15.6.dist-info/top_level.txt +1 -0
@@ -0,0 +1,924 @@
1
+ # SPDX-FileCopyrightText: 2026 HI-REST and the HFIM contributors
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """
5
+ Outcome classifier for fault injection results.
6
+
7
+ This module implements the FAIL* methodology for classifying fault injection
8
+ outcomes into five categories: MASKED, SDC, DETECTED, CRASH, and TIMEOUT.
9
+
10
+ Classification Priority (highest to lowest):
11
+ 1. TIMEOUT: Execution exceeded time limit
12
+ 2. INFRASTRUCTURE_FAILURE: Fault was never written to hardware (verify_injection mismatch)
13
+ 3. CRASH: System crash, hang, or exception
14
+ 4. DETECTED: Benchmark's own detection triggered
15
+ 5. SDC: Silent Data Corruption (output differs, undetected)
16
+ 6. MASKED: Fault had no observable effect
17
+
18
+ References:
19
+ - FAIL*: A Framework for Assessing the Fault Tolerance of Soft Error Mitigation Techniques
20
+ - Hari et al., "Relyzer: Exploiting application-level fault equivalence to analyze
21
+ application resiliency to transient faults" (ASPLOS 2012)
22
+ """
23
+
24
+ from enum import Enum
25
+ from typing import Any, Iterable, List, Optional, TYPE_CHECKING
26
+
27
+ if TYPE_CHECKING:
28
+ from fim.analysis.comparator import StateComparator
29
+ from fim.analysis.observable_state import ObservableState
30
+
31
+
32
+ class Outcome(Enum):
33
+ """
34
+ Fault injection outcome categories following FAIL* methodology.
35
+
36
+ Attributes:
37
+ MASKED: Fault had no observable effect on output.
38
+ SDC: Silent Data Corruption - wrong output, undetected by benchmark.
39
+ DETECTED: Benchmark detected the fault (e.g., DMR mismatch).
40
+ CRASH: System crash, exception, hang, or abnormal termination.
41
+ TIMEOUT: Execution exceeded configured timeout limit.
42
+ UNKNOWN: Classification failed or indeterminate.
43
+ """
44
+ MASKED = "masked"
45
+ SDC = "sdc"
46
+ DETECTED = "detected"
47
+ CRASH = "crash"
48
+ TIMEOUT = "timeout"
49
+ UNKNOWN = "unknown"
50
+ INFRASTRUCTURE_FAILURE = "infrastructure_failure"
51
+ # NVMain endurance-driven stuck-at after N writes
52
+ STUCK_AFTER_WEAR = "stuck_after_wear"
53
+ # Cache ECC on read. A fault sat in the cache long enough
54
+ # to be evicted without ever being read. Distinct from MASKED (which
55
+ # means the workload computed correctly *despite* observing the
56
+ # corrupted bits): a latent fault was never observed.
57
+ # LATENT_CLEAN - line evicted clean; fault discarded with the line.
58
+ # LATENT_DIRTY - line evicted dirty; corrupted bytes propagated to
59
+ # L2 / DRAM with stale check bits (Liu et al. 2022
60
+ # deferred writeback model).
61
+ LATENT_CLEAN = "latent_clean"
62
+ LATENT_DIRTY = "latent_dirty"
63
+ # ECC check-bit injection. A fault in the SRAM cells
64
+ # holding ECC check bits (not data bits) produces:
65
+ # - false-correct: decoder sees nonzero syndrome on a clean line,
66
+ # miscorrects a data bit, SDC results. The SECDED guarantee is
67
+ # ITSELF broken by this failure mode.
68
+ # - false-DUE: decoder signals 2-bit error on a clean line (no
69
+ # real data fault) - surfaces as DETECTED in our taxonomy.
70
+ # ECC_FALSE_CORRECT is the dedicated bucket; false-DUE rolls into
71
+ # DETECTED because the workload-side signature is identical.
72
+ ECC_FALSE_CORRECT = "ecc_false_correct"
73
+ # Tag-array parity injection outcomes. The tag SRAM
74
+ # cell flipped; depending on whether the corrupted tag still
75
+ # matches the lookup, the workload sees:
76
+ # TAG_FALSE_MISS - would-have-hit becomes miss; extra L2/DRAM
77
+ # fetch but the data the CPU reads is clean.
78
+ # Workload-visible signature: slower.
79
+ # TAG_FALSE_HIT - would-have-missed accidentally matches some
80
+ # other resident block's tag; the CPU reads
81
+ # bytes from the wrong line. Silent SDC; the
82
+ # data ECC syndrome wouldn't catch it.
83
+ # TAG_LATENT - corrupted tag never visited (line evicted
84
+ # before the next lookup that would have
85
+ # triggered the verdict).
86
+ TAG_FALSE_MISS = "tag_false_miss"
87
+ TAG_FALSE_HIT = "tag_false_hit"
88
+ TAG_LATENT = "tag_latent"
89
+
90
+ def __str__(self) -> str:
91
+ """Return lowercase string representation."""
92
+ return self.value
93
+
94
+
95
+
96
+ # ---------------------------------------------------------------------------
97
+ # Outcome vocabulary - the ONE place the outcome strings are enumerated.
98
+ # run_campaign, consolidate, reporter, ecc_quartet and burst_sdc derive
99
+ # every outcome list from the enum so a new outcome cannot silently drop
100
+ # out of a summary or a quartet filter.
101
+ # ---------------------------------------------------------------------------
102
+
103
+ # The classic five plus unknown, in the order summaries print them.
104
+ # INFRASTRUCTURE_FAILURE belongs here even though it describes the
105
+ # framework rather than the chip: a summary that lists six outcomes
106
+ # under "Total injections: 10" invites reading rates off a denominator
107
+ # that never ran. Counting it keeps the arithmetic honest; the outcome
108
+ # name says plainly that those runs measured nothing.
109
+ CORE_OUTCOME_ORDER = [
110
+ Outcome.MASKED.value, Outcome.SDC.value, Outcome.DETECTED.value,
111
+ Outcome.CRASH.value, Outcome.TIMEOUT.value, Outcome.UNKNOWN.value,
112
+ Outcome.INFRASTRUCTURE_FAILURE.value,
113
+ ]
114
+
115
+ # Report ordering: most severe first (reporter.py bar charts).
116
+ REPORT_OUTCOME_ORDER = [
117
+ Outcome.SDC.value, Outcome.CRASH.value, Outcome.TIMEOUT.value,
118
+ Outcome.DETECTED.value, Outcome.MASKED.value, Outcome.UNKNOWN.value,
119
+ ]
120
+
121
+ # Outcomes that describe the simulated silicon (a fault was written and
122
+ # the run finished with a verdict). Excludes UNKNOWN and
123
+ # INFRASTRUCTURE_FAILURE, which describe the framework, not the chip.
124
+ NON_SILICON_OUTCOMES = frozenset({
125
+ Outcome.UNKNOWN.value, Outcome.INFRASTRUCTURE_FAILURE.value,
126
+ })
127
+ SILICON_OUTCOMES = frozenset(
128
+ o.value for o in Outcome if o.value not in NON_SILICON_OUTCOMES
129
+ )
130
+
131
+ # Module-level set for fast "is this a valid outcome class?" checks
132
+ # Used by the outcome registration contract.
133
+ OUTCOME_CLASSES = frozenset(o.value for o in Outcome)
134
+
135
+
136
+ # Signatures of "simulator aborted mid-run" - to distinguish a genuine
137
+ # simulator crash (CRASH outcome) from a framework wiring gap
138
+ # (INFRASTRUCTURE_FAILURE outcome). Added to fix
139
+ # CLASSIFIER-CONSISTENCY-1: gem5 O3CPU's
140
+ # `void gem5::o3::Commit::commitInsts(): Assertion ... failed`
141
+ # was being classified as INFRASTRUCTURE_FAILURE because state_dump.json
142
+ # never got written. It's a real simulator-level crash; should be
143
+ # reported as CRASH consistently with the wearstorm/NVMain
144
+ # "gem5 teardown noise" path which uses error_message tagging.
145
+ _SIMULATOR_ABORT_SIGNATURES = (
146
+ "program aborted at tick", # gem5 assertion / panic / fatal
147
+ "panic:", # gem5 panic message prefix
148
+ "fatal:", # gem5 fatal_if / fatal
149
+ "Assertion `", # generic C++ assertion (gem5, NVMain, etc.)
150
+ "segmentation fault", # SIGSEGV from a SimObject
151
+ "--- BEGIN LIBC BACKTRACE ---", # gem5's backtrace banner
152
+ "QEMU: Terminated", # qemu plugin path equivalent
153
+ )
154
+
155
+
156
+ # The ONE crash decision. Both simulator controllers fill
157
+ # InjectionRun.crashed through this function, and classify() consumes the
158
+ # flag plus the raw evidence, so the controllers, classify_batch and
159
+ # base_campaign share one rule and the evidence is never rewritten to make
160
+ # the classifier agree with the controller.
161
+
162
+ CRASH_SIGNATURES = (
163
+ "panic", "abort", "fatal", "segfault", "segmentation fault",
164
+ "page table fault",
165
+ )
166
+
167
+ INFRA_MARKERS = (
168
+ "infrastructure failure",
169
+ "failed to start qemu",
170
+ "exited immediately",
171
+ # Post-launch port theft: QEMU bound its port, then a second
172
+ # process stole it before GDB connected. The fault was never
173
+ # written, so this is infra, not a fault-induced crash.
174
+ "failed to connect gdb",
175
+ )
176
+
177
+
178
+ def is_infrastructure_message(error_message: Optional[str]) -> bool:
179
+ if not error_message:
180
+ return False
181
+ em = error_message.lower()
182
+ return any(m in em for m in INFRA_MARKERS)
183
+
184
+
185
+ def decide_crash(
186
+ exit_code: Optional[int],
187
+ completed: Optional[bool] = None,
188
+ exit_cause: str = "",
189
+ error_message: Optional[str] = None,
190
+ timed_out: bool = False,
191
+ ) -> bool:
192
+ """Decide whether a run's evidence says the simulated program crashed.
193
+
194
+ Rules, in order:
195
+ 1. A timeout is never a crash (TIMEOUT owns it).
196
+ 2. An abort signature in the exit cause or error message is a crash,
197
+ whether or not the run "completed" (a post-injection panic still
198
+ writes stats before gem5 aborts).
199
+ 3. A framework marker in the error message is never a crash (the
200
+ fault was never written; INFRASTRUCTURE_FAILURE owns it).
201
+ 4. A completed run (stats + injection report present) is not a crash
202
+ even with a non-zero exit code: gem5 v23 SE-mode segfaults in
203
+ Py_FinalizeEx AFTER the run, on every run including golden.
204
+ 5. exit_code > 1 is a crash. exit_code == 1 is the benchmark's own
205
+ DETECTED convention (fim_exit(1)), never a crash.
206
+ 6. A transport error with no exit status at all (gdb lost the
207
+ target) is a crash.
208
+ """
209
+ if timed_out:
210
+ return False
211
+ text = f"{exit_cause or ''} {error_message or ''}".lower()
212
+ if any(sig in text for sig in CRASH_SIGNATURES):
213
+ return True
214
+ if is_infrastructure_message(error_message):
215
+ return False
216
+ if completed:
217
+ return False
218
+ if exit_code is not None and exit_code > 1:
219
+ return True
220
+ if exit_code is None and error_message:
221
+ return True
222
+ return False
223
+
224
+
225
+ def _looks_like_simulator_abort(output: str) -> bool:
226
+ """Return True iff `output` contains a known simulator-abort
227
+ signature. Used by classify() to disambiguate
228
+ `observed_state is None` between "simulator crashed" (CRASH)
229
+ and "framework wiring missing" (INFRASTRUCTURE_FAILURE).
230
+ """
231
+ if not output:
232
+ return False
233
+ lowered = output.lower()
234
+ for sig in _SIMULATOR_ABORT_SIGNATURES:
235
+ if sig.lower() in lowered:
236
+ return True
237
+ return False
238
+
239
+
240
+ def override_outcome_for_endurance(result: Any) -> None:
241
+ """Endurance hook - if NVMain reported an endurance failure for this
242
+ injection, override the instruction-level outcome with STUCK_AFTER_WEAR.
243
+
244
+ Endurance failure dominates because it represents a physical-medium
245
+ failure mode that's orthogonal to whether the workload completed:
246
+ the cell died regardless of what the program was doing.
247
+
248
+ Pure function, idempotent. Operates on the InjectionResult-shaped object
249
+ (anything with `.endurance_failed` and `.outcome` attributes).
250
+ """
251
+ if getattr(result, "endurance_failed", None) is True:
252
+ result.outcome = Outcome.STUCK_AFTER_WEAR.value
253
+
254
+
255
+ def override_outcome_for_cache_ecc(result: Any) -> None:
256
+ """Cache ECC hook - reclassify based on cache ECC shadow-map verdict.
257
+
258
+ Override matrix:
259
+ - cache_evicted_unread True + classifier said masked/sdc/etc
260
+ -> LATENT_CLEAN or LATENT_DIRTY (depending on the dirty flag
261
+ captured by the producer; producer sets outcome directly).
262
+ - cache_ecc_detected_bits == 2 + cache_ecc_engaged True
263
+ -> DETECTED (SECDED-DUE; processor would trap in silicon).
264
+ - cache_ecc_corrected True + classifier said sdc
265
+ -> MASKED (decoder corrected the bit; SDC is impossible).
266
+ We trust the C++ verdict over a UART/state-dump
267
+ misclassification.
268
+ - everything else: leave classifier verdict alone.
269
+
270
+ The producer already sets `result.outcome` to latent_* / detected
271
+ when applicable; this function reapplies the rules after
272
+ classify_batch overwrites outcome from UART/state. Pure function,
273
+ idempotent.
274
+ """
275
+ engaged = getattr(result, "cache_ecc_engaged", None)
276
+ if engaged is None:
277
+ return
278
+
279
+ evicted_unread = getattr(result, "cache_evicted_unread", None) is True
280
+ corrected = getattr(result, "cache_ecc_corrected", None) is True
281
+ detected_bits = getattr(result, "cache_ecc_detected_bits", None)
282
+ false_correct = getattr(result, "ecc_false_correct", None) is True
283
+
284
+ if false_correct:
285
+ # ECC check-bit fault miscorrected a clean data bit.
286
+ # Override regardless of classifier verdict.
287
+ result.outcome = Outcome.ECC_FALSE_CORRECT.value
288
+ return
289
+
290
+ if evicted_unread:
291
+ # Producer set outcome to latent_clean/latent_dirty. If
292
+ # classify_batch overwrote it (masked / sdc / etc), recover
293
+ # the dirty/clean distinction from the producer's snapshot
294
+ # at result.cache_evicted_dirty. The two outcomes are
295
+ # silicon-distinct: latent_dirty propagated stale bytes to
296
+ # L2/DRAM, latent_clean was discarded with the line.
297
+ # Confusing them silently downgrades real propagation events
298
+ # to no-ops in the SDC accounting.
299
+ if result.outcome not in (
300
+ Outcome.LATENT_CLEAN.value, Outcome.LATENT_DIRTY.value
301
+ ):
302
+ cache_dirty = getattr(result, "cache_evicted_dirty", None)
303
+ if cache_dirty is True:
304
+ result.outcome = Outcome.LATENT_DIRTY.value
305
+ else:
306
+ result.outcome = Outcome.LATENT_CLEAN.value
307
+ return
308
+
309
+ if engaged and detected_bits == 2:
310
+ # SECDED detected uncorrectable.
311
+ if result.outcome != Outcome.DETECTED.value:
312
+ result.outcome = Outcome.DETECTED.value
313
+ return
314
+
315
+ if corrected and result.outcome == Outcome.SDC.value:
316
+ # The classifier saw a UART/state mismatch and called SDC, but
317
+ # the ECC decoder corrected the bit before it reached the CPU.
318
+ # The mismatch must be from somewhere else (test bug); trust
319
+ # ECC and call it masked. Log on the result.sdc_details so the
320
+ # reviewer can spot the discrepancy.
321
+ prev_details = getattr(result, "sdc_details", "") or ""
322
+ result.sdc_details = (
323
+ (prev_details + " | " if prev_details else "")
324
+ + "[cache ECC corrected; classifier SDC overridden -> masked]"
325
+ )
326
+ result.outcome = Outcome.MASKED.value
327
+
328
+
329
+ def override_outcome_for_tag_parity(result: Any) -> None:
330
+ """Tag parity hook - reclassify based on tag-array parity verdict.
331
+
332
+ The producer sets `result.outcome` to tag_false_miss /
333
+ tag_false_hit / tag_latent when FIM-TAG markers were emitted.
334
+ `classify_batch` then overwrites outcome from UART/state. This
335
+ function reapplies the tag verdict afterward.
336
+
337
+ Override matrix:
338
+ - tag_fault_engaged True + producer-set tag_* outcome
339
+ -> preserve the tag_* outcome (classifier verdict wrong here
340
+ because the workload-side signature for a tag fault is
341
+ often invisible: false_miss looks like extra latency,
342
+ false_hit looks like correct data from a wrong line).
343
+ - tag_fault_engaged True + no producer-set tag_* outcome
344
+ -> default to tag_latent (the inform marker fired but the
345
+ workload exit beat it).
346
+ """
347
+ engaged = getattr(result, "tag_fault_engaged", None)
348
+ if engaged is not True:
349
+ return
350
+
351
+ tag_outcomes = (
352
+ Outcome.TAG_FALSE_MISS.value,
353
+ Outcome.TAG_FALSE_HIT.value,
354
+ Outcome.TAG_LATENT.value,
355
+ )
356
+ if result.outcome not in tag_outcomes:
357
+ # classify_batch overwrote the producer's tag verdict.
358
+ # Restore from the producer's snapshot when present - silently
359
+ # collapsing tag_false_hit (silent SDC) into tag_latent (no-op)
360
+ # would lose a real silicon-visible event in the SDC accounting.
361
+ snapshot = getattr(result, "tag_verdict_snapshot", None)
362
+ if snapshot in tag_outcomes:
363
+ result.outcome = snapshot
364
+ else:
365
+ # Conservative fallback - the fault registered but no
366
+ # producer-side verdict survived. tag_latent is the
367
+ # silicon-faithful no-effect interpretation.
368
+ result.outcome = Outcome.TAG_LATENT.value
369
+
370
+
371
+ class ClassifierError(Exception):
372
+ """Base exception for classifier-related errors."""
373
+ pass
374
+
375
+
376
+ def outcome_statistics(outcomes: Iterable[str]) -> dict:
377
+ """The outcome distribution of a campaign, from its outcomes alone.
378
+
379
+ OutcomeClassifier.get_statistics documents the dictionary. It stands
380
+ apart from the classifier because the fleet's consolidate() has CSV rows
381
+ and no golden reference to build a classifier from.
382
+ """
383
+ outcomes = list(outcomes)
384
+ total = len(outcomes)
385
+ if total == 0:
386
+ return {
387
+ 'total': 0,
388
+ 'valid_total': 0,
389
+ 'masked': {'count': 0, 'percentage': 0.0},
390
+ 'sdc': {'count': 0, 'percentage': 0.0},
391
+ 'detected': {'count': 0, 'percentage': 0.0},
392
+ 'crash': {'count': 0, 'percentage': 0.0},
393
+ 'timeout': {'count': 0, 'percentage': 0.0},
394
+ 'unknown': {'count': 0, 'percentage': 0.0},
395
+ 'dmr_effectiveness': 0.0,
396
+ }
397
+
398
+ # Count outcomes
399
+ counts = {outcome.value: 0 for outcome in Outcome}
400
+ for outcome in outcomes:
401
+ if outcome in counts:
402
+ counts[outcome] += 1
403
+ else:
404
+ counts['unknown'] += 1
405
+
406
+ # Calculate percentages. Framework rows (infrastructure_failure,
407
+ # unknown) say nothing about the silicon, so the outcome rates are
408
+ # over the valid rows only; the framework rows keep a share of the
409
+ # full total so they stay visible.
410
+ invalid = sum(counts[o] for o in NON_SILICON_OUTCOMES)
411
+ valid_total = total - invalid
412
+ stats = {'total': total, 'valid_total': valid_total}
413
+ for outcome_value in counts:
414
+ count = counts[outcome_value]
415
+ base = total if outcome_value in NON_SILICON_OUTCOMES else valid_total
416
+ percentage = (count / base) * 100.0 if base > 0 else 0.0
417
+ stats[outcome_value] = {
418
+ 'count': count,
419
+ 'percentage': percentage
420
+ }
421
+
422
+ # Calculate DMR effectiveness
423
+ # Effectiveness = DETECTED / (DETECTED + SDC + CRASH)
424
+ # This metric measures how well detection mechanisms work
425
+ detected = counts[Outcome.DETECTED.value]
426
+ sdc = counts[Outcome.SDC.value]
427
+ crash = counts[Outcome.CRASH.value]
428
+
429
+ denominator = detected + sdc + crash
430
+ if denominator > 0:
431
+ dmr_effectiveness = (detected / denominator) * 100.0
432
+ else:
433
+ dmr_effectiveness = 0.0
434
+
435
+ stats['dmr_effectiveness'] = dmr_effectiveness
436
+
437
+ return stats
438
+
439
+
440
+ class OutcomeClassifier:
441
+ """
442
+ Classifies fault injection results into outcome categories.
443
+
444
+ The classifier determines the outcome based on:
445
+ - Execution status (timeout, crash, normal completion)
446
+ - Output comparison with golden reference
447
+ - Detection string presence in output
448
+
449
+ Classification follows strict priority order to ensure consistency.
450
+
451
+ Example:
452
+ >>> classifier = OutcomeClassifier(
453
+ ... detection_string="MISMATCH",
454
+ ... golden_output="Expected result: 42"
455
+ ... )
456
+ >>> outcome = classifier.classify(
457
+ ... timed_out=False,
458
+ ... crashed=False,
459
+ ... output="Expected result: 42",
460
+ ... error_message=None
461
+ ... )
462
+ >>> print(outcome)
463
+ masked
464
+ """
465
+
466
+ def __init__(
467
+ self,
468
+ detection_string: Optional[str] = None,
469
+ golden_output: Optional[str] = None,
470
+ enable_strict_mode: bool = False,
471
+ state_comparator: Optional["StateComparator"] = None,
472
+ crash_patterns: Optional[List[str]] = None,
473
+ ):
474
+ """
475
+ Initialize the outcome classifier.
476
+
477
+ Args:
478
+ detection_string: String that indicates benchmark detected a fault
479
+ (e.g., "MISMATCH", "ERROR DETECTED"). Case-sensitive.
480
+ golden_output: Expected output from golden run for comparison.
481
+ enable_strict_mode: If True, require exact byte-for-byte match.
482
+ If False (default), use normalized comparison
483
+ (strips whitespace, ignores trailing newlines).
484
+ state_comparator: Optional StateComparator for variable-based SDC detection.
485
+ When provided, SDC/MASKED classification uses ObservableState
486
+ comparison instead of UART output comparison. This follows
487
+ FAIL* methodology and is immune to UART corruption.
488
+ crash_patterns: Output strings that mean the guest crashed
489
+ (e.g. "ZEPHYR FATAL ERROR"). Checked before the
490
+ timeout: an OS that halts after a fatal error
491
+ then times out, but the crash is the cause.
492
+
493
+ Raises:
494
+ ClassifierError: If both detection_string and golden_output are None
495
+ and state_comparator is also None.
496
+ """
497
+ if detection_string is None and golden_output is None and state_comparator is None:
498
+ raise ClassifierError(
499
+ "At least one of detection_string, golden_output, or state_comparator must be provided"
500
+ )
501
+
502
+ self.detection_string = detection_string
503
+ self.golden_output = golden_output
504
+ self.enable_strict_mode = enable_strict_mode
505
+ self.state_comparator = state_comparator
506
+ self.crash_patterns = list(crash_patterns or [])
507
+
508
+ # Store last observed state for debugging
509
+ self._last_observed_state: Optional["ObservableState"] = None
510
+ self._last_sdc_details: Optional[str] = None
511
+
512
+ def classify(
513
+ self,
514
+ timed_out: bool,
515
+ crashed: bool,
516
+ output: str,
517
+ error_message: Optional[str] = None,
518
+ exit_code: Optional[int] = None,
519
+ observed_state: Optional["ObservableState"] = None,
520
+ completed: Optional[bool] = None,
521
+ ) -> Outcome:
522
+ """
523
+ Classify a fault injection outcome.
524
+
525
+ Classification follows strict priority order:
526
+ 1. TIMEOUT: timed_out flag is True
527
+ 2. CRASH: exit_code > 1 OR (crashed flag is True OR error_message present)
528
+ 3. DETECTED: exit_code == 1 OR detection_string found in output
529
+ 4. SDC vs MASKED: Determined by state comparison or output comparison
530
+ - If state_comparator is configured AND observed_state provided:
531
+ * MASKED: observed_state matches golden state (regardless of UART)
532
+ * SDC: observed_state differs from golden state (regardless of UART)
533
+ - Otherwise (UART-based mode):
534
+ * MASKED: exit_code == 0 AND output matches golden_output
535
+ * SDC: exit_code == 0 AND output differs from golden_output
536
+
537
+ The exit_code from fim_exit() provides reliable classification:
538
+ - exit_code == 0: Benchmark completed successfully (MASKED or SDC)
539
+ - exit_code == 1: Benchmark detected an error (DETECTED)
540
+ - exit_code > 1: Benchmark crashed or unexpected error (CRASH)
541
+
542
+ Args:
543
+ timed_out: True if execution exceeded timeout limit.
544
+ crashed: True if execution crashed or terminated abnormally.
545
+ output: UART output captured during execution.
546
+ error_message: Error message if exception occurred (None if successful).
547
+ exit_code: QEMU exit code from fim_exit() (0=pass, 1=detected, >1=crash).
548
+ observed_state: Optional ObservableState captured at program end.
549
+ When provided with state_comparator, enables variable-based
550
+ SDC detection (FAIL* methodology).
551
+
552
+ Returns:
553
+ Outcome enum value indicating classification.
554
+
555
+ Raises:
556
+ ClassifierError: If classification cannot be determined.
557
+
558
+ Example:
559
+ >>> # UART-based classification
560
+ >>> classifier = OutcomeClassifier(
561
+ ... detection_string="DMR MISMATCH",
562
+ ... golden_output="Result: 100"
563
+ ... )
564
+ >>> classifier.classify(False, False, "Result: 100", None, 0)
565
+ <Outcome.MASKED: 'masked'>
566
+ >>> classifier.classify(False, False, "Result: 99", None, 0)
567
+ <Outcome.SDC: 'sdc'>
568
+ >>>
569
+ >>> # Variable-based classification (professional mode)
570
+ >>> state_comp = StateComparator("golden/benchmark")
571
+ >>> classifier = OutcomeClassifier(
572
+ ... detection_string="DMR MISMATCH",
573
+ ... state_comparator=state_comp
574
+ ... )
575
+ >>> observed = ObservableState.capture(gdb, elf, vars)
576
+ >>> classifier.classify(False, False, "", None, 0, observed)
577
+ <Outcome.MASKED: 'masked'> # if state matches golden
578
+ """
579
+ # Per-call comparison state. Left over from the previous row, it made
580
+ # a DETECTED/CRASH/TIMEOUT row (which returns before comparing) report
581
+ # the previous row's state_match.
582
+ self._last_sdc_details = None
583
+ self._last_observed_state = None
584
+
585
+ # Priority 0: the guest printed its own crash report. A halted OS
586
+ # then runs into the timeout, so this has to come first.
587
+ if self.crash_patterns and output and any(
588
+ p in output for p in self.crash_patterns):
589
+ return Outcome.CRASH
590
+
591
+ # Priority 1: TIMEOUT
592
+ if timed_out:
593
+ return Outcome.TIMEOUT
594
+
595
+ # Priority 2: INFRASTRUCTURE_FAILURE (before CRASH - fault was never written)
596
+ # A QEMU boot flake (process exits immediately, empty stdout/stderr) is
597
+ # NOT a fault-induced crash: no fault was ever written, so it must not
598
+ # count against the crash tally. Match both the explicit marker and the
599
+ # raw launch-failure signatures emitted at the QEMU start sites.
600
+ if is_infrastructure_message(error_message):
601
+ return Outcome.INFRASTRUCTURE_FAILURE
602
+
603
+ # Priority 3: CRASH
604
+ # The controller's verdict (decide_crash) wins. The raw exit code
605
+ # and error message only count when the run did NOT complete:
606
+ # a completed gem5 run (stats + injection report) exits non-zero
607
+ # on every run from the Py_FinalizeEx teardown segfault, and that
608
+ # noise must not become a silicon crash. Evidence is never
609
+ # rewritten upstream to get this effect.
610
+ if crashed:
611
+ return Outcome.CRASH
612
+ if not completed:
613
+ if exit_code is not None and exit_code > 1:
614
+ return Outcome.CRASH
615
+ if error_message:
616
+ return Outcome.CRASH
617
+
618
+ # Priority 3: DETECTED
619
+ # Check exit_code == 1 (benchmark detected error) or detection string in output
620
+ if exit_code == 1:
621
+ return Outcome.DETECTED
622
+ if self.detection_string and self.detection_string in output:
623
+ return Outcome.DETECTED
624
+
625
+ # Priority 4 & 5: SDC vs MASKED
626
+ # At this point, exit_code is 0 (success) or None (unknown)
627
+
628
+ # ─────────────────────────────────────────────────────────────
629
+ # AUTHORITY: when observable_outputs is configured
630
+ # AND state_dump.json is harvested, the byte-level state_dump
631
+ # is authoritative. UART is a fallback ONLY for QEMU
632
+ # benchmarks that publish results via stdout. This rule is
633
+ # gated by tests/test_classifier_authority.py.
634
+ # state_dump wins. Variable-based comparison takes precedence
635
+ # over UART-based.
636
+ # If state_comparator is configured we MUST have observed_state - otherwise
637
+ # the result is uninterpretable. Falling back to UART comparison silently
638
+ # would produce false SDCs for benchmarks like fibonacci that publish
639
+ # results via memory variables (empty golden UART vs. non-empty gem5
640
+ # framework prints would always mismatch). Surface this as an
641
+ # INFRASTRUCTURE_FAILURE so it's visible in the CSV instead of hiding
642
+ # behind a meaningless SDC/MASKED verdict.
643
+ if self.state_comparator is not None:
644
+ if observed_state is None:
645
+ # State capture didn't run. Two distinct reasons:
646
+ #
647
+ # (a) gem5 actually crashed mid-run (assertion failed,
648
+ # panic, SIGABRT) - the framework is fine, the
649
+ # simulated system aborted. This is a CRASH and
650
+ # should be reported as such.
651
+ #
652
+ # (b) State capture wiring is missing for a backend
653
+ # (e.g. QEMU on a memory-only benchmark with no
654
+ # observable_outputs path) - the framework is
655
+ # broken. This is an INFRASTRUCTURE_FAILURE.
656
+ #
657
+ # Pre-fix the classifier collapsed both cases to (b),
658
+ # which hid genuine simulator crashes (e.g. gem5 O3CPU's
659
+ # `Commit::commitInsts` assertion fires when register
660
+ # injection violates the thread-context invariants) as
661
+ # framework-bug noise. Disambiguate by sniffing `output`
662
+ # for known gem5/simulator abort signatures.
663
+ if _looks_like_simulator_abort(output):
664
+ return Outcome.CRASH
665
+ return Outcome.INFRASTRUCTURE_FAILURE
666
+
667
+ # Professional mode: Compare actual computation results (immune to UART corruption)
668
+ try:
669
+ match, differences = self.state_comparator.compare_state(observed_state)
670
+
671
+ # Store for get_sdc_details()
672
+ self._last_observed_state = observed_state
673
+
674
+ if match:
675
+ # Computation result matches golden - fault had no effect
676
+ self._last_sdc_details = None
677
+ return Outcome.MASKED
678
+ else:
679
+ # Computation result differs - Silent Data Corruption detected
680
+ self._last_sdc_details = self.state_comparator.get_sdc_details()
681
+ return Outcome.SDC
682
+
683
+ except Exception as e:
684
+ # State comparison itself raised against a real captured
685
+ # state (e.g. a typed-vs-bytes representation mismatch).
686
+ # Falling back to UART here is wrong: memory-published
687
+ # benchmarks have an empty golden UART, so every such row
688
+ # would compare equal and read as MASKED. The verdict is
689
+ # unknowable, so it is a framework failure.
690
+ from fim.utils.logger import get_logger
691
+ logger = get_logger("fim.analysis.classifier")
692
+ logger.error(f"State comparison failed: {e}")
693
+ self._last_sdc_details = None
694
+ return Outcome.INFRASTRUCTURE_FAILURE
695
+
696
+ # UART-based comparison
697
+ if self.golden_output is None:
698
+ # Cannot distinguish SDC from MASKED without golden output or state
699
+ # If we reached here, execution completed without timeout/crash/detection
700
+ # Conservative classification: assume UNKNOWN
701
+ return Outcome.UNKNOWN
702
+
703
+ # Compare output with golden reference
704
+ if self._outputs_match(output, self.golden_output):
705
+ return Outcome.MASKED
706
+ else:
707
+ return Outcome.SDC
708
+
709
+ def _outputs_match(self, output1: str, output2: str) -> bool:
710
+ """
711
+ Compare two outputs for equivalence.
712
+
713
+ In strict mode: exact byte-for-byte comparison.
714
+ In normal mode: normalized comparison (strip whitespace, ignore trailing newlines).
715
+
716
+ Args:
717
+ output1: First output string.
718
+ output2: Second output string.
719
+
720
+ Returns:
721
+ True if outputs are considered equivalent.
722
+ """
723
+ if self.enable_strict_mode:
724
+ return output1 == output2
725
+ else:
726
+ # Normalized comparison: strip leading/trailing whitespace
727
+ # This handles common variations in output formatting
728
+ normalized1 = output1.strip()
729
+ normalized2 = output2.strip()
730
+ return normalized1 == normalized2
731
+
732
+ def classify_batch(
733
+ self,
734
+ results: list,
735
+ golden_output: Optional[str] = None
736
+ ) -> list:
737
+ """
738
+ Classify multiple injection results in batch.
739
+
740
+ This is a convenience method for classifying many results at once.
741
+ Updates the 'outcome' field of each result in place.
742
+
743
+ Args:
744
+ results: List of InjectionResult objects to classify.
745
+ golden_output: Override golden output for this batch (optional).
746
+ If None, uses the classifier's initialized golden_output.
747
+
748
+ Returns:
749
+ List of classified results (same objects, modified in place).
750
+
751
+ Raises:
752
+ ClassifierError: If classification fails for any result.
753
+
754
+ Example:
755
+ >>> classifier = OutcomeClassifier(golden_output="OK")
756
+ >>> results = [result1, result2, result3]
757
+ >>> classified = classifier.classify_batch(results)
758
+ >>> all(r.outcome is not None for r in classified)
759
+ True
760
+ """
761
+ # Use provided golden_output if given, otherwise use initialized value
762
+ effective_golden = golden_output if golden_output is not None else self.golden_output
763
+
764
+ # Temporarily update golden_output if override provided
765
+ original_golden = self.golden_output
766
+ if golden_output is not None:
767
+ self.golden_output = golden_output
768
+
769
+ try:
770
+ for result in results:
771
+ # A harness exception row (_create_error_result: the run
772
+ # never produced an injection record) carries only the
773
+ # exception text. Deriving TIMEOUT/CRASH from that text
774
+ # turns "GDB MI response timeout" into a silicon TIMEOUT
775
+ # and a KeyError into a CRASH, so these rows are framework
776
+ # failures and never reach classify().
777
+ if getattr(result, 'target_type', None) == 'error':
778
+ result.outcome = Outcome.INFRASTRUCTURE_FAILURE.value
779
+ result.state_match = None
780
+ continue
781
+
782
+ # Determine execution status flags
783
+ # Prefer timed_out attribute if available, fallback to error_message parsing
784
+ timed_out = getattr(result, 'timed_out', False)
785
+ if not timed_out and result.error_message:
786
+ timed_out = "timeout" in result.error_message.lower()
787
+
788
+ # The controller's crash verdict (decide_crash)
789
+ # rides on the result when the backend supplied one; the
790
+ # error_message derivation remains for producers
791
+ # that never filled it (QEMU direct path).
792
+ crashed = getattr(result, 'crashed', None)
793
+ if crashed is None:
794
+ crashed = bool(result.error_message and not timed_out)
795
+ completed = getattr(result, 'completed', None)
796
+
797
+ # Get exit_code if available
798
+ exit_code = getattr(result, 'exit_code', None)
799
+
800
+ # Get observed_state if available (for variable-based SDC detection)
801
+ observed_state = getattr(result, 'observed_state', None)
802
+
803
+ # Classify outcome
804
+ outcome = self.classify(
805
+ timed_out=timed_out,
806
+ crashed=crashed,
807
+ output=result.uart_output,
808
+ error_message=result.error_message,
809
+ exit_code=exit_code,
810
+ observed_state=observed_state,
811
+ completed=completed,
812
+ )
813
+
814
+ # Update result object
815
+ result.outcome = outcome.value
816
+
817
+ # Set state_match if state comparison was performed
818
+ # The classify() method stores the last comparison result
819
+ if self.state_comparator is not None and observed_state is not None:
820
+ # State comparison was performed - set state_match based on outcome
821
+ # MASKED means state matched, SDC means state mismatched
822
+ # For other outcomes (TIMEOUT, CRASH, DETECTED), state_match indicates
823
+ # whether the corrupted state matched the golden state (which may differ from outcome)
824
+ if outcome == Outcome.MASKED:
825
+ result.state_match = True
826
+ elif outcome == Outcome.SDC:
827
+ result.state_match = False
828
+ else:
829
+ # For CRASH/TIMEOUT/DETECTED, check the last comparison result
830
+ # (state may have been captured but outcome is not SDC/MASKED)
831
+ # If we have _last_observed_state, that means comparison was attempted
832
+ if self._last_observed_state is not None:
833
+ # If no SDC details, state matched
834
+ result.state_match = (self._last_sdc_details is None)
835
+ else:
836
+ # State comparison was not performed (e.g., crash before state capture)
837
+ result.state_match = None
838
+ else:
839
+ # State comparison not configured or state not captured
840
+ result.state_match = None
841
+
842
+ # Capture SDC details if available
843
+ if outcome == Outcome.SDC:
844
+ sdc_details = self.get_sdc_details()
845
+ if sdc_details:
846
+ result.sdc_details = sdc_details
847
+ finally:
848
+ # Restore original golden_output
849
+ self.golden_output = original_golden
850
+
851
+ return results
852
+
853
+ def get_statistics(self, results: list) -> dict:
854
+ """
855
+ Calculate outcome distribution statistics from classified results.
856
+
857
+ Args:
858
+ results: List of InjectionResult objects with 'outcome' field set.
859
+
860
+ Returns:
861
+ Dictionary with outcome counts and percentages:
862
+ {
863
+ 'total': int,
864
+ 'masked': {'count': int, 'percentage': float},
865
+ 'sdc': {'count': int, 'percentage': float},
866
+ 'detected': {'count': int, 'percentage': float},
867
+ 'crash': {'count': int, 'percentage': float},
868
+ 'timeout': {'count': int, 'percentage': float},
869
+ 'unknown': {'count': int, 'percentage': float},
870
+ 'dmr_effectiveness': float # DETECTED / (DETECTED + SDC + CRASH)
871
+ }
872
+
873
+ Example:
874
+ >>> stats = classifier.get_statistics(results)
875
+ >>> print(f"Masked: {stats['masked']['percentage']:.1f}%")
876
+ Masked: 45.2%
877
+ """
878
+ return outcome_statistics(
879
+ result.outcome if hasattr(result, 'outcome') else 'unknown'
880
+ for result in results)
881
+
882
+ def get_sdc_details(self) -> Optional[str]:
883
+ """
884
+ Get detailed information about the last SDC detection.
885
+
886
+ This returns the detailed difference information from the last
887
+ classify() call that resulted in SDC outcome. Useful for reporting
888
+ and debugging which specific variables or memory regions were corrupted.
889
+
890
+ Returns:
891
+ String describing the differences, or None if last outcome wasn't SDC
892
+ or if UART-based comparison was used.
893
+
894
+ Example:
895
+ >>> classifier = OutcomeClassifier(state_comparator=state_comp)
896
+ >>> outcome = classifier.classify(..., observed_state=state)
897
+ >>> if outcome == Outcome.SDC:
898
+ ... details = classifier.get_sdc_details()
899
+ ... print(f"Corruption: {details}")
900
+ Corruption: sorted_array[5]: expected 42, got 43
901
+ """
902
+ return self._last_sdc_details
903
+
904
+ def get_comparison_mode(self) -> str:
905
+ """
906
+ Get the active comparison mode.
907
+
908
+ Returns:
909
+ String describing the comparison mode:
910
+ - "variable-based" if state_comparator is configured
911
+ - "uart-based" if only golden_output is configured
912
+ - "detection-only" if only detection_string is configured
913
+
914
+ Example:
915
+ >>> classifier = OutcomeClassifier(state_comparator=state_comp)
916
+ >>> classifier.get_comparison_mode()
917
+ 'variable-based'
918
+ """
919
+ if self.state_comparator is not None:
920
+ return "variable-based"
921
+ elif self.golden_output is not None:
922
+ return "uart-based"
923
+ else:
924
+ return "detection-only"