polyrun 3.0.1 → 3.2.0

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 (59) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +21 -0
  3. data/README.md +16 -2
  4. data/docs/QUALITY.md +82 -0
  5. data/docs/QUALITY_CONFIGURATION.md +95 -0
  6. data/ext/polyrun_coverage_merge/coverage_merge.c +13 -26
  7. data/lib/polyrun/cli/ci_shard_run_command.rb +1 -1
  8. data/lib/polyrun/cli/graph_command.rb +68 -0
  9. data/lib/polyrun/cli/help.rb +5 -1
  10. data/lib/polyrun/cli/helpers.rb +3 -2
  11. data/lib/polyrun/cli/mutation_command.rb +67 -0
  12. data/lib/polyrun/cli/quality_commands.rb +65 -0
  13. data/lib/polyrun/cli/run_shards_parallel_wait.rb +48 -70
  14. data/lib/polyrun/cli/run_shards_plan_options.rb +1 -1
  15. data/lib/polyrun/cli/run_shards_worker_interrupt.rb +16 -0
  16. data/lib/polyrun/cli/tool_options.rb +48 -0
  17. data/lib/polyrun/cli.rb +17 -1
  18. data/lib/polyrun/config/effective.rb +9 -0
  19. data/lib/polyrun/config/resolver.rb +9 -0
  20. data/lib/polyrun/config/schema.rb +8 -3
  21. data/lib/polyrun/config/suite.rb +6 -1
  22. data/lib/polyrun/config/tool_defaults.rb +42 -0
  23. data/lib/polyrun/config/tool_validation.rb +79 -0
  24. data/lib/polyrun/config/tools.rb +120 -0
  25. data/lib/polyrun/config.rb +6 -4
  26. data/lib/polyrun/coverage/collector.rb +7 -1
  27. data/lib/polyrun/coverage/example_diff.rb +4 -8
  28. data/lib/polyrun/error.rb +3 -0
  29. data/lib/polyrun/graph/client.rb +64 -0
  30. data/lib/polyrun/graph/error.rb +13 -0
  31. data/lib/polyrun/graph/index.rb +75 -0
  32. data/lib/polyrun/graph/inspect.rb +58 -0
  33. data/lib/polyrun/graph/plan.rb +134 -0
  34. data/lib/polyrun/graph/planner.rb +117 -0
  35. data/lib/polyrun/graph/syntax.rb +114 -0
  36. data/lib/polyrun/graph/transaction.rb +81 -0
  37. data/lib/polyrun/graph/worker.rb +55 -0
  38. data/lib/polyrun/graph/workspace.rb +117 -0
  39. data/lib/polyrun/minitest_support.rb +1 -1
  40. data/lib/polyrun/mutation/candidates.rb +91 -0
  41. data/lib/polyrun/mutation/operators.rb +51 -0
  42. data/lib/polyrun/mutation/runner.rb +133 -0
  43. data/lib/polyrun/mutation/subjects.rb +88 -0
  44. data/lib/polyrun/process_stdio.rb +13 -8
  45. data/lib/polyrun/quality/command.rb +84 -0
  46. data/lib/polyrun/quality/measure.rb +38 -0
  47. data/lib/polyrun/quality/observe.rb +53 -0
  48. data/lib/polyrun/quality/observe_hook.rb +103 -0
  49. data/lib/polyrun/quality/sandbox.rb +70 -0
  50. data/lib/polyrun/rspec_support.rb +1 -1
  51. data/lib/polyrun/spec_quality/config.rb +8 -3
  52. data/lib/polyrun/spec_quality.rb +3 -4
  53. data/lib/polyrun/version.rb +1 -1
  54. data/lib/polyrun/worker_output.rb +25 -33
  55. data/lib/polyrun/worker_output_forwarders.rb +11 -7
  56. data/lib/polyrun.rb +1 -2
  57. data/polyrun.gemspec +6 -1
  58. data/sig/polyrun/config.rbs +2 -2
  59. metadata +44 -2
@@ -23,13 +23,15 @@ module Polyrun
23
23
  idle_sec = ctx[:worker_idle_timeout_sec]
24
24
  idle_sec = nil if idle_sec.is_a?(Numeric) && idle_sec <= 0
25
25
 
26
- Polyrun::Debug.time("Process.wait (#{pids.size} worker process(es))") do
27
- if timeout_sec || idle_sec
28
- run_shards_wait_all_children_multiplex(
29
- pids, hook_cfg, ctx, workers, timeout_sec, idle_sec, shard_results, after_hook_err
30
- )
31
- else
32
- run_shards_wait_all_children_sequential(pids, hook_cfg, workers, shard_results, after_hook_err)
26
+ run_shards_with_interrupt_handlers do
27
+ Polyrun::Debug.time("Process.wait (#{pids.size} worker process(es))") do
28
+ if timeout_sec || idle_sec
29
+ run_shards_wait_all_children_multiplex(
30
+ pids, hook_cfg, ctx, workers, timeout_sec, idle_sec, shard_results, after_hook_err
31
+ )
32
+ else
33
+ run_shards_wait_all_children_sequential(pids, hook_cfg, workers, shard_results, after_hook_err)
34
+ end
33
35
  end
