quint_driver 0.1.0 → 0.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.
@@ -56,11 +56,14 @@ module QuintDriver
56
56
  # definition has in the trace's state. +ignore+ names variables the
57
57
  # driver does not report, such as what a remote service answers, which
58
58
  # the spec models and the driver only reads to set the system up; the
59
- # driver reports every other variable. Returns the steps it ran, so a
60
- # caller can count the actions and states its traces reached.
61
- def self.replay(path, driver, log: nil, state: [], action: nil, spec: nil, observe: [], ignore: [])
62
- observe, ignore = observe.map(&:to_s), ignore.map(&:to_s)
63
- observed = observed(path, spec, observe)
59
+ # driver reports every other variable. +invariants+ names predicates of
60
+ # +spec+, expectations that have to hold in every state: once the driver
61
+ # agrees at a step, one that is false in that step's state raises
62
+ # Violated. Returns the steps it ran, so a caller can count the actions
63
+ # and states its traces reached.
64
+ def self.replay(path, driver, log: nil, state: [], action: nil, spec: nil, observe: [], ignore: [], invariants: [])
65
+ observe, ignore, invariants = observe.map(&:to_s), ignore.map(&:to_s), invariants.map(&:to_s)
66
+ evaluated = evaluated(path, spec, observe:, invariants:)
64
67
  ran = []
65
68
  steps = steps(path, state:, action:)
66
69
  Agreement.ignorable!(ignore, steps.first.expected.keys, "the trace's state") if steps.any?
@@ -75,29 +78,43 @@ module QuintDriver
75
78
  driver.step(step.action, step.picks)
76
79
  driver.state
77
80
  end
78
- Agreement.check!(at, step.expected.merge(observed[step.index]), actual, by: "trace", steps: ran, observe:, spec:, ignore:)
81
+ values = evaluated[step.index]
82
+ Agreement.check!(at, step.expected.merge(values.slice(*observe)), actual, by: "trace", steps: ran, observe:, spec:, ignore:)
83
+ broken = invariants.reject { values[_1] }
84
+ Agreement.violated!(at, broken, steps: ran, state: variables(path, step.index)) if broken.any?
79
85
  end
80
- rescue Mismatch, StepRaised => failure
86
+ rescue NamedTrace => failure
81
87
  Quint.send(:name_trace, failure, path)
82
88
  raise
83
89
  end
84
90
 
85
- # The value of each definition +observe+ names, in each state of the
86
- # trace. The model reads the state as quint wrote it, so the driver's
87
- # steps never pass through the model; it reads only the spec's variables,
88
- # so the mbt:: entries stay.
89
- def self.observed(path, spec, observe)
90
- return Hash.new({}) if observe.empty?
91
- Agreement.refuse "quint: observe needs spec:, the Spec that evaluates #{observe.join(', ')}" unless spec
91
+ # The value of each definition +observe+ and +invariants+ name, in each
92
+ # state of the trace, so a name refused or one the model cannot
93
+ # evaluate fails before the driver runs a step. The model reads the
94
+ # state as quint wrote it, so the driver's steps never pass through the
95
+ # model; it reads only the spec's variables, so the mbt:: entries stay.
96
+ def self.evaluated(path, spec, observe:, invariants:)
97
+ names = observe | invariants
98
+ return Hash.new({}) if names.empty?
92
99
 
100
+ { "observe" => observe, "invariants" => invariants }.each do |argument, named|
101
+ Agreement.refuse "quint: #{argument} needs spec:, the Spec that evaluates #{named.join(', ')}" if named.any? && !spec
102
+ end
93
103
  spec.observable!(observe)
104
+ spec.predicates!(invariants, "invariants")
94
105
  model = spec.model(nil)
95
106
  JSON.parse(File.read(path)).fetch("states").map do |values|
96
107
  model.enter(decode(values) { |tag, inner| Model::Variant.new(tag, inner) })
97
- model.observe(observe)
108
+ model.observe(names)
98
109
  end
99
110
  end
100
- private_class_method :observed
111
+ private_class_method :evaluated
112
+
113
+ # The spec's variables in state +index+ of the trace, as plain values.
114
+ def self.variables(path, index)
115
+ decode(JSON.parse(File.read(path)).fetch("states").fetch(index)).reject { |name, _| name.start_with?("mbt::") }
116
+ end
117
+ private_class_method :variables
101
118
 
102
119
  # ITF (https://apalache-mc.org/docs/adr/015adr-trace.html) to plain values.
103
120
  # An Option is nil for None and its value for Some, as Model.plain gives one.
@@ -1,3 +1,3 @@
1
1
  module QuintDriver
2
- VERSION = "0.1.0"
2
+ VERSION = "0.2.0"
3
3
  end
data/lib/quint_driver.rb CHANGED
@@ -39,6 +39,25 @@ module QuintDriver
39
39
  include NamedTrace
40
40
  end
41
41
 
42
+ # The system agreed with the spec at every step, and an expectation, a
43
+ # predicate of the spec that invariants: names, does not hold: the spec
44
+ # lets the system reach a state the expectation rules out. That is a bug
45
+ # suspect, not a disagreement, so it is no Mismatch, and a caller that
46
+ # rescues Mismatch does not catch it. The message names the expectation,
47
+ # the steps from init, and the state where it broke.
48
+ class Violated < StandardError
49
+ include NamedTrace
50
+
51
+ # The names of the expectations that broke, and the steps from init, as
52
+ # [action, picks], that reached the state.
53
+ attr_reader :expectations, :steps
54
+
55
+ def initialize(message = nil, expectations: [], steps: [])
56
+ super(message)
57
+ @expectations, @steps = expectations, steps
58
+ end
59
+ end
60
+
42
61
  # A step raised: the driver's code, or the system's beneath it, while it
