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,625 @@
1
+ # SPDX-FileCopyrightText: 2026 HI-REST and the HFIM contributors
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """Parallel-result consolidation.
5
+
6
+ The distributed path runs each injection as its own worker job; each job
7
+ writes a one-row CSV at <out>/injections/<i>/injections.csv (see
8
+ run_campaign.run_single_index). When the last job finishes, exactly one
9
+ worker calls consolidate() to merge those per-index rows into one
10
+ <out>/injections.csv -- the SAME artifact the single-process run produces,
11
+ sorted by injection_id -- and to compute the outcome tally the ledger
12
+ compares against single-process.
13
+
14
+ Why a separate merge instead of N workers appending to one file: concurrent
15
+ appends race and interleave rows; per-index files are collision-free (each
16
+ worker owns its own path), and the merge is a single-reader pass after the
17
+ fleet is done.
18
+ """
19
+ import csv
20
+ import glob
21
+ import json
22
+ import logging
23
+ import os
24
+ import shutil
25
+ import time
26
+
27
+ from fim.analysis.classifier import (CORE_OUTCOME_ORDER, NON_SILICON_OUTCOMES,
28
+ outcome_statistics)
29
+ from fim.analysis.results_txt import write_results_txt
30
+ from typing import Optional, Tuple
31
+
32
+ logger = logging.getLogger(__name__)
33
+
34
+
35
+ # Columns the human-facing injections.csv always keeps, even when empty for a
36
+ # given run, so the core schema is stable across backends and outcome mixes.
37
+ # Everything else (the gem5 cache/power/ECC block) is dropped when no row in
38
+ # the campaign populates it -- a QEMU register/memory run thus sheds ~24 always
39
+ # -empty trailing columns instead of emitting a wall of commas.
40
+ _CSV_CORE_COLUMNS = (
41
+ "injection_id", "timestamp", "instruction_count", "target_type",
42
+ "target_name", "original_value", "faulty_value", "bit_position",
43
+ "outcome", "execution_time", "exit_code", "timed_out", "sdc_details",
44
+ "state_match",
45
+ )
46
+
47
+
48
+ def _campaign(config):
49
+ """The campaign View of the configuration a caller passed; an absent
50
+ one reads as empty."""
51
+ from fim.campaigns.campaign_view import campaign_spec
52
+ return campaign_spec(config)
53
+
54
+
55
+ def _plan(config):
56
+ from fim.campaigns.fault_plan import fault_plan
57
+ return fault_plan(config or {})
58
+
59
+
60
+ def _text(value):
61
+ """A value as the summary writes it: absent is empty, not None."""
62
+ return "" if value is None else value
63
+
64
+
65
+ def _cell_has_value(v) -> bool:
66
+ return v is not None and str(v) != ""
67
+
68
+
69
+ def prune_empty_columns(fieldnames, rows):
70
+ """Drop columns that are empty in every row, keeping the core schema.
71
+
72
+ `fieldnames` is the full ordered header; `rows` is a list of dicts. Returns
73
+ a new ordered fieldnames list: a column survives if it is in the core set OR
74
+ at least one row has a non-empty value for it. Order is preserved.
75
+ """
76
+ kept = []
77
+ for col in fieldnames:
78
+ if col in _CSV_CORE_COLUMNS:
79
+ kept.append(col)
80
+ continue
81
+ # 0 is a value (cache way 0, set 0, exit code 0), not
82
+ # an empty cell. Only None and "" mean "nothing recorded".
83
+ if any(_cell_has_value(r.get(col)) for r in rows):
84
+ kept.append(col)
85
+ return kept
86
+
87
+
88
+ def _unreadable_index_row(path: str) -> dict:
89
+ """A stand-in row when one per-index CSV cannot be parsed.
90
+
91
+ The directory name is the 1-based injection id (injections/0149/).
92
+ """
93
+ inj = os.path.basename(os.path.dirname(path))
94
+ try:
95
+ inj_id = str(int(inj))
96
+ except ValueError:
97
+ inj_id = inj
98
+ return {
99
+ "injection_id": inj_id,
100
+ "outcome": "infrastructure_failure",
101
+ "error_message": "injections.csv field exceeds the reader limit",
102
+ "sdc_details": "",
103
+ }
104
+
105
+
106
+ def _out_dir_from_index_csv(index_csv: str) -> str:
107
+ """<out>/injections/<i>/injections.csv -> <out>. The per-index layout is
108
+ fixed by run_single_index, so two dirname() hops off the <i> dir."""
109
+ index_dir = os.path.dirname(os.path.abspath(index_csv)) # .../<i>
110
+ injections_dir = os.path.dirname(index_dir) # .../injections
111
+ return os.path.dirname(injections_dir) # .../<out>
112
+
113
+
114
+ def consolidate(out_dir: str,
115
+ config: Optional[dict] = None,
116
+ campaign_id: Optional[str] = None,
117
+ expected_count: Optional[int] = None) -> Tuple[str, dict, int]:
118
+ """Merge <out>/injections/*/injections.csv into <out>/injections.csv.
119
+
120
+ Returns (consolidated_csv_path, outcome_tally, row_count). Rows are sorted
121
+ by injection_id (int) so the merged file is byte-stable regardless of the
122
+ order workers finished -- the property that makes the parallel tally
123
+ comparable to single-process. Missing/empty per-index files are skipped;
124
+ the caller decides whether a short count is acceptable.
125
+
126
+ Also writes report.tsv, metadata.json and results.txt next to
127
+ injections.csv so the parallel result tree carries the SAME summary
128
+ artifacts a single-process run produces (the inline runner writes them
129
+ via _save_tsv_report / _save_metadata / _save_results_txt; the parallel
130
+ path never calls those, so without this the summary download has only
131
+ injections.csv). config/campaign_id, when
132
+ provided, populate metadata fields that aren't in the per-index rows
133
+ (benchmark, seed, fault_model); they default sensibly when absent.
134
+ """
135
+ from fim.analysis.csv_io import raise_injections_field_limit
136
+ raise_injections_field_limit()
137
+
138
+ pattern = os.path.join(out_dir, "injections", "*", "injections.csv")
139
+ rows = []
140
+ fieldnames: Optional[list] = None
141
+ for path in glob.glob(pattern):
142
+ try:
143
+ with open(path, newline="") as fh:
144
+ reader = csv.DictReader(fh)
145
+ names = list(reader.fieldnames) if reader.fieldnames else None
146
+ file_rows = list(reader)
147
+ except csv.Error:
148
+ # One cell still over the raised limit. Keep the injection in
149
+ # the merge as a failed read so the closer does not abort the
150
+ # campaign, and so the row is not silently missing.
151
+ rows.append(_unreadable_index_row(path))
152
+ continue
153
+ except OSError:
154
+ continue
155
+ if fieldnames is None and names:
156
+ fieldnames = names
157
+ rows.extend(file_rows)
158
+
159
+ def _ikey(r: dict) -> int:
160
+ try:
161
+ return int(r.get("injection_id") or 0)
162
+ except (TypeError, ValueError):
163
+ return 0
164
+
165
+ rows.sort(key=_ikey)
166
+
167
+ tally: dict = {}
168
+ for r in rows:
169
+ outcome = (r.get("outcome") or "unknown").strip()
170
+ tally[outcome] = tally.get(outcome, 0) + 1
171
+
172
+ consolidated = os.path.join(out_dir, "injections.csv")
173
+ if fieldnames is None:
174
+ # No per-index rows found; write a header-only file so downstream
175
+ # readers don't choke on a missing artifact.
176
+ fieldnames = [
177
+ "injection_id", "timestamp", "instruction_count", "target_type",
178
+ "target_name", "original_value", "faulty_value", "bit_position",
179
+ "outcome", "execution_time", "error_message",
180
+ ]
181
+ out_fieldnames = prune_empty_columns(fieldnames, rows)
182
+ with open(consolidated, "w", newline="") as fh:
183
+ writer = csv.DictWriter(fh, fieldnames=out_fieldnames)
184
+ writer.writeheader()
185
+ for r in rows:
186
+ writer.writerow({k: r.get(k, "") for k in out_fieldnames})
187
+
188
+ _write_report_tsv(out_dir, rows, tally, config, campaign_id)
189
+ _write_metadata(out_dir, rows, tally, config, campaign_id, expected_count)
190
+ _write_fleet_provenance(out_dir)
191
+ _write_results_summary(out_dir, rows, config, campaign_id, expected_count)
192
+ _snapshot_source(out_dir, config)
193
+
194
+ return consolidated, tally, len(rows)
195
+
196
+
197
+ def _file_hash(entry) -> Optional[str]:
198
+ """The sha256 of a file entry of a provenance manifest (here the
199
+ campaign file's)."""
200
+ return (entry or {}).get("sha256")
201
+
202
+
203
+ def _provenance_identity(manifest: dict) -> dict:
204
+ """The parts of a per-index manifest that must agree across a campaign:
205
+ what was run (ELF, config, golden, included files) and what ran it (core
206
+ version and source tree, resolved simulator). Hostnames and times may
207
+ differ between workers; these may not. The ELF is compared by its
208
+ loaded image: two builds of the same code that differ only
209
+ in debug information or build metadata ran the same program. A
210
+ manifest without the image hash has only the whole-file hash."""
211
+ inputs = manifest.get("inputs") or {}
212
+ tool = manifest.get("toolchain") or {}
213
+ bench = inputs.get("benchmark") or {}
214
+ return {
215
+ "elf_image_sha256": bench.get("elf_image_sha256") or bench.get("elf_sha256"),
216
+ "config_sha256": _file_hash(inputs.get("config")),
217
+ "golden": inputs.get("golden_run"),
218
+ "included_files": [(f.get("path"), f.get("sha256"))
219
+ for f in inputs.get("included_files") or []],
220
+ "core_version": (tool.get("fim") or {}).get("version"),
221
+ "core_source_sha256": (tool.get("fim") or {}).get("source_tree_sha256"),
222
+ "simulator": tool.get("qemu_resolved"),
223
+ "parameters": manifest.get("parameters"),
224
+ }
225
+
226
+
227
+ def _write_fleet_provenance(out_dir: str) -> None:
228
+ """Merge the per-index provenance.json files into the campaign's.
229
+
230
+ Each fleet job fingerprints its own inputs. They should all agree; when
231
+ one does not (a rebuild, a golden retaken or a core deployed while the
232
+ campaign was still running), the campaign is a mix and says so, listing
233
+ the indices that differ from the first."""
234
+ manifests = {}
235
+ for path in glob.glob(os.path.join(out_dir, "injections", "*", "provenance.json")):
236
+ try:
237
+ idx = int(os.path.basename(os.path.dirname(path)))
238
+ with open(path) as fh:
239
+ manifests[idx] = json.load(fh)
240
+ except (OSError, ValueError):
241
+ continue
242
+ if not manifests:
243
+ return
244
+ first = min(manifests)
245
+ ref = _provenance_identity(manifests[first])
246
+ differing = sorted(i for i, m in manifests.items()
247
+ if _provenance_identity(m) != ref)
248
+ base = manifests[first]
249
+ merged = {
250
+ "schema_version": base.get("schema_version"),
251
+ "campaign_id": base.get("campaign_id"),
252
+ "inputs": base.get("inputs"),
253
+ "toolchain": base.get("toolchain"),
254
+ "parameters": base.get("parameters"),
255
+ # The Records the result was made from and, on a Server,
256
+ # the Campaign Machine: the same for every index.
257
+ "artifacts": base.get("artifacts") or {},
258
+ **({"campaign_machine": base["campaign_machine"]}
259
+ if base.get("campaign_machine") else {}),
260
+ "fleet": {
261
+ "indices_with_provenance": len(manifests),
262
+ "reference_index": first,
263
+ "consistent": not differing,
264
+ "differing_indices": differing,
265
+ },
266
+ }
267
+ try:
268
+ with open(os.path.join(out_dir, "provenance.json"), "w") as f:
269
+ json.dump(merged, f, indent=2)
270
+ except OSError:
271
+ pass
272
+
273
+
274
+ def _write_results_summary(out_dir: str, rows: list, config: Optional[dict],
275
+ campaign_id: Optional[str],
276
+ expected_count: Optional[int]) -> None:
277
+ """results.txt for a fleet campaign. The simulator it names comes from the
278
+ provenance.json _write_fleet_provenance just merged. Best effort: a
279
+ summary that cannot be written must not fail a campaign whose rows are
280
+ already merged."""
281
+ try:
282
+ ran = None
283
+ try:
284
+ with open(os.path.join(out_dir, "provenance.json")) as fh:
285
+ ran = (json.load(fh).get("toolchain") or {}).get("qemu_resolved")
286
+ except (OSError, ValueError):
287
+ pass
288
+ expected_ids = _expected_ids(config or {}, expected_count)
289
+ write_results_txt(
290
+ out_dir, campaign_id or os.path.basename(os.path.normpath(out_dir)), config, rows,
291
+ outcome_statistics((r.get("outcome") or "unknown").strip() for r in rows),
292
+ ran, len(expected_ids) if expected_ids is not None else None)
293
+ except Exception: # noqa: BLE001
294
+ logger.warning("results.txt not written for %s", out_dir, exc_info=True)
295
+
296
+
297
+ def _snapshot_source(out_dir: str, config: Optional[dict]) -> None:
298
+ """Capture the benchmark source + the injected ELF into <out>/source/, so
299
+ the parallel result tree is self-contained for reproduction -- the same
300
+ thing the inline runner's bash _snapshot_source does on the --follow path.
301
+
302
+ The parallel/fire-and-forget path never blocks in an ssh session, so that bash
303
+ snapshot never runs for it; this is the gateway-side equivalent, executed
304
+ once by the worker that closes the count (the single consolidate() call).
305
+
306
+ The ELF path comes from config['elf_path'] (an absolute path the submitter
307
+ bakes into the campaign config). The benchmark source dir is its grandparent
308
+ (<bench_dir>/build/<elf>). Best-effort: a missing ELF or already-present
309
+ source/ dir is left alone rather than failing the campaign's terminal stamp.
310
+ """
311
+ if not config:
312
+ return
313
+ source_dir = os.path.join(out_dir, "source")
314
+ if os.path.isdir(source_dir):
315
+ # The inline path already snapshotted this tree; don't clobber it.
316
+ return
317
+ elf_path = _campaign(config).elf_path
318
+ if not elf_path or not os.path.isfile(elf_path):
319
+ return
320
+ bench_dir = os.path.dirname(os.path.dirname(os.path.abspath(elf_path)))
321
+ os.makedirs(source_dir, exist_ok=True)
322
+
323
+ src_exts = (".c", ".h", ".rs", ".S", ".py")
324
+ src_names = ("Cargo.toml", "fim.yaml", "Makefile")
325
+ try:
326
+ for name in os.listdir(bench_dir):
327
+ full = os.path.join(bench_dir, name)
328
+ if not os.path.isfile(full):
329
+ continue
330
+ if name.endswith(src_exts) or name in src_names:
331
+ shutil.copyfile(full, os.path.join(source_dir, name))
332
+ except OSError:
333
+ pass
334
+
335
+ build_dir = os.path.join(source_dir, "build")
336
+ os.makedirs(build_dir, exist_ok=True)
337
+ try:
338
+ shutil.copyfile(
339
+ elf_path, os.path.join(build_dir, os.path.basename(elf_path)))
340
+ except OSError:
341
+ pass
342
+
343
+ # provenance.json mirrors the inline bash _snapshot_source so the summary
344
+ # download finds it on the parallel path too. Written only if absent.
345
+ prov_path = os.path.join(out_dir, "provenance.json")
346
+ bench_name = os.path.basename(bench_dir)
347
+ provenance = {}
348
+ if os.path.exists(prov_path):
349
+ # The merged fleet provenance may already be there; add the snapshot
350
+ # fields to it rather than leaving them out.
351
+ try:
352
+ with open(prov_path) as f:
353
+ provenance = json.load(f) or {}
354
+ except (OSError, ValueError):
355
+ provenance = {}
356
+ for key, value in (
357
+ ("snapshot_time", time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())),
358
+ ("benchmark", bench_name),
359
+ ("elf", os.path.basename(elf_path)),
360
+ ("restore_hint", f"cp source/* benchmarks/{bench_name}/"),
361
+ ):
362
+ provenance.setdefault(key, value)
363
+ try:
364
+ with open(prov_path, "w") as f:
365
+ json.dump(provenance, f, indent=2)
366
+ except OSError:
367
+ pass
368
+
369
+
370
+ # Outcome ordering shared by the TSV footer and metadata stats so both files
371
+ # agree on which outcomes exist and in what order.
372
+ _OUTCOME_ORDER = list(CORE_OUTCOME_ORDER)
373
+
374
+
375
+ def _write_report_tsv(out_dir: str, rows: list, tally: dict,
376
+ config: Optional[dict],
377
+ campaign_id: Optional[str]) -> str:
378
+ """Greppable one-line-per-injection TSV, mirroring run_campaign's
379
+ _save_tsv_report column order so a parallel report.tsv is interchangeable
380
+ with a single-process one. Values come straight from the merged CSV rows
381
+ (original_value/faulty_value are already hex strings there), so this does
382
+ no re-formatting beyond the state_match True/False/'' normalization the
383
+ inline writer applies."""
384
+ cfg = _campaign(config)
385
+ tsv_path = os.path.join(out_dir, "report.tsv")
386
+ header = [
387
+ "index", "target_type", "target_name", "instruction_count",
388
+ "bit_position", "original_value", "faulty_value", "outcome",
389
+ "exit_code", "execution_time", "timed_out", "state_match",
390
+ "error_message",
391
+ ]
392
+ # Same rule as the inline writer: hart columns, appended, multicore only.
393
+ multicore = cfg.num_cores > 1
394
+ if multicore:
395
+ header += ["target_core", "target_cluster", "target_pc"]
396
+ with open(tsv_path, "w") as f:
397
+ f.write("\t".join(header) + "\n")
398
+ for r in rows:
399
+ sm = (r.get("state_match") or "").strip()
400
+ if sm in ("True", "true", "1"):
401
+ sm = "True"
402
+ elif sm in ("False", "false", "0"):
403
+ sm = "False"
404
+ else:
405
+ sm = ""
406
+ timed_out = (r.get("timed_out") or "").strip().lower()
407
+ fields = [
408
+ str(r.get("injection_id", "")),
409
+ r.get("target_type", ""),
410
+ r.get("target_name", ""),
411
+ str(r.get("instruction_count", "")),
412
+ str(r.get("bit_position", "")),
413
+ r.get("original_value", ""),
414
+ r.get("faulty_value", ""),
415
+ (r.get("outcome") or "unknown").strip(),
416
+ str(r.get("exit_code", "") or ""),
417
+ str(r.get("execution_time", "")),
418
+ timed_out,
419
+ sm,
420
+ (r.get("error_message") or "").replace("\t", " ").replace("\n", " "),
421
+ ]
422
+ if multicore:
423
+ fields += ["" if r.get(k) is None else str(r.get(k)) for k in
424
+ ("target_core", "target_cluster", "target_pc")]
425
+ f.write("\t".join(fields) + "\n")
426
+
427
+ total = len(rows)
428
+ f.write("\n")
429
+ f.write("# CAMPAIGN SUMMARY\n")
430
+ f.write("# " + "=" * 78 + "\n")
431
+ f.write(f"# Campaign ID:\t{campaign_id or ''}\n")
432
+ f.write(f"# Benchmark:\t{_text(cfg.benchmark)}\n")
433
+ f.write(f"# Seed:\t{_text(cfg.seed)}\n")
434
+ f.write(f"# Fault Model:\t{_text(cfg.fault_model)}\n")
435
+ f.write(f"# Total Injections:\t{total}\n")
436
+ # Same denominators as metadata.json and the inline report: silicon
437
+ # outcomes over valid rows, framework rows over everything.
438
+ invalid = sum(tally.get(o, 0) for o in NON_SILICON_OUTCOMES)
439
+ valid_total = total - invalid
440
+ f.write(f"# Valid Injections:\t{valid_total}\n")
441
+ f.write("#\n")
442
+ f.write("# Outcome Distribution:\n")
443
+ for name in _OUTCOME_ORDER:
444
+ count = tally.get(name, 0)
445
+ if count > 0:
446
+ base = total if name in NON_SILICON_OUTCOMES else valid_total
447
+ pct = (count / base * 100.0) if base else 0.0
448
+ f.write(f"# {name.upper():12s}:\t{count:5d}\t({pct:5.1f}%)\n")
449
+ f.write("# " + "=" * 78 + "\n")
450
+ return tsv_path
451
+
452
+
453
+ def _target_block_from_rows(rows: list, cfg: dict) -> Optional[dict]:
454
+ """Describe the injected memory span for the fleet path's metadata.json.
455
+
456
+ Mode/name/access_size come from config. The address span is harder: the
457
+ consolidating worker never sees the campaign's RESOLVED range (it is computed
458
+ inside each per-injection subprocess and not propagated back), so the only
459
+ span signal here is the addresses in the rows -- a SAMPLE, not the extent.
460
+
461
+ For .stack-live that sample IS the answer: there is no static span (the live
462
+ window is [live SP, __stack_top] per injection), so the observed min/max of
463
+ what landed is exactly what we want -> span_source='observed'.
464
+
465
+ For variable/section/range, the observed min/max UNDER-reports whenever the
466
+ PRNG didn't draw the extremes (a 4-byte variable hit once reads as 0 bytes).
467
+ Rather than stamp a wrong number, we record mode/name/access_size with a null
468
+ span and span_source='unresolved-in-fleet' so a reader knows the fleet path
469
+ couldn't see the resolved extent. The run_campaign (sequential) path, which
470
+ holds the campaign object, fills the real span for those modes.
471
+
472
+ Returns None for register/non-memory campaigns (no memory rows -> no span)."""
473
+ addrs = []
474
+ for r in rows:
475
+ if r.get("target_type") != "memory":
476
+ continue
477
+ name = r.get("target_name")
478
+ if not name:
479
+ continue
480
+ try:
481
+ addrs.append(int(str(name), 0))
482
+ except (TypeError, ValueError):
483
+ continue
484
+ if not addrs:
485
+ return None
486
+
487
+ plan = _plan(cfg)
488
+ section = plan.section
489
+ if plan.target_variable:
490
+ mode, name = "variable", plan.target_variable
491
+ elif section:
492
+ mode, name = "section", section
493
+ else:
494
+ mode, name = "range", None
495
+
496
+ block = {
497
+ "mode": mode,
498
+ "name": name,
499
+ "access_size": plan.memory_access_size,
500
+ }
501
+
502
+ if section in (".stack-live", "stack-live"):
503
+ lo, hi = min(addrs), max(addrs)
504
+ block.update({
505
+ "span_source": "observed",
506
+ "start": f"0x{lo:x}",
507
+ "end": f"0x{hi:x}",
508
+ "bytes": hi - lo,
509
+ })
510
+ else:
511
+ block.update({
512
+ "span_source": "unresolved-in-fleet",
513
+ "start": None,
514
+ "end": None,
515
+ "bytes": None,
516
+ })
517
+ return block
518
+
519
+
520
+ def _expected_ids(cfg: dict, expected_count: Optional[int] = None) -> Optional[list]:
521
+ """The injection_ids the campaign planned, or None when unknown.
522
+
523
+ A faultlist replay plans the CSV's own injection_ids (which need not be
524
+ 1..N, e.g. a SOFIA subset); a fan-out capped with -n runs only the first
525
+ expected_count of them in injection_id order, the order the faultlist is
526
+ built in. Otherwise the ids are 1..N."""
527
+ if isinstance(expected_count, bool) or not isinstance(expected_count, int) \
528
+ or expected_count <= 0:
529
+ expected_count = None
530
+ plan = _plan(cfg)
531
+ fl = plan.faultlist_csv
532
+ if fl:
533
+ try:
534
+ with open(fl, newline="") as fh:
535
+ ids = sorted(int(r["injection_id"]) for r in csv.DictReader(fh))
536
+ except (OSError, csv.Error, KeyError, TypeError, ValueError):
537
+ ids = None
538
+ if ids:
539
+ return ids[:expected_count] if expected_count else ids
540
+ return list(range(1, expected_count + 1)) if expected_count else None
541
+ n = expected_count or plan.num_injections
542
+ if isinstance(n, bool) or not isinstance(n, int) or n <= 0:
543
+ return None
544
+ return list(range(1, n + 1))
545
+
546
+
547
+ def _write_metadata(out_dir: str, rows: list, tally: dict,
548
+ config: Optional[dict],
549
+ campaign_id: Optional[str],
550
+ expected_count: Optional[int] = None) -> str:
551
+ """metadata.json carrying campaign identity + the outcome tally as
552
+ statistics. The per-index rows don't know seed/fault_model, so those come
553
+ from config when the caller passes it; the tally is authoritative for the
554
+ outcome counts (it's what the ledger compares)."""
555
+ spec = _campaign(config)
556
+ cfg = config or {}
557
+ total = len(rows)
558
+ # Same denominators as OutcomeClassifier.get_statistics: silicon rates
559
+ # over the valid rows, framework rows as a share of everything.
560
+ invalid = sum(tally.get(o, 0) for o in NON_SILICON_OUTCOMES)
561
+ valid_total = total - invalid
562
+ statistics = {"total": total, "valid_total": valid_total}
563
+ for name in _OUTCOME_ORDER:
564
+ count = tally.get(name, 0)
565
+ base = total if name in NON_SILICON_OUTCOMES else valid_total
566
+ statistics[name] = {
567
+ "count": count,
568
+ "percentage": (count / base * 100.0) if base else 0.0,
569
+ }
570
+
571
+ metadata = {
572
+ "campaign_id": campaign_id or "",
573
+ "benchmark": _text(spec.benchmark),
574
+ "seed": _text(spec.seed),
575
+ "num_injections": total if spec.num_injections is None else spec.num_injections,
576
+ "fault_model": _text(spec.fault_model),
577
+ "target_types": spec.target_types if spec.target_types is not None else [],
578
+ "statistics": statistics,
579
+ "completed_at": time.strftime("%Y-%m-%d %H:%M:%S"),
580
+ }
581
+
582
+ # A fleet index that died before writing its CSV simply has no file, so
583
+ # a short merge looks exactly like a finished one. Say so in the
584
+ # artifact instead of leaving it to whoever reads the counts.
585
+ expected_ids = _expected_ids(cfg, expected_count)
586
+ if expected_ids is not None:
587
+ seen = set()
588
+ for r in rows:
589
+ try:
590
+ seen.add(int(r.get("injection_id") or 0))
591
+ except (TypeError, ValueError):
592
+ pass
593
+ missing = [i for i in expected_ids if i not in seen]
594
+ metadata["expected_injections"] = len(expected_ids)
595
+ metadata["partial"] = bool(missing)
596
+ if missing:
597
+ metadata["missing_indices"] = missing
598
+
599
+ target = _target_block_from_rows(rows, cfg)
600
+ if target is not None:
601
+ metadata["target"] = target
602
+
603
+ meta_path = os.path.join(out_dir, "metadata.json")
604
+ with open(meta_path, "w") as f:
605
+ json.dump(metadata, f, indent=2)
606
+ return meta_path
607
+
608
+
609
+ def consolidate_from_index_csv(
610
+ index_csv: str,
611
+ config: Optional[dict] = None,
612
+ campaign_id: Optional[str] = None,
613
+ expected_count: Optional[int] = None) -> Tuple[str, dict, int]:
614
+ """Convenience: derive <out> from a per-index CSV path, then consolidate.
615
+
616
+ The worker only knows the per-index CSV it just wrote (scraped from the
617
+ runner's 'Results:' line), so this saves it from reconstructing <out>.
618
+ config/campaign_id are forwarded to consolidate() so the summary artifacts
619
+ carry benchmark/seed/fault_model identity."""
620
+ return consolidate(
621
+ _out_dir_from_index_csv(index_csv),
622
+ config=config,
623
+ campaign_id=campaign_id,
624
+ expected_count=expected_count,
625
+ )
fim/analysis/csv_io.py ADDED
@@ -0,0 +1,28 @@
1
+ # SPDX-FileCopyrightText: 2026 HI-REST and the HFIM contributors
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """Readers of injections.csv.
5
+
6
+ Python's csv module rejects a field larger than 131072 bytes. An SDC
7
+ detail for a long array used to exceed that. New rows stay under
8
+ SDC_DETAILS_CSV_MAX; this limit is what still lets an already-written
9
+ long row be read instead of failing the campaign.
10
+ """
11
+
12
+ import csv
13
+ import sys
14
+ from typing import Optional
15
+
16
+ # 8 MiB stays under the platform C long, so field_size_limit does not
17
+ # raise OverflowError. A quicksort SDC detail was about 158 KB.
18
+ INJECTIONS_CSV_FIELD_LIMIT = 8 * 1024 * 1024
19
+
20
+
21
+ def raise_injections_field_limit(limit: Optional[int] = None) -> int:
22
+ """Raise the process-wide csv field limit. Returns the previous limit."""
23
+ if limit is None:
24
+ limit = INJECTIONS_CSV_FIELD_LIMIT
25
+ try:
26
+ return csv.field_size_limit(limit)
27
+ except OverflowError:
28
+ return csv.field_size_limit(min(limit, sys.maxsize))