34
36
  rescue Interrupt
35
37
  run_shards_shutdown_on_signal!(pids, 130)
@@ -67,41 +69,38 @@ module Polyrun
67
69
  return [shard_results, after_hook_err] if pending.empty?
68
70
 
69
71
  now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
70
- violation = run_shards_timeout_violation(pids, pending, ctx, now, timeout_sec, idle_sec)
72
+ violation = run_shards_timeout_violation(pending, ctx, now, timeout_sec, idle_sec)
71
73
  if violation
72
74
  reason, timed_h = violation
73
- others = pending.reject { |x| x[:pid] == timed_h[:pid] }
74
- case reason
75
+ code = case reason
75
76
  when :wall_timeout
76
- return run_shards_wait_flush_after_worker_timeout!(
77
- timed_h, others, hook_cfg, ctx, timeout_sec, workers, shard_results, after_hook_err
78
- )
77
+ run_shards_warn_worker_timeout!(timed_h, ctx, timeout_sec)
78
+ WORKER_TIMEOUT_EXIT_STATUS
79
79
  when :idle_timeout
80
- return run_shards_wait_flush_after_worker_idle!(
81
- timed_h, others, hook_cfg, ctx, idle_sec, workers, shard_results, after_hook_err
82
- )
80
+ run_shards_warn_worker_idle!(timed_h, ctx, idle_sec)
81
+ WORKER_IDLE_TIMEOUT_EXIT_STATUS
83
82
  end
83
+ return run_shards_wait_flush_after_timeout!(
84
+ timed_h, pending, hook_cfg, code, workers, shard_results, after_hook_err
85
+ )
84
86
  end
85
87
 
86
- sleep(0.2)
88
+ delay = timeout_sec ? run_shards_wall_deadline(pending.first, ctx, timeout_sec) - now : 0.2
89
+ sleep([0.2, delay].min)
87
90
  end
88
91
  end
89
92
 
90
93
  # @return [(Symbol, Hash), nil] e.g. +[:wall_timeout, h]+ when a limit is exceeded
91
- def run_shards_timeout_violation(pids_order, pending, ctx, now, timeout_sec, idle_sec)
92
- pids_order.each do |h|
93
- next unless pending.any? { |p| p[:pid] == h[:pid] }
94
-
95
- if timeout_sec && timeout_sec > 0
96
- spawned_at = h[:spawned_at] || ctx[:run_t0]
97
- return [:wall_timeout, h] if now >= spawned_at + timeout_sec
98
- end
94
+ def run_shards_timeout_violation(pending, ctx, now, timeout_sec, idle_sec)
95
+ # Polling removes completed workers in place, preserving spawn order.
96
+ first = pending.first
97
+ if timeout_sec && now >= run_shards_wall_deadline(first, ctx, timeout_sec)
98
+ return [:wall_timeout, first]
99
99
  end
100
+ return unless idle_sec
100
101
 
101
- pids_order.each do |h|
102
- next unless pending.any? { |p| p[:pid] == h[:pid] }
103
-
104
- next unless idle_sec && idle_sec > 0 && h[:ping_path]
102
+ pending.each do |h|
103
+ next unless h[:ping_path]
105
104
 
106
105
  t, = run_shards_read_worker_ping_payload(h[:ping_path])
107
106
  return [:idle_timeout, h] if t && (now - t) > idle_sec
@@ -110,16 +109,22 @@ module Polyrun
110
109
  nil
111
110
  end
112
111
 
112
+ def run_shards_wall_deadline(worker, ctx, timeout_sec)
113
+ (worker[:spawned_at] || ctx[:run_t0]) + timeout_sec
114
+ end
115
+
113
116
  def run_shards_finalize_reaped_worker!(h, hook_cfg, workers, st, shard_results, after_hook_err)
117
+ exitstatus = st.exitstatus || (128 + st.termsig)
118
+ Polyrun::Debug.log("[parent pid=#{$$}] run-shards: Process.wait child_pid=#{h[:pid]} shard=#{h[:shard]} exit=#{exitstatus} success=#{st.success?}")
119
+ run_shards_finalize_worker!(h, hook_cfg, workers, exitstatus, shard_results, after_hook_err)
120
+ end
121
+
122
+ def run_shards_finalize_worker!(h, hook_cfg, workers, exitstatus, shard_results, after_hook_err)
114
123
  Polyrun::WorkerOutput.finish_worker(h[:pid])
