polyrun 3.2.0-java

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 (225) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +234 -0
  3. data/CODE_OF_CONDUCT.md +26 -0
  4. data/CONTRIBUTING.md +23 -0
  5. data/LICENSE +21 -0
  6. data/README.md +251 -0
  7. data/SECURITY.md +25 -0
  8. data/bin/polyrun +6 -0
  9. data/docs/QUALITY.md +82 -0
  10. data/docs/QUALITY_CONFIGURATION.md +95 -0
  11. data/docs/SETUP_PROFILE.md +139 -0
  12. data/lib/polyrun/benchmark/pressure/cooker.rb +191 -0
  13. data/lib/polyrun/benchmark/pressure/process_sample.rb +127 -0
  14. data/lib/polyrun/benchmark/pressure.rb +144 -0
  15. data/lib/polyrun/benchmark/profile.rb +191 -0
  16. data/lib/polyrun/benchmark/report.rb +87 -0
  17. data/lib/polyrun/cli/benchmark_commands.rb +66 -0
  18. data/lib/polyrun/cli/ci_shard_hooks.rb +129 -0
  19. data/lib/polyrun/cli/ci_shard_run_command.rb +177 -0
  20. data/lib/polyrun/cli/ci_shard_run_parse.rb +68 -0
  21. data/lib/polyrun/cli/config_command.rb +42 -0
  22. data/lib/polyrun/cli/coverage_commands.rb +150 -0
  23. data/lib/polyrun/cli/coverage_merge_io.rb +150 -0
  24. data/lib/polyrun/cli/database_commands.rb +163 -0
  25. data/lib/polyrun/cli/default_run.rb +144 -0
  26. data/lib/polyrun/cli/doctor_command.rb +94 -0
  27. data/lib/polyrun/cli/env_commands.rb +43 -0
  28. data/lib/polyrun/cli/failure_commands.rb +99 -0
  29. data/lib/polyrun/cli/graph_command.rb +68 -0
  30. data/lib/polyrun/cli/help.rb +83 -0
  31. data/lib/polyrun/cli/helpers.rb +162 -0
  32. data/lib/polyrun/cli/hooks_command.rb +97 -0
  33. data/lib/polyrun/cli/init_command.rb +108 -0
  34. data/lib/polyrun/cli/mutation_command.rb +67 -0
  35. data/lib/polyrun/cli/partition_diagnostics.rb +22 -0
  36. data/lib/polyrun/cli/plan_command.rb +184 -0
  37. data/lib/polyrun/cli/prepare_command.rb +70 -0
  38. data/lib/polyrun/cli/prepare_recipe.rb +82 -0
  39. data/lib/polyrun/cli/quality_commands.rb +65 -0
  40. data/lib/polyrun/cli/queue_command.rb +161 -0
  41. data/lib/polyrun/cli/quick_command.rb +13 -0
  42. data/lib/polyrun/cli/report_commands.rb +108 -0
  43. data/lib/polyrun/cli/run_queue_command.rb +127 -0
  44. data/lib/polyrun/cli/run_shards_command.rb +164 -0
  45. data/lib/polyrun/cli/run_shards_parallel_children.rb +112 -0
  46. data/lib/polyrun/cli/run_shards_parallel_wait.rb +252 -0
  47. data/lib/polyrun/cli/run_shards_plan_boot_phases.rb +207 -0
  48. data/lib/polyrun/cli/run_shards_plan_options.rb +74 -0
  49. data/lib/polyrun/cli/run_shards_planning.rb +123 -0
  50. data/lib/polyrun/cli/run_shards_run.rb +171 -0
  51. data/lib/polyrun/cli/run_shards_worker_interrupt.rb +101 -0
  52. data/lib/polyrun/cli/skip_env.rb +34 -0
  53. data/lib/polyrun/cli/spec_quality_commands.rb +149 -0
  54. data/lib/polyrun/cli/start_bootstrap.rb +126 -0
  55. data/lib/polyrun/cli/timing_command.rb +31 -0
  56. data/lib/polyrun/cli/tool_options.rb +48 -0
  57. data/lib/polyrun/cli/validate_command.rb +26 -0
  58. data/lib/polyrun/cli.rb +272 -0
  59. data/lib/polyrun/config/dotted_path.rb +21 -0
  60. data/lib/polyrun/config/effective.rb +82 -0
  61. data/lib/polyrun/config/resolver.rb +114 -0
  62. data/lib/polyrun/config/schema.rb +39 -0
  63. data/lib/polyrun/config/suite.rb +109 -0
  64. data/lib/polyrun/config/tool_defaults.rb +42 -0
  65. data/lib/polyrun/config/tool_validation.rb +79 -0
  66. data/lib/polyrun/config/tools.rb +120 -0
  67. data/lib/polyrun/config.rb +97 -0
  68. data/lib/polyrun/coverage/cobertura_zero_lines.rb +32 -0
  69. data/lib/polyrun/coverage/collector.rb +169 -0
  70. data/lib/polyrun/coverage/collector_blob.rb +53 -0
  71. data/lib/polyrun/coverage/collector_finish.rb +98 -0
  72. data/lib/polyrun/coverage/collector_fragment_meta.rb +57 -0
  73. data/lib/polyrun/coverage/config_resolve.rb +131 -0
  74. data/lib/polyrun/coverage/example_diff.rb +184 -0
  75. data/lib/polyrun/coverage/example_diff_snapshot.rb +44 -0
  76. data/lib/polyrun/coverage/example_diff_track_filter.rb +51 -0
  77. data/lib/polyrun/coverage/file_stats_report.rb +36 -0
  78. data/lib/polyrun/coverage/filter.rb +22 -0
  79. data/lib/polyrun/coverage/formatter.rb +137 -0
  80. data/lib/polyrun/coverage/merge/formatters.rb +188 -0
  81. data/lib/polyrun/coverage/merge/formatters_html.rb +221 -0
  82. data/lib/polyrun/coverage/merge/html/_file_list.html.erb +21 -0
  83. data/lib/polyrun/coverage/merge/html/_file_section.html.erb +26 -0
  84. data/lib/polyrun/coverage/merge/html/_groups_table.html.erb +18 -0
  85. data/lib/polyrun/coverage/merge/html/_overview.html.erb +47 -0
  86. data/lib/polyrun/coverage/merge/html/report.css +147 -0
  87. data/lib/polyrun/coverage/merge/html/report.js +48 -0
  88. data/lib/polyrun/coverage/merge/html/template.html.erb +30 -0
  89. data/lib/polyrun/coverage/merge.rb +160 -0
  90. data/lib/polyrun/coverage/merge_fragment_meta.rb +58 -0
  91. data/lib/polyrun/coverage/merge_merge_two.rb +168 -0
  92. data/lib/polyrun/coverage/merge_native.rb +39 -0
  93. data/lib/polyrun/coverage/rails.rb +126 -0
  94. data/lib/polyrun/coverage/reporting.rb +41 -0
  95. data/lib/polyrun/coverage/result.rb +18 -0
  96. data/lib/polyrun/coverage/track_files.rb +150 -0
  97. data/lib/polyrun/data/cached_fixtures.rb +122 -0
  98. data/lib/polyrun/data/factory_counts.rb +48 -0
  99. data/lib/polyrun/data/factory_instrumentation.rb +50 -0
  100. data/lib/polyrun/data/fixtures.rb +68 -0
  101. data/lib/polyrun/data/parallel_provisioning.rb +93 -0
  102. data/lib/polyrun/data/snapshot.rb +84 -0
  103. data/lib/polyrun/database/clone_shards.rb +106 -0
  104. data/lib/polyrun/database/provision.rb +83 -0
  105. data/lib/polyrun/database/shard.rb +64 -0
  106. data/lib/polyrun/database/url_builder/connection/infer.rb +53 -0
  107. data/lib/polyrun/database/url_builder/connection/url_builders.rb +43 -0
  108. data/lib/polyrun/database/url_builder/connection.rb +191 -0
  109. data/lib/polyrun/database/url_builder/template_prepare.rb +21 -0
  110. data/lib/polyrun/database/url_builder.rb +188 -0
  111. data/lib/polyrun/debug.rb +81 -0
  112. data/lib/polyrun/env/ci.rb +65 -0
  113. data/lib/polyrun/error.rb +3 -0
  114. data/lib/polyrun/export/csv.rb +25 -0
  115. data/lib/polyrun/export/markdown.rb +47 -0
  116. data/lib/polyrun/graph/client.rb +64 -0
  117. data/lib/polyrun/graph/error.rb +13 -0
  118. data/lib/polyrun/graph/index.rb +75 -0
  119. data/lib/polyrun/graph/inspect.rb +58 -0
  120. data/lib/polyrun/graph/plan.rb +134 -0
  121. data/lib/polyrun/graph/planner.rb +117 -0
  122. data/lib/polyrun/graph/syntax.rb +114 -0
  123. data/lib/polyrun/graph/transaction.rb +81 -0
  124. data/lib/polyrun/graph/worker.rb +55 -0
  125. data/lib/polyrun/graph/workspace.rb +117 -0
  126. data/lib/polyrun/hooks/dsl.rb +128 -0
  127. data/lib/polyrun/hooks/shell_runner.rb +33 -0
  128. data/lib/polyrun/hooks/worker_runner.rb +27 -0
  129. data/lib/polyrun/hooks/worker_shell.rb +50 -0
  130. data/lib/polyrun/hooks.rb +190 -0
  131. data/lib/polyrun/log.rb +86 -0
  132. data/lib/polyrun/minitest_support.rb +60 -0
  133. data/lib/polyrun/mutation/candidates.rb +91 -0
  134. data/lib/polyrun/mutation/operators.rb +51 -0
  135. data/lib/polyrun/mutation/runner.rb +133 -0
  136. data/lib/polyrun/mutation/subjects.rb +88 -0
  137. data/lib/polyrun/partition/constraints.rb +80 -0
  138. data/lib/polyrun/partition/hrw.rb +70 -0
  139. data/lib/polyrun/partition/min_heap.rb +64 -0
  140. data/lib/polyrun/partition/paths.rb +175 -0
  141. data/lib/polyrun/partition/paths_build.rb +141 -0
  142. data/lib/polyrun/partition/plan.rb +250 -0
  143. data/lib/polyrun/partition/plan_lpt.rb +91 -0
  144. data/lib/polyrun/partition/plan_sharding.rb +56 -0
  145. data/lib/polyrun/partition/reports.rb +139 -0
  146. data/lib/polyrun/partition/stable_shuffle.rb +18 -0
  147. data/lib/polyrun/partition/suite.rb +120 -0
  148. data/lib/polyrun/partition/timing_diagnostics.rb +138 -0
  149. data/lib/polyrun/partition/timing_keys.rb +86 -0
  150. data/lib/polyrun/prepare/artifacts.rb +40 -0
  151. data/lib/polyrun/prepare/assets.rb +64 -0
  152. data/lib/polyrun/process_stdio.rb +96 -0
  153. data/lib/polyrun/quality/command.rb +84 -0
  154. data/lib/polyrun/quality/measure.rb +38 -0
  155. data/lib/polyrun/quality/observe.rb +53 -0
  156. data/lib/polyrun/quality/observe_hook.rb +103 -0
  157. data/lib/polyrun/quality/sandbox.rb +70 -0
  158. data/lib/polyrun/queue/duration.rb +30 -0
  159. data/lib/polyrun/queue/file_store.rb +413 -0
  160. data/lib/polyrun/queue/file_store_intent.rb +188 -0
  161. data/lib/polyrun/queue/file_store_pending.rb +48 -0
  162. data/lib/polyrun/queue/worker_loop.rb +73 -0
  163. data/lib/polyrun/quick/assertions.rb +32 -0
  164. data/lib/polyrun/quick/config.rb +56 -0
  165. data/lib/polyrun/quick/errors.rb +6 -0
  166. data/lib/polyrun/quick/example_group.rb +111 -0
  167. data/lib/polyrun/quick/example_runner.rb +129 -0
  168. data/lib/polyrun/quick/matchers.rb +159 -0
  169. data/lib/polyrun/quick/matchers_predicates.rb +122 -0
  170. data/lib/polyrun/quick/reporter.rb +76 -0
  171. data/lib/polyrun/quick/runner.rb +224 -0
  172. data/lib/polyrun/quick.rb +1 -0
  173. data/lib/polyrun/railtie.rb +7 -0
  174. data/lib/polyrun/reporting/failure_merge.rb +171 -0
  175. data/lib/polyrun/reporting/junit.rb +126 -0
  176. data/lib/polyrun/reporting/junit_emit.rb +58 -0
  177. data/lib/polyrun/reporting/junit_report.rb +87 -0
  178. data/lib/polyrun/reporting/rspec_failure_fragment_formatter.rb +95 -0
  179. data/lib/polyrun/reporting/rspec_junit.rb +39 -0
  180. data/lib/polyrun/rspec_support/active_record_timeout_recovery.rb +51 -0
  181. data/lib/polyrun/rspec_support/example_debug.rb +167 -0
  182. data/lib/polyrun/rspec_support/example_debug_instrumentation.rb +73 -0
  183. data/lib/polyrun/rspec_support/sharded_formatter_compat.rb +57 -0
  184. data/lib/polyrun/rspec_support.rb +110 -0
  185. data/lib/polyrun/spec_quality/config.rb +139 -0
  186. data/lib/polyrun/spec_quality/fragment.rb +39 -0
  187. data/lib/polyrun/spec_quality/merge.rb +78 -0
  188. data/lib/polyrun/spec_quality/minitest_hook.rb +42 -0
  189. data/lib/polyrun/spec_quality/plan_loader.rb +47 -0
  190. data/lib/polyrun/spec_quality/profile.rb +102 -0
  191. data/lib/polyrun/spec_quality/report.rb +363 -0
  192. data/lib/polyrun/spec_quality/rspec_hook.rb +55 -0
  193. data/lib/polyrun/spec_quality/sql_counter.rb +34 -0
  194. data/lib/polyrun/spec_quality.rb +212 -0
  195. data/lib/polyrun/sus_support.rb +55 -0
  196. data/lib/polyrun/templates/POLYRUN.md +51 -0
  197. data/lib/polyrun/templates/ci_matrix.polyrun.yml +22 -0
  198. data/lib/polyrun/templates/minimal_gem.polyrun.yml +13 -0
  199. data/lib/polyrun/templates/polyrun_hooks_spec_quality.rb +12 -0
  200. data/lib/polyrun/templates/polyrun_spec_quality.yml +20 -0
  201. data/lib/polyrun/templates/rails_prepare.polyrun.yml +51 -0
  202. data/lib/polyrun/templates/rails_prepare_task.rake +16 -0
  203. data/lib/polyrun/timing/merge.rb +36 -0
  204. data/lib/polyrun/timing/rspec_example_formatter.rb +60 -0
  205. data/lib/polyrun/timing/stats.rb +76 -0
  206. data/lib/polyrun/timing/summary.rb +78 -0
  207. data/lib/polyrun/timing/variance_report.rb +51 -0
  208. data/lib/polyrun/version.rb +3 -0
  209. data/lib/polyrun/worker_output.rb +181 -0
  210. data/lib/polyrun/worker_output_forwarders.rb +94 -0
  211. data/lib/polyrun/worker_ping.rb +77 -0
  212. data/lib/polyrun.rb +59 -0
  213. data/polyrun.gemspec +49 -0
  214. data/sig/polyrun/cli.rbs +6 -0
  215. data/sig/polyrun/config.rbs +20 -0
  216. data/sig/polyrun/debug.rbs +12 -0
  217. data/sig/polyrun/log.rbs +12 -0
  218. data/sig/polyrun/minitest_support.rbs +7 -0
  219. data/sig/polyrun/quick.rbs +19 -0
  220. data/sig/polyrun/rspec_support.rbs +21 -0
  221. data/sig/polyrun/sus_support.rbs +7 -0
  222. data/sig/polyrun/worker_output.rbs +11 -0
  223. data/sig/polyrun/worker_ping.rbs +10 -0
  224. data/sig/polyrun.rbs +11 -0
  225. metadata +463 -0
