pbt 0.7.0 → 0.9.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 (54) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +23 -0
  3. data/README.md +117 -80
  4. data/lib/pbt/arbitrary/arbitrary.rb +63 -10
  5. data/lib/pbt/arbitrary/arbitrary_methods.rb +51 -24
  6. data/lib/pbt/arbitrary/array_arbitrary.rb +45 -11
  7. data/lib/pbt/arbitrary/choose_arbitrary.rb +27 -0
  8. data/lib/pbt/arbitrary/constant.rb +0 -1
  9. data/lib/pbt/arbitrary/constant_arbitrary.rb +5 -0
  10. data/lib/pbt/arbitrary/constant_from_arbitrary.rb +39 -0
  11. data/lib/pbt/arbitrary/filter_arbitrary.rb +40 -2
  12. data/lib/pbt/arbitrary/fixed_hash_arbitrary.rb +16 -0
  13. data/lib/pbt/arbitrary/float_arbitrary.rb +31 -0
  14. data/lib/pbt/arbitrary/frequency_arbitrary.rb +61 -0
  15. data/lib/pbt/arbitrary/integer_arbitrary.rb +11 -0
  16. data/lib/pbt/arbitrary/map_arbitrary.rb +40 -2
  17. data/lib/pbt/arbitrary/one_of_arbitrary.rb +46 -13
  18. data/lib/pbt/arbitrary/sample.rb +97 -0
  19. data/lib/pbt/arbitrary/tuple_arbitrary.rb +22 -0
  20. data/lib/pbt/check/case.rb +1 -1
  21. data/lib/pbt/check/configuration.rb +5 -3
  22. data/lib/pbt/check/property.rb +23 -4
  23. data/lib/pbt/check/runner_iterator.rb +84 -10
  24. data/lib/pbt/check/runner_methods.rb +53 -19
  25. data/lib/pbt/check/tosser.rb +1 -1
  26. data/lib/pbt/reporter/run_details.rb +2 -2
  27. data/lib/pbt/reporter/run_details_reporter.rb +46 -4
  28. data/lib/pbt/reporter/run_execution.rb +47 -4
  29. data/lib/pbt/stateful/command.rb +215 -0
  30. data/lib/pbt/stateful/errors.rb +58 -0
  31. data/lib/pbt/stateful/property.rb +276 -276
  32. data/lib/pbt/stateful/shrinker.rb +295 -0
  33. data/lib/pbt/stateful/spec.rb +299 -0
  34. data/lib/pbt/stateful/types.rb +308 -0
  35. data/lib/pbt/statistics.rb +28 -0
  36. data/lib/pbt/version.rb +1 -1
  37. data/lib/pbt.rb +62 -26
  38. data/sig/manifest.yaml +2 -0
  39. data/sig/pbt/arbitrary.rbs +139 -0
  40. data/sig/pbt/check.rbs +74 -0
  41. data/sig/pbt/reporter.rbs +44 -0
  42. data/sig/pbt/stateful.rbs +241 -0
  43. data/sig/pbt.rbs +40 -1
  44. metadata +18 -13
  45. data/.rspec +0 -3
  46. data/.standard.yml +0 -3
  47. data/CLAUDE.md +0 -104
  48. data/Rakefile +0 -70
  49. data/benchmark/README.md +0 -103
  50. data/benchmark/example.txt +0 -299
  51. data/benchmark/failure_simple.rb +0 -29
  52. data/benchmark/success_cpu_bound.rb +0 -35
  53. data/benchmark/success_io_bound.rb +0 -28
  54. data/benchmark/success_simple.rb +0 -24
@@ -1,357 +1,357 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "pbt/stateful/errors"
4
+ require "pbt/stateful/types"
5
+ require "pbt/stateful/command"
6
+ require "pbt/stateful/spec"
7
+ require "pbt/stateful/shrinker"
8
+
3
9
  module Pbt
4
10
  module Stateful
5
- # Property-compatible wrapper for command-based stateful testing.
6
- # It provides `generate`, `shrink` and `run`, so existing runners can execute it.
11
+ # Property-compatible stateful test driver backing `Pbt.stateful { |m| ... }`.
7
12
  class Property