115
- exitstatus = st.exitstatus
116
- ok = st.success?
117
- Polyrun::Debug.log("[parent pid=#{$$}] run-shards: Process.wait child_pid=#{h[:pid]} shard=#{h[:shard]} exit=#{exitstatus} success=#{ok}")
118
- rc = run_shards_invoke_after_shard!(hook_cfg, h[:shard], workers, exitstatus)
119
- after_hook_err = rc if rc != 0 && after_hook_err == 0
120
- shard_results << {shard: h[:shard], exitstatus: exitstatus, success: ok}
121
124
  run_shards_unlink_ping_path(h[:ping_path])
122
- after_hook_err
125
+ rc = run_shards_invoke_after_shard!(hook_cfg, h[:shard], workers, exitstatus)
126
+ shard_results << {shard: h[:shard], exitstatus: exitstatus, success: exitstatus == 0}
127
+ after_hook_err.zero? ? rc : after_hook_err
123
128
  end
124
129
 
125
130
  def run_shards_unlink_ping_path(path)
@@ -155,42 +160,15 @@ module Polyrun
155
160
  [nil, nil]
156
161
  end
157
162
 
158
- def run_shards_wait_flush_after_worker_idle!(timed_h, others, hook_cfg, ctx, idle_sec, workers, shard_results, after_hook_err)
159
- run_shards_warn_worker_idle!(timed_h, ctx, idle_sec)
163
+ def run_shards_wait_flush_after_timeout!(timed_h, pending, hook_cfg, code, workers, shard_results, after_hook_err)
160
164
  run_shards_force_stop_pid_status(timed_h[:pid])
161
- run_shards_unlink_ping_path(timed_h[:ping_path])
162
- rc = run_shards_invoke_after_shard!(hook_cfg, timed_h[:shard], workers, WORKER_IDLE_TIMEOUT_EXIT_STATUS)
163
- after_hook_err = rc if rc != 0 && after_hook_err == 0
164
- shard_results << {shard: timed_h[:shard], exitstatus: WORKER_IDLE_TIMEOUT_EXIT_STATUS, success: false}
165
- others.each do |h2|
166
- st2 = run_shards_wait_or_force_stop_status(h2[:pid])
167
- exit2 = st2&.exitstatus
168
- ok2 = st2 ? st2.success? : false
169
- exit2 = WORKER_IDLE_TIMEOUT_EXIT_STATUS if exit2.nil?
170
- run_shards_unlink_ping_path(h2[:ping_path])
171
- rc2 = run_shards_invoke_after_shard!(hook_cfg, h2[:shard], workers, exit2)
172
- after_hook_err = rc2 if rc2 != 0 && after_hook_err == 0
173
- shard_results << {shard: h2[:shard], exitstatus: exit2, success: ok2}
165
+ pending.delete(timed_h)
166
+ statuses = pending.map do |worker|
167
+ run_shards_wait_or_force_stop_status(worker[:pid])&.exitstatus || code
174
168
  end
175
- [shard_results, after_hook_err]
176
- end
177
-
178
- def run_shards_wait_flush_after_worker_timeout!(timed_h, others, hook_cfg, ctx, timeout_sec, workers, shard_results, after_hook_err)
179
- run_shards_warn_worker_timeout!(timed_h, ctx, timeout_sec)
180
- run_shards_force_stop_pid_status(timed_h[:pid])
181
- run_shards_unlink_ping_path(timed_h[:ping_path])
182
- rc = run_shards_invoke_after_shard!(hook_cfg, timed_h[:shard], workers, WORKER_TIMEOUT_EXIT_STATUS)
183
- after_hook_err = rc if rc != 0 && after_hook_err == 0
184
- shard_results << {shard: timed_h[:shard], exitstatus: WORKER_TIMEOUT_EXIT_STATUS, success: false}
185
- others.each do |h2|
186
- st2 = run_shards_wait_or_force_stop_status(h2[:pid])
187
- exit2 = st2&.exitstatus
188
- ok2 = st2 ? st2.success? : false
189
- exit2 = WORKER_TIMEOUT_EXIT_STATUS if exit2.nil?
190
- run_shards_unlink_ping_path(h2[:ping_path])
191
- rc2 = run_shards_invoke_after_shard!(hook_cfg, h2[:shard], workers, exit2)
192
- after_hook_err = rc2 if rc2 != 0 && after_hook_err == 0
193
- shard_results << {shard: h2[:shard], exitstatus: exit2, success: ok2}
169
+ after_hook_err = run_shards_finalize_worker!(timed_h, hook_cfg, workers, code, shard_results, after_hook_err)
170
+ pending.zip(statuses).each do |worker, exitstatus|
171
+ after_hook_err = run_shards_finalize_worker!(worker, hook_cfg, workers, exitstatus, shard_results, after_hook_err)
194
172
  end
195
173
  [shard_results, after_hook_err]
196
174
  end