@@ -0,0 +1,171 @@
1
+ require "json"
2
+ require "fileutils"
3
+
4
+ require_relative "../export/csv"
5
+ require_relative "../export/markdown"
6
+
7
+ module Polyrun
8
+ module Reporting
9
+ # Merge per-worker / per-shard failure fragments (JSONL or RSpec JSON) into one report.
10
+ # Fragment basenames align with {Coverage::CollectorFragmentMeta} (worker index and optional matrix shard).
11
+ module FailureMerge
12
+ DEFAULT_FRAGMENT_DIR = "tmp/polyrun_failures".freeze
13
+ FRAGMENT_GLOB = "polyrun-failure-fragment-*.jsonl".freeze
14
+ CSV_HEADERS = %w[
15
+ id full_description location file_path line_number message exception_class
16
+ polyrun_shard_index polyrun_shard_total source
17
+ ].freeze
18
+
19
+ module_function
20
+
21
+ def default_fragment_glob(dir = nil)
22
+ root = File.expand_path(dir || DEFAULT_FRAGMENT_DIR, Dir.pwd)
23
+ File.join(root, FRAGMENT_GLOB)
24
+ end
25
+
26
+ def merge_fragment_paths(quiet: false)
27
+ p = default_fragment_glob
28
+ Dir.glob(p).sort.tap do |paths|
29
+ Polyrun::Log.warn "merge-failures: no files matched #{p}" if paths.empty? && !quiet
30
+ end
31
+ end
32
+
33
+ # @param paths [Array<String>] fragment paths (.jsonl and/or RSpec --format json outputs)
34
+ # @param format [String] "jsonl", "json", "csv", or "markdown"
35
+ # @param output [String] destination path
36
+ # @return [Integer] count of failure rows merged
37
+ def merge_files!(paths, output:, format: "jsonl")
38
+ fmt = format.to_s.downcase
39
+ rows = collect_rows(paths)
40
+ out_abs = File.expand_path(output)
41
+ FileUtils.mkdir_p(File.dirname(out_abs))
42
+ case fmt
43
+ when "json"
44
+ write_json_output!(out_abs, paths, rows)
45
+ when "jsonl"
46
+ write_jsonl_output!(out_abs, rows)
47
+ when "csv"
48
+ write_csv_output!(out_abs, rows)
49
+ when "markdown", "md"
50
+ write_markdown_output!(out_abs, rows)
51
+ else
52
+ raise Polyrun::Error, "merge-failures: unknown format #{fmt.inspect} (use jsonl, json, csv, or markdown)"
53
+ end
54
+ rows.size
55
+ end
56
+
57
+ def write_json_output!(out_abs, paths, rows)
58
+ doc = {
59
+ "meta" => {
60
+ "polyrun_merge" => true,
61
+ "inputs" => paths.map { |p| File.expand_path(p) },
62
+ "failure_count" => rows.size
63
+ },
64
+ "failures" => rows
65
+ }
66
+ File.write(out_abs, JSON.generate(doc))
67
+ end
68
+
69
+ def write_jsonl_output!(out_abs, rows)
70
+ File.write(out_abs, rows.map { |h| JSON.generate(h) }.join("\n") + (rows.empty? ? "" : "\n"))
71
+ end
72
+
73
+ def write_csv_output!(out_abs, rows)
74
+ csv_rows = rows.map { |row| CSV_HEADERS.map { |key| row[key] } }
75
+ File.write(out_abs, Export::Csv.generate(CSV_HEADERS, csv_rows))
76
+ end
77
+
78
+ def write_markdown_output!(out_abs, rows)
79
+ sections = rows.map.with_index(1) do |row, index|
80
+ {
81
+ heading: "Failure #{index}: #{row["full_description"] || row["location"] || row["id"]}",
82
+ headers: %w[field value],
83
+ rows: row.sort_by { |key, _| key.to_s }.map { |key, value| [key, value] }
84
+ }
85
+ end
86
+ sections = [{heading: "Failures", body: "(none)"}] if sections.empty?
87
+ File.write(out_abs, Export::Markdown.document("Polyrun failure report", sections))
88
+ end
89
+
90
+ def collect_rows(paths)
91
+ rows = []
92
+ paths.each do |p|
93
+ rows.concat(rows_from_path(p))
94
+ end
95
+ rows
96
+ end
97
+
98
+ def rows_from_path(path)
99
+ ext = File.extname(path).downcase
100
+ if ext == ".jsonl"
101
+ return rows_from_jsonl_file(path)
102
+ end
103
+
104
+ text = File.read(path, encoding: Encoding::UTF_8)
105
+ data =
106
+ begin
107
+ JSON.parse(text)
108
+ rescue JSON::ParserError => e
109
+ raise Polyrun::Error, "merge-failures: #{path} is not valid JSON: #{e.message}"
110
+ end
111
+ if data.is_a?(Hash) && data["examples"].is_a?(Array)
112
+ return failures_from_rspec_examples(data["examples"])
113
+ end
114
+
115
+ hint =
116
+ if data.is_a?(Hash)
117
+ keys = data.keys
118
+ "got JSON object with keys: #{keys.take(12).join(", ")}" + ((keys.size > 12) ? ", …" : "")
119
+ else
120
+ "got #{data.class}"
121
+ end
122
+ raise Polyrun::Error,
123
+ "merge-failures: #{path} is not RSpec JSON (expected top-level \"examples\" array). #{hint}. " \
124
+ "Use RSpec --format json, or polyrun failure JSONL (.jsonl fragments)."
125
+ end
126
+
127
+ def rows_from_jsonl_file(path)
128
+ acc = []
129
+ File.readlines(path, chomp: true, encoding: Encoding::UTF_8).each_with_index do |line, idx|
130
+ line = line.strip
131
+ next if line.empty?
132
+
133
+ acc << parse_jsonl_line!(path, idx + 1, line)
134
+ end
135
+ acc
136
+ end
137
+
138
+ def parse_jsonl_line!(path, line_number, line)
139
+ JSON.parse(line)
140
+ rescue JSON::ParserError => e
141
+ raise Polyrun::Error,
142
+ "merge-failures: invalid JSONL at #{path} line #{line_number}: #{e.message}"
143
+ end
144
+
145
+ def failures_from_rspec_examples(examples)
146
+ examples.each_with_object([]) do |ex, acc|
147
+ next unless ex.is_a?(Hash)
148
+ next unless ex["status"].to_s == "failed"
149
+
150
+ acc << rspec_example_to_row(ex)
151
+ end
152
+ end
153
+
154
+ def rspec_example_to_row(ex)
155
+ ex = ex.transform_keys(&:to_s)
156
+ exc = ex["exception"] || {}
157
+ exc = exc.transform_keys(&:to_s) if exc.is_a?(Hash)
158
+ {
159
+ "id" => ex["id"],
160
+ "full_description" => ex["full_description"],
161
+ "location" => (ex["file_path"] && ex["line_number"]) ? "#{ex["file_path"]}:#{ex["line_number"]}" : ex["full_description"],
162
+ "file_path" => ex["file_path"],
163
+ "line_number" => ex["line_number"],
164
+ "message" => exc["message"] || ex["full_description"],
165
+ "exception_class" => exc["class"],
166
+ "source" => "rspec_json"
167
+ }.compact
168
+ end
169
+ end
170
+ end
171
+ end
@@ -0,0 +1,126 @@
1
+ require "cgi"
2
+ require "json"
3
+
4
+ module Polyrun
5
+ module Reporting
6
+ # JUnit XML for CI (replaces rspec_junit_formatter) — stdlib only.
7
+ #
8
+ # Input JSON may be:
9
+ # - **RSpec JSON** — output of +rspec --format json --out rspec.json+ (+examples+ array).
10
+ # - **Polyrun canonical** — +{ "name" => "...", "testcases" => [ ... ] }+ (see +emit_xml+).
11
+ #
12
+ # Each testcase hash supports: +classname+, +name+, +time+, +status+ (+passed+, +failed+, +pending+/+skipped+),
13
+ # and optional +failure+ => +{ "message" => "...", "body" => "..." }+.
14
+ module Junit
15
+ module_function
16
+
17
+ def write_from_json_file(json_path, output_path:, format: "xml")
18
+ data = JSON.parse(File.read(json_path))
19
+ write_from_hash(data, output_path: output_path, format: format)
20
+ end
21
+
22
+ # Merge several RSpec JSON outputs (parallel shards) by concatenating +examples+.
23
+ def merge_rspec_json_files(paths, output_path:, format: "xml")
24
+ merged = {"examples" => []}
25
+ paths.each do |p|
26
+ data = JSON.parse(File.read(p))
27
+ merged["examples"].concat(data["examples"] || [])
28
+ end
29
+ merged["summary"] = {"summary_line" => "merged #{paths.size} RSpec JSON file(s)"}
30
+ write_from_hash(merged, output_path: output_path, format: format)
31
+ end
32
+
33
+ def write_from_hash(data, output_path:, format: "xml")
34
+ doc = parse_input(data)
35
+ body = render(doc, format: format)
36
+ File.write(output_path, body)
37
+ output_path
38
+ end
39
+
40
+ def parse_input(data)
41
+ raise Polyrun::Error, "JUnit input must be a Hash" unless data.is_a?(Hash)
42
+
43
+ if data["examples"].is_a?(Array)
44
+ from_rspec_json(data)
45
+ elsif data["testcases"].is_a?(Array)
46
+ from_polyrun_hash(data)
47
+ else
48
+ raise Polyrun::Error,
49
+ 'JUnit input: expected top-level "examples" (RSpec JSON) or "testcases" (Polyrun schema)'
50
+ end
51
+ end
52
+
53
+ def from_rspec_json(data)
54
+ cases = []
55
+ data["examples"].each do |ex|
56
+ next unless ex.is_a?(Hash)
57
+
58
+ cases << junit_rspec_example_to_case(ex)
59
+ end
60
+
61
+ name = (data.dig("summary", "summary_line") || data["name"] || "RSpec").to_s
62
+ from_polyrun_hash("name" => name, "hostname" => hostname, "testcases" => cases)
63
+ end
64
+
65
+ def junit_rspec_example_to_case(ex)
66
+ status = (ex["status"] || "unknown").to_s
67
+ file = ex["file_path"].to_s.sub(%r{\A\./}, "")
68
+ tc = {
69
+ "classname" => file.empty? ? "rspec" : file,
70
+ "name" => (ex["full_description"] || ex["description"] || ex["id"]).to_s,
71
+ "time" => (ex["run_time"] || ex["time"] || 0).to_f,
72
+ "status" => status
73
+ }
74
+ if status == "failed"
75
+ tc["failure"] = junit_rspec_failure_hash(ex)
76
+ end
77
+ tc
78
+ end
79
+
80
+ def junit_rspec_failure_hash(ex)
81
+ e = ex["exception"]
82
+ if e.is_a?(Hash)
83
+ {
84
+ "message" => e["message"].to_s,
85
+ "body" => Array(e["backtrace"]).join("\n")
86
+ }
87
+ else
88
+ {"message" => "failed", "body" => ex.inspect}
89
+ end
90
+ end
91
+
92
+ def from_polyrun_hash(data)
93
+ {
94
+ "name" => (data["name"] || data["testsuite_name"] || "tests").to_s,
95
+ "hostname" => (data["hostname"] || hostname).to_s,
96
+ "testcases" => Array(data["testcases"])
97
+ }
98
+ end
99
+
100
+ def hostname
101
+ require "socket"
102
+ Socket.gethostname
103
+ rescue
104
+ "localhost"
105
+ end
106
+
107
+ def status_of(c)
108
+ s = (c["status"] || c[:status] || "passed").to_s
109
+ return "skipped" if s == "pending"
110
+
111
+ s
112
+ end
113
+
114
+ def format_float(x)
115
+ format("%.6f", x.to_f)
116
+ end
117
+
118
+ def esc(s)
119
+ CGI.escapeHTML(s.to_s)
120
+ end
121
+ end
122
+ end
123
+ end
124
+
125
+ require_relative "junit_emit"
126
+ require_relative "junit_report"
@@ -0,0 +1,58 @@
1
+ module Polyrun
2
+ module Reporting
3
+ module Junit
4
+ module_function
5
+
6
+ # +doc+ is +{ "name", "hostname", "testcases" => [ ... ] }+
7
+ def emit_xml(doc)
8
+ cases = doc["testcases"] || []
9
+ lines = []
10
+ lines << junit_xml_header(doc, cases)
11
+ cases.each do |c|
12
+ lines << junit_xml_testcase_line(c)
13
+ end
14
+ lines << %(</testsuite>)
15
+ lines << %(</testsuites>)
16
+ lines.join("\n") + "\n"
17
+ end
18
+
19
+ def junit_xml_header(doc, cases)
20
+ total_time = cases.sum { |c| (c["time"] || c[:time] || 0).to_f }
21
+ failures = cases.count { |c| status_of(c) == "failed" }
22
+ errors = cases.count { |c| status_of(c) == "error" }
23
+ skipped = cases.count { |c| %w[pending skipped].include?(status_of(c)) }
24
+ tests = cases.size
25
+ lines = []
26
+ lines << %(<?xml version="1.0" encoding="UTF-8"?>)
27
+ lines << %(<testsuites name="#{esc(doc["name"])}">)
28
+ lines << %(<testsuite name="#{esc(doc["name"])}" tests="#{tests}" failures="#{failures}" errors="#{errors}" skipped="#{skipped}" time="#{format_float(total_time)}" hostname="#{esc(doc["hostname"])}">)
29
+ lines.join("\n")
30
+ end
31
+
32
+ def junit_xml_testcase_line(c)
33
+ c = c.transform_keys(&:to_s)
34
+ classname = c["classname"].to_s
35
+ name = c["name"].to_s
36
+ time = (c["time"] || 0).to_f
37
+ lines = []
38
+ lines << %(<testcase classname="#{esc(classname)}" name="#{esc(name)}" file="#{esc(c["file"] || classname)}" line="#{esc(c["line"] || "")}" time="#{format_float(time)}">)
39
+ case status_of(c)
40
+ when "failed", "error"
41
+ lines << junit_xml_failure_body(c)
42
+ when "pending", "skipped"
43
+ lines << %(<skipped/>)
44
+ end
45
+ lines << %(</testcase>)
46
+ lines.join("\n")
47
+ end
48
+
49
+ def junit_xml_failure_body(c)
50
+ f = c["failure"] || {}
51
+ fm = f["message"] || f[:message] || status_of(c)
52
+ fb = f["body"] || f[:body] || ""
53
+ tag = (status_of(c) == "error") ? "error" : "failure"
54
+ %(<#{tag} message="#{esc(fm)}">#{esc(fb)}</#{tag}>)
55
+ end
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,87 @@
1
+ require "json"
2
+
3
+ require_relative "../export/csv"
4
+ require_relative "../export/markdown"
5
+
6
+ module Polyrun
7
+ module Reporting
8
+ module Junit
9
+ CSV_HEADERS = %w[classname name status time_seconds failure_message].freeze
10
+ MARKDOWN_HEADERS = %w[classname name status time_seconds].freeze
11
+
12
+ module_function
13
+
14
+ def render(doc, format: "xml")
15
+ case format.to_s.downcase
16
+ when "xml" then emit_xml(doc)
17
+ when "csv" then emit_csv(doc)
18
+ when "markdown", "md" then emit_markdown(doc)
19
+ else
20
+ raise Polyrun::Error, "report-junit: unknown format #{format.inspect} (use xml, csv, or markdown)"
21
+ end
22
+ end
23
+
24
+ def emit_csv(doc)
25
+ rows = Array(doc["testcases"]).map { |testcase| csv_row(testcase) }
26
+ Export::Csv.generate(CSV_HEADERS, rows)
27
+ end
28
+
29
+ def csv_row(testcase)
30
+ testcase = testcase.transform_keys(&:to_s)
31
+ failure = testcase["failure"] || {}
32
+ failure = failure.transform_keys(&:to_s) if failure.is_a?(Hash)
33
+ [
34
+ testcase["classname"],
35
+ testcase["name"],
36
+ status_of(testcase),
37
+ format_float(testcase["time"] || 0),
38
+ failure["message"]
39
+ ]
40
+ end
41
+
42
+ def emit_markdown(doc)
43
+ cases = Array(doc["testcases"])
44
+ sections = [
45
+ markdown_summary_section(doc, cases),
46
+ markdown_testcases_section(cases)
47
+ ]
48
+ failure_section = markdown_failures_section(cases)
49
+ sections << failure_section if failure_section
50
+ Export::Markdown.document(doc["name"].to_s, sections)
51
+ end
52
+
53
+ def markdown_summary_section(doc, cases)
54
+ total_time = cases.sum { |testcase| (testcase["time"] || testcase[:time] || 0).to_f }
55
+ summary_rows = [
56
+ ["tests", cases.size],
57
+ ["failures", cases.count { |testcase| status_of(testcase) == "failed" }],
58
+ ["errors", cases.count { |testcase| status_of(testcase) == "error" }],
59
+ ["skipped", cases.count { |testcase| %w[pending skipped].include?(status_of(testcase)) }],
60
+ ["time_seconds", format_float(total_time)],
61
+ ["hostname", doc["hostname"]]
62
+ ]
63
+ {heading: "Summary", headers: %w[metric value], rows: summary_rows}
64
+ end
65
+
66
+ def markdown_testcases_section(cases)
67
+ testcase_rows = cases.map do |testcase|
68
+ testcase = testcase.transform_keys(&:to_s)
69
+ [testcase["classname"], testcase["name"], status_of(testcase), format_float(testcase["time"] || 0)]
70
+ end
71
+ {heading: "Test cases", headers: MARKDOWN_HEADERS, rows: testcase_rows}
72
+ end
73
+
74
+ def markdown_failures_section(cases)
75
+ failed = cases.select { |testcase| %w[failed error].include?(status_of(testcase)) }
76
+ return if failed.empty?
77
+
78
+ failure_rows = failed.map do |testcase|
79
+ testcase = testcase.transform_keys(&:to_s)
80
+ failure = (testcase["failure"] || {}).transform_keys(&:to_s)
81
+ [testcase["name"], status_of(testcase), failure["message"], failure["body"]]
82
+ end
83
+ {heading: "Failures", headers: %w[name status message body], rows: failure_rows}
84
+ end
85
+ end
86
+ end
87
+ end
@@ -0,0 +1,95 @@
1
+ require "json"
2
+ require "fileutils"
3
+
4
+ module Polyrun
5
+ module Reporting
6
+ # RSpec formatter: appends one JSON object per failed example to the shard fragment file.
7
+ # Enable via +Polyrun::RSpecSupport.install_failure_fragments!+ and +POLYRUN_FAILURE_FRAGMENTS=1+ (set by run-shards --merge-failures).
8
+ #
9
+ # Output: +tmp/polyrun_failures/polyrun-failure-fragment-<workerN|shardM-workerN>.jsonl+
10
+ # (same basename rules as {Coverage::CollectorFragmentMeta}.)
11
+ class RspecFailureFragmentFormatter
12
+ ::RSpec::Core::Formatters.register self, :start, :example_failed
13
+
14
+ attr_reader :output
15
+
16
+ def initialize(output)
17
+ @output = output
18
+ @path = fragment_path
19
+ end
20
+
21
+ def start(_notification)
22
+ FileUtils.mkdir_p(File.dirname(@path))
23
+ File.write(@path, "")
24
+ end
25
+
26
+ def example_failed(notification)
27
+ ex = notification.example
28
+ exc = notification.exception
29
+ row = {
30
+ "id" => ex.id,
31
+ "full_description" => ex.full_description,
32
+ "location" => ex.location,
33
+ "file_path" => ex.file_path,
34
+ "line_number" => example_line_number(ex),
35
+ "message" => exc.message.to_s,
36
+ "exception_class" => exc.class.name,
37
+ "polyrun_shard_index" => ENV["POLYRUN_SHARD_INDEX"],
38
+ "polyrun_shard_total" => ENV["POLYRUN_SHARD_TOTAL"],
39
+ "polyrun_shard_matrix_index" => matrix_env_or_nil("POLYRUN_SHARD_MATRIX_INDEX"),
40
+ "polyrun_shard_matrix_total" => matrix_env_or_nil("POLYRUN_SHARD_MATRIX_TOTAL"),
41
+ "rspec_seed" => seed_if_known,
42
+ "rspec_order" => order_if_known
43
+ }
44
+ trim_backtrace!(row, exc)
45
+ File.open(@path, "a") { |f| f.puts(JSON.generate(row.compact)) }
46
+ end
47
+
48
+ private
49
+
50
+ def example_line_number(ex)
51
+ return ex.line_number if ex.respond_to?(:line_number)
52
+
53
+ ex.metadata[:line_number]
54
+ end
55
+
56
+ def fragment_path
57
+ dir = ENV.fetch("POLYRUN_FAILURE_FRAGMENT_DIR", FailureMerge::DEFAULT_FRAGMENT_DIR)
58
+ base = Polyrun::Coverage::CollectorFragmentMeta.fragment_default_basename_from_env
59
+ File.expand_path(File.join(dir, "polyrun-failure-fragment-#{base}.jsonl"))
60
+ end
61
+
62
+ def matrix_env_or_nil(name)
63
+ v = ENV[name]
64
+ return nil if v.nil? || v.to_s.strip.empty?
65
+
66
+ v
67
+ end
68
+
69
+ def seed_if_known
70
+ return unless defined?(::RSpec) && ::RSpec.respond_to?(:configuration)
71
+
72
+ ::RSpec.configuration.seed
73
+ rescue
74
+ nil
75
+ end
76
+
77
+ def order_if_known
78
+ return unless defined?(::RSpec) && ::RSpec.respond_to?(:configuration)
79
+
80
+ ::RSpec.configuration.order.to_s
81
+ rescue
82
+ nil
83
+ end
84
+
85
+ MAX_BT = 20
86
+
87
+ def trim_backtrace!(row, exc)
88
+ bt = exc.backtrace
89
+ return unless bt.is_a?(Array) && bt.any?
90
+
91
+ row["backtrace"] = bt.first(MAX_BT)
92
+ end
93
+ end
94
+ end
95
+ end
@@ -0,0 +1,39 @@
1
+ require "fileutils"
2
+
3
+ module Polyrun
4
+ module Reporting
5
+ # CI: emit JUnit XML from RSpec's JSON formatter output (replaces +rspec_junit_formatter+).
6
+ #
7
+ # require "polyrun/reporting/rspec_junit"
8
+ # Polyrun::Reporting::RspecJunit.install!(only_if: -> { ENV["CI"] })
9
+ #
10
+ # Ensure +.rspec+ or CLI keeps a human formatter (e.g. documentation) in addition to JSON.
11
+ module RspecJunit
12
+ module_function
13
+
14
+ def install!(json_path: "rspec.json", junit_path: "coverage/junit-coverage.xml", only_if: nil)
15
+ pred = only_if || -> { ENV["CI"] }
16
+ return unless pred.call
17
+
18
+ json_abs = File.expand_path(json_path)
19
+ FileUtils.mkdir_p(File.dirname(json_abs))
20
+
21
+ require "rspec/core"
22
+ require "rspec/core/formatters/json_formatter"
23
+
24
+ ::RSpec.configure do |config|
25
+ config.add_formatter ::RSpec::Core::Formatters::JsonFormatter, json_abs
26
+ end
27
+
28
+ at_exit do
29
+ next unless pred.call
30
+
31
+ FileUtils.mkdir_p(File.dirname(File.expand_path(junit_path)))
32
+ if File.file?(json_abs)
33
+ Junit.write_from_json_file(json_abs, output_path: junit_path)
34
+ end
35
+ end
36
+ end
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,51 @@
1
+ module Polyrun
2
+ module RSpecSupport
3
+ # Drops pooled connections after per-example Timeout interrupts database I/O.
4
+ # Uses only ActiveRecord connection-pool APIs (PostgreSQL, MySQL, SQLite, SQL Server, etc.).
5
+ module ActiveRecordTimeoutRecovery
6
+ module_function
7
+
8
+ def disconnect_all_connection_pools!
9
+ return unless active_record_loaded?
10
+
11
+ if defined?(ActiveRecord) && ActiveRecord.respond_to?(:disconnect_all!)
12
+ ActiveRecord.disconnect_all!
13
+ return
14
+ end
15
+
16
+ each_connection_pool(&:disconnect!)
17
+ end
18
+
19
+ def active_record_loaded?
20
+ defined?(ActiveRecord::Base) &&
21
+ ActiveRecord::Base.respond_to?(:connection_handler)
22
+ end
23
+
24
+ def each_connection_pool
25
+ connection_handlers.each do |handler|
26
+ pools_for(handler).each { |pool| yield pool }
27
+ end
28
+ end
29
+
30
+ def connection_handlers
31
+ base = ActiveRecord::Base
32
+ if base.respond_to?(:connection_handlers)
33
+ base.connection_handlers.values
34
+ else
35
+ [base.connection_handler]
36
+ end
37
+ end
38
+
39
+ def pools_for(handler)
40
+ if handler.respond_to?(:all_connection_pools)
41
+ handler.all_connection_pools
42
+ elsif handler.respond_to?(:connection_pool_list)
43
+ handler.connection_pool_list
44
+ else
45
+ []
46
+ end
47
+ end
48
+ private_class_method :active_record_loaded?, :each_connection_pool, :connection_handlers, :pools_for
49
+ end
50
+ end
51
+ end