8
- ARG_AWARE_GENERATION_ATTEMPTS = 5
9
-
10
- REQUIRED_COMMAND_METHODS = %i[
11
- name
12
- arguments
13
- applicable?
14
- next_state
15
- run!
16
- verify!
17
- ].freeze
18
-
19
- Step = Struct.new(:command, :args, keyword_init: true) do
20
- def inspect
21
- "#<Pbt::Stateful::Step command=#{command_label}, args=#{args.inspect}>"
22
- end
13
+ PER_STEP_MAX_ATTEMPTS = 32
14
+ private_constant :PER_STEP_MAX_ATTEMPTS
23
15
 
24
- private
16
+ attr_reader :spec, :max_steps, :min_steps, :max_shrink_attempts
25
17
 
26
- def command_label
27
- if command.respond_to?(:name)
28
- command.name.inspect
29
- else
30
- command.class.name || command.class.inspect
31
- end
32
- end
33
- end
34
-
35
- # @param model [Object]
36
- # @param sut [Proc]
18
+ # @param spec [Spec]
37
19
  # @param max_steps [Integer]
38
- def initialize(model:, sut:, max_steps:)
39
- validate_model!(model)
40
- raise Pbt::InvalidConfiguration, "sut must be callable" unless sut.respond_to?(:call)
41
- raise Pbt::InvalidConfiguration, "max_steps must be an Integer" unless max_steps.is_a?(Integer)
42
- raise Pbt::InvalidConfiguration, "max_steps must be non-negative" if max_steps.negative?
43
-
44
- @model = model
45
- @sut_factory = sut
20
+ # @param min_steps [Integer]
21
+ # @param max_shrink_attempts [Integer]
22
+ def initialize(spec:, max_steps: 20, min_steps: 1, max_shrink_attempts: 1_000)
23
+ validate_options!(max_steps: max_steps, min_steps: min_steps, max_shrink_attempts: max_shrink_attempts)
24
+
25
+ @spec = spec
46
26
  @max_steps = max_steps
27
+ @min_steps = min_steps
28
+ @max_shrink_attempts = max_shrink_attempts
29
+ @shrinker = Shrinker.new(spec)
47
30
  end
48
31
 
49
- # Generate a sequence of commands valid for the current model state.
32
+ def stateful?
33
+ true
34
+ end
35
+
36
+ # Generate a pure immutable `Pbt::Stateful::Run` (compatible with `Pbt.statistics`).
50
37
  #
51
38
  # @param rng [Random]
52
- # @return [Array<Step>]
39
+ # @return [Run]
53
40
  def generate(rng = Random.new)
54
- length = rng.rand(0..@max_steps)
55
- state = @model.initial_state
56
- sequence = []
41
+ generate_for_check(rng).value
42
+ end
57
43
 
58
- length.times do
59
- candidates = generate_candidates_for(state, rng, context: "generate")
60
- break if candidates.empty?
44
+ # Generate a `RunSample` carrying contextual shrink provenance for `Pbt.check` / `Pbt.assert`.
45
+ #
46
+ # @param rng [Random]
47
+ # @return [RunSample]
48
+ def generate_for_check(rng = Random.new)
49
+ target_length = (@min_steps == @max_steps) ? @min_steps : rng.rand(@min_steps..@max_steps)
50
+ initial_state, initial_state_sample, initial_eligible = draw_initial_state(rng, target_length)
51
+
52
+ state = initial_state
53
+ steps = []
54
+ step_samples = {}
55
+ next_id = 0
56
+
57
+ target_length.times do |step_index|
58
+ eligible = (step_index == 0) ? initial_eligible : eligible_commands(state)
59
+ break if eligible.empty?
60
+
61
+ selected = select_step(eligible, state, step_index, next_id, rng)
62
+ if selected.nil?
63
+ break unless steps.empty?
64
+
65
+ raise GenerationError,
66
+ "all eligible commands produced empty argument domains at step #{step_index} " \
67
+ "(eligible: #{eligible.map(&:name).inspect})"
68
+ end
61
69
 
62
- command, args = candidates[rng.rand(candidates.length)]
63
- sequence << Step.new(command:, args:)
64
- state = command.next_state(state, args)
70
+ step, sample, next_state = selected
71
+ next_id += 1
72
+ steps << step
73
+ step_samples[step.id] = sample
74
+ state = next_state
65
75
  end
66
76
 