@@ -32,7 +32,7 @@ module Polyrun
32
32
  merge_spec_quality: false,
33
33
  merge_spec_quality_output: nil,
34
34
  report_spec_quality: true,
35
- worker_timeout_sec: nil,
35
+ worker_timeout_sec: env_worker_timeout_sec(cfg),
36
36
  worker_idle_timeout_sec: nil
37
37
  }
38
38
  end
@@ -6,6 +6,22 @@ module Polyrun
6
6
  module RunShardsWorkerInterrupt
7
7
  private
8
8
 
9
+ def run_shards_with_interrupt_handlers
10
+ previous = {}
11
+ handlers = {"INT" => ->(_) { raise Interrupt }, "TERM" => ->(_) { raise SignalException, "SIGTERM" }}
12
+ handlers.each do |signal, handler|
13
+ original = Signal.trap(signal, handler)
14
+ if original == "DEFAULT"
15
+ previous[signal] = original
16
+ else
17
+ Signal.trap(signal, original)
18
+ end
19
+ end
20
+ yield
21
+ ensure
22
+ previous.each { |signal, handler| Signal.trap(signal, handler) }
23
+ end
24
+
9
25
  def run_shards_log_interrupt_workers(pids, _ctx)
10
26
  parts = pids.map { |h| "shard=#{h[:shard]} pid=#{h[:pid]}" }
11
27
  Polyrun::Log.orchestration_warn "polyrun run-shards: SIGINT/SIGTERM while waiting on workers — stopping: #{parts.join(", ")}"
@@ -0,0 +1,48 @@
1
+ require_relative "../config"
2
+
3
+ module Polyrun
4
+ class CLI
5
+ module ToolOptions
6
+ private
7
+
8
+ def common_tool_options(parser, options)
9
+ parser.on("--[no-]enable") { |value| options[:enabled] = value }
10
+ parser.on("--root PATH") { |value| options[:root] = value }
11
+ parser.on("--timeout SECONDS", Float) { |value| options[:timeout] = value }
12
+ parser.on("--max-output-bytes N", Integer) { |value| options[:max_output_bytes] = value }
13
+ end
14
+
15
+ def configured_tool(feature, overrides)
16
+ overrides = overrides.dup
17
+ overrides[:root] = File.expand_path(overrides[:root]) if overrides.key?(:root)
18
+ root = File.expand_path(overrides[:root] || Dir.pwd)
19
+ cfg = Config.load(path: ENV["POLYRUN_CONFIG"], root: root)
20
+ settings = Config::Tools.resolve(cfg, feature, overrides: overrides, root: root)
21
+ if feature == "mutation"
22
+ graph = Config::Tools.resolve(cfg, "graph", root: root)
23
+ settings["staging"]["exclude_paths"] |= [graph["state_dir"]]
24
+ end
25
+ unless settings["enabled"]
26
+ raise Graph::Error.new("FEATURE_DISABLED", "#{feature} is disabled; enable it in polyrun.yml or use --enable", exitstatus: 2)
27
+ end
28
+ settings
29
+ end
30
+
31
+ def extract_tool_command!(argv)
32
+ separator = argv.index("--")
33
+ separator ? argv.slice!(separator..).drop(1) : nil
34
+ end
35
+
36
+ def tool_execution_options(settings, *keys)
37
+ settings.slice("root", "timeout", *keys).transform_keys(&:to_sym).merge(max_output: settings["max_output_bytes"])
38
+ end
39
+
40
+ def tool_command(settings, explicit)
41
+ command = explicit || settings.fetch("command")
42
+ raise ArgumentError, "a command is required after -- or in configuration" if command.empty?
43
+
44
+ command
45
+ end
46
+ end
47
+ end
48
+ end
data/lib/polyrun/cli.rb CHANGED
@@ -25,6 +25,10 @@ require_relative "cli/doctor_command"
25
25
  require_relative "cli/default_run"
26
26
  require_relative "cli/hooks_command"
27
27
  require_relative "cli/help"
28
+ require_relative "cli/tool_options"
29
+ require_relative "cli/graph_command"
30
+ require_relative "cli/mutation_command"
31
+ require_relative "cli/quality_commands"
28
32
 
29
33
  module Polyrun
30
34
  class CLI
@@ -36,7 +40,7 @@ module Polyrun
36
40
 
37
41
  # Keep in sync with +dispatch_cli_command_subcommands+ (+when+ branches). Used for implicit path routing.
38
42
  DISPATCH_SUBCOMMAND_NAMES = %w[
39
- plan prepare merge-coverage merge-failures merge-spec-quality report-coverage report-junit report-timing report-spec-quality report-benchmark bench
43
+ graph mutate measure observe plan prepare merge-coverage merge-failures merge-spec-quality report-coverage report-junit report-timing report-spec-quality report-benchmark bench
40
44
  env config merge-timing db:setup-template db:setup-shard db:clone-shards
41
45
  run-shards parallel-rspec parallel-minitest parallel-sus parallel-quick start build-paths init queue run-queue quick hook validate doctor
42
46
  ].freeze