43
62
  # ran a step or reported its state, so the spec and the system were never
44
63
  # compared. The message names the step, the project's frame that raised,
@@ -84,6 +103,21 @@ module QuintDriver
84
103
  "#{lines.map(&:last).join("\n")}\n#{ran(steps)}", outside(caller_locations)
85
104
  end
86
105
 
106
+ # Raises Violated naming each expectation in +broken+, which is false in
107
+ # +state+, the spec's variables after +after+, once the driver agreed
108
+ # with the spec at each of the [action, picks] +steps+ from init, the
109
+ # last of which is +after+. The state is the spec's, so it holds the
110
+ # variables ignore: names too, which an expectation can read.
111
+ def self.violated!(after, broken, steps:, state:)
112
+ expectations = "#{broken.one? ? 'expectation' : 'expectations'} #{broken.map { "`#{_1}`" }.join(' and ')}"
113
+ variables = state.sort_by(&:first).map { |name, value| " #{name}: #{show(value)}" }
114
+ error = Violated.new("quint: the system agreed with the spec at every step, and the #{expectations} " \
115
+ "#{broken.one? ? 'does' : 'do'} not hold after #{after}\n#{ran(steps)}\nstate:\n#{variables.join("\n")}",
116
+ expectations: broken.dup, steps: steps.map { |action, picks| [ action, picks.dup ] })
117
+ error.set_backtrace(outside(caller_locations))
118
+ raise error
119
+ end
120
+
87
121
  # A name +ignore+ holds that +names+ lacks is refused, so a misspelt name
88
122
  # reads as one rather than as its variable left out.
89
123
  def self.ignorable!(ignore, names, within)
@@ -107,10 +141,10 @@ module QuintDriver
107
141
  # StepRaised with +steps+; the gem's own errors pass through.
108
142
  def self.drive(at, steps:)
109
143
  yield
110
- rescue Mismatch, StepRaised => failure
144
+ rescue NamedTrace => failure
145
+ raise lead_outside(failure)
146
+ rescue Unsupported, QuintFailed => failure
111
147
  raise lead_outside(failure)
112
- rescue Unsupported, QuintFailed
113
- raise
114
148
  rescue StandardError => error
115
149
  raise StepRaised, "quint: at #{at}, the step raised #{error.class}: #{error.message}\n#{raised_in(error)}#{ran(steps)}",
116
150
  outside(error.backtrace_locations || error.backtrace)
@@ -121,9 +155,11 @@ module QuintDriver
121
155
  # the driver's, the system's, or the test's: RSpec hides the frames of an
122
156
  # installed gem, but not of one a Gemfile loads from a path, and Minitest
123
157
  # hides none. Hegel groups the failures it shrinks by the first frame, so
124
- # the frames stay Locations where Ruby can set them, from 3.4 on.
158
+ # the frames stay Locations where Ruby can set them, from 3.4 on. Ruby's
159
+ # own <internal:...> frames go too: on 3.4 a Kernel method written in
160
+ # Ruby, between Hegel's frames and the test's, would lead otherwise.
125
161
  def self.outside(frames)
126
- kept = frames.reject { _1.to_s.start_with?(*@hidden) }
162
+ kept = frames.reject { _1.to_s.start_with?(*@hidden, "<internal:") }
127
163
  kept = frames if kept.empty?
128
164
  RUBY_VERSION >= "3.4" ? kept : kept.map(&:to_s)
129
165
  end
@@ -197,3 +233,7 @@ require_relative "quint_driver/quint"
197
233
  require_relative "quint_driver/trace"
198
234
  require_relative "quint_driver/spec"
199
235
  require_relative "quint_driver/model"
236
+ require_relative "quint_driver/steps"
237
+ require_relative "quint_driver/outline"
238
+ require_relative "quint_driver/hold"
239
+ require_relative "quint_driver/targets"
@@ -1,12 +1,14 @@
1
1
  ---
2
2
  name: quint_driver
3
- description: Use when testing a Ruby system against a Quint spec with the quint_driver gem. Shape the spec so every move names an action, write a driver, replay Quint's traces, check the Ruby model, then let Hegel choose and shrink the steps.
3
+ description: Use when testing a Ruby system against a Quint spec with the quint_driver gem. Shape the spec so every move names an action, write a driver, replay Quint's traces, check the Ruby model, then let Hegel choose and shrink the steps. Also use it to hunt for bugs in a Rails app: write what the operator expects as boolean vals, aim traces at each with violate:, and read QuintDriver::Violated as a bug suspect.
4
4
  ---
5
5
 
6
6
  # quint_driver
7
7
 
8
8
  quint_driver runs a Ruby system the way a Quint spec says and compares the two after every step. You write the spec and a driver. Quint or Hegel chooses the steps. A disagreement raises `QuintDriver::Mismatch` with the steps that reproduce it.
9
9
 
10
+ In a Rails app, take this path: pick code from "Choose a target", write its actions and expectations as "Hunt for bugs" says and shape them by section 1, print a driver to fill with `bundle exec quint_driver outline spec/quint/<name>.qnt` (section 2), write the driver and the example as "In a Rails app with RSpec" shows, then aim `violate:` at each expectation and read each `Violated` as "Hunt for bugs" says.
11
+
10
12
  ## Install
