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,738 @@
1
+ # SPDX-FileCopyrightText: 2026 HI-REST and the HFIM contributors
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """
5
+ Golden run comparator for fault injection results.
6
+
7
+ This module compares fault injection execution results against golden run
8
+ reference data to detect Silent Data Corruption (SDC) and execution divergence.
9
+
10
+ The comparator provides:
11
+ - Output comparison with strict and normalized modes
12
+ - Execution trace comparison to identify divergence points
13
+ - First difference location reporting for debugging
14
+ - Variable-based state comparison for professional SDC detection (FAIL* methodology)
15
+
16
+ References:
17
+ - FIM Golden Run specification: golden/<benchmark>/trace.json, expected_output.txt
18
+ - FAIL*: An Open and Versatile Fault-Injection Framework (Schirmeier et al., EDCC 2015)
19
+ """
20
+
21
+ import json
22
+ from dataclasses import dataclass
23
+ from pathlib import Path
24
+ from typing import Dict, List, Any, Optional, Tuple
25
+
26
+ from fim.analysis.observable_state import ObservableState, StateDifference
27
+ from fim.utils.logger import get_logger
28
+
29
+ logger = get_logger("fim.analysis.comparator")
30
+
31
+
32
+ class ComparatorError(Exception):
33
+ """Base exception for comparator-related errors."""
34
+ pass
35
+
36
+
37
+ class GoldenDataNotFoundError(ComparatorError):
38
+ """Raised when golden run data files are not found."""
39
+ pass
40
+
41
+
42
+ class StateComparisonError(ComparatorError):
43
+ """Raised when state comparison fails."""
44
+ pass
45
+
46
+
47
+ @dataclass
48
+ class DivergencePoint:
49
+ """
50
+ Represents a point where execution diverged from golden trace.
51
+
52
+ Attributes:
53
+ instruction_index: Index in trace array where divergence occurred.
54
+ golden_pc: Expected PC value from golden trace.
55
+ actual_pc: Actual PC value from fault injection run.
56
+ instruction_count: Approximate instruction count at divergence.
57
+ """
58
+ instruction_index: int
59
+ golden_pc: int
60
+ actual_pc: int
61
+ instruction_count: int
62
+
63
+ def __str__(self) -> str:
64
+ """Format divergence point for logging."""
65
+ return (
66
+ f"Divergence at trace[{self.instruction_index}]: "
67
+ f"golden_pc=0x{self.golden_pc:x}, actual_pc=0x{self.actual_pc:x}, "
68
+ f"inst_count={self.instruction_count}"
69
+ )
70
+
71
+
72
+ @dataclass
73
+ class OutputDifference:
74
+ """
75
+ Represents a difference in output comparison.
76
+
77
+ Attributes:
78
+ position: Character position where difference starts.
79
+ golden_excerpt: Excerpt from golden output (max 50 chars).
80
+ actual_excerpt: Excerpt from actual output (max 50 chars).
81
+ length_golden: Total length of golden output.
82
+ length_actual: Total length of actual output.
83
+ """
84
+ position: int
85
+ golden_excerpt: str
86
+ actual_excerpt: str
87
+ length_golden: int
88
+ length_actual: int
89
+
90
+ def __str__(self) -> str:
91
+ """Format output difference for logging."""
92
+ return (
93
+ f"Output differs at position {self.position}:\n"
94
+ f" Golden ({self.length_golden} chars): {repr(self.golden_excerpt)}\n"
95
+ f" Actual ({self.length_actual} chars): {repr(self.actual_excerpt)}"
96
+ )
97
+
98
+
99
+ class GoldenComparator:
100
+ """
101
+ Compares fault injection results against golden run reference data.
102
+
103
+ The comparator loads golden run data from standard FIM directory structure
104
+ and provides methods to detect output differences and execution divergence.
105
+
106
+ Example:
107
+ >>> comparator = GoldenComparator("golden/quicksort_dmr")
108
+ >>> match = comparator.compare_output("Sorted: [1, 2, 3, 4, 5]")
109
+ >>> if not match:
110
+ ... diff = comparator.get_output_difference("Wrong: [5, 4, 3, 2, 1]")
111
+ ... print(diff)
112
+ """
113
+
114
+ def __init__(
115
+ self,
116
+ golden_dir: str,
117
+ enable_strict_mode: bool = False
118
+ ):
119
+ """
120
+ Initialize golden comparator.
121
+
122
+ Args:
123
+ golden_dir: Path to golden run directory (e.g., "golden/quicksort_dmr").
124
+ enable_strict_mode: If True, require exact byte-for-byte match for output.
125
+ If False (default), use normalized comparison
126
+ (strips whitespace, ignores trailing newlines).
127
+
128
+ Raises:
129
+ GoldenDataNotFoundError: If golden directory or required files don't exist.
130
+ """
131
+ self.golden_dir = Path(golden_dir)
132
+ self.strict_mode = enable_strict_mode
133
+
134
+ # Validate golden directory exists
135
+ if not self.golden_dir.exists():
136
+ raise GoldenDataNotFoundError(
137
+ f"Golden directory not found: {golden_dir}"
138
+ )
139
+
140
+ # Define paths to golden data files
141
+ self.output_path = self.golden_dir / "expected_output.txt"
142
+ self.trace_path = self.golden_dir / "trace.json"
143
+
144
+ # Load golden data
145
+ self._golden_output: Optional[str] = None
146
+ self._golden_trace: Optional[Dict[str, Any]] = None
147
+ self._load_golden_data()
148
+
149
+ def _load_golden_data(self) -> None:
150
+ """
151
+ Load golden run data from files.
152
+
153
+ Raises:
154
+ GoldenDataNotFoundError: If required files are missing.
155
+ """
156
+ # Load expected output
157
+ if not self.output_path.exists():
158
+ raise GoldenDataNotFoundError(
159
+ f"Golden output file not found: {self.output_path}"
160
+ )
161
+
162
+ with open(self.output_path, 'r') as f:
163
+ self._golden_output = f.read()
164
+
165
+ # Load execution trace (optional - some benchmarks may not generate traces)
166
+ if self.trace_path.exists():
167
+ with open(self.trace_path, 'r') as f:
168
+ self._golden_trace = json.load(f)
169
+ else:
170
+ self._golden_trace = None
171
+
172
+ @staticmethod
173
+ def _normalize_output(output: str) -> str:
174
+ """
175
+ Normalize output for comparison.
176
+
177
+ Normalization:
178
+ - Strip leading/trailing whitespace
179
+ - Normalize line endings to \n
180
+ - Remove trailing newlines
181
+
182
+ Args:
183
+ output: Raw output string.
184
+
185
+ Returns:
186
+ Normalized output string.
187
+ """
188
+ # Normalize line endings
189
+ normalized = output.replace('\r\n', '\n').replace('\r', '\n')
190
+ # Strip trailing whitespace and newlines
191
+ normalized = normalized.rstrip()
192
+ return normalized
193
+
194
+ def compare_output(
195
+ self,
196
+ actual_output: str,
197
+ strict: Optional[bool] = None
198
+ ) -> bool:
199
+ """
200
+ Compare actual output against golden reference.
201
+
202
+ Args:
203
+ actual_output: Output from fault injection run.
204
+ strict: Override instance strict mode for this comparison.
205
+ If None, uses instance setting.
206
+
207
+ Returns:
208
+ True if output matches golden reference, False otherwise.
209
+ """
210
+ if self._golden_output is None:
211
+ raise ComparatorError("Golden output not loaded")
212
+
213
+ use_strict = strict if strict is not None else self.strict_mode
214
+
215
+ if use_strict:
216
+ # Strict mode: exact byte-for-byte comparison
217
+ return actual_output == self._golden_output
218
+ else:
219
+ # Normalized mode: ignore whitespace variations
220
+ golden_norm = self._normalize_output(self._golden_output)
221
+ actual_norm = self._normalize_output(actual_output)
222
+ return golden_norm == actual_norm
223
+
224
+ def get_output_difference(
225
+ self,
226
+ actual_output: str,
227
+ strict: Optional[bool] = None,
228
+ context_length: int = 50
229
+ ) -> Optional[OutputDifference]:
230
+ """
231
+ Get detailed information about output differences.
232
+
233
+ Args:
234
+ actual_output: Output from fault injection run.
235
+ strict: Override instance strict mode for this comparison.
236
+ context_length: Number of characters to include in excerpts.
237
+
238
+ Returns:
239
+ OutputDifference object if outputs differ, None if they match.
240
+ """
241
+ if self._golden_output is None:
242
+ raise ComparatorError("Golden output not loaded")
243
+
244
+ use_strict = strict if strict is not None else self.strict_mode
245
+
246
+ # Get comparison strings
247
+ if use_strict:
248
+ golden = self._golden_output
249
+ actual = actual_output
250
+ else:
251
+ golden = self._normalize_output(self._golden_output)
252
+ actual = self._normalize_output(actual_output)
253
+
254
+ # Find first difference position
255
+ min_len = min(len(golden), len(actual))
256
+ position = 0
257
+
258
+ for i in range(min_len):
259
+ if golden[i] != actual[i]:
260
+ position = i
261
+ break
262
+ else:
263
+ # All common characters match, difference is in length
264
+ if len(golden) == len(actual):
265
+ return None # Complete match
266
+ position = min_len
267
+
268
+ # Extract excerpts around difference point
269
+ start = max(0, position - 10)
270
+ end = min(len(golden), position + context_length)
271
+ golden_excerpt = golden[start:end]
272
+
273
+ end_actual = min(len(actual), position + context_length)
274
+ actual_excerpt = actual[start:end_actual]
275
+
276
+ return OutputDifference(
277
+ position=position,
278
+ golden_excerpt=golden_excerpt,
279
+ actual_excerpt=actual_excerpt,
280
+ length_golden=len(golden),
281
+ length_actual=len(actual)
282
+ )
283
+
284
+ def compare_trace(
285
+ self,
286
+ actual_trace: List[Dict[str, Any]],
287
+ check_registers: bool = False
288
+ ) -> Optional[DivergencePoint]:
289
+ """
290
+ Compare execution trace against golden reference.
291
+
292
+ Args:
293
+ actual_trace: Trace from fault injection run. Each entry should
294
+ contain at least: {"instruction_count": int, "pc": int}
295
+ check_registers: If True, also compare register values.
296
+ If False (default), only compare PC values.
297
+
298
+ Returns:
299
+ DivergencePoint if traces diverge, None if execution matches golden.
300
+ Returns None if golden trace is not available.
301
+ """
302
+ if self._golden_trace is None:
303
+ # No golden trace available for comparison
304
+ return None
305
+
306
+ golden_trace_array = self._golden_trace.get("trace", [])
307
+
308
+ # Compare traces entry by entry
309
+ min_len = min(len(golden_trace_array), len(actual_trace))
310
+
311
+ for i in range(min_len):
312
+ golden_entry = golden_trace_array[i]
313
+ actual_entry = actual_trace[i]
314
+
315
+ # Compare PC values
316
+ golden_pc = golden_entry.get("pc")
317
+ actual_pc = actual_entry.get("pc")
318
+
319
+ if golden_pc != actual_pc:
320
+ return DivergencePoint(
321
+ instruction_index=i,
322
+ golden_pc=golden_pc,
323
+ actual_pc=actual_pc,
324
+ instruction_count=golden_entry.get("instruction_count", -1)
325
+ )
326
+
327
+ # Optionally compare register values
328
+ if check_registers:
329
+ golden_regs = golden_entry.get("registers", {})
330
+ actual_regs = actual_entry.get("registers", {})
331
+
332
+ # Check common registers
333
+ for reg_name in golden_regs:
334
+ if reg_name in actual_regs:
335
+ if golden_regs[reg_name] != actual_regs[reg_name]:
336
+ # Register divergence detected, but PC still matches
337
+ # This is not a control flow divergence, so we continue
338
+ # (register differences are expected with faults)
339
+ pass
340
+
341
+ # Check for length mismatch (early termination or infinite loop)
342
+ if len(actual_trace) != len(golden_trace_array):
343
+ # Trace length differs - this indicates divergence
344
+ # Return divergence at the point where shorter trace ends
345
+ diverge_idx = min_len
346
+
347
+ if diverge_idx > 0:
348
+ # Get last known PC values
349
+ last_golden = golden_trace_array[diverge_idx - 1] if diverge_idx <= len(golden_trace_array) else golden_trace_array[-1]
350
+ last_actual = actual_trace[diverge_idx - 1] if diverge_idx <= len(actual_trace) else actual_trace[-1]
351
+
352
+ return DivergencePoint(
353
+ instruction_index=diverge_idx,
354
+ golden_pc=last_golden.get("pc", 0),
355
+ actual_pc=last_actual.get("pc", 0),
356
+ instruction_count=last_golden.get("instruction_count", -1)
357
+ )
358
+ else:
359
+ # Empty actual trace but golden has entries
360
+ # Return divergence at start with first golden PC
361
+ first_golden = golden_trace_array[0] if len(golden_trace_array) > 0 else None
362
+ if first_golden:
363
+ return DivergencePoint(
364
+ instruction_index=0,
365
+ golden_pc=first_golden.get("pc", 0),
366
+ actual_pc=0,
367
+ instruction_count=first_golden.get("instruction_count", 0)
368
+ )
369
+
370
+ # Traces match
371
+ return None
372
+
373
+ def get_golden_output(self) -> str:
374
+ """
375
+ Get the golden output string.
376
+
377
+ Returns:
378
+ Golden output as string.
379
+
380
+ Raises:
381
+ ComparatorError: If golden output not loaded.
382
+ """
383
+ if self._golden_output is None:
384
+ raise ComparatorError("Golden output not loaded")
385
+ return self._golden_output
386
+
387
+ def get_golden_trace(self) -> Optional[Dict[str, Any]]:
388
+ """
389
+ Get the golden trace data.
390
+
391
+ Returns:
392
+ Golden trace as dictionary, or None if not available.
393
+ """
394
+ return self._golden_trace
395
+
396
+ def get_golden_instruction_count(self) -> Optional[int]:
397
+ """
398
+ Get total instruction count from golden run.
399
+
400
+ Returns:
401
+ Total instruction count, or None if trace not available.
402
+ """
403
+ if self._golden_trace is None:
404
+ return None
405
+ return self._golden_trace.get("total_instructions")
406
+
407
+ def has_golden_trace(self) -> bool:
408
+ """
409
+ Check if golden trace data is available.
410
+
411
+ Returns:
412
+ True if golden trace is loaded, False otherwise.
413
+ """
414
+ return self._golden_trace is not None
415
+
416
+
417
+ # Python's csv reader refuses a field larger than 131072 bytes. One SDC
418
+ # whose observable is a long array (quicksort result[4096]) used to put
419
+ # every mismatch in this one cell and the server then abandoned the rest
420
+ # of the campaign. Stay far under that limit. The full observed values
421
+ # are written to injections/<id>/state.json; this string is the summary.
422
+ SDC_DETAILS_CSV_MAX = 8192
423
+ _DETAIL_JOIN = "; "
424
+
425
+
426
+ def _golden_sequence_length(golden, name: str):
427
+ """Length of a golden list variable, or None when it is not a list."""
428
+ if golden is None:
429
+ return None
430
+ var = golden.variables.get(name)
431
+ if var is None or not isinstance(var.value, list):
432
+ return None
433
+ return len(var.value)
434
+
435
+
436
+ def _golden_byte_length(golden, name: str):
437
+ """Byte length of a golden memory region, or None when it is absent."""
438
+ if golden is None:
439
+ return None
440
+ region = golden.memory_regions.get(name)
441
+ if region is None:
442
+ return None
443
+ if isinstance(region.data, (bytes, bytearray)):
444
+ return len(region.data)
445
+ if isinstance(region.size, int):
446
+ return region.size
447
+ return None
448
+
449
+
450
+ def _summary_headers(differences, golden) -> List[str]:
451
+ """One count line per list or memory region that has element diffs.
452
+
453
+ An array_length mismatch is not counted here: that difference is a
454
+ length, and 'N/TOTAL elements differ' would describe the wrong thing.
455
+ """
456
+ element_counts: Dict[str, int] = {}
457
+ byte_counts: Dict[str, int] = {}
458
+ for diff in differences:
459
+ if diff.diff_type == "array_element":
460
+ element_counts[diff.variable_name] = element_counts.get(diff.variable_name, 0) + 1
461
+ elif diff.diff_type == "memory_byte":
462
+ byte_counts[diff.variable_name] = byte_counts.get(diff.variable_name, 0) + 1
463
+
464
+ headers: List[str] = []
465
+ seen = set()
466
+ for diff in differences:
467
+ name = diff.variable_name
468
+ if name in seen:
469
+ continue
470
+ if diff.diff_type == "array_element":
471
+ seen.add(name)
472
+ count = element_counts[name]
473
+ total = _golden_sequence_length(golden, name)
474
+ if total is None:
475
+ headers.append(f"{name}: {count} elements differ")
476
+ else:
477
+ headers.append(f"{name}: {count}/{total} elements differ")
478
+ elif diff.diff_type == "memory_byte":
479
+ seen.add(name)
480
+ count = byte_counts[name]
481
+ total = _golden_byte_length(golden, name)
482
+ if total is None:
483
+ headers.append(f"{name}: {count} bytes differ")
484
+ else:
485
+ headers.append(f"{name}: {count}/{total} bytes differ")
486
+ return headers
487
+
488
+
489
+ def _clip(text: str, limit: int) -> str:
490
+ if limit <= 0:
491
+ return ""
492
+ if len(text) <= limit:
493
+ return text
494
+ if limit <= 3:
495
+ return text[:limit]
496
+ return text[: limit - 3] + "..."
497
+
498
+
499
+ def _summarize_sdc_details(differences, golden, limit: int) -> str:
500
+ """Summary plus the first diffs that fit, then '(+N more)'."""
501
+ pieces = [str(diff) for diff in differences]
502
+ headers = _summary_headers(differences, golden)
503
+
504
+ def render(shown: List[str], omitted: int) -> str:
505
+ body = _DETAIL_JOIN.join(headers + shown)
506
+ if omitted:
507
+ trailer = f"(+{omitted} more)"
508
+ body = f"{body}; {trailer}" if body else trailer
509
+ return body
510
+
511
+ shown: List[str] = []
512
+ for index, piece in enumerate(pieces):
513
+ rest = len(pieces) - (index + 1)
514
+ if len(render(shown + [piece], rest)) <= limit:
515
+ shown.append(piece)
516
+ continue
517
+ base = _DETAIL_JOIN.join(headers + shown)
518
+ sep = _DETAIL_JOIN if base else ""
519
+ trailer = f"; (+{rest} more)" if rest else ""
520
+ clipped = _clip(piece, limit - len(base) - len(sep) - len(trailer))
521
+ if clipped and len(render(shown + [clipped], rest)) <= limit:
522
+ return render(shown + [clipped], rest)
523
+ break
524
+
525
+ return _clip(render(shown, len(pieces) - len(shown)), limit)
526
+
527
+
528
+ class StateComparator:
529
+ """
530
+ Compares fault injection ObservableState against golden reference.
531
+
532
+ This comparator implements professional variable-based SDC detection
533
+ following the FAIL* methodology. Unlike UART-based comparison (which
534
+ can be corrupted by radiation affecting communication), this checks
535
+ the actual computation results by comparing variable values.
536
+
537
+ The StateComparator provides:
538
+ - Loading golden ObservableState from JSON
539
+ - Variable-by-variable comparison with detailed diffs
540
+ - Array element-wise comparison
541
+ - Memory region byte-by-byte comparison
542
+ - Tolerance-based comparison for floating-point values
543
+ - Structured SDC details for reporting
544
+
545
+ Example:
546
+ >>> comparator = StateComparator("golden/quicksort_dmr")
547
+ >>> actual_state = ObservableState.capture(gdb, elf, variables)
548
+ >>> match, diff_details = comparator.compare_state(actual_state)
549
+ >>> if not match:
550
+ ... sdc_info = comparator.get_sdc_details()
551
+ ... print(f"SDC detected: {sdc_info}")
552
+ """
553
+
554
+ def __init__(
555
+ self,
556
+ golden_dir: str,
557
+ tolerance: Optional[float] = None,
558
+ variable_tolerances: Optional[Dict[str, float]] = None,
559
+ ):
560
+ """
561
+ Initialize state comparator.
562
+
563
+ Args:
564
+ golden_dir: Path to golden run directory (e.g., "golden/quicksort_dmr").
565
+ tolerance: Optional tolerance for floating-point comparison.
566
+ If None, uses exact comparison.
567
+
568
+ Raises:
569
+ GoldenDataNotFoundError: If golden directory or observable_state.json don't exist.
570
+ """
571
+ self.golden_dir = Path(golden_dir)
572
+ self.tolerance = tolerance
573
+ self.variable_tolerances = dict(variable_tolerances or {})
574
+ self._golden_state: Optional[ObservableState] = None
575
+ self._last_differences: List[StateDifference] = []
576
+
577
+ # Validate golden directory exists
578
+ if not self.golden_dir.exists():
579
+ raise GoldenDataNotFoundError(
580
+ f"Golden directory not found: {golden_dir}"
581
+ )
582
+
583
+ # Define path to golden state file
584
+ self.state_path = self.golden_dir / "observable_state.json"
585
+
586
+ # Load golden state
587
+ self._load_golden_state()
588
+
589
+ def _load_golden_state(self) -> None:
590
+ """
591
+ Load golden ObservableState from JSON file.
592
+
593
+ Raises:
594
+ GoldenDataNotFoundError: If observable_state.json is missing.
595
+ StateComparisonError: If JSON parsing fails.
596
+ """
597
+ if not self.state_path.exists():
598
+ raise GoldenDataNotFoundError(
599
+ f"Golden observable state file not found: {self.state_path}\n"
600
+ f"Run golden execution with observable_outputs configured to generate this file."
601
+ )
602
+
603
+ try:
604
+ with open(self.state_path, 'r') as f:
605
+ state_data = json.load(f)
606
+
607
+ self._golden_state = ObservableState.from_dict(state_data)
608
+
609
+ logger.info(
610
+ f"Loaded golden state: {len(self._golden_state.variables)} variables, "
611
+ f"{len(self._golden_state.memory_regions)} memory regions"
612
+ )
613
+
614
+ except json.JSONDecodeError as e:
615
+ raise StateComparisonError(
616
+ f"Failed to parse golden state JSON: {e}"
617
+ )
618
+ except Exception as e:
619
+ raise StateComparisonError(
620
+ f"Failed to load golden state: {e}"
621
+ )
622
+
623
+ def compare_state(
624
+ self,
625
+ actual_state: ObservableState,
626
+ tolerance: Optional[float] = None
627
+ ) -> Tuple[bool, List[StateDifference]]:
628
+ """
629
+ Compare actual state against golden reference.
630
+
631
+ Args:
632
+ actual_state: ObservableState captured from fault injection run.
633
+ tolerance: Override instance tolerance for this comparison.
634
+ If None, uses instance setting.
635
+
636
+ Returns:
637
+ Tuple of (match: bool, differences: List[StateDifference])
638
+ - match is True if states are identical within tolerance
639
+ - differences lists all detected differences with detailed info
640
+
641
+ Raises:
642
+ StateComparisonError: If golden state not loaded or comparison fails.
643
+ """
644
+ if self._golden_state is None:
645
+ raise StateComparisonError("Golden state not loaded")
646
+
647
+ # Use provided tolerance or fall back to instance tolerance
648
+ use_tolerance = tolerance if tolerance is not None else self.tolerance
649
+
650
+ try:
651
+ # Use ObservableState's built-in compare method
652
+ match, differences = self._golden_state.compare(
653
+ actual_state, use_tolerance, self.variable_tolerances)
654
+
655
+ # Store differences for get_sdc_details()
656
+ self._last_differences = differences
657
+
658
+ logger.debug(
659
+ f"State comparison: match={match}, differences={len(differences)}"
660
+ )
661
+
662
+ return match, differences
663
+
664
+ except Exception as e:
665
+ raise StateComparisonError(f"State comparison failed: {e}")
666
+
667
+ def get_sdc_details(self) -> str:
668
+ """
669
+ Get structured SDC details from last comparison.
670
+
671
+ A short difference list is returned in full, one clause per
672
+ difference. A list long enough to blow past the CSV field limit
673
+ is shortened to a count (`name: N/TOTAL elements differ`, or
674
+ `N/TOTAL bytes differ` for a memory region) plus the first
675
+ differences that fit and `(+N more)`. The omitted values stay in
676
+ the comparison result and in the injection's state.json.
677
+
678
+ Returns:
679
+ Formatted string describing the differences, or empty string if
680
+ there are none. Never longer than SDC_DETAILS_CSV_MAX.
681
+
682
+ Example output:
683
+ "sorted_array[5]: expected 42, got 43; sorted_array[12]: expected 100, got 101"
684
+ """
685
+ if not self._last_differences:
686
+ return ""
687
+
688
+ diff_strings = [str(diff) for diff in self._last_differences]
689
+ full = _DETAIL_JOIN.join(diff_strings)
690
+ if len(full) <= SDC_DETAILS_CSV_MAX:
691
+ return full
692
+ return _summarize_sdc_details(
693
+ self._last_differences, self._golden_state, SDC_DETAILS_CSV_MAX)
694
+
695
+ def get_golden_state(self) -> ObservableState:
696
+ """
697
+ Get the golden ObservableState.
698
+
699
+ Returns:
700
+ Golden ObservableState object.
701
+
702
+ Raises:
703
+ StateComparisonError: If golden state not loaded.
704
+ """
705
+ if self._golden_state is None:
706
+ raise StateComparisonError("Golden state not loaded")
707
+ return self._golden_state
708
+
709
+ def has_golden_state(self) -> bool:
710
+ """
711
+ Check if golden state is loaded and available.
712
+
713
+ Returns:
714
+ True if golden ObservableState is loaded, False otherwise.
715
+ """
716
+ return self._golden_state is not None
717
+
718
+ def get_variable_count(self) -> int:
719
+ """
720
+ Get number of variables in golden state.
721
+
722
+ Returns:
723
+ Number of variables being compared, or 0 if not loaded.
724
+ """
725
+ if self._golden_state is None:
726
+ return 0
727
+ return len(self._golden_state.variables)
728
+
729
+ def get_memory_region_count(self) -> int:
730
+ """
731
+ Get number of memory regions in golden state.
732
+
733
+ Returns:
734
+ Number of memory regions being compared, or 0 if not loaded.
735
+ """
736
+ if self._golden_state is None:
737
+ return 0
738
+ return len(self._golden_state.memory_regions)