@@ -70,6 +74,10 @@ module Polyrun
70
74
  include DefaultRun
71
75
  include HooksCommand
72
76
  include Help
77
+ include ToolOptions
78
+ include GraphCommand
79
+ include MutationCommand
80
+ include QualityCommands
73
81
 
74
82
  def self.run(argv = ARGV)
75
83
  new.run(argv)
@@ -176,6 +184,14 @@ module Polyrun
176
184
  # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity -- explicit dispatch table
177
185
  def dispatch_cli_command_subcommands(command, argv, config_path)
178
186
  case command
187
+ when "graph"
188
+ cmd_graph(argv)
189
+ when "mutate"
190
+ cmd_mutate(argv)
191
+ when "measure"
192
+ cmd_measure(argv)
193
+ when "observe"
194
+ cmd_observe(argv)
179
195
  when "plan"
180
196
  cmd_plan(argv, config_path)
181
197
  when "prepare"
@@ -1,5 +1,6 @@
1
1
  require_relative "dotted_path"
2
2
  require_relative "resolver"
3
+ require_relative "tools"
3
4
 
4
5
  module Polyrun
5
6
  class Config
@@ -50,9 +51,17 @@ module Polyrun
50
51
  base["partition"] = part
51
52
 
52
53
  base["workers"] = r.parallel_worker_count(cfg, env)
54
+ apply_tools!(base, cfg, env)
53
55
  base["suite"] = cfg.suite if cfg.respond_to?(:suite) && cfg.suite
54
56
 
55
57
  base
58
+ rescue ArgumentError => error
59
+ raise Polyrun::Error, error.message
60
+ end
61
+
62
+ def apply_tools!(base, cfg, env)
63
+ %w[graph mutation].each { |feature| base[feature] = Tools.resolve(cfg, feature, env: env) }
64
+ base["quality"] = (base["quality"] || {}).merge(%w[observe measure].to_h { |feature| [feature, Tools.resolve(cfg, feature, env: env)] })
56
65
  end
57
66
 
58
67
  def deep_stringify_keys(obj)
@@ -76,6 +76,8 @@ module Polyrun
76
76
 
77
77
  # +POLYRUN_WORKERS+ then top-level YAML +workers:+ then {Config::DEFAULT_PARALLEL_WORKERS}.
78
78
  def parallel_worker_count(cfg = nil, env = ENV)
79
+ validate_shared_tools!(cfg) if cfg
80
+
79
81
  s = env["POLYRUN_WORKERS"]
80
82
  unless s.nil? || s.empty?
81
83
  i = Integer(s, exception: false)
@@ -88,6 +90,13 @@ module Polyrun
88
90
  Polyrun::Config::DEFAULT_PARALLEL_WORKERS
89
91
  end
90
92
 
93
+ def validate_shared_tools!(cfg)
94
+ raw = cfg.respond_to?(:raw) ? cfg.raw : cfg
95
+ errors = Tools.validate(raw)
96
+ raise Polyrun::Error, errors.join("; ") unless errors.empty?
97
+ end
98
+ private_class_method :validate_shared_tools!
99
+
91
100
  def yaml_top_level_workers(cfg)
92
101
  return nil unless cfg
93
102
 
@@ -1,3 +1,5 @@
1
+ require_relative "tool_defaults"
2
+
1
3
  module Polyrun
2
4
  class Config
3
5
  # Lightweight top-level key checks for +polyrun validate+.
@@ -11,9 +13,11 @@ module Polyrun
11
13
  start
12
14
  hooks
13
15
  reporting
14
- workers
15
16
  suites
16
- ].freeze
17
+ graph
18
+ mutation
19
+ quality
20
+ ].concat(ToolDefaults::SHARED.keys).freeze
17
21
 
18
22
  module_function
19
23
 
@@ -27,7 +31,8 @@ module Polyrun
27
31
 
28
32
  unknown = raw.keys.map(&:to_s) - KNOWN_TOP_LEVEL
29
33
  messages = unknown.sort.map { |k| "polyrun validate: unknown top-level key #{k.inspect}" }
30
- {ok: messages.empty?, messages: messages}
34
+ messages.concat(Polyrun::Config::Tools.validate(raw).map { |message| "polyrun validate: #{message}" })
35
+ {ok: messages.empty?, messages: messages.uniq}
31
36
  end
32
37
  end
33
38
  end
@@ -1,3 +1,5 @@
1
+ require_relative "tools"
2
+
1
3
  module Polyrun
2
4
  class Config
3
5
  # Applies a named +suites:+ overlay onto a loaded polyrun.yml hash.
@@ -8,7 +10,7 @@ module Polyrun
8
10
  shard_workers workers_per_shard
