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,150 @@
1
+ require "pathname"
2
+
3
+ require_relative "merge"
4
+
5
+ module Polyrun
6
+ module Coverage
7
+ # SimpleCov-compatible +track_files+ (globs from project root) and +add_group+ statistics
8
+ # for the JSON payload (+groups+ with +lines.covered_percent+ per group).
9
+ module TrackFiles
10
+ module_function
11
+
12
+ # Expands one or more glob patterns relative to +root+ (supports +{a,b}/**/*.rb+ with File::FNM_EXTGLOB).
13
+ def expand_globs(root, track_files)
14
+ root = File.expand_path(root)
15
+ patterns = Array(track_files).map(&:to_s).reject(&:empty?)
16
+ return [] if patterns.empty?
17
+
18
+ patterns.flat_map do |pattern|
19
+ Dir.chdir(root) do
20
+ Dir.glob(pattern, File::FNM_EXTGLOB)
21
+ end
22
+ end.map { |rel| File.expand_path(rel, root) }.uniq
23
+ end
24
+
25
+ # Keeps only loaded files that match configured +track_files+ globs.
26
+ def keep_tracked_files(blob, root, track_files)
27
+ tracked = expand_globs(root, track_files).each_with_object({}) { |abs, acc| acc[abs] = true }
28
+ blob.each_with_object({}) do |(path, entry), out|
29
+ abs = File.expand_path(path.to_s)
30
+ out[abs] = entry if tracked[abs]
31
+ end
32
+ end
33
+
34
+ # Adds tracked files that were never required, with simulated line arrays (blank/comment => nil, else 0).
35
+ # Matches SimpleCov +add_not_loaded_files+ behavior for coverage completeness.
36
+ def merge_untracked_into_blob(blob, root, track_files)
37
+ root = File.expand_path(root)
38
+ out = {}
39
+ blob.each do |k, v|
40
+ out[File.expand_path(k.to_s)] = v
41
+ end
42
+
43
+ expand_globs(root, track_files).each do |abs|
44
+ next if out.key?(abs)
45
+ next unless File.file?(abs)
46
+
47
+ out[abs] = {"lines" => simulated_lines_for_unloaded(abs)}
48
+ end
49
+ out
50
+ end
51
+
52
+ def simulated_lines_for_unloaded(path)
53
+ lines = []
54
+ File.foreach(path) do |line|
55
+ lines << (blank_or_comment?(line) ? nil : 0)
56
+ end
57
+ lines
58
+ rescue Errno::ENOENT, Errno::EACCES
59
+ []
60
+ end
61
+
62
+ def blank_or_comment?(line)
63
+ s = line.strip
64
+ s.empty? || s.start_with?("#")
65
+ end
66
+
67
+ # +groups+ is a Hash of group_name => glob pattern (relative to +root+), SimpleCov +add_group+ style.
68
+ # Produces the +groups+ section of SimpleCov JSON: each group has lines.covered_percent.
69
+ # Assignment uses paths present in +blob+ matching each glob (+File.fnmatch?+), not a fresh Dir.glob,
70
+ # so in-memory coverage lines up with reported files. Files matching no group get "Ungrouped".
71
+ def group_summaries(blob, root, groups)
72
+ return {} if groups.nil? || groups.empty?
73
+
74
+ root = File.expand_path(root)
75
+ normalized = {}
76
+ blob.each { |k, v| normalized[File.expand_path(k.to_s)] = v }
77
+
78
+ accum, ungrouped, any_ungrouped = group_summaries_accumulate(normalized, root, groups)
79
+ group_summaries_build_payload(groups, accum, ungrouped, any_ungrouped)
80
+ end
81
+
82
+ def group_summaries_accumulate(normalized, root, groups)
83
+ accum = Hash.new { |h, k| h[k] = {relevant: 0, covered: 0} }
84
+ ungrouped = {relevant: 0, covered: 0}
85
+ any_ungrouped_file = false
86
+
87
+ normalized.each do |abs, entry|
88
+ counts = Merge.line_counts(entry)
89
+ matched = []
90
+ groups.each do |name, glob_pattern|
91
+ matched << name.to_s if file_matches_glob?(abs, glob_pattern, root)
92
+ end
93
+ if matched.empty?
94
+ any_ungrouped_file = true
95
+ ungrouped[:relevant] += counts[:relevant]
96
+ ungrouped[:covered] += counts[:covered]
97
+ else
98
+ matched.each { |n| add_counts!(accum[n], counts) }
99
+ end
100
+ end
101
+ [accum, ungrouped, any_ungrouped_file]
102
+ end
103
+
104
+ def group_summaries_build_payload(groups, accum, ungrouped, any_ungrouped_file)
105
+ out = {}
106
+ groups.each_key do |name|
107
+ n = name.to_s
108
+ a = accum[n]
109
+ out[n] = {
110
+ "lines" => {
111
+ "covered_percent" => percent_from_counts(a[:relevant], a[:covered])
112
+ }
113
+ }
114
+ end
115
+
116
+ if any_ungrouped_file
117
+ out["Ungrouped"] = {
118
+ "lines" => {
119
+ "covered_percent" => percent_from_counts(ungrouped[:relevant], ungrouped[:covered])
120
+ }
121
+ }
122
+ end
123
+
124
+ out
125
+ end
126
+
127
+ def add_counts!(acc, delta)
128
+ acc[:relevant] += delta[:relevant]
129
+ acc[:covered] += delta[:covered]
130
+ end
131
+
132
+ def percent_from_counts(relevant, covered)
133
+ return round_percent(0.0) if relevant <= 0
134
+
135
+ round_percent(100.0 * covered / relevant)
136
+ end
137
+
138
+ def file_matches_glob?(absolute_path, pattern, root)
139
+ rel = Pathname.new(absolute_path).relative_path_from(Pathname.new(root)).to_s
140
+ File.fnmatch?(pattern, rel, File::FNM_PATHNAME | File::FNM_EXTGLOB)
141
+ rescue ArgumentError
142
+ File.fnmatch?(pattern, absolute_path, File::FNM_PATHNAME | File::FNM_EXTGLOB)
143
+ end
144
+
145
+ def round_percent(x)
146
+ x.to_f.round(2)
147
+ end
148
+ end
149
+ end
150
+ end
@@ -0,0 +1,122 @@
1
+ module Polyrun
2
+ module Data
3
+ # Process-local memoization for expensive fixture setup (+register+ / +cached+).
4
+ # Use inside +before(:suite)+ or a support file so each parallel **process** builds once; not for threads
5
+ # without external locking (see {ParallelProvisioning}).
6
+ #
7
+ # Example:
8
+ #
9
+ # Polyrun::Data::CachedFixtures.register(:admin) { User.create!(email: "a@example.com") }
10
+ # Polyrun::Data::CachedFixtures.fetch(:admin) # => same object
11
+ #
12
+ module CachedFixtures
13
+ # :nodoc:
14
+ class Cache
15
+ attr_reader :store
16
+
17
+ def initialize
18
+ @store = {}
19
+ @stats = {}
20
+ end
21
+
22
+ def fetch(key, &block)
23
+ k = key.to_s
24
+ if store.key?(k)
25
+ @stats[k][:hits] += 1
26
+ return store[k]
27
+ end
28
+
29
+ t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
30
+ store[k] = yield
31
+ @stats[k] = {
32
+ build_time: Process.clock_gettime(Process::CLOCK_MONOTONIC) - t0,
33
+ hits: 0
34
+ }
35
+ store[k]
36
+ end
37
+
38
+ def clear
39
+ store.clear
40
+ @stats.clear
41
+ end
42
+
43
+ def stats_snapshot
44
+ @stats.transform_values(&:dup)
45
+ end
46
+ end
47
+
48
+ # Mutable process-local state lives on a plain object so the singleton class avoids class ivars
49
+ # (ThreadSafety/ClassInstanceVariable); still one cache per process, not thread-safe for concurrent threads.
50
+ class Registry
51
+ attr_accessor :disabled
52
+ attr_reader :cache, :callbacks
53
+
54
+ def initialize
55
+ @disabled = false
56
+ @cache = Cache.new
57
+ @callbacks = {before_reset: [], after_reset: []}
58
+ end
59
+ end
60
+ private_constant :Registry
61
+
62
+ REGISTRY = Registry.new
63
+ private_constant :REGISTRY
64
+
65
+ class << self
66
+ def fetch(id, &block)
67
+ return yield if disabled?
68
+
69
+ REGISTRY.cache.fetch(id.to_s, &block)
70
+ end
71
+
72
+ alias_method :register, :fetch
73
+
74
+ def cached(id)
75
+ return unless REGISTRY.cache.store.key?(id.to_s)
76
+
77
+ REGISTRY.cache.store[id.to_s]
78
+ end
79
+
80
+ def reset!
81
+ REGISTRY.callbacks[:before_reset].each(&:call)
82
+ REGISTRY.cache.clear
83
+ REGISTRY.callbacks[:after_reset].each(&:call)
84
+ REGISTRY.callbacks[:before_reset].clear
85
+ REGISTRY.callbacks[:after_reset].clear
86
+ end
87
+
88
+ def before_reset(&block)
89
+ REGISTRY.callbacks[:before_reset] << block if block
90
+ end
91
+
92
+ def after_reset(&block)
93
+ REGISTRY.callbacks[:after_reset] << block if block
94
+ end
95
+
96
+ def disable!
97
+ REGISTRY.disabled = true
98
+ end
99
+
100
+ def enable!
101
+ REGISTRY.disabled = false
102
+ end
103
+
104
+ def disabled?
105
+ REGISTRY.disabled == true
106
+ end
107
+
108
+ def stats
109
+ REGISTRY.cache.stats_snapshot
110
+ end
111
+
112
+ def format_stats_report(title: "Polyrun cached fixtures")
113
+ lines = [title]
114
+ REGISTRY.cache.stats_snapshot.each do |key, s|
115
+ lines << format(" %-40s build: %0.4fs hits: %d", key, s[:build_time], s[:hits])
116
+ end
117
+ lines.join("\n") + "\n"
118
+ end
119
+ end
120
+ end
121
+ end
122
+ end
@@ -0,0 +1,48 @@
1
+ module Polyrun
2
+ module Data
3
+ # Lightweight per-example factory/build counters with zero dependencies.
4
+ # Call +reset!+ in +before(:suite)+ or +setup+, +record+ inside factory helpers, +summary+ in +after(:suite)+.
5
+ module FactoryCounts
6
+ class << self
7
+ def reset!
8
+ @counts = Hash.new(0)
9
+ @example_counts = Hash.new(0)
10
+ end
11
+
12
+ def reset_example!
13
+ @example_counts = Hash.new(0)
14
+ end
15
+
16
+ def record(factory_name)
17
+ @counts ||= Hash.new(0)
18
+ @example_counts ||= Hash.new(0)
19
+ name = factory_name.to_s
20
+ @counts[name] += 1
21
+ @example_counts[name] += 1
22
+ end
23
+
24
+ def counts
25
+ @counts ||= Hash.new(0)
26
+ @counts.dup
27
+ end
28
+
29
+ def example_counts
30
+ @example_counts ||= Hash.new(0)
31
+ @example_counts.dup
32
+ end
33
+
34
+ def summary_lines(top: 20)
35
+ @counts ||= Hash.new(0)
36
+ sorted = @counts.sort_by { |_, n| -n }
37
+ sorted[0, top].map { |name, n| " #{name}: #{n}" }
38
+ end
39
+
40
+ def format_summary(title: "Polyrun factory counts")
41
+ lines = [title]
42
+ lines.concat(summary_lines)
43
+ lines.join("\n") + "\n"
44
+ end
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,50 @@
1
+ module Polyrun
2
+ module Data
3
+ # Opt-in FactoryBot hook so {#FactoryCounts} sees every factory run (minimal patch).
4
+ # Requires the +factory_bot+ gem and must run after FactoryBot is loaded.
5
+ #
6
+ # require "factory_bot"
7
+ # Polyrun::Data::FactoryInstrumentation.instrument_factory_bot!
8
+ module FactoryInstrumentation
9
+ class << self
10
+ def instrument_factory_bot!
11
+ return false unless defined?(FactoryBot)
12
+
13
+ factory_class = resolve_factory_runner_class
14
+ return false unless factory_class
15
+
16
+ return true if factory_class.instance_variable_defined?(:@polyrun_factory_instrumented) &&
17
+ factory_class.instance_variable_get(:@polyrun_factory_instrumented)
18
+
19
+ patch = Module.new do
20
+ def run(...)
21
+ Polyrun::Data::FactoryCounts.record(name)
22
+ super
23
+ end
24
+ end
25
+ factory_class.prepend(patch)
26
+ factory_class.instance_variable_set(:@polyrun_factory_instrumented, true)
27
+ true
28
+ end
29
+
30
+ def instrumented?
31
+ return false unless defined?(FactoryBot)
32
+
33
+ fc = resolve_factory_runner_class
34
+ return false unless fc
35
+
36
+ fc.instance_variable_defined?(:@polyrun_factory_instrumented) &&
37
+ fc.instance_variable_get(:@polyrun_factory_instrumented)
38
+ end
39
+
40
+ private
41
+
42
+ def resolve_factory_runner_class
43
+ return FactoryBot::Factory if defined?(FactoryBot::Factory)
44
+
45
+ nil
46
+ end
47
+ end
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,68 @@
1
+ require "yaml"
2
+
3
+ module Polyrun
4
+ module Data
5
+ # Declarative YAML fixture batches (**YAML → table → rows**).
6
+ # Polyrun does **not** ship a seed/register loader DSL—only **stdlib YAML** + iteration helpers.
7
+ # Typical layout: +spec/fixtures/polyrun/*.yml+ with top-level keys = table names.
8
+ #
9
+ # users:
10
+ # - name: Ada
11
+ # email: ada@example.com
12
+ module Fixtures
13
+ module_function
14
+
15
+ def load_yaml(path)
16
+ YAML.safe_load_file(path, permitted_classes: [Symbol], aliases: true) || {}
17
+ end
18
+
19
+ # Returns { "batch_name" => { "table" => [rows] } } for every +.yml+ under +dir+ (recursive).
20
+ def load_directory(dir)
21
+ Dir.glob(File.join(dir, "**", "*.yml")).sort.each_with_object({}) do |path, acc|
22
+ key = File.basename(path, ".*")
23
+ acc[key] = load_yaml(path)
24
+ end
25
+ end
26
+
27
+ # Iterates each table in a single batch hash. Skips keys starting with "_".
28
+ def each_table(batch)
29
+ return enum_for(:each_table, batch) unless block_given?
30
+
31
+ batch.each do |table, rows|
32
+ t = table.to_s
33
+ next if t.start_with?("_")
34
+
35
+ raise Polyrun::Error, "fixtures: #{t} must be an Array of rows" unless rows.is_a?(Array)
36
+
37
+ yield(t, rows)
38
+ end
39
+ end
40
+
41
+ # Loads all batches from +dir+ and yields (batch_name, table, rows).
42
+ def each_table_in_directory(dir)
43
+ return enum_for(:each_table_in_directory, dir) unless block_given?
44
+
45
+ load_directory(dir).each do |batch_name, batch|
46
+ each_table(batch) do |table, rows|
47
+ yield(batch_name, table, rows)
48
+ end
49
+ end
50
+ end
51
+
52
+ # Bulk insert YAML rows via ActiveRecord (batch load optimization). Requires ActiveRecord
53
+ # and a +connection+ that responds to +insert_all(table_name, records)+ (Rails 6+).
54
+ def apply_insert_all!(batch, connection: nil)
55
+ unless defined?(ActiveRecord::Base)
56
+ raise Polyrun::Error, "Fixtures.apply_insert_all! requires ActiveRecord"
57
+ end
58
+
59
+ conn = connection || ActiveRecord::Base.connection
60
+ each_table(batch) do |table, rows|
61
+ next if rows.empty?
62
+
63
+ conn.insert_all(table, rows)
64
+ end
65
+ end
66
+ end
67
+ end
68
+ end
@@ -0,0 +1,93 @@
1
+ module Polyrun
2
+ module Data
3
+ # Branching helpers for **serial** vs **parallel worker** test DB setup (seeds, truncate).
4
+ # Polyrun does not call Rails +truncate+ or +load_seed+ for you — wire those in the callbacks you assign.
5
+ #
6
+ # Typical split (empty parallel DBs get seeds only; serial run truncates then seeds):
7
+ #
8
+ # Polyrun::Data::ParallelProvisioning.configure do |c|
9
+ # c.serial { replant_and_load_seed }
10
+ # c.parallel_worker { load_seed_only }
11
+ # end
12
+ # # In spec_helper after configure:
13
+ # Polyrun::Data::ParallelProvisioning.run_suite_hooks!
14
+ #
15
+ # Or use {Polyrun::RSpecSupport.install_parallel_provisioning!} (+before(:suite)+) or {Polyrun::MinitestSupport.install_parallel_provisioning!}
16
+ # (+require+ +polyrun/minitest_support+ from +test/test_helper.rb+).
17
+ module ParallelProvisioning
18
+ class Configuration
19
+ attr_accessor :serial_hook, :parallel_worker_hook
20
+
21
+ def serial(&block)
22
+ self.serial_hook = block if block
23
+ end
24
+
25
+ def parallel_worker(&block)
26
+ self.parallel_worker_hook = block if block
27
+ end
28
+ end
29
+
30
+ class Storage
31
+ attr_accessor :configuration
32
+
33
+ def initialize
34
+ @configuration = Configuration.new
35
+ end
36
+ end
37
+ private_constant :Storage
38
+
39
+ STORAGE = Storage.new
40
+ private_constant :STORAGE
41
+
42
+ class << self
43
+ def configure
44
+ yield configuration
45
+ end
46
+
47
+ def configuration
48
+ STORAGE.configuration
49
+ end
50
+
51
+ def reset_configuration!
52
+ STORAGE.configuration = Configuration.new
53
+ end
54
+
55
+ # True when multiple shards are in use ({Database::Shard} sets +POLYRUN_SHARD_TOTAL+).
56
+ def parallel_workers?
57
+ shard_total > 1
58
+ end
59
+
60
+ # 0-based worker index; prefers +POLYRUN_SHARD_INDEX+, else derives from +TEST_ENV_NUMBER+ (parallel_tests).
61
+ def shard_index
62
+ if (s = ENV["POLYRUN_SHARD_INDEX"]) && !s.to_s.empty?
63
+ Integer(s)
64
+ elsif (n = ENV["TEST_ENV_NUMBER"]).to_s.empty? || n == "0"
65
+ 0
66
+ else
67
+ Integer(n) - 1
68
+ end
69
+ rescue ArgumentError
70
+ 0
71
+ end
72
+
73
+ def shard_total
74
+ t = ENV["POLYRUN_SHARD_TOTAL"]
75
+ return Integer(t) if t && !t.to_s.empty?
76
+
77
+ 1
78
+ rescue ArgumentError
79
+ 1
80
+ end
81
+
82
+ # Runs +parallel_worker_hook+ when {#parallel_workers?}, else +serial_hook+. No-op if the chosen hook is nil.
83
+ def run_suite_hooks!
84
+ if parallel_workers?
85
+ configuration.parallel_worker_hook&.call
86
+ else
87
+ configuration.serial_hook&.call
88
+ end
89
+ end
90
+ end
91
+ end
92
+ end
93
+ end
@@ -0,0 +1,84 @@
1
+ require "fileutils"
2
+ require "open3"
3
+
4
+ module Polyrun
5
+ module Data
6
+ # PostgreSQL data snapshots via +pg_dump+ / +psql+ (no +pg+ gem). Configure with ENV or explicit args.
7
+ # Non-Postgres adapters: use native backup/export tools; not covered here.
8
+ module SqlSnapshot
9
+ module_function
10
+
11
+ def default_connection
12
+ {
13
+ host: ENV["PGHOST"],
14
+ port: ENV["PGPORT"],
15
+ username: ENV["PGUSER"] || ENV["USER"],
16
+ database: ENV["PGDATABASE"]
17
+ }
18
+ end
19
+
20
+ # Writes data-only SQL to +root+/spec/fixtures/sql_snapshots/<name>.sql
21
+ def create!(name, root:, database: nil, username: nil, host: nil, port: nil)
22
+ database ||= default_connection[:database] or raise Polyrun::Error, "SqlSnapshot: set database: or PGDATABASE"
23
+ username ||= default_connection[:username]
24
+ path = File.join(root, "spec", "fixtures", "sql_snapshots", "#{name}.sql")
25
+ FileUtils.mkdir_p(File.dirname(path))
26
+
27
+ cmd = ["pg_dump", "--data-only", "-U", username]
28
+ cmd += ["-h", host] if host && !host.to_s.empty?
29
+ cmd += ["-p", port.to_s] if port && !port.to_s.empty?
30
+ cmd << database
31
+
32
+ out, err, st = Open3.capture3(*cmd)
33
+ raise Polyrun::Error, "pg_dump failed: #{err}" unless st.success?
34
+
35
+ File.write(path, out)
36
+ path
37
+ end
38
+
39
+ # Truncates listed tables (if any), then loads snapshot SQL. +tables+ optional; if nil and ActiveRecord
40
+ # is loaded, uses +connection.tables+.
41
+ def load!(name, root:, database: nil, username: nil, host: nil, port: nil, tables: nil)
42
+ database ||= default_connection[:database] or raise Polyrun::Error, "SqlSnapshot: set database: or PGDATABASE"
43
+ username ||= default_connection[:username]
44
+ path = File.join(root, "spec", "fixtures", "sql_snapshots", "#{name}.sql")
45
+ raise Polyrun::Error, "SqlSnapshot: missing #{path}" unless File.file?(path)
46
+
47
+ if tables.nil? && defined?(ActiveRecord::Base) && ActiveRecord::Base.connected?
48
+ tables = ActiveRecord::Base.connection.tables
49
+ end
50
+ tables ||= []
51
+
52
+ psql = sql_snapshot_psql_base(username, database, host, port)
53
+ sql_snapshot_truncate_tables!(psql, tables) if tables.any?
54
+ sql_snapshot_load_file!(psql, path)
55
+ true
56
+ end
57
+
58
+ def sql_snapshot_psql_base(username, database, host, port)
59
+ psql = ["psql", "-U", username, "-d", database]
60
+ psql += ["-h", host] if host && !host.to_s.empty?
61
+ psql += ["-p", port.to_s] if port && !port.to_s.empty?
62
+ psql
63
+ end
64
+
65
+ def sql_snapshot_truncate_tables!(psql, tables)
66
+ quoted = tables.map { |t| %("#{t.gsub('"', '""')}") }.join(", ")
67
+ trunc = "TRUNCATE TABLE #{quoted} CASCADE;"
68
+ _trunc_out, err, st = Open3.capture3(*psql, "-v", "ON_ERROR_STOP=1", "-c", trunc)
69
+ raise Polyrun::Error, "psql truncate failed: #{err}" unless st.success?
70
+ end
71
+
72
+ def sql_snapshot_load_file!(psql, path)
73
+ _load_out, err, st = Open3.capture3(
74
+ *psql,
75
+ "-v", "ON_ERROR_STOP=1",
76
+ "-c", "SET session_replication_role = 'replica';",
77
+ "-f", path,
78
+ "-c", "SET session_replication_role = 'origin';"
79
+ )
80
+ raise Polyrun::Error, "psql load failed: #{err}" unless st.success?
81
+ end
82
+ end
83
+ end
84
+ end