67
- sequence
77
+ run = Run.new(initial_state: initial_state, steps: steps.freeze)
78
+ RunSample.new(
79
+ run,
80
+ initial_state_sample: initial_state_sample,
81
+ step_samples: step_samples,
82
+ session: ShrinkSession.new(max_attempts: @max_shrink_attempts)
83
+ )
68
84
  end
69
85
 
70
- # Shrink a sequence by trying shorter prefixes first.
86
+ # Execute a `Run` against a fresh SUT with full lifecycle, verification, and invariants.
71
87
  #
72
- # @param sequence [Array<Hash, Step>]
73
- # @return [Enumerator<Array<Hash, Step>>]
74
- def shrink(sequence)
75
- Enumerator.new do |y|
76
- seen = {}
77
- state = @model.initial_state
88
+ # @param run [Run]
89
+ # @return [void]
90
+ def run(run)
91
+ sym_state = Resolver.deep_freeze(Resolver.deep_dup(run.initial_state))
92
+ env = {}
93
+ sut_initial = Resolver.resolve(sym_state, env, detach: true)
78
94
 
79
- (sequence.length - 1).downto(0) do |length|
80
- yield_shrink_candidate(y, seen, sequence.first(length))
81
- end
95
+ @spec.with_sut(sut_initial) do |sut|
96
+ inv_initial = Resolver.resolve(sym_state, env)
97
+ check_invariants!(inv_initial, sut, step_index: nil, step: nil)
98
+
99
+ run.steps.each_with_index do |step, index|
100
+ command = @spec.command_by_name(step.command)
101
+ concrete_args = Resolver.resolve(step.args, env, detach: true)
102
+
103
+ result = execute_stage(stage: :run, target: command.name, step_index: index, step: step) do
104
+ command.run!(sut, concrete_args)
105
+ end
106
+
107
+ after_sym = command.next_state(sym_state, step.args, Ref.new(step_id: step.id))
108
+ env[step.id] = result
82
109
 
83
- sequence.each_with_index do |step, index|
84
- command, args = unpack_step(step)
85
- validate_command_protocol!(command, state:, context: "shrink step #{index}")
86
- break unless applicable?(command, state, args, context: "shrink step #{index}")
110
+ before_concrete = Resolver.resolve(sym_state, env)
111
+ after_concrete = Resolver.resolve(after_sym, env)
112
+ verify_args = Resolver.resolve(step.args, env)
87
113
 
88
- arbitrary_for(command, state, context: "shrink step #{index}").shrink(args).each do |shrunk_args|
89
- candidate = replace_step(sequence, index, command:, args: shrunk_args)
90
- next unless valid_sequence?(candidate)
114
+ context = Context.new(
115
+ step: step,
116
+ before: before_concrete,
117
+ after: after_concrete,
118
+ args: verify_args,
119
+ result: result,
120
+ sut: sut
121
+ )
91
122
 
92
- yield_shrink_candidate(y, seen, candidate)
123
+ execute_stage(stage: :verify, target: command.name, step_index: index, step: step) do
124
+ command.verify!(context)
93
125
  end
94
126
 
95
- state = command.next_state(state, args)
127
+ check_invariants!(after_concrete, sut, step_index: index, step: step)
128
+ sym_state = after_sym
96
129
  end
97
130
  end
98
131
  end
99
132
 
100
- # @return [Boolean]
101
- def stateful?
102
- true
103
- end
104
-
105
- # Stateful properties currently require sequential execution because the model,
106
- # commands and SUT factory are ordinary Ruby objects and are not guaranteed to be
107
- # Ractor-shareable.
133
+ # Deterministically replay a `Pbt::Stateful::Run` (e.g. `details.counterexample`).
108
134
  #
109
- # @param _sequence [Array<Hash, Step>]
110
- # @raise [Pbt::InvalidConfiguration]
111
- def run_in_ractor(_sequence)
112
- raise Pbt::InvalidConfiguration, "Pbt.stateful does not support worker: :ractor yet; use worker: :none"
135
+ # @param run [Run]
136
+ # @return [void]
137
+ def replay(run)
138
+ unless run.is_a?(Run)
139
+ raise ArgumentError, "replay expects a Pbt::Stateful::Run, got #{run.class}"
140
+ end
141
+
142
+ validate_replay_run!(run)
143
+ self.run(run)
113
144
  end