9
11
  ].freeze
10
12
 
11
- TOP_MERGE_KEYS = %w[workers prepare start hooks reporting coverage databases].freeze
13
+ TOP_MERGE_KEYS = (%w[prepare start hooks reporting coverage databases graph mutation quality] + ToolDefaults::SHARED.keys).freeze
12
14
 
13
15
  module_function
14
16
 
@@ -33,6 +35,9 @@ module Polyrun
33
35
  end
34
36
 
35
37
  def apply_overlay!(base, overlay)
38
+ errors = Tools.validate(overlay)
39
+ raise Polyrun::Error, errors.join("; ") unless errors.empty?
40
+
36
41
  merge_partition_block!(base, overlay)
37
42
  merge_partition_shortcuts!(base, overlay)
38
43
  merge_top_keys!(base, overlay)
@@ -0,0 +1,42 @@
1
+ module Polyrun
2
+ class Config
3
+ module ToolDefaults
4
+ STAGING = {"max_bytes" => 67_108_864, "max_files" => 10_000,
5
+ "exclude" => %w[vendor node_modules tmp log pkg benchmarks],
6
+ "exclude_paths" => %w[coverage], "include_hidden" => %w[.rspec .ruby-version]}.freeze
7
+ COMMON = {"enabled" => false, "root" => nil, "workers" => 1, "timeout" => 300,
8
+ "command" => [], "output" => nil, "max_output_bytes" => 1_048_576,
9
+ "max_input_bytes" => 1_048_576, "max_artifact_bytes" => 67_108_864,
10
+ "source_roots" => %w[lib app], "source_fallback" => true,
11
+ "source_exclude" => %w[spec test features examples benchmarks vendor node_modules tmp log coverage pkg],
12
+ "max_nodes" => 250_000, "max_source_files" => 100_000, "max_source_file_bytes" => 10_485_760,
13
+ "max_source_bytes" => 67_108_864, "staging" => STAGING}.freeze
14
+ SHARED = COMMON.except("enabled").freeze
15
+ GRAPH = {"timeout" => 60, "state_dir" => ".polyrun/graph", "json" => false,
16
+ "calls" => false, "callers" => false, "callees" => false, "control_plane" => false, "prove" => false,
17
+ "max_operations" => 1000, "max_diff_bytes" => 524_288,
18
+ "max_plan_bytes" => 1_048_576, "max_receipt_files" => 100_000}.freeze
19
+ MUTATION = {"max_workers" => 32, "max_mutations" => 1000, "max_subjects" => 10_000,
20
+ "max_report_bytes" => 16_777_216, "max_copy_bytes" => 1_073_741_824,
21
+ "operators" => %w[literal operator body], "subjects" => [], "subjects_file" => nil,
22
+ "observed" => [], "plan" => nil, "shard" => 1, "total" => 1}.freeze
23
+ OBSERVE = {"max_entries" => 10_000, "max_artifact_bytes" => 16_777_216}.freeze
24
+ MEASURE = {"label" => "command", "ceilings" => {}}.freeze
25
+ EXECUTION = %w[enabled root timeout command output max_output_bytes].freeze
26
+ FEATURES = {"graph" => GRAPH, "mutation" => MUTATION, "observe" => OBSERVE, "measure" => MEASURE}.freeze
27
+
28
+ module_function
29
+
30
+ def for(feature)
31
+ feature = feature.to_s
32
+ common = case feature
33
+ when "graph" then COMMON.except("workers")
34
+ when "observe" then COMMON.slice(*EXECUTION, "max_artifact_bytes")
35
+ when "measure" then COMMON.slice(*EXECUTION)
36
+ else COMMON
37
+ end
38
+ Marshal.load(Marshal.dump(common.merge(FEATURES.fetch(feature))))
39
+ end
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,79 @@
1
+ require_relative "tool_defaults"
2
+
3
+ module Polyrun
4
+ class Config
5
+ module ToolValidation
6
+ OPTIONAL_STRINGS = %w[root output subjects_file plan].freeze
7
+ COUNTS = %w[min_line_churn min_query_count hot_line_example_overlap minimum_unique_lines_per_example max_zero_hit_examples max_hot_line_overlap].freeze
8
+
9
+ module_function
10
+
11
+ def check(value, defaults, prefix)
12
+ return ["#{prefix} must be a mapping"] unless value.is_a?(Hash)
13
+
14
+ value.flat_map do |key, item|
15
+ path = "#{prefix}.#{key}"
16
+ next ["unknown setting #{path}"] unless defaults.key?(key)
17
+ expected = defaults[key]
18
+ if expected.is_a?(Hash)
19
+ (key == "ceilings") ? check_ceilings(item, path) : check(item, expected, path)
20
+ elsif valid?(key, item, expected)
21
+ []
22
+ else
23
+ ["invalid setting #{path}"]
24
+ end
25
+ end
26
+ end
27
+
28
+ def valid?(key, value, expected)
29
+ return value.nil? || valid_string?(value) if OPTIONAL_STRINGS.include?(key)
30
+ return value.is_a?(Numeric) && value.finite? && value.positive? if key == "timeout"
31
+ return relative_path?(value) if key == "state_dir"
32
+ return valid_count?(value, expected) if COUNTS.include?(key)
33
+ return value.nil? || nonnegative?(value) if expected.nil?
34
+ return positive_integer?(value) if expected.is_a?(Integer)
35
+ return nonnegative?(value) && value <= 1 if key == "sample"
36
+ return value == true || value == false if expected == true || expected == false
37
+ return valid_array?(key, value) if expected.is_a?(Array)
38
+
39
+ valid_string?(value)
40
+ end
41
+
42
+ def positive_integer?(value)
43
+ value.is_a?(Integer) && value.positive?
44
+ end
45
+
46
+ def valid_count?(value, expected)
47
+ (expected.nil? && value.nil?) || (value.is_a?(Integer) && value >= 0)
48
+ end
49
+
50
+ def valid_string?(value)
51
+ value.is_a?(String) && !value.empty? && !value.include?("\0")
52
+ end
53
+
54
+ def nonnegative?(value)
55
+ value.is_a?(Numeric) && value.finite? && value >= 0
56
+ end
57
+
58
+ def valid_array?(key, value)
59
+ return false unless value.is_a?(Array) && value.all? { |entry| valid_string?(entry) }
60
+ return !value.empty? && (value - %w[literal operator body]).empty? if key == "operators"
61
+ return value.all? { |entry| relative_path?(entry) || entry == "." } if key == "source_roots"
62
+
63
+ true
64
+ end
65
+
66
+ def relative_path?(value)
67
+ value.is_a?(String) && !value.empty? && !value.include?("\0") && !value.split("/", -1).any? { |part| ["", ".", ".."].include?(part) }
68
+ end
69
+
70
+ def check_ceilings(value, prefix)
71
+ return ["#{prefix} must be a mapping"] unless value.is_a?(Hash)
72
+
73
+ value.filter_map do |key, item|
74
+ "invalid setting #{prefix}.#{key}" unless item.is_a?(Numeric) && item.finite? && item >= 0
75
+ end
76
+ end
77
+ end
78
+ end
79
+ end
@@ -0,0 +1,120 @@
1
+ require_relative "tool_validation"
2
+
3
+ module Polyrun
4
+ class Config
5
+ module Tools
6
+ module_function
7
+
8
+ def merge(base, overlay)
9
+ base.merge(overlay) { |_, before, after| (before.is_a?(Hash) && after.is_a?(Hash)) ? merge(before, after) : after }
10
+ end
11
+
12
+ def runtime(feature, settings = {})
13
+ raise ArgumentError, "settings must be a mapping" unless settings.is_a?(Hash)
14
+
15
+ value = merge(ToolDefaults.for(feature), stringify(settings))
16
+ errors = ToolValidation.check(value, ToolDefaults.for(feature), feature.to_s)
17
+ raise ArgumentError, errors.join("; ") unless errors.empty?
18
+
19
+ value
20
+ end
21
+
22
+ def resolve(cfg, feature, overrides: {}, env: ENV, root: Dir.pwd)
23
+ errors = validate(cfg.raw)
24
+ raise ArgumentError, errors.join("; ") unless errors.empty?
25
+
26
+ raw = stringify(cfg.raw)
27
+ defaults = ToolDefaults.for(feature)
28
+ shared = shared_defaults(raw).slice(*defaults.keys)
29
+ value = merge(merge(defaults, shared), feature_config(raw, feature))
30
+ value = merge(value, environment(feature, env))
31
+ value = runtime(feature, merge(value, stringify(overrides)))
32
+ normalize_paths(value, root)
33
+ end
34
+
35
+ def shared_defaults(raw)
36
+ shared = raw.slice(*ToolDefaults::SHARED.keys)
37
+ if shared["workers"].is_a?(String)
38
+ shared["workers"] = Integer(shared["workers"], exception: false) || shared["workers"]
39
+ end
40
+ shared
41
+ end
42
+
43
+ def normalize_paths(value, root)
44
+ value["root"] = File.expand_path(value["root"] || root, root)
45
+ %w[output subjects_file].each { |key| value[key] = File.expand_path(value[key], value["root"]) if value[key] }
46
+ value
47
+ end
48
+
49
+ def feature_config(raw, feature)
50
+ return raw.fetch(feature, {}) unless %w[observe measure].include?(feature)
51
+
52
+ quality = raw.fetch("quality", {})
53
+ merge(quality.slice(*ToolDefaults.for(feature).keys), quality.fetch(feature, {}))
54
+ end
55
+
56
+ def environment(feature, env)
57
+ result = {}
58
+ applicable = ToolDefaults.for(feature)
59
+ {"workers" => "POLYRUN_WORKERS", "timeout" => "POLYRUN_TIMEOUT", "max_output_bytes" => "POLYRUN_MAX_OUTPUT_BYTES"}.each do |key, name|
60
+ next if !applicable.key?(key) || env[name].nil? || env[name].empty?
61
+
62
+ result[key] = (key == "timeout") ? Float(env[name]) : Integer(env[name])
63
+ end
64
+ name = "POLYRUN_#{%w[observe measure].include?(feature) ? "QUALITY" : feature.upcase}"
65
+ if env.key?(name)
66
+ raise ArgumentError, "invalid #{name}" unless %w[1 true yes on 0 false no off].include?(env[name].downcase)
67
+
68
+ result["enabled"] = %w[1 true yes on].include?(env[name].downcase)
69
+ end
70
+ result
71
+ end
72
+
73
+ def validate(raw)
74
+ raw = stringify(raw)
75
+ errors = ToolValidation.check(shared_defaults(raw), ToolDefaults::SHARED, "config")
76
+ errors << 'unknown top-level key "global"' if raw.key?("global")
77
+ %w[graph mutation].each do |feature|
78
+ errors.concat(ToolValidation.check(raw[feature], ToolDefaults.for(feature), feature)) if raw.key?(feature)
79
+ end
80
+ errors.concat(validate_quality(raw["quality"])) if raw.key?("quality")
81
+ errors
82
+ end
83
+
84
+ def validate_quality(quality)
85
+ return ["quality must be a mapping"] unless quality.is_a?(Hash)
86
+
87
+ errors = ToolValidation.check(quality.except("observe", "measure", "spec_quality"), ToolDefaults::COMMON.slice(*ToolDefaults::EXECUTION, "max_artifact_bytes"), "quality")
88
+ %w[observe measure].each do |feature|
89
+ errors.concat(ToolValidation.check(quality[feature], ToolDefaults.for(feature), "quality.#{feature}")) if quality.key?(feature)
90
+ end
91
+ if quality.key?("spec_quality")
92
+ require_relative "../spec_quality/config"
93
+ defaults = SpecQuality::Config::DEFAULTS.merge("enabled" => false)
94
+ errors.concat(ToolValidation.check(quality["spec_quality"], defaults, "quality.spec_quality"))
95
+ end
96
+ errors
97
+ end
98
+
99
+ def spec_quality(root:, env: ENV)
100
+ cfg = Config.load(path: env["POLYRUN_CONFIG"], root: root, suite: env["POLYRUN_SUITE"])
101
+ errors = validate(cfg.raw)
102
+ raise ArgumentError, errors.join("; ") unless errors.empty?
103
+
104
+ raw = stringify(cfg.raw)
105
+ shared = shared_defaults(raw)
106
+ settings = {}
107
+ settings["track_under"] = shared["source_roots"] if shared.key?("source_roots")
108
+ merge(settings, raw.fetch("quality", {}).fetch("spec_quality", {}))
109
+ end
110
+
111
+ def stringify(value)
112
+ case value
113
+ when Hash then value.to_h { |key, item| [key.to_s, stringify(item)] }
114
+ when Array then value.map { |item| stringify(item) }
115
+ else value
116
+ end
117
+ end
118
+ end
119
+ end
120
+ end
@@ -11,9 +11,9 @@ module Polyrun
11
11
 
