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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +21 -0
- data/README.md +16 -2
- data/docs/QUALITY.md +82 -0
- data/docs/QUALITY_CONFIGURATION.md +95 -0
- data/ext/polyrun_coverage_merge/coverage_merge.c +13 -26
- data/lib/polyrun/cli/ci_shard_run_command.rb +1 -1
- data/lib/polyrun/cli/graph_command.rb +68 -0
- data/lib/polyrun/cli/help.rb +5 -1
- data/lib/polyrun/cli/helpers.rb +3 -2
- data/lib/polyrun/cli/mutation_command.rb +67 -0
- data/lib/polyrun/cli/quality_commands.rb +65 -0
- data/lib/polyrun/cli/run_shards_parallel_wait.rb +48 -70
- data/lib/polyrun/cli/run_shards_plan_options.rb +1 -1
- data/lib/polyrun/cli/run_shards_worker_interrupt.rb +16 -0
- data/lib/polyrun/cli/tool_options.rb +48 -0
- data/lib/polyrun/cli.rb +17 -1
- data/lib/polyrun/config/effective.rb +9 -0
- data/lib/polyrun/config/resolver.rb +9 -0
- data/lib/polyrun/config/schema.rb +8 -3
- data/lib/polyrun/config/suite.rb +6 -1
- data/lib/polyrun/config/tool_defaults.rb +42 -0
- data/lib/polyrun/config/tool_validation.rb +79 -0
- data/lib/polyrun/config/tools.rb +120 -0
- data/lib/polyrun/config.rb +6 -4
- data/lib/polyrun/coverage/collector.rb +7 -1
- data/lib/polyrun/coverage/example_diff.rb +4 -8
- data/lib/polyrun/error.rb +3 -0
- data/lib/polyrun/graph/client.rb +64 -0
- data/lib/polyrun/graph/error.rb +13 -0
- data/lib/polyrun/graph/index.rb +75 -0
- data/lib/polyrun/graph/inspect.rb +58 -0
- data/lib/polyrun/graph/plan.rb +134 -0
- data/lib/polyrun/graph/planner.rb +117 -0
- data/lib/polyrun/graph/syntax.rb +114 -0
- data/lib/polyrun/graph/transaction.rb +81 -0
- data/lib/polyrun/graph/worker.rb +55 -0
- data/lib/polyrun/graph/workspace.rb +117 -0
- data/lib/polyrun/minitest_support.rb +1 -1
- data/lib/polyrun/mutation/candidates.rb +91 -0
- data/lib/polyrun/mutation/operators.rb +51 -0
- data/lib/polyrun/mutation/runner.rb +133 -0
- data/lib/polyrun/mutation/subjects.rb +88 -0
- data/lib/polyrun/process_stdio.rb +13 -8
- data/lib/polyrun/quality/command.rb +84 -0
- data/lib/polyrun/quality/measure.rb +38 -0
- data/lib/polyrun/quality/observe.rb +53 -0
- data/lib/polyrun/quality/observe_hook.rb +103 -0
- data/lib/polyrun/quality/sandbox.rb +70 -0
- data/lib/polyrun/rspec_support.rb +1 -1
- data/lib/polyrun/spec_quality/config.rb +8 -3
- data/lib/polyrun/spec_quality.rb +3 -4
- data/lib/polyrun/version.rb +1 -1
- data/lib/polyrun/worker_output.rb +25 -33
- data/lib/polyrun/worker_output_forwarders.rb +11 -7
- data/lib/polyrun.rb +1 -2
- data/polyrun.gemspec +6 -1
- data/sig/polyrun/config.rbs +2 -2
- metadata +44 -2
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
require_relative "workspace"
|
|
2
|
+
|
|
3
|
+
module Polyrun
|
|
4
|
+
module Graph
|
|
5
|
+
class Transaction
|
|
6
|
+
def initialize(root, directory, settings: {})
|
|
7
|
+
@workspace = Workspace.new(root, settings: settings)
|
|
8
|
+
relative = File.realpath(directory).delete_prefix("#{@workspace.root}/")
|
|
9
|
+
@directory = @workspace.path(relative)
|
|
10
|
+
@journal = "#{relative}/transaction.json"
|
|
11
|
+
end
|
|
12
|
+
|
|
13
|
+
def recover!
|
|
14
|
+
return false unless File.file?(@workspace.path(@journal))
|
|
15
|
+
|
|
16
|
+
journal = @workspace.read_json(@journal)
|
|
17
|
+
return false unless %w[prepared writing restoring].include?(journal["state"])
|
|
18
|
+
|
|
19
|
+
save(journal.merge("state" => "restoring"))
|
|
20
|
+
journal.fetch("files").reverse_each do |relative, hashes|
|
|
21
|
+
source = @workspace.path(relative)
|
|
22
|
+
backup = @workspace.path("backups/#{relative}", base: @directory)
|
|
23
|
+
unless File.file?(source) && File.file?(backup) && Digest::SHA256.file(backup).hexdigest == hashes["before"]
|
|
24
|
+
raise Error.new("RECOVERY_REQUIRED", "source recovery needs a valid original: #{relative}")
|
|
25
|
+
end
|
|
26
|
+
restore_source(source, backup, hashes, relative)
|
|
27
|
+
end
|
|
28
|
+
save(journal.merge("state" => "restored"))
|
|
29
|
+
true
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
def commit(replacements)
|
|
33
|
+
files = replacements.to_h do |relative, before, after|
|
|
34
|
+
backup = @workspace.path("backups/#{relative}", base: @directory)
|
|
35
|
+
FileUtils.mkdir_p(File.dirname(backup))
|
|
36
|
+
File.binwrite(backup, before)
|
|
37
|
+
[relative, {"before" => Digest::SHA256.hexdigest(before), "after" => Digest::SHA256.hexdigest(after)}]
|
|
38
|
+
end
|
|
39
|
+
journal = {"state" => "prepared", "files" => files}
|
|
40
|
+
save(journal)
|
|
41
|
+
save(journal.merge("state" => "writing"))
|
|
42
|
+
replacements.each do |relative, before, after|
|
|
43
|
+
source = @workspace.path(relative)
|
|
44
|
+
raise Error.new("STALE_SNAPSHOT", "source changed during apply") unless File.binread(source) == before
|
|
45
|
+
|
|
46
|
+
write_source(source, after)
|
|
47
|
+
end
|
|
48
|
+
save(journal.merge("state" => "applied"))
|
|
49
|
+
true
|
|
50
|
+
rescue Exception # rubocop:disable Lint/RescueException -- rollback also covers cooperative cancellation
|
|
51
|
+
recover!
|
|
52
|
+
raise
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
private
|
|
56
|
+
|
|
57
|
+
def restore_source(source, backup, hashes, relative)
|
|
58
|
+
current = Digest::SHA256.file(source).hexdigest
|
|
59
|
+
raise Error.new("RECOVERY_REQUIRED", "source changed outside graph apply: #{relative}") unless [hashes["before"], hashes["after"]].include?(current)
|
|
60
|
+
|
|
61
|
+
write_source(source, File.binread(backup)) unless current == hashes["before"]
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
def save(journal)
|
|
65
|
+
@workspace.write_json(@journal, journal)
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
def write_source(path, bytes)
|
|
69
|
+
mode = File.stat(path).mode & 0o777
|
|
70
|
+
Tempfile.create("polyrun-apply", File.dirname(path)) do |file|
|
|
71
|
+
file.chmod(mode)
|
|
72
|
+
file.binmode
|
|
73
|
+
file.write(bytes)
|
|
74
|
+
file.flush
|
|
75
|
+
file.fsync
|
|
76
|
+
File.rename(file.path, path)
|
|
77
|
+
end
|
|
78
|
+
end
|
|
79
|
+
end
|
|
80
|
+
end
|
|
81
|
+
end
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
require "json"
|
|
2
|
+
require_relative "planner"
|
|
3
|
+
require_relative "inspect"
|
|
4
|
+
|
|
5
|
+
module Polyrun
|
|
6
|
+
module Graph
|
|
7
|
+
module Worker
|
|
8
|
+
module_function
|
|
9
|
+
|
|
10
|
+
def run(arguments)
|
|
11
|
+
root = ENV.fetch("POLYRUN_GRAPH_ROOT", Dir.pwd)
|
|
12
|
+
json = arguments.include?("--json")
|
|
13
|
+
arguments = arguments.reject { |argument| argument == "--json" }
|
|
14
|
+
settings = JSON.parse(ENV.delete("POLYRUN_GRAPH_SETTINGS") || "{}")
|
|
15
|
+
result = dispatch(root, arguments, settings)
|
|
16
|
+
puts(json ? JSON.generate(result) : text_result(arguments.first, result))
|
|
17
|
+
0
|
|
18
|
+
rescue Error => error
|
|
19
|
+
warn(json ? JSON.generate("ok" => false, "code" => error.code, "message" => error.message) : "#{error.code}: #{error.message}")
|
|
20
|
+
error.exitstatus
|
|
21
|
+
rescue SystemCallError, ArgumentError, KeyError, JSON::ParserError => error
|
|
22
|
+
warn(json ? JSON.generate("ok" => false, "code" => "INVALID_ARGUMENT", "message" => error.message) : error.message)
|
|
23
|
+
2
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
def dispatch(root, arguments, settings)
|
|
27
|
+
verb, argument, *flags = arguments
|
|
28
|
+
index = Index.new(root, settings: settings)
|
|
29
|
+
case verb
|
|
30
|
+
when "index"
|
|
31
|
+
graph = index.call
|
|
32
|
+
{"ok" => true, "snapshot" => graph["snapshot"], "nodes" => graph["methods"].size + graph["calls"].size, "reused" => graph["reused"]}
|
|
33
|
+
when "inspect" then Inspect.new(index.load).call(argument, flags + (argument&.start_with?("--") ? [argument] : []))
|
|
34
|
+
when "plan" then Planner.new(root, settings: settings).call(argument)
|
|
35
|
+
when "check" then Plan.new(root, argument, settings: settings).check!
|
|
36
|
+
when "apply"
|
|
37
|
+
Plan.new(root, argument, settings: settings).apply!
|
|
38
|
+
{"ok" => true, "plan_id" => argument, "applied" => true, "snapshot" => index.call["snapshot"]}
|
|
39
|
+
else raise Error.new("INVALID_ARGUMENT", "unknown graph command")
|
|
40
|
+
end
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
def text_result(verb, result)
|
|
44
|
+
case verb
|
|
45
|
+
when "index" then "indexed #{result["snapshot"]} nodes=#{result["nodes"]} reused=#{result["reused"]}"
|
|
46
|
+
when "plan" then "plan #{result["plan_id"]}\n#{result["diff"]}"
|
|
47
|
+
when "check" then "checked plan: #{result["status"]}"
|
|
48
|
+
when "apply" then "applied #{result["plan_id"]}"
|
|
49
|
+
else JSON.pretty_generate(result)
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
private_class_method :dispatch, :text_result
|
|
53
|
+
end
|
|
54
|
+
end
|
|
55
|
+
end
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
require "digest"
|
|
2
|
+
require "fileutils"
|
|
3
|
+
require "find"
|
|
4
|
+
require "json"
|
|
5
|
+
require "tempfile"
|
|
6
|
+
require_relative "error"
|
|
7
|
+
require_relative "../config/tools"
|
|
8
|
+
|
|
9
|
+
module Polyrun
|
|
10
|
+
module Graph
|
|
11
|
+
class Workspace
|
|
12
|
+
STATE = Config::ToolDefaults::GRAPH.fetch("state_dir")
|
|
13
|
+
attr_reader :root, :settings
|
|
14
|
+
|
|
15
|
+
def state
|
|
16
|
+
@settings.fetch("state_dir", STATE)
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
def initialize(root, settings: {})
|
|
20
|
+
@settings = Config::Tools.runtime("graph", settings)
|
|
21
|
+
@root = File.realpath(root)
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
def path(relative, base: @root)
|
|
25
|
+
parts = relative.is_a?(String) ? relative.split("/", -1) : []
|
|
26
|
+
if parts.empty? || parts.any? { |part| part.empty? || part == "." || part == ".." || part.include?("\0") }
|
|
27
|
+
raise Error.new("INVALID_PLAN", "invalid project path")
|
|
28
|
+
end
|
|
29
|
+
parts.reduce(base) do |parent, part|
|
|
30
|
+
result = File.join(parent, part)
|
|
31
|
+
raise Error.new("INVALID_PLAN", "symbolic link in project path") if File.symlink?(result)
|
|
32
|
+
|
|
33
|
+
result
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
def files
|
|
38
|
+
found = source_directories.flat_map { |directory| source_files(directory) }.uniq.sort
|
|
39
|
+
raise Error.new("RESOURCE_LIMIT", "too many source files") if found.size > @settings["max_source_files"]
|
|
40
|
+
|
|
41
|
+
found
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
def hashes
|
|
45
|
+
total = 0
|
|
46
|
+
files.to_h do |relative|
|
|
47
|
+
absolute = path(relative)
|
|
48
|
+
total += File.size(absolute)
|
|
49
|
+
raise Error.new("RESOURCE_LIMIT", "source file is too large") if File.size(absolute) > @settings["max_source_file_bytes"]
|
|
50
|
+
raise Error.new("RESOURCE_LIMIT", "source tree exceeds configured byte limit") if total > @settings["max_source_bytes"]
|
|
51
|
+
|
|
52
|
+
[relative, Digest::SHA256.file(absolute).hexdigest]
|
|
53
|
+
end
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
def snapshot(hashes)
|
|
57
|
+
"snapshot-#{Digest::SHA256.hexdigest(JSON.generate(hashes))}"
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def read_json(relative, limit: @settings["max_artifact_bytes"])
|
|
61
|
+
file = path(relative)
|
|
62
|
+
raise Error.new("MISSING_STATE", "graph state missing; run polyrun graph index") unless File.file?(file)
|
|
63
|
+
raise Error.new("RESOURCE_LIMIT", "graph state is too large") if File.size(file) > limit
|
|
64
|
+
|
|
65
|
+
JSON.parse(File.binread(file))
|
|
66
|
+
rescue JSON::ParserError
|
|
67
|
+
raise Error.new("INVALID_PLAN", "invalid graph data")
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
def write_json(relative, value, limit: @settings["max_artifact_bytes"])
|
|
71
|
+
destination = path(relative)
|
|
72
|
+
payload = JSON.generate(value)
|
|
73
|
+
raise Error.new("RESOURCE_LIMIT", "graph state is too large") if payload.bytesize > limit
|
|
74
|
+
|
|
75
|
+
FileUtils.mkdir_p(File.dirname(destination))
|
|
76
|
+
Tempfile.create("polyrun-graph", File.dirname(destination)) do |file|
|
|
77
|
+
file.write(payload)
|
|
78
|
+
file.flush
|
|
79
|
+
file.fsync
|
|
80
|
+
File.rename(file.path, destination)
|
|
81
|
+
end
|
|
82
|
+
value
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
private
|
|
86
|
+
|
|
87
|
+
def source_directories
|
|
88
|
+
roots = @settings["source_roots"].map { |name| (name == ".") ? @root : path(name) }.select { |directory| File.directory?(directory) }
|
|
89
|
+
roots = [@root] if roots.empty? && @settings["source_fallback"]
|
|
90
|
+
roots
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
def source_files(directory)
|
|
94
|
+
found = []
|
|
95
|
+
Find.find(directory) do |entry|
|
|
96
|
+
relative = entry.delete_prefix("#{@root}/")
|
|
97
|
+
if entry != directory && (relative == state || excluded?(relative))
|
|
98
|
+
Find.prune if File.directory?(entry)
|
|
99
|
+
next
|
|
100
|
+
end
|
|
101
|
+
if File.symlink?(entry)
|
|
102
|
+
raise Error.new("INVALID_PLAN", "symbolic link in source tree")
|
|
103
|
+
elsif File.file?(entry) && entry.end_with?(".rb")
|
|
104
|
+
found << relative
|
|
105
|
+
raise Error.new("RESOURCE_LIMIT", "too many source files") if found.length > @settings["max_source_files"]
|
|
106
|
+
end
|
|
107
|
+
end
|
|
108
|
+
found
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
def excluded?(relative)
|
|
112
|
+
name = File.basename(relative)
|
|
113
|
+
name.start_with?(".") || @settings["source_exclude"].any? { |pattern| File.fnmatch?(pattern, name) || File.fnmatch?(pattern, relative, File::FNM_PATHNAME) }
|
|
114
|
+
end
|
|
115
|
+
end
|
|
116
|
+
end
|
|
117
|
+
end
|
|
@@ -50,7 +50,7 @@ module Polyrun
|
|
|
50
50
|
|
|
51
51
|
# Per-test spec quality when +POLYRUN_SPEC_QUALITY=1+ (requires stdlib +Coverage+ for line deltas).
|
|
52
52
|
def install_spec_quality!(only_if: nil, root: nil, output_path: nil)
|
|
53
|
-
pred = only_if || -> { Polyrun::SpecQuality.enabled? }
|
|
53
|
+
pred = only_if || -> { Polyrun::SpecQuality.enabled?(root: root || Dir.pwd) }
|
|
54
54
|
return unless pred.call
|
|
55
55
|
|
|
56
56
|
require_relative "spec_quality/minitest_hook"
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
require "prism"
|
|
2
|
+
require "digest"
|
|
3
|
+
require_relative "../graph/syntax"
|
|
4
|
+
require_relative "../graph/workspace"
|
|
5
|
+
require_relative "operators"
|
|
6
|
+
|
|
7
|
+
module Polyrun
|
|
8
|
+
module Mutation
|
|
9
|
+
class Candidates
|
|
10
|
+
def initialize(root, operators: nil, limit: nil, settings: {})
|
|
11
|
+
settings = Config::Tools.runtime("mutation", settings)
|
|
12
|
+
graph = settings.slice(*Config::ToolDefaults.for("graph").keys)
|
|
13
|
+
@workspace = Graph::Workspace.new(root, settings: graph)
|
|
14
|
+
@operators = operators || Operators.select(settings["operators"])
|
|
15
|
+
@limit = limit || settings["max_mutations"]
|
|
16
|
+
@count = 0
|
|
17
|
+
@seen = {}
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
def call(subjects)
|
|
21
|
+
inventory = source_inventory
|
|
22
|
+
subjects.flat_map do |subject|
|
|
23
|
+
matches = select_methods(inventory, subject)
|
|
24
|
+
matches.flat_map { |path, source, method| generate(path, source, method) }
|
|
25
|
+
end.uniq { |mutation| [mutation["path"], mutation["source_hash"]] }
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
private
|
|
29
|
+
|
|
30
|
+
def source_inventory
|
|
31
|
+
nodes = 0
|
|
32
|
+
@workspace.hashes.keys.map do |relative|
|
|
33
|
+
source = File.binread(@workspace.path(relative))
|
|
34
|
+
syntax = Graph::Syntax.new(relative, source, max_nodes: @workspace.settings["max_nodes"]).parse
|
|
35
|
+
nodes += syntax.methods.size + syntax.calls.size
|
|
36
|
+
raise ArgumentError, "mutation source exceeds configured node limit" if nodes > @workspace.settings["max_nodes"]
|
|
37
|
+
|
|
38
|
+
[relative, source, syntax.methods]
|
|
39
|
+
end
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
def select_methods(inventory, subject)
|
|
43
|
+
matches = inventory.flat_map { |path, source, methods| methods.filter_map { |method| [path, source, method] if match?(subject, method["subject"]) } }
|
|
44
|
+
raise ArgumentError, "unknown mutation subject: #{subject}" if matches.empty?
|
|
45
|
+
names = matches.map { |_, _, method| method["subject"] }
|
|
46
|
+
raise ArgumentError, "ambiguous mutation subject: #{subject}" unless names.uniq.length == names.length
|
|
47
|
+
|
|
48
|
+
matches
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
def match?(selector, subject)
|
|
52
|
+
subject && (selector == subject || (selector.include?("*") && File.fnmatch?(selector, subject)))
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
def generate(path, source, method)
|
|
56
|
+
parsed = Prism.parse(source)
|
|
57
|
+
nodes = [parsed.value]
|
|
58
|
+
edits = []
|
|
59
|
+
until nodes.empty?
|
|
60
|
+
node = nodes.pop
|
|
61
|
+
location = node.location
|
|
62
|
+
if location.start_offset >= method["byte_start"] && location.end_offset <= method["byte_end"]
|
|
63
|
+
@operators.each { |operator| edits.concat(operator.call(node)) }
|
|
64
|
+
end
|
|
65
|
+
nodes.concat(node.compact_child_nodes)
|
|
66
|
+
end
|
|
67
|
+
edits.filter_map do |location, replacement, operator|
|
|
68
|
+
next if source.byteslice(location.start_offset, location.length) == replacement
|
|
69
|
+
|
|
70
|
+
changed = source.byteslice(0, location.start_offset) + replacement.b + source.byteslice(location.end_offset..)
|
|
71
|
+
next if Prism.parse(changed).failure?
|
|
72
|
+
|
|
73
|
+
build_candidate(path, source, changed, method, location, replacement, operator)
|
|
74
|
+
end
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
def build_candidate(path, source, changed, method, location, replacement, operator)
|
|
78
|
+
digest = Digest::SHA256.hexdigest(changed)
|
|
79
|
+
return if @seen[[path, digest]]
|
|
80
|
+
|
|
81
|
+
@seen[[path, digest]] = true
|
|
82
|
+
@count += 1
|
|
83
|
+
raise ArgumentError, "mutation limit exceeded; narrow subjects or raise --max-mutations" if @count > @limit
|
|
84
|
+
|
|
85
|
+
{"id" => "mutation-#{Digest::SHA256.hexdigest(path + digest)[0, 24]}", "subject" => method["subject"],
|
|
86
|
+
"path" => path, "line" => location.start_line, "operator" => operator, "start" => location.start_offset,
|
|
87
|
+
"end" => location.end_offset, "replacement" => replacement, "original_hash" => Digest::SHA256.hexdigest(source), "source_hash" => digest}
|
|
88
|
+
end
|
|
89
|
+
end
|
|
90
|
+
end
|
|
91
|
+
end
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
module Polyrun
|
|
2
|
+
module Mutation
|
|
3
|
+
module Operators
|
|
4
|
+
class Literal
|
|
5
|
+
def call(node)
|
|
6
|
+
replacements = case node
|
|
7
|
+
when Prism::TrueNode then ["false"]
|
|
8
|
+
when Prism::FalseNode then ["true"]
|
|
9
|
+
when Prism::NilNode then ["true"]
|
|
10
|
+
when Prism::IntegerNode then ["0", "1", (node.value + 1).to_s]
|
|
11
|
+
when Prism::FloatNode then ["0.0", "1.0"]
|
|
12
|
+
when Prism::StringNode, Prism::InterpolatedStringNode then ['""']
|
|
13
|
+
when Prism::ArrayNode then ["[]"]
|
|
14
|
+
when Prism::HashNode then ["{}"]
|
|
15
|
+
else []
|
|
16
|
+
end
|
|
17
|
+
replacements.map { |value| [node.location, value, "literal"] }
|
|
18
|
+
end
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
class Operator
|
|
22
|
+
REPLACEMENTS = {"==" => "!=", "!=" => "==", ">" => "<=", ">=" => "<", "<" => ">=", "<=" => ">",
|
|
23
|
+
"+" => "-", "-" => "+", "*" => "/", "/" => "*", "&" => "|", "|" => "&"}.freeze
|
|
24
|
+
|
|
25
|
+
def call(node)
|
|
26
|
+
return [] unless node.is_a?(Prism::CallNode) && node.message_loc
|
|
27
|
+
|
|
28
|
+
replacement = REPLACEMENTS[node.name.to_s]
|
|
29
|
+
replacement ? [[node.message_loc, replacement, "operator"]] : []
|
|
30
|
+
end
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
class Body
|
|
34
|
+
def call(node)
|
|
35
|
+
return [] unless node.is_a?(Prism::DefNode)
|
|
36
|
+
|
|
37
|
+
return %w[false true 0].map { |value| [node.end_keyword_loc.copy(length: 0), ";#{value};", "body"] } unless node.body
|
|
38
|
+
|
|
39
|
+
%w[nil false true 0].map { |value| [node.body.location, value, "body"] }
|
|
40
|
+
end
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
REGISTRY = {"literal" => Literal.new, "operator" => Operator.new, "body" => Body.new}.freeze
|
|
44
|
+
STANDARD = REGISTRY.values.freeze
|
|
45
|
+
|
|
46
|
+
def self.select(names)
|
|
47
|
+
names.map { |name| REGISTRY.fetch(name) }
|
|
48
|
+
end
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
end
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
require "tmpdir"
|
|
2
|
+
require_relative "../quality/command"
|
|
3
|
+
require_relative "../quality/sandbox"
|
|
4
|
+
require_relative "candidates"
|
|
5
|
+
|
|
6
|
+
module Polyrun
|
|
7
|
+
module Mutation
|
|
8
|
+
class Runner
|
|
9
|
+
def initialize(root: Dir.pwd, workers: nil, timeout: nil, arguments: [], max_mutations: nil,
|
|
10
|
+
max_report_bytes: nil, operators: nil, settings: {})
|
|
11
|
+
overrides = {"workers" => workers, "timeout" => timeout, "max_mutations" => max_mutations, "max_report_bytes" => max_report_bytes}.compact
|
|
12
|
+
@settings = Config::Tools.runtime("mutation", settings.merge(overrides))
|
|
13
|
+
raise ArgumentError, "workers exceed configured maximum" if @settings["workers"] > @settings["max_workers"]
|
|
14
|
+
|
|
15
|
+
@root, @workers, @timeout, @arguments = File.realpath(root), @settings["workers"], @settings["timeout"], arguments
|
|
16
|
+
@max_mutations, @max_report_bytes = @settings["max_mutations"], @settings["max_report_bytes"]
|
|
17
|
+
@operators = operators || Operators.select(@settings["operators"])
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
def call(subjects, shard: 1, total: 1)
|
|
21
|
+
subjects = select_subjects(subjects, shard, total)
|
|
22
|
+
return aggregate(subjects, [], nil) if subjects.empty?
|
|
23
|
+
raise ArgumentError, "a test command is required after --" if @arguments.empty?
|
|
24
|
+
|
|
25
|
+
mutations = Candidates.new(@root, operators: @operators, limit: @max_mutations, settings: @settings).call(subjects)
|
|
26
|
+
raise ArgumentError, "no supported mutations for selected subjects" if mutations.empty?
|
|
27
|
+
budget = {remaining: @max_report_bytes, mutex: Mutex.new}
|
|
28
|
+
Dir.mktmpdir("polyrun-mutations") do |template|
|
|
29
|
+
project = Quality::Sandbox.new(@root, settings: @settings["staging"])
|
|
30
|
+
enforce_copy_budget!(project.bytes, mutations.size)
|
|
31
|
+
|
|
32
|
+
project.copy_to(template)
|
|
33
|
+
baseline = retain_result(execute(template, nil), budget)
|
|
34
|
+
unless baseline["exitstatus"].zero? && baseline["code"] != "REPORT_LIMIT"
|
|
35
|
+
return aggregate(subjects, [], baseline).merge("ok" => false, "code" => "BASELINE_FAILED", "killed" => nil, "survived" => nil)
|
|
36
|
+
end
|
|
37
|
+
results = parallel(mutations, template, budget)
|
|
38
|
+
aggregate(subjects, results, baseline)
|
|
39
|
+
end
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
private
|
|
43
|
+
|
|
44
|
+
def enforce_copy_budget!(bytes, mutations)
|
|
45
|
+
raise ArgumentError, "mutation copy budget exceeded; narrow subjects or raise max_copy_bytes" if bytes * (mutations + 2) > @settings["max_copy_bytes"]
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
def parallel(mutations, template, budget)
|
|
49
|
+
pending = ::Queue.new
|
|
50
|
+
results = Array.new(mutations.size)
|
|
51
|
+
mutations.each_with_index { |mutation, index| pending << [mutation, index] }
|
|
52
|
+
threads = Array.new([@workers, mutations.size].min) do
|
|
53
|
+
Thread.new do # rubocop:disable ThreadSafety/NewThread -- bounded subprocess workers with isolated copies
|
|
54
|
+
loop do
|
|
55
|
+
mutation, index = pending.pop(true)
|
|
56
|
+
result = execute(template, mutation)
|
|
57
|
+
results[index] = retain_result(result, budget)
|
|
58
|
+
rescue ThreadError
|
|
59
|
+
break
|
|
60
|
+
end
|
|
61
|
+
end
|
|
62
|
+
end
|
|
63
|
+
threads.each(&:value)
|
|
64
|
+
results
|
|
65
|
+
ensure
|
|
66
|
+
threads&.each { |thread| thread.kill if thread.alive? }
|
|
67
|
+
threads&.each(&:join)
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
def execute(template, mutation)
|
|
71
|
+
Dir.mktmpdir("polyrun-mutation") do |directory|
|
|
72
|
+
project = Quality::Sandbox.new(template, settings: @settings["staging"])
|
|
73
|
+
project.copy_to(directory)
|
|
74
|
+
apply_mutation(directory, mutation) if mutation
|
|
75
|
+
command = @arguments.map { |argument| argument.start_with?("#{@root}/") ? File.join(directory, argument.delete_prefix("#{@root}/")) : argument }
|
|
76
|
+
# Baseline keeps a floor so short per-mutation timeouts do not fail the clean run under load.
|
|
77
|
+
timeout = mutation ? @timeout : [@timeout, 5.0].max
|
|
78
|
+
result = Quality::Command.call(command, root: directory, timeout: timeout, max_output: @settings["max_output_bytes"], env: Quality::Sandbox.environment(directory))
|
|
79
|
+
result.merge!(mutation) if mutation
|
|
80
|
+
result["code"] = {0 => mutation ? "SURVIVED" : "BASELINE_OK", 1 => mutation ? "KILLED" : "BASELINE_FAILED",
|
|
81
|
+
122 => "OUTPUT_LIMIT", 124 => "TIMEOUT", 127 => "COMMAND_UNAVAILABLE"}.fetch(result["exitstatus"], "COMMAND_FAILED")
|
|
82
|
+
result
|
|
83
|
+
end
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
def retain_result(result, budget)
|
|
87
|
+
budget[:mutex].synchronize do
|
|
88
|
+
size = result["stdout"].bytesize + result["stderr"].bytesize
|
|
89
|
+
if size > budget[:remaining]
|
|
90
|
+
result.merge!("stdout" => "", "stderr" => "", "code" => "REPORT_LIMIT")
|
|
91
|
+
else
|
|
92
|
+
budget[:remaining] -= size
|
|
93
|
+
end
|
|
94
|
+
end
|
|
95
|
+
result
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
def apply_mutation(directory, mutation)
|
|
99
|
+
file = File.join(directory, mutation["path"])
|
|
100
|
+
source = File.binread(file)
|
|
101
|
+
raise ArgumentError, "source changed before mutation testing" unless Digest::SHA256.hexdigest(source) == mutation["original_hash"]
|
|
102
|
+
|
|
103
|
+
source[mutation["start"]...mutation["end"]] = mutation["replacement"].b
|
|
104
|
+
File.binwrite(file, source)
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
def select_subjects(subjects, shard, total)
|
|
108
|
+
unless shard.is_a?(Integer) && total.is_a?(Integer) && total.positive? && (1..total).cover?(shard)
|
|
109
|
+
raise ArgumentError, "shard must be between 1 and total"
|
|
110
|
+
end
|
|
111
|
+
raise ArgumentError, "at least one subject is required" unless subjects.is_a?(Array) && !subjects.empty?
|
|
112
|
+
raise ArgumentError, "too many mutation subjects" if subjects.size > @settings["max_subjects"]
|
|
113
|
+
unless subjects.all? { |subject| valid_subject?(subject) }
|
|
114
|
+
raise ArgumentError, "invalid mutation subject"
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
subjects.uniq.sort.each_with_index.filter_map { |subject, index| subject if index % total == shard - 1 }
|
|
118
|
+
end
|
|
119
|
+
|
|
120
|
+
def valid_subject?(subject)
|
|
121
|
+
subject.is_a?(String) && !subject.empty? && !subject.start_with?("-") && !subject.match?(/[\s\x00]/)
|
|
122
|
+
end
|
|
123
|
+
|
|
124
|
+
def aggregate(subjects, results, baseline)
|
|
125
|
+
complete = results.all? { |result| %w[KILLED SURVIVED].include?(result["code"]) }
|
|
126
|
+
killed = complete ? results.count { |result| result["code"] == "KILLED" } : nil
|
|
127
|
+
survived = complete ? results.count { |result| result["code"] == "SURVIVED" } : nil
|
|
128
|
+
{"ok" => complete && survived.zero?, "engine" => "polyrun", "subjects" => subjects, "mutations" => results.size,
|
|
129
|
+
"killed" => killed, "survived" => survived, "baseline" => baseline, "results" => results}
|
|
130
|
+
end
|
|
131
|
+
end
|
|
132
|
+
end
|
|
133
|
+
end
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
require "prism"
|
|
2
|
+
require_relative "../graph/plan"
|
|
3
|
+
|
|
4
|
+
module Polyrun
|
|
5
|
+
module Mutation
|
|
6
|
+
module Subjects
|
|
7
|
+
module_function
|
|
8
|
+
|
|
9
|
+
def from_observation(path, max_bytes: 16_777_216)
|
|
10
|
+
raise ArgumentError, "observation is too large" if File.size(path) > max_bytes
|
|
11
|
+
|
|
12
|
+
observation = JSON.parse(File.read(path))
|
|
13
|
+
unless observation.is_a?(Hash) && observation["provenance"] == "observed" && observation["calls"].is_a?(Array)
|
|
14
|
+
raise ArgumentError, "invalid observation"
|
|
15
|
+
end
|
|
16
|
+
raise ArgumentError, "truncated observation requires explicit subjects" if observation["truncated"]
|
|
17
|
+
unless observation["calls"].all? { |row| row.is_a?(Hash) && row["subject"].is_a?(String) }
|
|
18
|
+
raise ArgumentError, "observation subjects must be strings"
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
observation["calls"].map { |row| row["subject"] }
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
def from_plan(root, id, settings: {})
|
|
25
|
+
plan = Graph::Plan.new(root, id, settings: settings)
|
|
26
|
+
plan.verify_originals!
|
|
27
|
+
plan.metadata.fetch("pre_hashes").keys.flat_map do |relative|
|
|
28
|
+
original = File.binread(File.join(root, relative))
|
|
29
|
+
staged = File.binread(File.join(plan.tree, relative))
|
|
30
|
+
next [] if original == staged
|
|
31
|
+
|
|
32
|
+
before = definitions(original)
|
|
33
|
+
after = definitions(staged)
|
|
34
|
+
(before.keys | after.keys).select { |subject| before[subject] != after[subject] }
|
|
35
|
+
end.uniq.sort
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
def definitions(source)
|
|
39
|
+
parsed = Prism.parse(source)
|
|
40
|
+
raise ArgumentError, "cannot select subjects from invalid Ruby" if parsed.failure?
|
|
41
|
+
|
|
42
|
+
result = {}
|
|
43
|
+
walk(parsed.value, [], false, result)
|
|
44
|
+
result
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
def walk(node, owners, singleton, result)
|
|
48
|
+
if node.is_a?(Prism::ClassNode) || node.is_a?(Prism::ModuleNode)
|
|
49
|
+
owners = scope_owners(node, owners)
|
|
50
|
+
singleton = false
|
|
51
|
+
elsif node.is_a?(Prism::SingletonClassNode)
|
|
52
|
+
raise ArgumentError, "only self singleton classes support subject selection" unless node.expression.is_a?(Prism::SelfNode)
|
|
53
|
+
|
|
54
|
+
singleton = true
|
|
55
|
+
elsif node.is_a?(Prism::DefNode)
|
|
56
|
+
add_definition(node, owners, singleton, result)
|
|
57
|
+
return
|
|
58
|
+
end
|
|
59
|
+
node.compact_child_nodes.each { |child| walk(child, owners, singleton, result) }
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
def scope_owners(node, owners)
|
|
63
|
+
name = node.constant_path.full_name
|
|
64
|
+
if !owners.empty? && name.include?("::") && !name.start_with?("::")
|
|
65
|
+
raise ArgumentError, "qualified nested owners require explicit mutation subjects"
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
name.start_with?("::") ? [name.delete_prefix("::")] : owners + [name]
|
|
69
|
+
rescue Prism::ConstantPathNode::DynamicPartsInConstantPathError
|
|
70
|
+
raise ArgumentError, "dynamic constant owners require explicit mutation subjects"
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
def add_definition(node, owners, singleton, result)
|
|
74
|
+
raise ArgumentError, "top-level methods require explicit mutation subjects" if owners.empty?
|
|
75
|
+
if node.receiver && !node.receiver.is_a?(Prism::SelfNode)
|
|
76
|
+
raise ArgumentError, "dynamic method owners require explicit mutation subjects"
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
separator = (singleton || node.receiver) ? "." : "#"
|
|
80
|
+
subject = "#{owners.join("::")}#{separator}#{node.name}"
|
|
81
|
+
raise ArgumentError, "redefined methods require explicit mutation subjects" if result.key?(subject)
|
|
82
|
+
|
|
83
|
+
result[subject] = node.location.slice
|
|
84
|
+
end
|
|
85
|
+
private_class_method :definitions, :walk, :scope_owners, :add_definition
|
|
86
|
+
end
|
|
87
|
+
end
|
|
88
|
+
end
|
|
@@ -24,6 +24,11 @@ module Polyrun
|
|
|
24
24
|
#
|
|
25
25
|
# @return [Array(Process::Status, String, String)] status, stdout capture, stderr capture
|
|
26
26
|
def spawn_wait(env, *argv, chdir: nil, silent: false)
|
|
27
|
+
if chdir && RUBY_ENGINE == "jruby"
|
|
28
|
+
# JRuby's shell launch can continue after its chdir fails.
|
|
29
|
+
argv = ["/bin/sh", "-c", 'cd -- "$1" && shift && exec "$@"', "polyrun", chdir, *argv]
|
|
30
|
+
chdir = nil
|
|
31
|
+
end
|
|
27
32
|
args = spawn_argv(env, *argv)
|
|
28
33
|
return spawn_wait_inherit(args, chdir) unless silent
|
|
29
34
|
|
|
@@ -71,20 +76,20 @@ module Polyrun
|
|
|
71
76
|
if st.success?
|
|
72
77
|
[st, "", ""]
|
|
73
78
|
else
|
|
74
|
-
|
|
75
|
-
err = File.binread(err_path)
|
|
76
|
-
[st, truncate_failure_capture(out), truncate_failure_capture(err)]
|
|
79
|
+
[st, read_failure_capture(out_path), read_failure_capture(err_path)]
|
|
77
80
|
end
|
|
78
81
|
end
|
|
79
82
|
end
|
|
80
83
|
end
|
|
81
84
|
|
|
82
|
-
def
|
|
83
|
-
|
|
84
|
-
|
|
85
|
+
def read_failure_capture(path)
|
|
86
|
+
File.open(path, "rb") do |capture|
|
|
87
|
+
size = capture.size
|
|
88
|
+
return capture.read(MAX_FAILURE_CAPTURE_BYTES).to_s if size <= MAX_FAILURE_CAPTURE_BYTES
|
|
85
89
|
|
|
86
|
-
|
|
87
|
-
|
|
90
|
+
capture.seek(size - MAX_FAILURE_CAPTURE_BYTES)
|
|
91
|
+
"... (#{size} bytes total; showing last #{MAX_FAILURE_CAPTURE_BYTES} bytes)\n" + capture.read(MAX_FAILURE_CAPTURE_BYTES).to_s
|
|
92
|
+
end
|
|
88
93
|
end
|
|
89
94
|
end
|
|
90
95
|
end
|