114
145
 
115
- # Run the command sequence against a fresh SUT and verify each step.
146
+ # Determine whether a shrink candidate failure matches the original failure signature.
147
+ # A shrink candidate that introduces a teardown error is always accepted so that `shrink_case`
148
+ # immediately halts shrinking and surfaces the cleanup breakage instead of masking it.
116
149
  #
117
- # @param sequence [Array<Hash, Step>]
118
- # @return [void]
119
- def run(sequence)
120
- state = @model.initial_state
121
- sut = @sut_factory.call
122
-
123
- sequence.each_with_index do |step, index|
124
- command, args = unpack_step(step)
125
- validate_command_protocol!(command, state:, context: "run step #{index}")
150
+ # @param initial_err [Exception]
151
+ # @param candidate_err [Exception]
152
+ # @return [Boolean]
153
+ def same_failure?(initial_err, candidate_err)
154
+ return false unless initial_err.is_a?(StepFailure) && candidate_err.is_a?(StepFailure)
155
+ return false if initial_err.teardown_error
156
+ return true if candidate_err.teardown_error
126
157
 
127
- unless applicable?(command, state, args, context: "run step #{index}")
128
- raise "invalid stateful sequence at step #{index}: #{command_name(command)}"
129
- end
158
+ initial_err.signature == candidate_err.signature
159
+ end
130
160
 