12
12
  attr_reader :path, :raw, :suite
13
13
 
14
- def self.load(path: nil, suite: nil)
14
+ def self.load(path: nil, suite: nil, root: Dir.pwd)
15
15
  explicit = path && !path.to_s.strip.empty?
16
- resolved = resolve_path(path)
16
+ resolved = resolve_path(path, root: root)
17
17
  if explicit && !(resolved && File.file?(resolved))
18
18
  raise Polyrun::Error, "polyrun config not found: #{path}"
19
19
  end
@@ -32,11 +32,11 @@ module Polyrun
32
32
  new(path: resolved, raw: merged, suite: applied)
33
33
  end
34
34
 
35
- def self.resolve_path(explicit)
35
+ def self.resolve_path(explicit, root: Dir.pwd)
36
36
  return File.expand_path(explicit) if explicit && !explicit.empty?
37
37
 
38
38
  DEFAULT_FILENAMES.each do |name|
39
- full = File.expand_path(name, Dir.pwd)
39
+ full = File.expand_path(name, root)
40
40
  return full if File.file?(full)
41
41
  end
42
42
  nil
@@ -93,3 +93,5 @@ require_relative "config/suite"
93
93
  require_relative "config/resolver"
94
94
  require_relative "config/effective"
95
95
  require_relative "config/schema"
96
+
97
+ require_relative "config/tools"