11
13
 
12
14
  ```sh
@@ -32,6 +34,181 @@ curl -sSL https://github.com/quint-co/quint/releases/download/evaluator/v0.7.0/q
32
34
 
33
35
  With that evaluator in place, `Quint.simulate` runs it directly and skips node; the same seed gives the same traces as `quint run`. Set `QUINT_EVALUATOR` to another copy of evaluator v0.7.0, or to an empty string to go through `quint run`.
34
36
 
37
+ ## Choose a target
38
+
39
+ To find bugs, model code where two places must change together and something can go wrong between them:
40
+
41
+ - Several entry points (pages, jobs, API calls) that write the same local table and the same outside service, such as a record and the code a remote controller holds for it.
42
+ - An outside call that can fail or time out, inside or next to a transaction.
43
+ - A job that can raise half-way and run again on retry.
44
+ - A row the code saves and whose return value it does not check, or a record another entry point can delete.
45
+
46
+ `quint_driver targets` lists those places in an app. It reads the source of `app/` and `lib/` (not `spec/` or `test/`), marks each line that matches one kind of place, and ranks the files by how many kinds meet in each, since the bugs sat where several kinds meet:
47
+
48
+ ```sh
49
+ bundle exec quint_driver targets test/fixture/depot --top 3
50
+ ```
51
+
52
+ ```text
53
+ app/jobs/intake_job.rb: retry, outside, unchecked-save, answers-false, transaction, check-then-write
54
+ 6 retry retry_on LockerApi::TimedOut, wait: 1.minute, attempts: 10
55
+ 6 outside retry_on LockerApi::TimedOut, wait: 1.minute, attempts: 10
56
+ 10 unchecked-save row.update(status: assign(row.parcel) ? "done" : "failed")
57
+ 18 answers-false return false unless parcel&.waiting? && compartment
58
+ 20 transaction Parcel.transaction { parcel.assign_to!(compartment) }
59
+ 20 check-then-write Parcel.transaction { parcel.assign_to!(compartment) }
60
+
61
+ app/controllers/assignments_controller.rb: transaction, rescue, outside, check-then-write
62
+ 8 transaction Parcel.transaction do
63
+ 9 check-then-write parcel.assign_to!(compartment)
64
+ 11 rescue rescue LockerApi::TimedOut
65
+ 11 outside rescue LockerApi::TimedOut
66
+
67
+ app/controllers/releases_controller.rb: transaction, rescue, outside
68
+ 7 transaction Parcel.transaction do
69
+ 10 rescue rescue LockerApi::TimedOut
70
+ 10 outside rescue LockerApi::TimedOut
71
+
72
+ 3 more files with fewer kinds; pass --top N to see them.
73
+ ```
74
+
75
+ The depot's four planted bugs sit in these three files. The kinds are `transaction`, `rescue`, `unchecked-save` (a save or update without `!` as a statement), `answers-false` (a method that answers `false` on failure), `dropped-result` (a call, as a statement, of a method with one of the two before it), `skips-callbacks` (`update_all`, `delete_all` and the like), `counter-write`, `retry`, `outside` (an HTTP client, a class named Api or Client, a broadcast, or an error class of the app's own, which is how a service says it can fail), and `check-then-write` (a write after an `if` or `unless` that reads stored state, in a method that takes no lock). Comments, strings and heredocs are skipped. A hit is a line to read, not a bug. A `check-then-write` is where two requests can both pass the check before either writes: split each request into its read and its write with `QuintDriver::Hold`, as "A request another one comes between" shows. When nothing matches, the command says so and names what to read instead; it does not mean a hunt cannot pay. Read the top files and ask of each: which entry points reach it, what do they write, and what can fail between two of the writes. Each answer that names two writes and a failure between them is an action with a pick, and the state after the failure is an expectation.
76
+
77
+ On another test app with four planted bugs, the command listed seven files: six of them hold part of a bug, the seventh is the payment client, and each bug's line where the failure is dropped is a hit. On a real app whose every write goes through one locked aggregate, no file gathered more than three kinds, and the three in the top file were the lock, its version counter and the broadcast after it. When no file brings together a failure (`rescue`, `answers-false`, `retry`, `outside`) and two writes, the hunt pays less: model the aggregate's commands and the promises the README makes about them, or spend the time elsewhere.
78
+
79
+ A status column on one model is a poor first target for a hunt: its transitions sit in one method, a reviewer reads them in a minute, and a spec of them holds no expectation the code could break. It is a good first target to learn the tool on, as the README's Quick start does.
80
+
81
+ ## Hunt for bugs
82
+
83
+ A hunt looks for a state the code reaches and the operator does not expect. Keep the two apart in the spec:
84
+
85
+ 1. Write what the code does now as actions, quirks included. If you think a branch is wrong, model it as it is written. The spec describes the system, so the system follows every trace, and a `Mismatch` means the spec or the driver is wrong, not the app.
86
+ 2. Write what the operator or the owner expects as boolean `val`s. These are the expectations, and the code may break them.
87
+ 3. For each expectation, aim Quint's traces at it with `violate:` and replay them with the same name in `invariants:`. Run the Hegel machine with all of them.
88
+
89
+ `test/fixture/depot` in the quint_driver repository is a small Rails app of parcel lockers with four bugs planted in it. Its `spec/quint/depot.qnt` writes the operator's expectations next to the actions:
90
+
91
+ ```quint
92
+ val taken_compartment_has_live_code = COMPARTMENTS.forall(c => taken(place, c) implies live.contains(c))
93
+ val free_compartment_has_no_code = COMPARTMENTS.forall(c => live.contains(c) implies taken(place, c))
94
+ val done_row_stays_done = everDone.forall(p => row.get(p) == "done")
95
+ val finished_job_leaves_no_row_pending = intake == "finished" implies PARCELS.forall(p => row.get(p) != "pending")
96
+ ```
97
+
98
+ Bugs hide where an outside call fails, so give each action that calls out a pick that says which call fails. The depot's pages call a locker controller, and `offline` names the compartment whose call times out; `OFFLINE` holds every compartment and `0`, so a step may also find every call answered. Name the pick after what fails, such as `offline` or `down` for a yes or no; quint reserves `fail` and refuses it with `Error [QNT101]: Built-in name 'fail' is redefined in module '<name>'`. When an expectation reads whether the call failed, such as "a page answers an error only when the controller timed out", keep the pick in a variable the action assigns, and name that variable in `ignore:`, since the system does not keep it:
99
+
100
+ ```quint
101
+ pure val OFFLINE = COMPARTMENTS.union(Set(0))
102
+ ```
103
+
104
+ ```quint
105
+ action release(p: str, offline: int): bool = {
106
+ val c = match place.get(p) { | In(n) => n | _ => 0 }
107
+ all {
108
+ c != 0,
109
+ place' = place.set(p, Collected),
110
+ live' = if (c == offline) live else live.exclude(Set(c)),
111
+ row' = row, intake' = intake, everDone' = everDone,
112
+ }
113
+ ```
114
+
115
+ The example stubs the outside service with the driver, and the driver fails the call the step picked, so the app's own rescue runs as it would in production:
116
+
117
+ ```ruby
118
+ before do
119
+ allow(LockerApi).to receive(:register) { |number, code| driver.register(number, code) }
120
+ allow(LockerApi).to receive(:revoke) { |number| driver.revoke(number) }
121
+ end
122
+ ```
123
+
124
+ ```ruby
125
+ def register(number, code) = online(number) { @codes[number] = code }
126
+ def revoke(number) = online(number) { @codes.delete(number) }
127
+ ```
128
+
129
+ ```ruby
130
+ def online(number)
131
+ raise LockerApi::TimedOut if number == @offline
132
+
133
+ yield
134
+ end
135
+ ```
136
+
137
+ A failure that is a pick of the action, and not an action of its own, lands inside the step that calls out, which is where a rescue in the wrong place does its harm. When the service stays down across steps, model it as a variable instead, as "A driver for code that calls remote services" does.
138
+
139
+ Its `spec/quint/depot_spec.rb` runs one simulation per expectation, and the Hegel machine with all of them:
140
+
141
+ ```ruby
142
+ expectations.each do |expectation|
143
+ it "keeps #{expectation} on the traces Quint aims at it" do
144
+ simulation = QuintDriver::Quint.simulate(qnt, traces: 200, max_steps: 12, seed: "1", violate: expectation) do |path|
145
+ rolled_back { QuintDriver::Trace.replay(path, driver, spec:, invariants: [ expectation ], ignore:) }
146
+ end
147
+ expect(simulation.never).to be_empty
148
+ end
149
+ end
150
+ ```
151
+
152
+ ```ruby
153
+ it "keeps every expectation on the sequences Hegel chooses" do
154
+ machine = QuintDriver.machine(spec, driver: -> { driver }, invariants: expectations, ignore:)
155
+ Hegel.test(test_cases: 50, seed: 1, suppress_health_check: %i[filter_too_much too_slow]) do |tc|
156
+ rolled_back { Hegel::Stateful.run(machine.new, tc) }
157
+ end
158
+ end
159
+ ```
160
+
161
+ `violate:` yields only the traces that break the expectation, each ending in the state where it breaks. When no trace of the run breaks it, `simulate` yields nothing and raises nothing; it returns a `Simulation` whose `traces` counts the traces quint ran and whose `violated` counts the ones that broke the expectation, so a run that found nothing can say how much it tried. Its `actions` counts the steps each action took across every trace quint ran, and its `never` lists the actions of `step` that no trace took. A hunt that never ran an action proves nothing about it, so the example checks `expect(simulation.never).to be_empty`. When that fails, raise `max_steps` (or `traces`) until it passes. An empty `never` is not enough to stop: it says each action ran once, not that the order a bug needs came up. In one hunt, an expectation whose bug needed four steps in one order and a failure on the last but one kept `violated` at 0 with `never` empty at `traces: 200, max_steps: 12`, and 1000 traces of 20 steps broke it 25 times. So when an expectation holds, run it again with five times the traces and more steps, and stop when that run finds nothing new either. `spec.expectations` lists every name `violate:` takes, so a loop over it also runs a `val` added later. A plain replay without `invariants:` passes on this app: the app follows the spec at every step, and only the expectation tells that the state is wrong.
162
+
163
+ On the app as committed, each expectation fails with a `QuintDriver::Violated`:
164
+
165
+ ```text
166
+ quint: the system agreed with the spec at every step, and the expectation `free_compartment_has_no_code` does not hold after step 2 `release` {"offline" => 1, "p" => "p3"}
167
+ steps:
168
+ init {}
169
+ assignParcel {"offline" => 2, "p" => "p3"}
170
+ release {"offline" => 1, "p" => "p3"}
171
+ state:
172
+ everDone: {}
173
+ intake: "none"
174
+ live: {1}
175
+ place: {"p1" => "Waiting", "p2" => "Waiting", "p3" => "Collected"}
176
+ row: {"p1" => "", "p2" => "", "p3" => ""}
177
+ ```
178
+
179
+ Read a `Violated` as a bug suspect: the parcel is collected, the compartment is free, and the locker controller still holds its code, because the release page rescued the controller's time-out inside its transaction. To pin a suspect, paste the text under `steps:` into `QuintDriver.replay_steps`. It runs those steps on the driver and on the spec's model, checks them as a replay does, and needs no quint run and no Hegel, so the example raises the same `Violated` on every run until the bug is fixed:
180
+
181
+ ```ruby
182
+ it "keeps free_compartment_has_no_code when a release times out" do
183
+ QuintDriver.replay_steps(spec, driver, <<~STEPS, invariants: %w[free_compartment_has_no_code], ignore:)
184
+ init {}
185
+ assignParcel {"offline" => 2, "p" => "p3"}
186
+ release {"offline" => 1, "p" => "p3"}
187
+ STEPS
188
+ end
189
+ ```
190
+
191
+ `replay_steps(spec, driver, steps, step: "step", observe: [], ignore: [], invariants: [])` takes the pasted text or a list of `[action, picks]`, and the `init` line may be left out. A step the spec does not allow raises a `Mismatch` that names it, such as `quint: the model refused borrow {"b" => "b1", "m" => "m2"}, at step 2 ...`. It returns the steps it ran, and it stops at the step where an expectation breaks: to show what a user sees after that step, such as a refusal the next request gets, pin the longer list in a second example without `invariants:`, and check what the driver reports. The pinned example stays red until the bug is fixed, which is how it tells the fix worked.
192
+
193
+ Quint's first trace that breaks an expectation is not the shortest. `QuintDriver.shrink_steps(steps) { |steps| ... }` takes steps out while the same expectations still break and returns the shortest list it found, as the text to paste into `replay_steps`. The block runs one list on a clean database and raises what `replay_steps` raises; a driver whose `init` resets it can be the same object each time. A `Violated` carries the steps it ran as `steps` and the names that broke as `expectations`:
194
+
195
+ ```ruby
196
+ QuintDriver::Quint.simulate(qnt, traces: 200, max_steps: 12, seed: "1", violate: expectation) do |path|
197
+ rolled_back { QuintDriver::Trace.replay(path, driver, spec:, invariants: [ expectation ], ignore:) }
198
+ rescue QuintDriver::Violated => broken
199
+ shortest = QuintDriver.shrink_steps(broken.steps) do |steps|
200
+ rolled_back { QuintDriver.replay_steps(spec, driver, steps, invariants: [ expectation ], ignore:) }
201
+ end
202
+ QuintDriver.replay_steps(spec, driver, shortest, invariants: [ expectation ], ignore:)
203
+ end
204
+ ```
205
+
206
+ On the depot, it cut the longest trace of each expectation from 7, 10, 8 and 10 steps, `init` counted, to 2, 6, 4 and 6, in 2 seconds or less each. A list that the spec refuses, or whose step raises, does not count as keeping the failure. It only takes steps out and never changes a pick, so a shorter failure with other picks can still exist: the Hegel machine changes picks too. The machine stops at the first expectation that breaks on the sequences it tries, which is the shallowest suspect, so it reports that one on every run. Once a suspect is pinned, leave its expectation out of `invariants:` (or change the action in the spec to the fixed behavior) and run the machine again to reach the next one. The machine needs the same stop rule as Quint: a bug that needs two requests to cross, as a lost update does, can stay hidden at 100 test cases. In one hunt, the machine found no such break at `test_cases: 100` and found it at 1000, in 10 seconds. When the machine finds nothing, run it again with ten times the test cases before you stop.
207
+
208
+ To confirm a suspect, show the state to the operator: the pinned example is the steps that reach it. If the operator agrees that the state is wrong, the suspect is a bug; fix the code, change the action in the spec to the fixed behavior, and run the hunt again. If the operator says the state is fine, the expectation was wrong; change the `val`.
209
+
210
+ Read a `Mismatch` in a hunt as an error in the spec or the driver first (see Read a failure). Fix that before you trust a `Violated`, because a driver that reports a wrong value can make an expectation break, or hold, by itself.
211
+
35
212
  ## 1. Shape the spec
36
213
 
37
214
  Each move of `step` must name the action that a driver runs.
@@ -52,6 +229,42 @@ When the file holds several modules, pass the module name as `main:` to `Spec.ne
52
229
 
53
230
  ## 2. Write the driver
54
231
 
232
+ Start from the outline the gem prints. It names every action the step action can take with the picks it receives, every variable `state` must report with the Ruby shape of its value, and the expectations. It exits 1 with the reason when the step action has a shape no driver can run, so run it after each change to the spec's shape:
233
+
234
+ ```sh
235
+ bundle exec quint_driver outline examples/loans/loans.qnt
236
+ ```
237
+
238
+ ```ruby
239
+ # A driver for the module loans, whose step action is step.
240
+ # Expectations, for invariants: or violate:
241
+ # one_book_each
242
+ # nothing_on_loan
243
+ # two_on_loan
244
+ class LoansDriver
245
+ def step(action, picks)
246
+ case action
247
+ when "init"
248
+ when "borrow" # picks["m"]: String, picks["b"]: String
249
+ when "borrow_refused" # picks["m"]: String, picks["b"]: String
250
+ when "give_back" # picks["b"]: String
251
+ when "give_back_refused" # picks["b"]: String
252
+ end
253
+ end
254
+
255
+ # A variable the system does not keep, such as a pick the spec
256
+ # remembers, goes in ignore: instead of here.
257
+ def state
258
+ {
259
+ "holder" => nil, # Hash of String => String
260
+ "outcome" => nil, # "Done" or ["Refused", String]
261
+ }
262
+ end
263
+ end
264
+ ```
265
+
266
+ `--main MODULE` reads another module of the file, and `--step ACTION` another step action. The driver the example fills in:
267
+
55
268
  ```ruby
56
269
  class LoansDriver
57
270
  def step(action, picks)
@@ -121,7 +334,11 @@ QuintDriver::Quint.simulate("spec.qnt", main: "loans", traces: 20, max_steps: 10
121
334
  end
122
335
  ```
123
336
 
124
- One of those traces runs `init give_back_refused borrow borrow`. When no trace gets there, `Quint.simulate` raises `QuintDriver::QuintFailed`: `quint: no trace of 20 reached two_on_loan within 1 steps; raise max_steps or traces`. Raise `max_steps` or `traces` then. `reach:` takes a predicate (a boolean `val` or `def` without parameters) and `step:` an action without parameters; a name of another kind, such as an action as `reach:`, raises `ArgumentError` before quint runs, and the message lists the names that fit. A name the module neither declares nor imports, such as a typo, raises the same `ArgumentError` once quint has run: `quint: step names borow, which loans neither declares nor imports; step takes an action without parameters, such as step`.
337
+ One of those traces runs `init give_back_refused borrow borrow`. When no trace gets there, `Quint.simulate` raises `QuintDriver::QuintFailed`: `quint: no trace of 20 reached two_on_loan within 1 steps; raise max_steps or traces`. Raise `max_steps` or `traces` then. `reach:` takes a predicate (a boolean `val` or `def` without parameters) and `step:` an action without parameters; a name of another kind, such as an action as `reach:`, raises `ArgumentError` before quint runs, and the message lists the names that fit. A name the module neither declares nor imports, such as a typo, raises the same `ArgumentError` once quint has run: `quint: step names borow, which loans neither declares nor imports; step takes an action without parameters, such as step`. `reach:` needs the default `backend: "rust"`. quint 0.33.0's typescript backend runs a trace on past the state where the definition first holds, and marks traces that never get there as ones that do, so `reach:` with `backend: "typescript"` raises `ArgumentError` before quint runs.
338
+
339
+ An expectation is a predicate that should hold in every state, such as `val one_book_each = MEMBERS.forall(m => BOOKS.filter(b => holder.get(b) == m).size() <= 1)`. Name it in `invariants:` with `spec:`: `Trace.replay(path, driver, spec:, invariants: %w[one_book_each])`. The model evaluates each one in each state of the trace, after the step's agreement check, and one that is false raises `QuintDriver::Violated` (see Read a failure). A name that is no predicate raises `ArgumentError` before the first step, with the predicates the module has, and so does `invariants:` without `spec:`.
340
+
341
+ To have quint search for the traces that break an expectation, pass its name as `violate:` to `Quint.simulate`. Quint checks it as its invariant, each trace ends at the first state where it is false, and only the traces that break it are yielded. Replay each with the same name in `invariants:`, and a system that agrees with the trace raises `QuintDriver::Violated` at its last step. Unlike `reach:`, a simulation where every trace keeps the expectation yields nothing and raises nothing. `Quint.simulate` returns a `QuintDriver::Quint::Simulation`: `traces` is how many traces quint ran, and `violated` how many of them broke the expectation, or `nil` without `violate:`. `Quint.simulate("spec.qnt", main: "loans", traces: 50, max_steps: 20, seed: "1", violate: "one_book_each")` returns `#<data QuintDriver::Quint::Simulation traces=50, violated=0, actions={"borrow" => 214, "borrow_refused" => 283, "give_back" => 161, "give_back_refused" => 342}, never=[]>`, and `Quint.simulate("test/unlimited.qnt", traces: 30, max_steps: 10, seed: "1", violate: "one_book_each")` in this repository returns `traces=30, violated=20`. `violate:` takes a predicate as `reach:` does and needs `backend: "rust"` for the same reason. `reach:` and `violate:` together raise `ArgumentError` before quint runs: `quint: simulate takes reach or violate, not both; each ends a trace where quint's one invariant breaks, so a trace it yielded could have met either`.
125
342
 
126
343
  To replay a named run (`run lendTest = init.then(...)`), use `Quint.test`. quint test writes no `mbt::actionTaken`, so the spec must record each step's action in a variable, as a sum type whose tag names the action and whose record holds its picks, the way a Choreo spec records it. Pass that variable's path as `action:`, and the path to the state the driver answers for as `state:`:
127
344
 
@@ -172,7 +389,7 @@ Hegel.test(test_cases: 100, seed: 1, suppress_health_check: %i[filter_too_much t
172
389
  end
173
390
  ```
174
391
 
175
- - `invariants:` names `val`s of the spec that must hold after every move.
392
+ - `invariants:` names expectations, predicates of the spec that should hold in every state, as `Trace.replay` takes them. Hegel checks them at `init` and after every move, after the move's agreement check, and one that is false raises `QuintDriver::Violated` with the shrunk steps. A name that is no predicate raises `ArgumentError` from `QuintDriver.machine`, with the predicates the module has.
176
393
  - `choose: :rotate` gives a disabled action's turn to the next enabled one. Use it when most actions are disabled in most states. The default, `:rule`, shrinks to the shortest sequence.
177
394
  - `Hegel::Stateful.run(machine.new, tc, step_count: 50)` sets the most moves in one test case.
178
395
 
@@ -881,6 +1098,63 @@ QuintDriver::Mismatch:
881
1098
 
882
1099
  Do not return `reorder(...)` from the wrap. A new relation loads records of its own, not the association's target, so the job changes records that `batch.update!` does not autosave. The same trace then fails with `driver {"i1" => "pending", "i2" => "pending", "i3" => "pending"}` while `free` drops to 0, and an item validation that fails no longer stops the update: with a blocked item that may not be assigned, `update!` raised `Validation failed: Items state blocked` when the job changed the loaded target, and saved when it changed the records of `reorder(:id)`.
883
1100
 
1101
+ ### A request another one comes between
1102
+
1103
+ A lost update needs a second request between the first one's read and its write. Split the request into two actions, one that reads and one that writes, and keep what the read saw in a variable. `examples/shelf/shelf.qnt` in the quint_driver repository:
1104
+
1105
+ ```quint
1106
+ action load(r: str): bool = all {
1107
+ not(loaded.keys().contains(r)),
1108
+ loaded' = loaded.put(r, stock),
1109
+ stock' = stock, reserved' = reserved,
1110
+ }
1111
+
1112
+ action save(r: str): bool = all {
1113
+ loaded.keys().contains(r),
1114
+ stock' = loaded.get(r) - 1,
1115
+ reserved' = reserved + 1,
1116
+ loaded' = loaded.keys().exclude(Set(r)).mapBy(k => loaded.get(k)),
1117
+ }
1118
+ ```
1119
+
1120
+ The driver runs the whole request in `QuintDriver::Hold`. `start(name) { ... }` runs the block until the code calls `pause(value)`, and returns that value. `finish(name)` lets it run to its end and returns the block's value. The code reaches `pause` through a stub at the point to stop; outside a held call, `pause` does nothing:
1121
+
1122
+ ```ruby
1123
+ when "init"
1124
+ @hold = QuintDriver::Hold.new
1125
+ @shelf = Shelf.new
1126
+ hold = @hold
1127
+ # The pause point: right after the reservation reads the stock.
1128
+ @shelf.define_singleton_method(:stock) { super().tap { hold.pause(_1) } }
1129
+ @loaded = {}
1130
+ when "load" then @loaded[picks["r"]] = @hold.start(picks["r"]) { @shelf.reserve }
1131
+ when "save" then @hold.finish(picks["r"]).then { @loaded.delete(picks["r"]) }
1132
+ ```
1133
+
1134
+ `every_reservation_takes_one` is the expectation, and two reads before two writes break it:
1135
+
1136
+ ```text
1137
+ quint: the system agreed with the spec at every step, and the expectation `every_reservation_takes_one` does not hold after step 4 `save` {"r" => "r2"}
1138
+ steps:
1139
+ init {}
1140
+ load {"r" => "r1"}
1141
+ load {"r" => "r2"}
1142
+ save {"r" => "r1"}
1143
+ save {"r" => "r2"}
1144
+ state:
1145
+ loaded: {}
1146
+ reserved: 2
1147
+ stock: 2
1148
+ ```
1149
+
1150
+ `start` returns the value given to `pause`, or the block's value when the call ended without one, such as a refusal before the write. Read `hold.held?(name)` after `start` to tell the two apart.
1151
+
1152
+ In a Rails app each request loads its own record, so a stub on one object never runs. Put the pause on every instance, before the write the spec splits: with RSpec, `allow_any_instance_of(Loan).to receive(:update!).and_wrap_original { |original, attributes| driver.before_update(original.receiver, attributes); original.call(attributes) }`, where the driver's `before_update` calls `@hold.pause` only for that write, such as when `attributes[:state] == "approved"`. In one hunt this split an approval that checks a limit and then writes, and two approvals held between their check and their write both passed the limit.
1153
+
1154
+ A held block runs as a Fiber, so it ends with `next`, never `return` or `break`, and it does not call `Fiber.yield` itself. A `pause` reached from another Fiber inside the held call, such as the block of an `Enumerator` read with `next`, cannot stop the call, so it raises `ArgumentError` rather than letting the call run through unheld.
1155
+
1156
+ Hegel's machine shrinks the same bug to these five steps. A held call runs in a Fiber on the same thread and shares its database connection, so the test transaction rolls it back too. On one connection the transactions of two held calls nest, so put the pause where the call holds no open transaction, such as after its read and before the transaction that writes. In the depot app, two calls held inside `transaction(requires_new: true)` and finished in the order they started raised `ActiveRecord::StatementInvalid: SQLite3::SQLException: cannot rollback - no transaction is active`. Real threads and separate connections are another tool's job: this one replays one order of steps at a time.
1157
+
884
1158
  ## Read a failure
885
1159
 
886
1160
  ```text
@@ -913,13 +1187,32 @@ trace: trace_0.itf.json of Quint.simulate("spec.qnt", traces: 50, max_steps: 20,
913
1187
  ```
914
1188
 
915
1189
  Under Hegel the line reads the same, and the number is the one Hegel's report gives the move (`Step 1: borrow`). A rule Hegel rejected counts too, so the number can be larger than the moves under `steps:`. A failure while the `driver:` lambda makes the driver, or at its first state, reads ``quint: at step 0 `init` {}, ...``, as on a replay. The machine makes its driver when it starts, so Hegel's report for that failure lists no step.
1190
+ - A `QuintDriver::Violated` is not a `Mismatch`, and `rescue QuintDriver::Mismatch` does not catch it: the system agreed with the spec at every step, and an expectation that `invariants:` names does not hold in the state they reached. The first line names the expectation and the step, `steps:` lists the steps from `init`, `state:` gives the spec's variables in that state, and `trace:` names the trace as for a `Mismatch`. Here `test/unlimited.qnt` in this repository models `BrokenLoans` as written, which lends a member a second book, and `LoansDriver.new(BrokenLoans)` replays its traces with `invariants: %w[one_book_each]`:
1191
+
1192
+ ```text
1193
+ quint: the system agreed with the spec at every step, and the expectation `one_book_each` does not hold after step 4 `borrow` {"b" => "b3", "m" => "m2"}
1194
+ steps:
1195
+ init {}
1196
+ borrow {"b" => "b2", "m" => "m2"}
1197
+ give_back {"b" => "b2"}
1198
+ borrow {"b" => "b2", "m" => "m2"}
1199
+ borrow {"b" => "b3", "m" => "m2"}
1200
+ state:
1201
+ holder: {"b1" => "", "b2" => "m2", "b3" => "m2"}
1202
+ outcome: "Done"
1203
+ trace: trace_1.itf.json of Quint.simulate("test/unlimited.qnt", traces: 30, max_steps: 10, seed: "1", step: "step", backend: "rust")
1204
+ ```
1205
+
1206
+ Expectations that break in one state are named together, as ``the expectations `one_on_the_shelf` and `one_book_each` do not hold``. Under Hegel the message has no `trace:` line, `steps:` is the shrunk sequence, and the step number is the one Hegel's report gives the move. An expectation that is false at `init` reads ``does not hold after step 0 `init` {}``, and Hegel's report lists no step.
916
1207
  - Under Hegel, there is no seed: Hegel's report ends with `To reproduce this failure, pass the blob below to Hegel.test:` and a blob. Pass it as `Hegel.test(reproduce_failure: "...")` to run that one case again with the same message.
917
1208
  - Under Hegel, `steps:` is the shrunk sequence. Hegel's own report names each draw after the pick it chose, and under `choose: :rotate` names the turn `rule` and the move `move`. A label drawn more than once in a test case is numbered in draw order (`m_1 = "m2"`, `m_2 = "m1"`); a label drawn once prints bare (`m = "m2"`).
1209
+ - Every `steps:` list, from a trace or from Hegel, pastes into `QuintDriver.replay_steps(spec, driver, <<~STEPS)` as it is (see Hunt for bugs), which runs it again with no quint run and no Hegel.
918
1210
 
919
1211
  | Error | Cause |
920
1212
  | --- | --- |
921
1213
  | `QuintDriver::Mismatch` | The system and the spec disagree, or the model cannot take a move a trace took, such as a pick its domain does not hold. |
922
1214
  | `QuintDriver::StepRaised` | The driver's `step` or `state`, the system it called, or the `driver:` lambda raised. `raised in:` names your project's frame. `cause` holds the error. |
1215
+ | `QuintDriver::Violated` | The system agreed with the spec at every step, and an expectation that `invariants:` names does not hold. The message names it, lists the steps from `init`, and gives the state where it broke. |
923
1216
  | `QuintDriver::Unsupported` | The spec uses an operator the model does not evaluate, a move names no action of `step`, or a move lacks a pick its action needs. |
924
1217
  | `ArgumentError` | `QuintDriver.machine`'s `step:`, or `spec.rules`, names no action of the module. The message lists the actions it has. Or the module has no action named `init`: every trace, model, and machine starts there, and no option names another, so add `action init = <the action that starts it>` to the spec. Its backtrace starts at your line that made the call. |
925
1218
  | `QuintDriver::QuintFailed` | quint rejected the spec (a failure at the flattening stage can come from another module of the file, as quint flattens every one), `main:` names no module of the file (the message lists the modules it has), the `QUINT` command is not installed, `QUINT` is unset and npx could not fetch quint, or the `QUINT_EVALUATOR` evaluator cannot run or answers in a format other than v0.7.0's. Its backtrace starts at your line that made the call. |
metadata CHANGED
@@ -1,15 +1,16 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: quint_driver
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 0.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - meganemura
8
- bindir: bin
8
+ bindir: exe
9
9
  cert_chain: []
10
10
  date: 1980-01-02 00:00:00.000000000 Z
11
11
  dependencies: []
12
- executables: []
12
+ executables:
13
+ - quint_driver
13
14
  extensions: []
14
15
  extra_rdoc_files: []
15
16
  files:
@@ -18,11 +19,18 @@ files:
18
19
  - README.md
19
20
  - examples/loans/loans.qnt
20
21
  - examples/loans/loans.rb
22
+ - examples/shelf/shelf.qnt
23
+ - examples/shelf/shelf.rb
24
+ - exe/quint_driver
21
25
  - lib/quint_driver.rb
22
26
  - lib/quint_driver/hegel.rb
27
+ - lib/quint_driver/hold.rb
23
28
  - lib/quint_driver/model.rb
29
+ - lib/quint_driver/outline.rb
24
30
  - lib/quint_driver/quint.rb
25
31
  - lib/quint_driver/spec.rb
32
+ - lib/quint_driver/steps.rb
33
+ - lib/quint_driver/targets.rb
26
34
  - lib/quint_driver/trace.rb
27
35
  - lib/quint_driver/version.rb
28
36
  - skills/quint_driver/SKILL.md