pbt 0.8.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.
@@ -0,0 +1,295 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "pbt/arbitrary/sample"
4
+ require "pbt/stateful/errors"
5
+ require "pbt/stateful/types"
6
+
7
+ module Pbt
8
+ module Stateful
9
+ # Per-failure shrink session sharing deduplication state and attempt budget across shrink passes.
10
+ class ShrinkSession
11
+ attr_reader :attempts, :max_attempts
12
+
13
+ def initialize(max_attempts:)
14
+ @max_attempts = max_attempts
15
+ @attempts = 0
16
+ @seen = {}
17
+ end
18
+
19
+ def exhausted?
20
+ @attempts >= @max_attempts
21
+ end
22
+
23
+ def seen?(run)
24
+ @seen.key?(run)
25
+ end
26
+
27
+ def mark_seen(run)
28
+ @seen[run] = true
29
+ end
30
+
31
+ def consume_attempt!
32
+ @attempts += 1
33
+ end
34
+ end
35
+
36
+ # Internal provenance wrapper carrying a pure `Run` alongside contextual `Sample` shrink trees.
37
+ class RunSample < Pbt::Arbitrary::Sample
38
+ attr_reader :initial_state_sample, :step_samples, :session
39
+
40
+ def initialize(run, initial_state_sample:, step_samples:, session:)
41
+ @initial_state_sample = initial_state_sample
42
+ @step_samples = step_samples
43
+ @session = session
44
+ super(run) { [].each }
45
+ end
46
+
47
+ def run
48
+ value
49
+ end
50
+ end
51
+
52
+ # Best-first stateful shrinker with offline 6-step model validation, deduplication, and attempt budget.
53
+ class Shrinker
54
+ def initialize(spec)
55
+ @spec = spec
56
+ end
57
+
58
+ # Build a lazy Enumerator of valid shrunk `RunSample` candidates for `run_sample`.
59
+ #
60
+ # @param run_sample [RunSample]
61
+ # @param failure [Exception, nil]
62
+ # @return [Enumerator<RunSample>]
63
+ def shrink(run_sample, failure:)
64
+ run = run_sample.run
65
+ session = run_sample.session
66
+ session.mark_seen(run)
67
+
68
+ Enumerator.new do |y|
69
+ next if session.exhausted?
70
+
71
+ # Stage 1: Immediate post-failure truncation.
72
+ if failure.is_a?(StepFailure)
73
+ truncated_steps = post_failure_truncation(run.steps, failure)
74
+ if truncated_steps
75
+ candidate = Run.new(initial_state: run.initial_state, steps: truncated_steps.freeze)
76
+ status = emit_candidate(
77
+ y,
78
+ candidate,
79
+ session: session,
80
+ initial_state_sample: run_sample.initial_state_sample,
81
+ step_samples: run_sample.step_samples,
82
+ validate: false
83
+ )
84
+ next if status == :exhausted
85
+ end
86
+ end
87
+
88
+ # Stage 2: Chunk deletions (ddmin-style, back to front).
89
+ next if shrink_by_chunk_deletions(y, run_sample, session) == :exhausted
90
+
91
+ # Stage 3: Single-step deletions (back to front).
92
+ next if shrink_by_single_deletions(y, run_sample, session) == :exhausted
93
+
94
+ # Stage 4: Initial state shrinking (when initial_state is an Arbitrary).
95
+ next if shrink_initial_state(y, run_sample, session) == :exhausted
96
+
97
+ # Stage 5: Step argument shrinking (step 0..n-1).
98
+ shrink_step_arguments(y, run_sample, session)
99
+ end
100
+ end
101
+
102
+ # Validate a candidate run purely against the model without touching the SUT.
103
+ #
104
+ # @param run [Run]
105
+ # @return [Boolean]
106
+ def valid_run?(run)
107
+ state = Resolver.deep_freeze(run.initial_state)
108
+ available_ids = Set.new
109
+
110
+ run.steps.each do |step|
111
+ ref_ids = Resolver.collect_ref_ids(step.args)
112
+ return false unless ref_ids.all? { |id| available_ids.include?(id) }
113
+
114
+ command = @spec.command_by_name(step.command)
115
+ return false unless command.guard?(state)
116
+
117
+ arb =
118
+ begin
119
+ command.arguments_for(state)
120
+ rescue Pbt::Arbitrary::EmptyDomainError
121
+ return false
122
+ end
123
+
124
+ return false if Pbt::Arbitrary::Arbitrary.cover_result(arb, step.args) == false
125
+ return false unless command.precondition?(state, step.args)
126
+
127
+ state = command.next_state(state, step.args, Ref.new(step_id: step.id))
128
+ available_ids << step.id
129
+ end
130
+
131
+ true
132
+ end
133
+
134
+ private
135
+
136
+ def post_failure_truncation(steps, failure)
137
+ if failure.step_index.is_a?(Integer) && failure.step_index < steps.length - 1
138
+ steps[0..failure.step_index]
139
+ elsif failure.step_index.nil? && (failure.stage == :invariant || failure.stage == :sut) && !steps.empty?
140
+ []
141
+ end
142
+ end
143
+
144
+ def shrink_by_chunk_deletions(y, run_sample, session)
145
+ run = run_sample.run
146
+ steps = run.steps
147
+ n = steps.length
148
+ chunk_size = n / 2
149
+
150
+ while chunk_size >= 2
151
+ chunk_starts(n, chunk_size).each do |start|
152
+ kept = steps[0...start] + steps[(start + chunk_size)..]
153
+ candidate = Run.new(initial_state: run.initial_state, steps: kept.freeze)
154
+ status = emit_candidate(
155
+ y,
156
+ candidate,
157
+ session: session,
158
+ initial_state_sample: run_sample.initial_state_sample,
159
+ step_samples: run_sample.step_samples
160
+ )
161
+ return :exhausted if status == :exhausted
162
+ end
163
+ chunk_size /= 2
164
+ end
165
+
166
+ :ok
167
+ end
168
+
169
+ def chunk_starts(length, chunk_size)
170
+ starts = []
171
+ pos = length - chunk_size
172
+ while pos >= 0
173
+ starts << pos
174
+ pos -= chunk_size
175
+ end
176
+ starts << 0 unless starts.last == 0
177
+ starts
178
+ end
179
+
180
+ def shrink_by_single_deletions(y, run_sample, session)
181
+ run = run_sample.run
182
+ steps = run.steps
183
+ (steps.length - 1).downto(0) do |idx|
184
+ kept = steps[0...idx] + steps[(idx + 1)..]
185
+ candidate = Run.new(initial_state: run.initial_state, steps: kept.freeze)
186
+ status = emit_candidate(
187
+ y,
188
+ candidate,
189
+ session: session,
190
+ initial_state_sample: run_sample.initial_state_sample,
191
+ step_samples: run_sample.step_samples
192
+ )
193
+ return :exhausted if status == :exhausted
194
+ end
195
+
196
+ :ok
197
+ end
198
+
199
+ def shrink_initial_state(y, run_sample, session)
200
+ initial_sample = run_sample.initial_state_sample
201
+ return :ok unless initial_sample
202
+
203
+ run = run_sample.run
204
+ initial_sample.shrink.each do |child_sample|
205
+ frozen_state = Resolver.deep_freeze(Resolver.deep_dup(child_sample.value))
206
+ candidate = Run.new(initial_state: frozen_state, steps: run.steps)
207
+ status = emit_candidate(
208
+ y,
209
+ candidate,
210
+ session: session,
211
+ initial_state_sample: child_sample,
212
+ step_samples: run_sample.step_samples
213
+ )
214
+ return :exhausted if status == :exhausted
215
+ end
216
+
217
+ :ok
218
+ end
219
+
220
+ def shrink_step_arguments(y, run_sample, session)
221
+ run = run_sample.run
222
+ steps = run.steps
223
+ step_samples = run_sample.step_samples
224
+ state = run.initial_state
225
+
226
+ steps.each_with_index do |step, idx|
227
+ command = @spec.command_by_name(step.command)
228
+ step_sample = step_samples[step.id]
229
+
230
+ if step_sample
231
+ step_sample.shrink.each do |child_sample|
232
+ frozen_arg = Resolver.deep_freeze(Resolver.deep_dup(child_sample.value))
233
+ new_step = Step.new(id: step.id, command: step.command, args: frozen_arg)
234
+ new_steps = steps.dup
235
+ new_steps[idx] = new_step
236
+ candidate = Run.new(initial_state: run.initial_state, steps: new_steps.freeze)
237
+ status = emit_candidate(
238
+ y,
239
+ candidate,
240
+ session: session,
241
+ initial_state_sample: run_sample.initial_state_sample,
242
+ step_samples: step_samples.merge(step.id => child_sample)
243
+ )
244
+ return :exhausted if status == :exhausted
245
+ end
246
+ else
247
+ arb =
248
+ begin
249
+ command.arguments_for(state)
250
+ rescue Pbt::Arbitrary::EmptyDomainError
251
+ nil
252
+ end
253
+ arb&.shrink(step.args)&.each do |shrunk_arg|
254
+ frozen_arg = Resolver.deep_freeze(Resolver.deep_dup(shrunk_arg))
255
+ new_step = Step.new(id: step.id, command: step.command, args: frozen_arg)
256
+ new_steps = steps.dup
257
+ new_steps[idx] = new_step
258
+ candidate = Run.new(initial_state: run.initial_state, steps: new_steps.freeze)
259
+ status = emit_candidate(
260
+ y,
261
+ candidate,
262
+ session: session,
263
+ initial_state_sample: run_sample.initial_state_sample,
264
+ step_samples: step_samples
265
+ )
266
+ return :exhausted if status == :exhausted
267
+ end
268
+ end
269
+
270
+ state = command.next_state(state, step.args, Ref.new(step_id: step.id))
271
+ end
272
+
273
+ :ok
274
+ end
275
+
276
+ def emit_candidate(y, candidate, session:, initial_state_sample:, step_samples:, validate: true)
277
+ return :exhausted if session.exhausted?
278
+ return :duplicate if session.seen?(candidate)
279
+
280
+ session.mark_seen(candidate)
281
+ session.consume_attempt!
282
+
283
+ return :invalid if validate && !valid_run?(candidate)
284
+
285
+ y << RunSample.new(
286
+ candidate,
287
+ initial_state_sample: initial_state_sample,
288
+ step_samples: step_samples,
289
+ session: session
290
+ )
291
+ :emitted
292
+ end
293
+ end
294
+ end
295
+ end
@@ -0,0 +1,299 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "pbt/stateful/errors"
4
+ require "pbt/stateful/types"
5
+ require "pbt/stateful/command"
6
+
7
+ module Pbt
8
+ module Stateful
9
+ Invariant = Data.define(:name, :block)
10
+
11
+ # Immutable stateful model specification built by `SpecBuilder`.
12
+ class Spec
13
+ attr_reader :commands, :invariants
14
+
15
+ def initialize(initial_state_kind:, initial_state_source:, lifecycle:, commands:, invariants:)
16
+ @initial_state_kind = initial_state_kind
17
+ @initial_state_source = initial_state_source
18
+ @lifecycle = lifecycle
19
+ @commands = commands.freeze
20
+ @commands_by_name = commands.each_with_object({}) { |cmd, h| h[cmd.name] = cmd }.freeze
21
+ @invariants = invariants.freeze
22
+ end
23
+
24
+ def arbitrary_initial_state?
25
+ @initial_state_kind == :arbitrary
26
+ end
27
+
28
+ # Resolve initial state, returning `[frozen_value, sample_or_nil]`.
29
+ #
30
+ # @param rng [Random]
31
+ # @return [Array(Object, Pbt::Arbitrary::Sample, nil)]
32
+ def sample_initial_state(rng)
33
+ case @initial_state_kind
34
+ when :arbitrary
35
+ sample = Pbt::Arbitrary::Sample.capture(@initial_state_source, rng)
36
+ [Resolver.deep_freeze(Resolver.deep_dup(sample.value)), sample]
37
+ when :block
38
+ value =
39
+ begin
40
+ @initial_state_source.call
41
+ rescue *Check::FATAL_EXCEPTIONS, Pbt::Arbitrary::EmptyDomainError, Pbt::Arbitrary::FilterExhaustedError
42
+ raise
43
+ rescue Exception => e # standard:disable Lint/RescueException
44
+ err = ModelError.new("initial_state raised #{e.class}: #{e.message}")
45
+ err.set_backtrace(e.backtrace) if e.backtrace
46
+ raise err
47
+ end
48
+ [Resolver.deep_freeze(value), nil]
49
+ else
50
+ [Resolver.deep_freeze(Resolver.deep_dup(@initial_state_source)), nil]
51
+ end
52
+ end
53
+
54
+ # @param name [Symbol]
55
+ # @return [Command]
56
+ def command_by_name(name)
57
+ @commands_by_name.fetch(name)
58
+ rescue KeyError
59
+ raise InvalidSpec, "unknown stateful command: #{name.inspect}"
60
+ end
61
+
62
+ # Execute `body` with a freshly initialized SUT, guaranteeing teardown/around cleanup.
63
+ #
64
+ # @param initial_state [Object]
65
+ # @yieldparam sut [Object]
66
+ # @return [void]
67
+ def with_sut(initial_state, &body)
68
+ @lifecycle.call(initial_state, body)
69
+ end
70
+ end
71
+
72
+ # Yield-builder for defining a stateful property specification.
73
+ class SpecBuilder
74
+ UNSET = Object.new.freeze
75
+ private_constant :UNSET
76
+
77
+ def initialize
78
+ @initial_state_kind = :constant
79
+ @initial_state_source = nil
80
+ @initial_state_defined = false
81
+ @sut_block = nil
82
+ @teardown_block = nil
83
+ @around_block = nil
84
+ @commands = []
85
+ @command_names = {}
86
+ @invariants = []
87
+ end
88
+
89
+ def initial_state(value = UNSET, &block)
90
+ raise InvalidSpec, "initial_state already defined" if @initial_state_defined
91
+
92
+ if block && !value.equal?(UNSET)
93
+ raise InvalidSpec, "initial_state accepts either a value/arbitrary or a block, not both"
94
+ end
95
+
96
+ if block
97
+ @initial_state_kind = :block
98
+ @initial_state_source = block
99
+ elsif !value.equal?(UNSET)
100
+ if Resolver.arbitrary?(value)
101
+ @initial_state_kind = :arbitrary
102
+ @initial_state_source = value
103
+ else
104
+ @initial_state_kind = :constant
105
+ @initial_state_source = value
106
+ end
107
+ else
108
+ raise InvalidSpec, "initial_state requires a value, an arbitrary, or a block"
109
+ end
110
+
111
+ @initial_state_defined = true
112
+ end
113
+
114
+ def sut(&block)
115
+ raise InvalidSpec, "sut requires a block" unless block
116
+ raise InvalidSpec, "sut already defined" if @sut_block
117
+ raise InvalidSpec, "sut cannot be combined with around" if @around_block
118
+
119
+ @sut_block = block
120
+ end
121
+
122
+ def teardown(&block)
123
+ raise InvalidSpec, "teardown requires a block" unless block
124
+ raise InvalidSpec, "teardown already defined" if @teardown_block
125
+ raise InvalidSpec, "teardown cannot be combined with around" if @around_block
126
+
127
+ @teardown_block = block
128
+ end
129
+
130
+ def around(&block)
131
+ raise InvalidSpec, "around requires a block" unless block
132
+ raise InvalidSpec, "around already defined" if @around_block
133
+ raise InvalidSpec, "around cannot be combined with sut or teardown" if @sut_block || @teardown_block
134
+
135
+ @around_block = block
136
+ end
137
+
138
+ def command(name, weight: 1)
139
+ raise InvalidSpec, "command #{name.inspect} requires a block" unless block_given?
140
+
141
+ builder = CommandBuilder.new(name: name, weight: weight)
142
+ yield(builder)
143
+ cmd = builder.build
144
+
145
+ raise InvalidSpec, "duplicate command name: #{cmd.name.inspect}" if @command_names.key?(cmd.name)
146
+
147
+ @command_names[cmd.name] = true
148
+ @commands << cmd
149
+ end
150
+
151
+ def invariant(name = nil, &block)
152
+ raise InvalidSpec, "invariant requires a block" unless block
153
+
154
+ @invariants << Invariant.new(name: name, block: block)
155
+ end
156
+
157
+ def build
158
+ raise InvalidSpec, "stateful spec must define at least one command" if @commands.empty?
159
+ if @teardown_block && !@sut_block
160
+ raise InvalidSpec, "teardown requires sut"
161
+ end
162
+ unless @sut_block || @around_block
163
+ raise InvalidSpec, "stateful spec must define sut or around"
164
+ end
165
+
166
+ Spec.new(
167
+ initial_state_kind: @initial_state_kind,
168
+ initial_state_source: @initial_state_source,
169
+ lifecycle: build_lifecycle,
170
+ commands: @commands,
171
+ invariants: @invariants
172
+ )
173
+ end
174
+
175
+ private
176
+
177
+ def build_lifecycle
178
+ if @around_block
179
+ build_around_lifecycle(@around_block)
180
+ else
181
+ build_sut_teardown_lifecycle(@sut_block, @teardown_block)
182
+ end
183
+ end
184
+
185
+ def build_sut_teardown_lifecycle(sut_block, teardown_block)
186
+ lambda do |initial_state, body|
187
+ sut =
188
+ begin
189
+ Resolver.invoke_with_arity(sut_block, initial_state)
190
+ rescue *Check::FATAL_EXCEPTIONS
191
+ raise
192
+ rescue Exception => e # standard:disable Lint/RescueException
193
+ err = StepFailure.new(
194
+ "sut setup failed: #{e.class}: #{e.message}",
195
+ step_index: nil,
196
+ step: nil,
197
+ stage: :sut,
198
+ target: nil,
199
+ exception_class: e.class
200
+ )
201
+ err.set_backtrace(e.backtrace) if e.backtrace
202
+ raise err
203
+ end
204
+
205
+ propagating_error = nil
206
+ begin
207
+ body.call(sut)
208
+ rescue Exception => e # standard:disable Lint/RescueException
209
+ propagating_error = e
210
+ raise
211
+ ensure
212
+ if teardown_block
213
+ begin
214
+ Resolver.invoke_with_arity(teardown_block, sut)
215
+ rescue *Check::FATAL_EXCEPTIONS
216
+ raise
217
+ rescue Exception => teardown_err # standard:disable Lint/RescueException
218
+ if propagating_error.is_a?(StepFailure)
219
+ propagating_error.attach_teardown_error(teardown_err)
220
+ elsif propagating_error.nil? || propagating_error.is_a?(PreconditionNotMet)
221
+ err = StepFailure.new(
222
+ "teardown failed: #{teardown_err.class}: #{teardown_err.message}",
223
+ step_index: nil,
224
+ step: nil,
225
+ stage: :teardown,
226
+ target: nil,
227
+ exception_class: teardown_err.class,
228
+ teardown_error: teardown_err
229
+ )
230
+ err.set_backtrace(teardown_err.backtrace) if teardown_err.backtrace
231
+ raise err
232
+ end
233
+ end
234
+ end
235
+ end
236
+ end
237
+ end
238
+
239
+ def build_around_lifecycle(around_block)
240
+ lambda do |initial_state, body|
241
+ call_count = 0
242
+ completed = false
243
+ propagating_error = nil
244
+
245
+ run = lambda do |sut|
246
+ call_count += 1
247
+ if call_count > 1
248
+ raise InvalidSpec, "around must call run exactly once (called #{call_count} times)"
249
+ end
250
+
251
+ begin
252
+ body.call(sut)
253
+ completed = true
254
+ rescue Exception => e # standard:disable Lint/RescueException
255
+ propagating_error = e
256
+ raise
257
+ end
258
+ end
259
+
260
+ begin
261
+ Resolver.invoke_with_arity(around_block, initial_state, run)
262
+ rescue StepFailure, InvalidSpec, ModelError, PreconditionNotMet, *Check::FATAL_EXCEPTIONS
263
+ raise
264
+ rescue Exception => e # standard:disable Lint/RescueException
265
+ if propagating_error.is_a?(StepFailure)
266
+ propagating_error.attach_teardown_error(e)
267
+ raise propagating_error
268
+ elsif propagating_error && !propagating_error.is_a?(PreconditionNotMet)
269
+ raise propagating_error
270
+ end
271
+
272
+ stage = (call_count == 0) ? :sut : :teardown
273
+ err = StepFailure.new(
274
+ "#{stage} failed: #{e.class}: #{e.message}",
275
+ step_index: nil,
276
+ step: nil,
277
+ stage: stage,
278
+ target: nil,
279
+ exception_class: e.class,
280
+ teardown_error: (stage == :teardown) ? e : nil
281
+ )
282
+ err.set_backtrace(e.backtrace) if e.backtrace
283
+ raise err
284
+ end
285
+
286
+ if call_count != 1
287
+ raise InvalidSpec, "around must call run exactly once (called #{call_count} times)"
288
+ end
289
+
290
+ raise propagating_error if propagating_error
291
+
292
+ unless completed
293
+ raise InvalidSpec, "around must let run complete before returning"
294
+ end
295
+ end
296
+ end
297
+ end
298
+ end
299
+ end