131
- before_state = state
132
-
133
- begin
134
- after_state = command.next_state(before_state, args)
135
- result = command.run!(sut, args)
136
- command.verify!(
137
- before_state:,
138
- after_state:,
139
- args:,
140
- result:,
141
- sut:
161
+ # Shrink a failing runner `Case` while preserving provenance and shared shrink session.
162
+ #
163
+ # @param test_case [Pbt::Check::Case]
164
+ # @return [Enumerator<RunSample>]
165
+ def shrink_case(test_case)
166
+ return [].each if test_case.exception.is_a?(StepFailure) && test_case.exception.teardown_error
167
+
168
+ run_sample =
169
+ if test_case.sample.is_a?(RunSample)
170
+ test_case.sample
171
+ else
172
+ RunSample.new(
173
+ test_case.val,
174
+ initial_state_sample: nil,
175
+ step_samples: {},
176
+ session: ShrinkSession.new(max_attempts: @max_shrink_attempts)
142
177
  )
143
- rescue Exception => e # standard:disable Lint/RescueException:
144
- raise e.class,
145
- "stateful step #{index} (#{command_name(command)}): #{e.message} [args=#{args.inspect}]",
146
- e.backtrace
147
178
  end
148
179
 
149
- state = after_state
150
- end
180
+ @shrinker.shrink(run_sample, failure: test_case.exception)
151
181
  end
152
182
 
153
- private
154
-
155
- # @param step [Hash, Step]
156
- # @return [Array<Object, Object>]
157
- def unpack_step(step)
158
- case step
159
- in Step(command:, args:)
160
- [command, args]
161
- in {command:, args:}
162
- [command, args]
163
- else
164
- raise ArgumentError, "invalid stateful step: #{step.inspect}"
183
+ # Plain-value shrink fallback yielding `Run` objects.
184
+ #
185
+ # @param run [Run]
186
+ # @return [Enumerator<Run>]
187
+ def shrink(run)
188
+ run_sample = RunSample.new(
189
+ run,
190
+ initial_state_sample: nil,
191
+ step_samples: {},
192
+ session: ShrinkSession.new(max_attempts: @max_shrink_attempts)
193
+ )
194
+ Enumerator.new do |y|
195
+ @shrinker.shrink(run_sample, failure: nil).each do |sample|
196
+ y << sample.value
197
+ end
165
198
  end
166
199
  end
167
200
 
168
- # @param command [Object]
169
- # @return [String]
170
- def command_name(command)
171
- command.respond_to?(:name) ? command.name.to_s : (command.class.name || command.class.inspect)
201
+ def run_in_ractor(_run)
202
+ raise Pbt::InvalidConfiguration, "Pbt.stateful does not support worker: :ractor. Use worker: :none instead."
172
203
  end
173
204
 
174
- # @param model [Object]
175
- # @return [void]
176
- def validate_model!(model)
177
- missing_methods = %i[initial_state commands].reject { |method_name| model.respond_to?(method_name) }
178
- return if missing_methods.empty?
205
+ private
179
206
 
180
- raise Pbt::InvalidConfiguration,
181
- "Pbt.stateful model must respond to #{missing_methods.join(", ")}"
207
+ def validate_options!(max_steps:, min_steps:, max_shrink_attempts:)
208
+ unless min_steps.is_a?(Integer) && min_steps >= 0
209
+ raise InvalidSpec, "min_steps must be a non-negative Integer, got #{min_steps.inspect}"
210
+ end
211
+ unless max_steps.is_a?(Integer) && max_steps.positive? && max_steps >= min_steps
212
+ raise InvalidSpec, "max_steps must be a positive Integer >= min_steps (#{min_steps}), got #{max_steps.inspect}"
213
+ end
214
+ unless max_shrink_attempts.is_a?(Integer) && max_shrink_attempts >= 0
215
+ raise InvalidSpec, "max_shrink_attempts must be a non-negative Integer, got #{max_shrink_attempts.inspect}"
216
+ end
182
217
  end
183
218
 
184
- # @param state [Object]
185
- # @param context [String]
186
- # @return [Array<Object>]
187
- def commands_for(state, context:)
188
- commands = @model.commands(state)
219
+ def draw_initial_state(rng, target_length)
220
+ initial_state, initial_state_sample = @spec.sample_initial_state(rng)
221
+ initial_eligible = eligible_commands(initial_state)
189
222
 
190
- unless commands.is_a?(Array)
191
- raise Pbt::InvalidConfiguration,
192
- "Pbt.stateful model.commands(state) must return Array, got #{commands.class} (context=#{context})"
223
+ unless @spec.arbitrary_initial_state?
224
+ if initial_eligible.empty?
225
+ raise InvalidSpec,
226
+ "no command guard is truthy at initial_state #{Resolver.format_value(initial_state)}"
227
+ end
228
+ return [initial_state, initial_state_sample, initial_eligible]
193
229
  end
194
230
 
195
- commands.each { |command| validate_command_protocol!(command, state:, context:) }
196
- commands
197
- end
231
+ return [initial_state, initial_state_sample, initial_eligible] unless initial_eligible.empty?
198
232
 
199
- # @param command [Object]
200
- # @param state [Object]
201
- # @param context [String]
202
- # @return [void]
203
- def validate_command_protocol!(command, state:, context:)
204
- missing_methods = REQUIRED_COMMAND_METHODS.reject { |method_name| command.respond_to?(method_name) }
205
- unless missing_methods.empty?
206
- raise Pbt::InvalidConfiguration,
207
- "Pbt.stateful command protocol mismatch for #{command.class} " \
208
- "(name=#{safe_command_label(command)}, missing: #{missing_methods.join(", ")}, context=#{context})"
233
+ if target_length.zero?
234
+ probe_rng = rng.dup
235
+ PER_STEP_MAX_ATTEMPTS.times do
236
+ probed_state, = @spec.sample_initial_state(probe_rng)
237
+ return [initial_state, initial_state_sample, initial_eligible] unless eligible_commands(probed_state).empty?
238
+ end
239
+ raise GenerationError,
240
+ "no command guard was truthy across #{PER_STEP_MAX_ATTEMPTS} initial_state samples"
209
241
  end
210
- end
211
242
 
212
- # @param command [Object]
213
- # @param arguments [Object]
214
- # @param context [String]
215
- # @return [void]
216
- def validate_arguments_protocol!(command, arguments, context:)
217
- missing_methods = %i[generate shrink].reject { |method_name| arguments.respond_to?(method_name) }
218
- return if missing_methods.empty?
243
+ (PER_STEP_MAX_ATTEMPTS - 1).times do
244
+ initial_state, initial_state_sample = @spec.sample_initial_state(rng)
245
+ initial_eligible = eligible_commands(initial_state)
246
+ return [initial_state, initial_state_sample, initial_eligible] unless initial_eligible.empty?
247
+ end
219
248
 
220
- raise Pbt::InvalidConfiguration,
221
- "Pbt.stateful command arguments protocol mismatch for #{command.class} " \
222
- "(name=#{safe_command_label(command)}, missing: #{missing_methods.join(", ")}, context=#{context})"
249
+ raise GenerationError,
250
+ "no command guard was truthy across #{PER_STEP_MAX_ATTEMPTS} initial_state samples"
223
251
  end
224
252
 
225
- # @param command [Object]
226
- # @return [String]
227
- def safe_command_label(command)
228
- command.respond_to?(:name) ? command.name.inspect : "<unknown>"
253
+ def validate_replay_run!(run)
254
+ available_ids = Set.new
255
+ run.steps.each_with_index do |step, index|
256
+ @spec.command_by_name(step.command)
257
+ ref_ids = Resolver.collect_ref_ids(step.args)
258
+ unbound = ref_ids.reject { |id| available_ids.include?(id) }
259
+ unless unbound.empty?
260
+ refs_str = unbound.map { |id| "v#{id}" }.join(", ")
261
+ raise InvalidSpec,
262
+ "cannot replay run: unbound Ref #{refs_str} in step #{index + 1} #{step.format}"
263
+ end
264
+ available_ids << step.id
265
+ end
229
266
  end
230
267
 
231
- # @param state [Object]
232
- # @param rng [Random]
233
- # @param context [String]
234
- # @return [Array<Array<Object, Object>>]
235
- def generate_candidates_for(state, rng, context:)
236
- commands_for(state, context:).filter_map do |command|
237
- args = generate_applicable_args(command, state, rng, context:)
238
- next if args.equal?(NoApplicableArgs)
239
-
240
- [command, args]
241
- end
268
+ def eligible_commands(state)
269
+ @spec.commands.select { |cmd| cmd.guard?(state) }
242
270
  end
243
271
 
244
- # @param command [Object]
245
- # @param state [Object]
246
- # @param rng [Random]
247
- # @param context [String]
248
- # @return [Object]
249
- def generate_applicable_args(command, state, rng, context:)
250
- arbitrary = arbitrary_for(command, state, context:)
272
+ # Returns `[step, sample, next_state]`, or `nil` if all eligible commands had empty domains.
273
+ # Raises `GenerationError` if eligible commands had non-empty domains but preconditions never passed.
274
+ def select_step(eligible, state, step_index, step_id, rng)
275
+ candidates = eligible.dup
276
+ attempts = 0
277
+
278
+ while attempts < PER_STEP_MAX_ATTEMPTS && !candidates.empty?
279
+ attempts += 1
280
+ command = pick_weighted(candidates, rng)
281
+
282
+ arb =
283
+ begin
284
+ command.arguments_for(state)
285
+ rescue Pbt::Arbitrary::EmptyDomainError
286
+ candidates.delete(command)
287
+ next
288
+ end
251
289
 
252
- ARG_AWARE_GENERATION_ATTEMPTS.times do
253
- args = generate_args_for(command, arbitrary, rng)
254
- return NoApplicableArgs if args.equal?(NoApplicableArgs)
290
+ sample =
291
+ begin
292
+ Pbt::Arbitrary::Sample.capture(arb, rng)
293
+ rescue Pbt::Arbitrary::EmptyDomainError
294
+ candidates.delete(command)
295
+ next
296
+ end
255
297
 
256
- return args if applicable?(command, state, args, context:)
298
+ frozen_args = Resolver.deep_freeze(Resolver.deep_dup(sample.value))
299
+ if command.precondition?(state, frozen_args)
300
+ ref = Ref.new(step_id: step_id)
301
+ next_state = command.next_state(state, frozen_args, ref)
302
+ step = Step.new(id: step_id, command: command.name, args: frozen_args)
303
+ return [step, sample, next_state]
304
+ end
257
305
  end
258
306
 
259
- NoApplicableArgs
260
- end
307
+ return nil if candidates.empty?
261
308
 
262
- # @param command [Object]
263
- # @param state [Object]
264
- # @param context [String]
265
- # @return [Object]
266
- def arguments_for(command, state, context:)
267
- command.arguments(state)
309
+ raise GenerationError,
310
+ "could not satisfy preconditions at step #{step_index} after #{PER_STEP_MAX_ATTEMPTS} attempts " \
311
+ "(eligible: #{eligible.map(&:name).inspect})"
268
312
  end
269
313
 
270
- # @param command [Object]
271
- # @param state [Object]
272
- # @param context [String]
273
- # @return [Object]
274
- def arbitrary_for(command, state, context:)
275
- arguments = arguments_for(command, state, context:)
276
- validate_arguments_protocol!(command, arguments, context:)
277
- arguments
278
- end
314
+ def pick_weighted(commands, rng)
315
+ return commands.first if commands.size == 1
279
316
 
280
- # @param command [Object]
281
- # @param arbitrary [Object]
282
- # @param rng [Random]
283
- # @return [Object]
284
- def generate_args_for(command, arbitrary, rng)
285
- arbitrary.generate(rng)
286
- rescue Pbt::Arbitrary::EmptyDomainError
287
- NoApplicableArgs
288
- end
289
-
290
- # @param command [Object]
291
- # @param state [Object]
292
- # @param args [Object]
293
- # @param context [String]
294
- # @return [Boolean]
295
- def applicable?(command, state, args, context:)
296
- command.applicable?(state, args)
297
- end
298
-
299
- # @param sequence [Array<Hash, Step>]
300
- # @param index [Integer]
301
- # @param command [Object]
302
- # @param args [Object]
303
- # @return [Array<Hash, Step>]
304
- def replace_step(sequence, index, command:, args:)
305
- candidate = sequence.dup
306
- candidate[index] = rebuild_step(sequence[index], command:, args:)
307
- candidate
308
- end
309
-
310
- # @param step [Hash, Step]
311
- # @param command [Object]
312
- # @param args [Object]
313
- # @return [Hash, Step]
314
- def rebuild_step(step, command:, args:)
315
- case step
316
- in Step
317
- Step.new(command:, args:)
318
- in Hash
319
- {command:, args:}
320
- else
321
- raise ArgumentError, "invalid stateful step: #{step.inspect}"
317
+ total = commands.sum(&:weight)
318
+ ticket = rng.rand(total)
319
+ cumulative = 0
320
+ commands.each do |cmd|
321
+ cumulative += cmd.weight
322
+ return cmd if ticket < cumulative
322
323
  end
324
+ commands.last
323
325
  end
324
326
 
325
- # @param sequence [Array<Hash, Step>]
326
- # @return [Boolean]
327
- def valid_sequence?(sequence)
328
- state = @model.initial_state
329
-
330
- sequence.each do |step|
331
- command, args = unpack_step(step)
332
- return false unless applicable?(command, state, args, context: "validate sequence")
333
-
334
- state = command.next_state(state, args)
327
+ def check_invariants!(state, sut, step_index:, step:)
328
+ @spec.invariants.each_with_index do |inv, idx|
329
+ target = inv.name || :"invariant_#{idx}"
330
+ label = inv.name ? "invariant #{inv.name.inspect}" : "invariant"
331
+ execute_stage(stage: :invariant, target: target, target_label: label, step_index: step_index, step: step) do
332
+ Resolver.invoke_with_arity(inv.block, state, sut)
333
+ end
335
334
  end
336
-
337
- true
338
- rescue
339
- false
340
335
  end
341
336
 
342
- # @param y [Enumerator::Yielder]
343
- # @param seen [Hash{Array<Hash, Step> => true}]
344
- # @param candidate [Array<Hash, Step>]
345
- # @return [void]
346
- def yield_shrink_candidate(y, seen, candidate)
347
- return if seen[candidate]
348
-
349
- seen[candidate] = true
350
- y << candidate
337
+ def execute_stage(stage:, target:, step_index:, step:, target_label: nil)
338
+ yield
339
+ rescue *Check::FATAL_EXCEPTIONS, InvalidSpec, ModelError, PreconditionNotMet
340
+ raise
341
+ rescue Exception => e # standard:disable Lint/RescueException
342
+ step_label = step_index ? "step #{step_index + 1} #{step.format}" : "initial"
343
+ label = target_label || stage.to_s
344
+ failure = StepFailure.new(
345
+ "#{step_label} [#{label}]: #{e.message}",
346
+ step_index: step_index,
347
+ step: step,
348
+ stage: stage,
349
+ target: target,
350
+ exception_class: e.class
351
+ )
352
+ failure.set_backtrace(e.backtrace) if e.backtrace
353
+ raise failure
351
354
  end
352
-
353
- NoApplicableArgs = Object.new
354
- private_constant :NoApplicableArgs
355
355
  end
356
356
  end
357
357
  end