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,188 @@
1
+ require "shellwords"
2
+ require "uri"
3
+ require_relative "url_builder/connection"
4
+
5
+ module Polyrun
6
+ module Database
7
+ # Builds database URLs from +polyrun.yml+ +databases+ (spec2 §5.2) — no Liquid; use ENV fallbacks.
8
+ # Use +adapter:+ or nested blocks: +postgresql+, +mysql+ / +mysql2+ / +trilogy+, +sqlserver+ / +mssql+,
9
+ # +sqlite3+ / +sqlite+, +mongodb+ / +mongo+.
10
+ module UrlBuilder
11
+ module_function
12
+
13
+ def postgres_url_for_template(databases_hash)
14
+ url_for_template(databases_hash)
15
+ end
16
+
17
+ def postgres_url_for_database_name(databases_hash, database_name)
18
+ url_for_database_name(databases_hash, database_name)
19
+ end
20
+
21
+ def postgres_url_for_shard(databases_hash, shard_index:, connection: nil)
22
+ url_for_shard(databases_hash, shard_index: shard_index, connection: connection)
23
+ end
24
+
25
+ def url_for_template(databases_hash)
26
+ dh = databases_hash.is_a?(Hash) ? databases_hash : {}
27
+ dbname = dh["template_db"] || dh[:template_db]
28
+ raise Polyrun::Error, "databases.template_db is required" if dbname.nil? || dbname.to_s.empty?
29
+
30
+ url_for_database_name(dh, dbname.to_s)
31
+ end
32
+
33
+ def url_for_database_name(databases_hash, database_name)
34
+ conn = Connection.resolve_connection(databases_hash)
35
+ Connection.build_database_url(database_name.to_s, conn)
36
+ end
37
+
38
+ # ENV overrides so +bin/rails db:prepare+ runs once for multi-DB apps: each connection keeps its own
39
+ # +migrations_paths+ (e.g. db/cache_migrate) instead of pointing DATABASE_URL at every template in turn.
40
+ def template_prepare_env(databases_hash)
41
+ dh = databases_hash.is_a?(Hash) ? databases_hash : {}
42
+ pt = (dh["template_db"] || dh[:template_db]).to_s
43
+ raise Polyrun::Error, "template_prepare_env: set databases.template_db" if pt.empty?
44
+
45
+ out = {}
46
+ out["DATABASE_URL"] = url_for_database_name(dh, pt)
47
+ template_prepare_env_fill_connections!(dh, pt, out)
48
+ end
49
+
50
+ def template_prepare_env_shell_log(databases_hash)
51
+ template_prepare_env(databases_hash).sort.map do |k, v|
52
+ "#{k}=#{Shellwords.escape(redact_url_userinfo_password(v.to_s))}"
53
+ end.join(" ")
54
+ end
55
+
56
+ def unique_template_migrate_urls(databases_hash)
57
+ dh = databases_hash.is_a?(Hash) ? databases_hash : {}
58
+ seen = {}
59
+ out = []
60
+ pt = (dh["template_db"] || dh[:template_db]).to_s
61
+ unless pt.empty?
62
+ out << url_for_database_name(dh, pt)
63
+ seen[pt] = true
64
+ end
65
+ Array(dh["connections"] || dh[:connections]).each do |c|
66
+ t = (c["template_db"] || c[:template_db]).to_s
67
+ t = pt if t.empty?
68
+ next if t.empty?
69
+ next if seen[t]
70
+
71
+ out << url_for_database_name(dh, t)
72
+ seen[t] = true
73
+ end
74
+ out
75
+ end
76
+
77
+ def shard_database_name(databases_hash, shard_index:, connection: nil)
78
+ extract_db_name(url_for_shard(databases_hash, shard_index: shard_index, connection: connection))
79
+ end
80
+
81
+ def template_database_name_for(databases_hash, connection: nil)
82
+ dh = databases_hash.is_a?(Hash) ? databases_hash : {}
83
+ if connection.nil?
84
+ return (dh["template_db"] || dh[:template_db]).to_s
85
+ end
86
+
87
+ c = Array(dh["connections"] || dh[:connections]).find { |x| (x["name"] || x[:name]).to_s == connection.to_s }
88
+ return "" unless c
89
+
90
+ (c["template_db"] || c[:template_db] || dh["template_db"] || dh[:template_db]).to_s
91
+ end
92
+
93
+ def shard_database_plan(databases_hash, shard_index:)
94
+ dh = databases_hash.is_a?(Hash) ? databases_hash : {}
95
+ rows = []
96
+ primary_shard = shard_database_name(dh, shard_index: shard_index, connection: nil)
97
+ primary_tmpl = template_database_name_for(dh, connection: nil)
98
+ if !primary_shard.empty? && !primary_tmpl.empty?
99
+ rows << {new_db: primary_shard, template_db: primary_tmpl}
100
+ end
101
+
102
+ Array(dh["connections"] || dh[:connections]).each do |c|
103
+ nm = (c["name"] || c[:name]).to_s
104
+ next if nm.empty?
105
+
106
+ sname = shard_database_name(dh, shard_index: shard_index, connection: nm)
107
+ tname = template_database_name_for(dh, connection: nm)
108
+ rows << {new_db: sname, template_db: tname} if !sname.empty? && !tname.empty?
109
+ end
110
+ rows
111
+ end
112
+
113
+ def url_for_shard(databases_hash, shard_index:, connection: nil)
114
+ dh = databases_hash.is_a?(Hash) ? databases_hash : {}
115
+ conn = Connection.resolve_connection(dh)
116
+ pattern = shard_pattern(dh, connection)
117
+ validate_shard_db_pattern!(pattern)
118
+
119
+ dbname = pattern.to_s.gsub("%{shard}", Integer(shard_index).to_s).gsub("%<shard>d", format("%d", Integer(shard_index)))
120
+ template_name = template_database_name_for(dh, connection: connection)
121
+ if !template_name.to_s.empty? && dbname == template_name.to_s
122
+ raise Polyrun::Error,
123
+ "databases.shard_db_pattern resolves to template_db #{template_name.inspect} for shard #{shard_index}"
124
+ end
125
+ Connection.build_database_url(dbname, conn)
126
+ end
127
+
128
+ def shard_pattern(dh, connection)
129
+ pattern =
130
+ if connection
131
+ conns = dh["connections"] || dh[:connections] || []
132
+ c = Array(conns).find { |x| (x["name"] || x[:name]).to_s == connection.to_s }
133
+ (c && (c["shard_db_pattern"] || c[:shard_db_pattern])) || dh["shard_db_pattern"]
134
+ else
135
+ dh["shard_db_pattern"] || dh[:shard_db_pattern]
136
+ end
137
+ pattern ||= "app_test_%{shard}"
138
+ pattern
139
+ end
140
+ private_class_method :shard_pattern
141
+
142
+ def validate_shard_db_pattern!(pattern)
143
+ p = pattern.to_s
144
+ return if p.include?("%{shard}") || p.include?("%<shard>d")
145
+
146
+ raise Polyrun::Error, "databases.shard_db_pattern must include %{shard} or %<shard>d (got #{p.inspect})"
147
+ end
148
+ private_class_method :validate_shard_db_pattern!
149
+
150
+ def redact_url_userinfo_password(url)
151
+ s = url.to_s
152
+ s.sub(%r{\A([a-z][a-z0-9+.-]*://[^:/?#]+:)[^@/?#]+(@)}i, '\1***\2')
153
+ end
154
+ private_class_method :redact_url_userinfo_password
155
+
156
+ def env_exports_for_databases(databases_hash, shard_index:)
157
+ dh = databases_hash.is_a?(Hash) ? databases_hash : {}
158
+ out = {}
159
+ primary_url = url_for_shard(dh, shard_index: shard_index)
160
+ out["DATABASE_URL"] = primary_url
161
+ out["TEST_DB_NAME"] = extract_db_name(primary_url)
162
+
163
+ conns = dh["connections"] || dh[:connections] || []
164
+ Array(conns).each do |c|
165
+ name = (c["name"] || c[:name]).to_s
166
+ next if name.empty?
167
+
168
+ u = url_for_shard(dh, shard_index: shard_index, connection: name)
169
+ key = (c["env_key"] || c[:env_key]).to_s.strip
170
+ key = "DATABASE_URL_#{name.upcase.tr("-", "_")}" if key.empty?
171
+ out[key] = u
172
+ end
173
+ out
174
+ end
175
+
176
+ def extract_db_name(url)
177
+ s = url.to_s
178
+ return s.sub(/\Asqlite3:/i, "") if s.match?(/\Asqlite3:/i)
179
+
180
+ URI.parse(s).path.delete_prefix("/").split("?", 2).first
181
+ rescue URI::InvalidURIError
182
+ nil
183
+ end
184
+ end
185
+ end
186
+ end
187
+
188
+ require_relative "url_builder/template_prepare"
@@ -0,0 +1,81 @@
1
+ module Polyrun
2
+ # Opt-in tracing: set +DEBUG=1+ or +POLYRUN_DEBUG=1+ (or +true+).
3
+ # Logs to stderr with wall-clock timestamps; use +.time+ for monotonic durations.
4
+ module Debug
5
+ module_function
6
+
7
+ def enabled?
8
+ truthy?(ENV["DEBUG"]) || truthy?(ENV["POLYRUN_DEBUG"])
9
+ end
10
+
11
+ def log(message)
12
+ return unless enabled?
13
+
14
+ Polyrun::Log.warn "[polyrun debug #{wall_clock}] #{message}"
15
+ end
16
+
17
+ def log_kv(pairs)
18
+ return unless enabled?
19
+
20
+ log(pairs.map { |k, v| "#{k}=#{v.inspect}" }.join(" "))
21
+ end
22
+
23
+ # Same as +log+, but tags lines from parallel RSpec workers so they are not confused with the parent +polyrun+ process (stderr interleaves arbitrarily).
24
+ def log_worker(message)
25
+ return unless enabled?
26
+
27
+ if parallel_worker_process?
28
+ Polyrun::Log.warn "[polyrun debug #{wall_clock}] [worker pid=#{$$} shard=#{ENV.fetch("POLYRUN_SHARD_INDEX", "?")}] #{message}"
29
+ else
30
+ Polyrun::Log.warn "[polyrun debug #{wall_clock}] #{message}"
31
+ end
32
+ end
33
+
34
+ def log_worker_kv(pairs)
35
+ return unless enabled?
36
+
37
+ if parallel_worker_process?
38
+ log_kv({role: "worker", pid: $$, shard: ENV["POLYRUN_SHARD_INDEX"]}.merge(pairs))
39
+ else
40
+ log_kv(pairs)
41
+ end
42
+ end
43
+
44
+ def parallel_worker_process?
45
+ ENV["POLYRUN_SHARD_TOTAL"].to_i > 1
46
+ end
47
+
48
+ # Yields and logs monotonic duration; re-raises after logging failures.
49
+ def time(label)
50
+ t0 = nil
51
+ return yield unless enabled?
52
+
53
+ t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
54
+ log("#{label} … start")
55
+ result = yield
56
+ elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - t0
57
+ elapsed_s = format("%0.3f", elapsed)
58
+ log("#{label} … done in #{elapsed_s}s")
59
+ result
60
+ rescue => e
61
+ if t0
62
+ elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - t0
63
+ elapsed_s = format("%0.3f", elapsed)
64
+ log("#{label} … failed after #{elapsed_s}s: #{e.class}: #{e.message}")
65
+ end
66
+ raise
67
+ end
68
+
69
+ def wall_clock
70
+ Time.now.getlocal.strftime("%H:%M:%S.%6N")
71
+ end
72
+
73
+ def truthy?(value)
74
+ return false if value.nil?
75
+
76
+ v = value.to_s.strip.downcase
77
+ %w[1 true yes on].include?(v)
78
+ end
79
+ private_class_method :truthy?
80
+ end
81
+ end
@@ -0,0 +1,65 @@
1
+ module Polyrun
2
+ module Env
3
+ # CI-native shard index/total (spec2 §6.4) without extra gems.
4
+ module Ci
5
+ module_function
6
+
7
+ # Returns Integer shard index or nil if not inferable from CI env.
8
+ def detect_shard_index
9
+ return Integer(ENV["POLYRUN_SHARD_INDEX"]) if present?(ENV["POLYRUN_SHARD_INDEX"])
10
+
11
+ ci = truthy?(ENV["CI"])
12
+ if present?(ENV["CI_NODE_INDEX"]) && ci
13
+ return Integer(ENV["CI_NODE_INDEX"])
14
+ end
15
+ if present?(ENV["BUILDKITE_PARALLEL_JOB"]) && ci
16
+ return Integer(ENV["BUILDKITE_PARALLEL_JOB"])
17
+ end
18
+ if present?(ENV["CIRCLE_NODE_INDEX"]) && ci
19
+ return Integer(ENV["CIRCLE_NODE_INDEX"])
20
+ end
21
+
22
+ nil
23
+ rescue ArgumentError, TypeError
24
+ nil
25
+ end
26
+
27
+ # Returns Integer shard total or nil.
28
+ def detect_shard_total
29
+ return Integer(ENV["POLYRUN_SHARD_TOTAL"]) if present?(ENV["POLYRUN_SHARD_TOTAL"])
30
+
31
+ ci = truthy?(ENV["CI"])
32
+ if present?(ENV["CI_NODE_TOTAL"]) && ci
33
+ return Integer(ENV["CI_NODE_TOTAL"])
34
+ end
35
+ if present?(ENV["BUILDKITE_PARALLEL_JOB_COUNT"]) && ci
36
+ return Integer(ENV["BUILDKITE_PARALLEL_JOB_COUNT"])
37
+ end
38
+ if present?(ENV["CIRCLE_NODE_TOTAL"]) && ci
39
+ return Integer(ENV["CIRCLE_NODE_TOTAL"])
40
+ end
41
+
42
+ nil
43
+ rescue ArgumentError, TypeError
44
+ nil
45
+ end
46
+
47
+ def polyrun_env
48
+ e = ENV["POLYRUN_ENV"]&.strip
49
+ return e if present?(e)
50
+
51
+ return "ci" if truthy?(ENV["CI"])
52
+
53
+ "local"
54
+ end
55
+
56
+ def present?(s)
57
+ !s.nil? && !s.to_s.empty?
58
+ end
59
+
60
+ def truthy?(s)
61
+ %w[1 true yes].include?(s.to_s.downcase)
62
+ end
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,3 @@
1
+ module Polyrun
2
+ class Error < StandardError; end
3
+ end
@@ -0,0 +1,25 @@
1
+ module Polyrun
2
+ module Export
3
+ # RFC-style CSV field escaping for report exports.
4
+ module Csv
5
+ module_function
6
+
7
+ def escape_field(value)
8
+ string = value.nil? ? "" : value.to_s
9
+ if string.match?(/[",\r\n]/)
10
+ "\"#{string.gsub('"', '""')}\""
11
+ else
12
+ string
13
+ end
14
+ end
15
+
16
+ def generate(headers, rows)
17
+ lines = [headers.map { |header| escape_field(header) }.join(",")]
18
+ rows.each do |row|
19
+ lines << Array(row).map { |cell| escape_field(cell) }.join(",")
20
+ end
21
+ lines.join("\n") + "\n"
22
+ end
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,47 @@
1
+ module Polyrun
2
+ module Export
3
+ # GitHub-flavored markdown tables for report exports.
4
+ module Markdown
5
+ module_function
6
+
7
+ def escape_cell(value)
8
+ value.nil? ? "" : value.to_s.gsub("|", "\\|").tr("\n", " ")
9
+ end
10
+
11
+ def heading(level, text)
12
+ level = level.to_i.clamp(1, 6)
13
+ "#{"#" * level} #{text}\n"
14
+ end
15
+
16
+ def table(headers, rows)
17
+ return "" if headers.nil? || headers.empty?
18
+
19
+ header_line = "| #{headers.map { |header| escape_cell(header) }.join(" | ")} |"
20
+ separator_line = "| #{headers.map { "---" }.join(" | ")} |"
21
+ body_lines = rows.map do |row|
22
+ "| #{Array(row).map { |cell| escape_cell(cell) }.join(" | ")} |"
23
+ end
24
+ ([header_line, separator_line] + body_lines).join("\n") + "\n"
25
+ end
26
+
27
+ def document(title, sections)
28
+ lines = [heading(1, title), ""]
29
+ sections.each do |section|
30
+ heading_text = section[:heading] || section["heading"]
31
+ lines << heading(2, heading_text) if heading_text && !heading_text.to_s.empty?
32
+
33
+ body = section[:body] || section["body"]
34
+ lines << body if body && !body.to_s.empty?
35
+
36
+ table_headers = section[:headers] || section["headers"]
37
+ table_rows = section[:rows] || section["rows"]
38
+ if table_headers && !table_headers.empty?
39
+ lines << table(table_headers, table_rows || [])
40
+ end
41
+ lines << ""
42
+ end
43
+ lines.join("\n")
44
+ end
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,64 @@
1
+ require "fileutils"
2
+ require_relative "plan"
3
+ require_relative "../quality/command"
4
+ require "rbconfig"
5
+ require_relative "../quality/sandbox"
6
+
7
+ module Polyrun
8
+ module Graph
9
+ class Client
10
+ def initialize(root: Dir.pwd, timeout: nil, settings: {})
11
+ @settings = Config::Tools.runtime("graph", settings.merge(timeout ? {"timeout" => timeout} : {}))
12
+ @root = File.realpath(root)
13
+ library = File.expand_path("../..", __dir__)
14
+ @command = [RbConfig.ruby, "-I", library, "-rpolyrun/graph/worker", "-e", "exit Polyrun::Graph::Worker.run(ARGV)", "--"]
15
+ @timeout = @settings["timeout"]
16
+ end
17
+
18
+ def call(arguments, prove: [])
19
+ state = Workspace.new(@root, settings: @settings).path(@settings["state_dir"])
20
+
21
+ FileUtils.mkdir_p(state)
22
+ lock_path = File.join(state, "polyrun.lock")
23
+ raise Error.new("INVALID_PLAN", "symbolic link in lock path") if File.symlink?(lock_path)
24
+
25
+ File.open(lock_path, File::RDWR | File::CREAT, 0o600) do |lock|
26
+ raise Error.new("WORKSPACE_BUSY", "another graph command is running") unless lock.flock(File::LOCK_EX | File::LOCK_NB)
27
+
28
+ dispatch(arguments, prove)
29
+ end
30
+ end
31
+
32
+ private
33
+
34
+ def dispatch(arguments, prove)
35
+ verb, id = arguments.reject { |argument| argument == "--json" }
36
+ return check(Plan.new(@root, id, settings: @settings), arguments, prove) if verb == "check"
37
+
38
+ invoke(arguments)
39
+ end
40
+
41
+ def invoke(arguments)
42
+ Quality::Command.call(@command + arguments, root: @root, timeout: @timeout, max_output: @settings["max_output_bytes"], env: {"POLYRUN_GRAPH_ROOT" => @root, "POLYRUN_GRAPH_SETTINGS" => JSON.generate(@settings), "RUBYOPT" => nil})
43
+ end
44
+
45
+ def check(plan, arguments, prove)
46
+ checked = false
47
+ plan.invalidate!
48
+ result = invoke(arguments)
49
+ return result unless result["exitstatus"].zero?
50
+
51
+ plan.record_check!
52
+ prove_result = prove.empty? ? nil : Quality::Command.call(prove, root: plan.tree, timeout: @timeout, max_output: @settings["max_output_bytes"], env: Quality::Sandbox.environment(plan.tree))
53
+ if prove_result && !prove_result["exitstatus"].zero?
54
+ raise Error.new("PROVE_FAILED", "prove command failed: #{prove_result["stderr"]}", exitstatus: prove_result["exitstatus"])
55
+ end
56
+ plan.verify!
57
+ checked = true
58
+ result
59
+ ensure
60
+ plan.invalidate! unless checked
61
+ end
62
+ end
63
+ end
64
+ end
@@ -0,0 +1,13 @@
1
+ module Polyrun
2
+ module Graph
3
+ class Error < StandardError
4
+ attr_reader :code, :exitstatus
5
+
6
+ def initialize(code, message, exitstatus: 1)
7
+ @code = code
8
+ @exitstatus = exitstatus
9
+ super(message)
10
+ end
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,75 @@
1
+ require_relative "workspace"
2
+ require_relative "syntax"
3
+
4
+ module Polyrun
5
+ module Graph
6
+ class Index
7
+ def initialize(root, settings: {})
8
+ @workspace = Workspace.new(root, settings: settings)
9
+ end
10
+
11
+ def call
12
+ hashes = @workspace.hashes
13
+ snapshot = @workspace.snapshot(hashes)
14
+ existing = cached_index(snapshot)
15
+ return existing if existing
16
+
17
+ methods = []
18
+ calls = []
19
+ hashes.each_key do |relative|
20
+ syntax = Syntax.new(relative, File.binread(@workspace.path(relative)), max_nodes: @workspace.settings["max_nodes"]).parse
21
+ methods.concat(syntax.methods)
22
+ calls.concat(syntax.calls)
23
+ enforce_node_limit!(methods.size + calls.size)
24
+ end
25
+ raise Error.new("STALE_SNAPSHOT", "source changed while indexing") unless @workspace.hashes == hashes
26
+
27
+ edges = resolve(methods, calls)
28
+ @workspace.write_json("#{@workspace.state}/index.json", {"format" => 1, "snapshot" => snapshot,
29
+ "files" => hashes, "methods" => methods, "calls" => calls, "edges" => edges, "reused" => false})
30
+ end
31
+
32
+ def load
33
+ value = @workspace.read_json("#{@workspace.state}/index.json")
34
+ unless value.is_a?(Hash) && value["format"] == 1 && %w[methods calls edges].all? { |key| value[key].is_a?(Array) }
35
+ raise Error.new("INVALID_PLAN", "invalid graph index")
36
+ end
37
+ value
38
+ end
39
+
40
+ private
41
+
42
+ def cached_index(snapshot)
43
+ return unless File.file?(@workspace.path("#{@workspace.state}/index.json"))
44
+
45
+ existing = load
46
+ return unless existing["snapshot"] == snapshot
47
+
48
+ enforce_node_limit!(existing["methods"].size + existing["calls"].size)
49
+ existing.merge("reused" => true)
50
+ end
51
+
52
+ def enforce_node_limit!(count)
53
+ raise Error.new("RESOURCE_LIMIT", "too many graph nodes") if count > @workspace.settings["max_nodes"]
54
+ end
55
+
56
+ def resolve(methods, calls)
57
+ lookup = methods.group_by { |method| [method["owner"], method["scope"], method["name"]] }
58
+ calls.filter_map do |call|
59
+ owner, scope = if call["receiver"].nil? || call["receiver"] == "self"
60
+ [call["owner"], call["scope"]]
61
+ else
62
+ [call["receiver"].delete_prefix("::"), "singleton"]
63
+ end
64
+ candidates = owner && lookup[[owner, scope, call["name"]]]
65
+ target = candidates&.one? ? candidates.first : nil
66
+ call["target"] = target && target["id"]
67
+ call["target_provenance"] = target ? "static_guess" : "unknown"
68
+ next unless target && call["method_id"]
69
+
70
+ {"from_id" => call["method_id"], "to_id" => target["id"], "call_id" => call["id"], "provenance" => "static_guess"}
71
+ end
72
+ end
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,58 @@
1
+ require_relative "index"
2
+
3
+ module Polyrun
4
+ module Graph
5
+ class Inspect
6
+ def initialize(index)
7
+ @index = index
8
+ end
9
+
10
+ def call(selector, flags)
11
+ return control_plane if flags.include?("--control-plane")
12
+
13
+ methods = select_methods(selector)
14
+ raise Error.new("UNKNOWN_TARGET", "no matching method") if methods.empty?
15
+ raise Error.new("AMBIGUOUS_NODE", "choose a method owner or source path") unless methods.one?
16
+
17
+ nodes = methods.map do |method|
18
+ value = method.dup
19
+ value["calls"] = @index["calls"].select { |node| node["method_id"] == method["id"] } if flags.include?("--calls")
20
+ %w[callers callees].each do |direction|
21
+ next unless flags.include?("--#{direction}")
22
+
23
+ value[direction] = connections(method, direction)
24
+ end
25
+ value
26
+ end
27
+ {"ok" => true, "snapshot" => @index["snapshot"], "nodes" => nodes}
28
+ end
29
+
30
+ private
31
+
32
+ def connections(method, direction)
33
+ lookup = @index["methods"].to_h { |entry| [entry["id"], entry] }
34
+ from, to = (direction == "callers") ? %w[to_id from_id] : %w[from_id to_id]
35
+ @index["edges"].select { |edge| edge[from] == method["id"] }.map do |edge|
36
+ lookup.fetch(edge[to]).merge("provenance" => edge["provenance"])
37
+ end
38
+ end
39
+
40
+ def select_methods(selector)
41
+ if selector&.start_with?("path:")
42
+ path, name = selector.delete_prefix("path:").split("#", 2)
43
+ @index["methods"].select { |method| method["path"] == path && (!name || method["name"] == name) }
44
+ else
45
+ @index["methods"].select { |method| [method["id"], method["subject"], method["name"]].include?(selector) }
46
+ end
47
+ end
48
+
49
+ def control_plane
50
+ lifecycle = @index["methods"].select { |method| method["name"].match?(/\A(?:start|stop|shutdown|run|perform|call|process|poll|tick|schedule)[!?]?\z/) }
51
+ signals = @index["calls"].select { |node| node["name"].match?(/\A(?:notify|broadcast|signal|enqueue|publish|perform_async)[!?]?\z/) }
52
+ signal_ids = signals.to_h { |node| [node["id"], true] }
53
+ {"ok" => true, "snapshot" => @index["snapshot"], "control_plane" => {"lifecycle" => lifecycle,
54
+ "signals" => signals, "signal_edges" => @index["edges"].select { |edge| signal_ids[edge["call_id"]] }}}
55
+ end
56
+ end
57
+ end
58
+ end