agent-formal-verify 0.4.14 → 0.4.15

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.
package/CHANGES.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changes
2
2
 
3
+ ## 0.4.15 - Kani generator types in the baseline, locked baseline updates and a checked Lean replay
4
+
5
+ `scripts/baseline.py` now records the whole `kani::any_where` call in a harness, with its explicit type arguments and its predicate, so changing `kani::any_where::<u16, _>(...)` to `kani::any_where::<u8, _>(...)` prints `CHANGED`. Before this change, the record held the predicate alone, so narrowing a generator's type printed `UNCHANGED`. A record made with 0.4.14 that holds an `any_where` predicate prints `CHANGED` once. Older records used one form for a plain assumption and a generator's predicate, so check the harness's assumptions and generator types against the revision the record was made from before you record the file again.
6
+
7
+ `scripts/baseline.py record` and `move` now lock a file named `.<record>.lock` beside the record while they read and replace it, so runs that update the same record at the same time keep every entry. Before this change, two runs could read the same old record, and the later write dropped the entry that the earlier one added.
8
+
9
+ `scripts/lean-check.sh` now fails with `FAIL <scope>: cannot locate <toolchain> for kernel replay (lean --print-prefix exit <n>)`, followed by the tool's output, when it cannot find the pinned toolchain's `bin/lean`. Before this change, a failed lookup reported kernel replay as unavailable, and the check passed without replay.
10
+
11
+ `scripts/lean-check.sh` now checks a module named `lakefile.lean` below the project root, such as `Model/lakefile.lean`, and leaves out only the project's own Lake configuration. Before this change, it skipped every file with that name, so a failing theorem in one passed the whole-project check.
12
+
13
+ `scripts/sync.py` now picks the files that can define each `--name` from the `--source` files and their rename history only, so the result no longer depends on the order of the names. Before this change, a file found while searching one name could become a definition candidate for a later name.
14
+
15
+ `scripts/tlc-matrix.sh` now prints a `FAIL` line, `malformed constant '<token>' in run '<label>': expected Name=Value`, for a run whose constants hold a token without a name or a value, such as `N=` or a bare word, and `scripts/baseline.py record` rejects the matrix. Before this change, the runner wrote such a token into TLC's configuration.
16
+
17
+ `scripts/mutate.py` now keeps one mutated source in memory at a time. On a 1,035,022-byte source with 64 mutations, its planner's peak fell from 66,260,062 bytes to 16,238 bytes. When the temporary directory lies inside a Rust crate's workspace, the Rust runner now leaves its own work directory out of the workspace copy that it stages for each mutation.
18
+
19
+ `references/setup.md` now says how Pi, OpenCode and Antigravity run the `setup` skill, and its CI example runs Kani on a crate at the repository root, where the Rust brief puts each harness. `docs/reference.md` now gives the steps to update the plugin in Antigravity.
20
+
3
21
  ## 0.4.14 - an HTML report of TLC runs, and Kani baselines that say what they did not read or check
4
22
 
5
23
  `scripts/tlc-matrix.sh` writes a self-contained HTML report when `TLC_HTML_REPORT` names a path. The report has a table of the runs and, for each failing or `reach` witness trace, a state chain to step through, the variables each step changed, and the trace as Mermaid `stateDiagram-v2` source to copy. It loads nothing over the network. The matrix runner checks the path after Java and TLC and before the first run, and replaces the file in one step. A written report leaves the printed lines and the exit status as they are without a report. A path where the report cannot be written prints an `UNAVAILABLE TLC_HTML_REPORT=...` line and exits with status 3. If the write fails after the runs, the runner prints that line and exits with status 1 when a run failed and 3 otherwise. `scripts/tlc_report.py` builds the report from the traces that `scripts/tlc_trace.py` now parses. The Mermaid labels keep the trace's TLA+ text: each character that Mermaid reads as syntax, such as `{`, `:` or `"`, is written as a Mermaid entity code, such as `#123;`, which Mermaid draws as that character. So are the space in words that Mermaid reads anywhere on a line, such as `direction LR`, and the first bracket of `[[fork]]`, `[[join]]` or `[[choice]]`, and a U+FEFF, which Mermaid reads as whitespace, so a state, transition or lasso label that holds them is kept. The last step of a liveness counter-example that ends in stuttering, which TLC prints as `State N: Stuttering` with no variables, lists the variables of the state it repeats. A matrix file name that is not valid UTF-8 shows U+FFFD in the report in place of the bytes that cannot be decoded. The table row of a failing run with a trace shows, beside the link to the trace, the lines that the matrix runner prints under the run.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-formal-verify",
3
- "version": "0.4.14",
3
+ "version": "0.4.15",
4
4
  "description": "Model-check protocols with TLA+, prove invariants with Lean 4, and check bounded Rust functions with Kani.",
5
5
  "author": {
6
6
  "name": "Michael Denyer",
@@ -25,7 +25,7 @@ Detailed behaviour of the verification scripts under `scripts/`. Run each helper
25
25
  - Output of `compare <record-file>`, which exits 1 when a recorded file changed. Each indented line under `CHANGED` counts as a change, except the `not checked against Kani at record, ...` line and the lines under it:
26
26
  - `UNCHANGED <file>`, `CHANGED <file>` or `NOT CHECKED <file>` for each recorded file, then `SUMMARY <n> unchanged, <m> changed`, which ends with `, <k> not checked` when a file printed `NOT CHECKED`.
27
27
  - An indented `removed <item>`, or `changed <item>` with its `old:` and `new:` values. A Kani harness's value is the `cfg` guards that can switch it off, followed by its `kani::should_panic` and `kani::unwind(<n>)` attributes and the `unread(...)` note that "Cannot see" describes. When more than one route that the record reads leads to the file, the value holds each route as its crate root's path relative to the harness file's directory and its guards, such as `routes(lib.rs: unguarded; main.rs: cfg(feature = "slow"))`, so adding, removing or guarding any route, or moving a guard from one route to another, changes the harness.
28
- - An indented `added <item>`, which only a new Kani assumption or stub prints.
28
+ - An indented `added <item>`, which only a new Kani assumption or stub prints. A `kani::any_where` assumption includes the complete call, including explicit type arguments. Older records used one representation for plain assumptions and generator predicates. For those records, check the assumptions and generator types against the original revision before recording the file again.
29
29
  - In a TLA+ module where a local `INSTANCE` introduces substitutions, or that has an indented definition outside a `LET` or a column-0 definition inside one, the helper compares the complete text of each local module it loaded, with comments removed, so a change to a definition that no property uses also needs review. So does a column-0 definition whose header the helper cannot read, such as an infix operator, which it records with the operators it references, whether or not a property references it.
30
30
  - An indented `file is missing`: the recorded file no longer exists.
31
31
  - An indented `not compiled harness <name>`: Kani compiles a stored harness on no route, such as when `Cargo.toml` drops a default feature that a route's `cfg` needs.
@@ -1,6 +1,6 @@
1
1
  # Tool setup
2
2
 
3
- Run `/agent-formal-verify:setup` once to prepare Java, Python, TLC, elan, Lean, Rust and Kani. In Codex, request this plugin's `setup` skill. The [setup skill](../../setup/SKILL.md) prepares all three verification tools independently of any repository and reuses existing runtimes and caches.
3
+ Run `/agent-formal-verify:setup` once to prepare Java, Python, TLC, elan, Lean, Rust and Kani. In Codex, request this plugin's `setup` skill. In Pi, use `/skill:setup`. In OpenCode or Antigravity, request the `setup` skill. The [setup skill](../../setup/SKILL.md) prepares all three verification tools independently of any repository and reuses existing runtimes and caches.
4
4
 
5
5
  The formal-verify skill selects tools from the current repository on every invocation. It reuses prepared tools and installs a missing Lean toolchain through the setup helper when a Lean pin changes. Repository changes do not require the user to rerun the full setup.
6
6
 
@@ -98,6 +98,6 @@ Install the chosen runtime and the pinned TLC JAR, and for Rust the pinned Kani,
98
98
  - run: python3 .formal-verify/skills/formal-verify/scripts/mutate.py "$GITHUB_WORKSPACE/lean/Model/Name.mutations"
99
99
  - run: cargo install --locked kani-verifier --version 0.68.0 && cargo kani setup
100
100
  - run: bash .formal-verify/skills/formal-verify/scripts/setup.sh rust
101
- - run: bash .formal-verify/skills/formal-verify/scripts/kani-check.sh "$GITHUB_WORKSPACE/verify"
102
- - run: python3 .formal-verify/skills/formal-verify/scripts/mutate.py "$GITHUB_WORKSPACE/verify/src/lib.mutations"
101
+ - run: bash .formal-verify/skills/formal-verify/scripts/kani-check.sh "$GITHUB_WORKSPACE"
102
+ - run: python3 .formal-verify/skills/formal-verify/scripts/mutate.py "$GITHUB_WORKSPACE/src/lib.mutations"
103
103
  ```
@@ -39,10 +39,12 @@ OLD to sit under NEW. Exit codes: 0 unchanged, 1 changed or a record or model
39
39
  file that fails to parse, 2 usage error.
40
40
  """
41
41
  import argparse
42
+ import fcntl
42
43
  import hashlib
43
44
  import json
44
45
  import re
45
46
  import sys
47
+ from contextlib import contextmanager
46
48
  from pathlib import Path
47
49
 
48
50
  sys.dont_write_bytecode = True
@@ -257,10 +259,10 @@ def tla_surface(path):
257
259
  for task in tasks:
258
260
  if task.reach:
259
261
  surface.add(f"reach {task.spec} {task.reach.operator} | {collapse(task.reach.match)}",
260
- {"run": collapse(task.run.label), "constants": collapse(task.run.constants)})
262
+ {"run": collapse(task.run.label), "constants": task.run.constants})
261
263
  specs[task.spec].add(task.reach.operator)
262
264
  else:
263
- run = surface.add(f"run {task.spec} {collapse(task.run.label)}", collapse(task.run.constants))
265
+ run = surface.add(f"run {task.spec} {collapse(task.run.label)}", task.run.constants)
264
266
  for check in task.checks:
265
267
  for name in check.names:
266
268
  surface.add(f"check {task.spec} {check.kind} {name} | [{run}]")
@@ -315,6 +317,11 @@ class TlaKind:
315
317
  return model_entry(self.name, joined(entry["surface"], new, existing))
316
318
 
317
319
 
320
+ def may_omit_generator_types(entry):
321
+ # Older entries used the same keys for plain assumptions and generator predicates.
322
+ return not entry.get("generator_types") and any(key.startswith("assume ") for key in entry["surface"])
323
+
324
+
318
325
  class KaniKind:
319
326
  """Record, compare and move the harnesses, assumptions, covers and stubs of a Kani file, checked against what Kani compiles."""
320
327
 
@@ -326,6 +333,7 @@ class KaniKind:
326
333
  def entry(self, path):
327
334
  surface = kani_surface(path, self.reader)
328
335
  entry = model_entry(self.name, surface)
336
+ entry["generator_types"] = True
329
337
  notes = [f" route not read: {route.message}" for route in self.reader.unread(path)]
330
338
  # A harness that no longer compiles is recorded from its text alone; compare asks Kani again.
331
339
  try:
@@ -341,6 +349,8 @@ class KaniKind:
341
349
  def changes(self, entry, path):
342
350
  surface = kani_surface(path, self.reader)
343
351
  lines = differences(entry["surface"], surface, ("assume", "stub"))
352
+ if may_omit_generator_types(entry):
353
+ lines.insert(0, " previous baseline stored assumptions without distinguishing any_where input types; review the original assumptions and record this file again")
344
354
  unchecked = (" not checked against Kani at record, so compare cannot tell a harness that "
345
355
  "stopped compiling from one that never compiled")
346
356
  try:
@@ -361,7 +371,7 @@ class KaniKind:
361
371
  def valid(self, entry):
362
372
  compiled = entry.get("compiled", [])
363
373
  return (isinstance(compiled, list) and all(isinstance(name, str) for name in compiled)
364
- and isinstance(entry.get("partial", False), bool))
374
+ and isinstance(entry.get("partial", False), bool) and isinstance(entry.get("generator_types", False), bool))
365
375
 
366
376
  def moved(self, entry, module, new, existing):
367
377
  surface, compiled = entry["surface"], entry.get("compiled")
@@ -377,6 +387,8 @@ class KaniKind:
377
387
  partial = partial or other is None or existing.get("partial", False)
378
388
  compiled = None if compiled is None and other is None else [*(other or []), *(compiled or [])]
379
389
  result = model_entry(self.name, surface)
390
+ if not any(may_omit_generator_types(part) for part in (entry, existing) if part is not None):
391
+ result["generator_types"] = True
380
392
  if compiled is not None:
381
393
  result["compiled"] = sorted(compiled)
382
394
  if partial:
@@ -418,8 +430,16 @@ def read_record(path, kinds):
418
430
  return models
419
431
 
420
432
 
421
- def write_record(path, models):
433
+ @contextmanager
434
+ def locked_models(path, kinds):
435
+ """Lock a stable sibling across the read and replacement of a record."""
422
436
  path.parent.mkdir(parents=True, exist_ok=True)
437
+ with path.with_name(f".{path.name}.lock").open("a") as lock:
438
+ fcntl.flock(lock, fcntl.LOCK_EX)
439
+ yield read_record(path, kinds) if path.exists() else {}
440
+
441
+
442
+ def write_record(path, models):
423
443
  runner.atomic_write(path, json.dumps({"format": FORMAT, "models": models}, ensure_ascii=False, indent=2, sort_keys=True) + "\n")
424
444
 
425
445
 
@@ -430,13 +450,14 @@ def record(record_path, files):
430
450
  if file.suffix not in by_suffix:
431
451
  print(f"usage: {file} has no model surface; expected one of {', '.join(by_suffix)}")
432
452
  return 2
433
- models = read_record(record_path, kinds) if record_path.exists() else {}
434
453
  updates, notes = {}, {}
435
454
  for file in files:
436
455
  model = str(file.resolve())
437
456
  updates[model], note = by_suffix[file.suffix].entry(file.resolve())
438
457
  if note:
439
458
  notes[model] = note
459
+ with locked_models(record_path, kinds) as models:
460
+ write_record(record_path, {**models, **updates})
440
461
  for model, entry in updates.items():
441
462
  print(f"RECORDED {model} {entry['digest']}")
442
463
  previous = models.get(model, {}).get("digest")
@@ -444,7 +465,6 @@ def record(record_path, files):
444
465
  print(f" previous {previous}")
445
466
  if model in notes:
446
467
  print(notes[model])
447
- write_record(record_path, {**models, **updates})
448
468
  return 0
449
469
 
450
470
 
@@ -467,21 +487,21 @@ def renamed(surface, old_module, new_module):
467
487
 
468
488
  def move(record_path, old_file, new_file, module):
469
489
  kinds = model_kinds()
470
- models = read_record(record_path, kinds) if record_path.is_file() else {}
471
490
  old, new = str(old_file.resolve()), str(new_file.resolve())
472
- if old not in models:
473
- print(f"usage: {old} has no record entry; record it before the move")
474
- return 2
475
- kind = kinds[models[old]["kind"]]
476
- if new_file.suffix != kind.suffix:
477
- print(f"usage: {new} is not a {kind.name} model file")
478
- return 2
479
- if module and not kind.renames:
480
- print("usage: --module applies only to a Kani harness file")
481
- return 2
482
- entry = models.pop(old)
483
- models[new] = kind.moved(entry, module, new, models.get(new))
484
- write_record(record_path, models)
491
+ with locked_models(record_path, kinds) as models:
492
+ if old not in models:
493
+ print(f"usage: {old} has no record entry; record it before the move")
494
+ return 2
495
+ kind = kinds[models[old]["kind"]]
496
+ if new_file.suffix != kind.suffix:
497
+ print(f"usage: {new} is not a {kind.name} model file")
498
+ return 2
499
+ if module and not kind.renames:
500
+ print("usage: --module applies only to a Kani harness file")
501
+ return 2
502
+ entry = models.pop(old)
503
+ models[new] = kind.moved(entry, module, new, models.get(new))
504
+ write_record(record_path, models)
485
505
  print(f"MOVED {old} -> {new}")
486
506
  return 0
487
507
 
@@ -86,17 +86,26 @@ class CrateSources:
86
86
  roots: set
87
87
  outputs: set
88
88
 
89
- def stage(self, crate, destination):
89
+ def stage(self, crate, work):
90
90
  """Copy local packages in their relative layout, omitting Cargo's build directories."""
91
91
  anchor = Path(os.path.commonpath(self.roots))
92
+ work = work.resolve()
93
+ # Other mutations can stage into the same workspace-local temporary root.
94
+ (work / "CACHEDIR.TAG").write_text("Signature: 8a477f597d28d172789f06886806bc55\n", encoding="ascii")
95
+ destination = work / "source"
92
96
 
93
97
  def ignore(directory, names):
94
98
  # Cargo tags each build directory, including one left behind after the target directory moved.
95
99
  # A dangling symlink, such as an editor's lock file, is skipped here because copytree's
96
100
  # ignore_dangling_symlinks reaches only the top directory before Python 3.10.
97
- return [name for name in names if name == ".git" or Path(directory) / name in self.outputs
98
- or (Path(directory) / name / "CACHEDIR.TAG").is_file()
99
- or (Path(directory) / name).is_symlink() and not (Path(directory) / name).exists()]
101
+ directory = Path(directory).resolve()
102
+ skipped = []
103
+ for name in names:
104
+ path = directory / name
105
+ if (name == ".git" or path == work or path in self.outputs or (path / "CACHEDIR.TAG").is_file()
106
+ or path.is_symlink() and (not path.exists() or path.resolve().is_relative_to(work))):
107
+ skipped.append(name)
108
+ return skipped
100
109
 
101
110
  for root in self.roots:
102
111
  if self.roots.isdisjoint(root.parents):
@@ -93,7 +93,7 @@ def rust_functions(mask):
93
93
  KANI_ATTRIBUTE = r"#\s*\[\s*(?:cfg_attr\s*\(\s*kani\s*,\s*)?kani\s*::\s*"
94
94
  MACROS = (
95
95
  ("assume", re.compile(r"\bkani\s*::\s*assume\s*\(")),
96
- ("assume", re.compile(r"\bkani\s*::\s*any_where\s*(?:::\s*<[^<>]*(?:<[^<>]*>[^<>]*)*>\s*)?\(")),
96
+ ("any_where", re.compile(r"\bkani\s*::\s*any_where\s*(?:::\s*<[^<>]*(?:<[^<>]*>[^<>]*)*>\s*)?\(")),
97
97
  ("cover", re.compile(r"\bkani\s*::\s*cover\s*!\s*\(")),
98
98
  ("stub", re.compile(KANI_ATTRIBUTE + r"stub\s*\(")),
99
99
  )
@@ -500,9 +500,14 @@ def kani_surface(path, reader):
500
500
  for match in pattern.finditer(mask):
501
501
  end = after_closing(mask, match.end() - 1)
502
502
  read.append((match.start(), end))
503
- argument = rust_masks(text[match.end():end - 1])
503
+ # The generator's explicit type arguments constrain its domain alongside its predicate.
504
+ if kind == "any_where":
505
+ item_kind, expression = "assume", text[match.start():end]
506
+ else:
507
+ item_kind, expression = kind, text[match.end():end - 1]
508
+ argument = rust_masks(expression)
504
509
  owner = owner_at(match.start(), attribute=kind == "stub").name
505
- spans.append((match.start(), f"{kind} {collapse(argument.uncommented, argument.literals)} in {owner}", ""))
510
+ spans.append((match.start(), f"{item_kind} {collapse(argument.uncommented, argument.literals)} in {owner}", ""))
506
511
  # Kani refuses these attributes on a function that is not a harness, so only a harness's are recorded.
507
512
  attributes = {}
508
513
  for start, end in applied_attributes(mask):
@@ -148,15 +148,18 @@ def step(command, *, merge=True, env=None):
148
148
  return 127, "", f"cannot run {command[0]}: {error}\n"
149
149
 
150
150
 
151
- def project_sources(project):
152
- """Every .lean file in the project outside its .lake directory, except Lake's own lakefile.lean."""
153
- found = []
151
+ def project_files(project):
152
+ """Find model sources and orphan records in the same walk, outside the root Lake build directory."""
153
+ sources, records = set(), []
154
154
  for top, directories, names in os.walk(project):
155
- found += [os.path.join(top, name) for name in directories + names
156
- if name.endswith(".lean") and name != "lakefile.lean"]
157
155
  if top == project and ".lake" in directories:
158
156
  directories.remove(".lake")
159
- return sorted(found)
157
+ for name in directories + names:
158
+ if name.endswith(".lean") and (top != project or name != "lakefile.lean"):
159
+ sources.add(os.path.join(top, name))
160
+ elif name.endswith(".statements"):
161
+ records.append(Path(top, name))
162
+ return sorted(sources), sorted(path for path in records if str(path.with_suffix(".lean")) not in sources)
160
163
 
161
164
 
162
165
  def layout(objects, search_path):
@@ -205,18 +208,14 @@ def records_by_name(modules, module):
205
208
  return records
206
209
 
207
210
 
208
- def check_orphans(project, out):
209
- """Report every record whose source file is gone, outside the .lake directory."""
210
- failed = False
211
- for path in sorted(project.rglob("*.statements")):
212
- if ".lake" in path.relative_to(project).parts or path.with_suffix(".lean").is_file():
213
- continue
211
+ def check_orphans(orphans, out):
212
+ """Report every record without a model source in the project."""
213
+ for path in orphans:
214
214
  record = read_record(path)
215
215
  out(f"FROZEN {path}: source file is missing")
216
216
  for declaration in record["declarations"]:
217
217
  out(f"FROZEN {declaration['name']}: statement changed (source deleted)")
218
- failed = True
219
- return int(failed)
218
+ return int(bool(orphans))
220
219
 
221
220
 
222
221
  def freeze_statements(toolchain, modules, sources, out):
@@ -313,14 +312,14 @@ def checked(project, toolchain, files, freeze, out, work):
313
312
  out(f"FAIL {source} does not exist")
314
313
  return 1
315
314
  else:
315
+ sources, orphans = project_files(project)
316
316
  if not freeze:
317
- status, output = statements(lambda sink: check_orphans(Path(project), sink))
317
+ status, output = statements(lambda sink: check_orphans(orphans, sink))
318
318
  if status:
319
319
  out(f"FAIL {scope}: frozen model sources are missing or their records are invalid")
320
320
  for line in output:
321
321
  out(line)
322
322
  return status
323
- sources = project_sources(project)
324
323
  if not sources:
325
324
  out(f"FAIL {project} has no .lean file to check")
326
325
  return 1
@@ -409,12 +408,17 @@ def checked(project, toolchain, files, freeze, out, work):
409
408
  # replays every declaration of the built modules through the kernel and rejects it. Use its exact-module
410
409
  # replayer rather than its CLI's prefix search, which also finds deleted sources' cached objects. A named
411
410
  # module rests on the project modules it imports, so replay those too.
412
- prefix = processes.guarded(["elan", "run", toolchain, "lean", "--print-prefix"],
413
- lambda process: process.communicate()[0], stdout=subprocess.PIPE,
414
- encoding="utf-8", errors="replace")
411
+ status, prefix, errors = step(["elan", "run", toolchain, "lean", "--print-prefix"], merge=False)
415
412
  prefix = prefix.rstrip("\n")
413
+ compiler = os.path.join(prefix, "bin", "lean")
414
+ if status or not os.path.isabs(prefix) or not os.path.isfile(compiler) or not os.access(compiler, os.X_OK):
415
+ out(f"FAIL {scope}: cannot locate {toolchain} for kernel replay (lean --print-prefix exit {status})")
416
+ for line in lines(errors) + lines(prefix):
417
+ out(line)
418
+ return 1
416
419
  replay = "unavailable"
417
- if os.access(f"{prefix}/bin/leanchecker", os.X_OK):
420
+ # The replayer imports LeanChecker. The installed CLI marks support even if its execute bit was lost.
421
+ if os.path.lexists(f"{prefix}/bin/leanchecker"):
418
422
  imported = [line.removeprefix("IMPORTED ") for line in audit if line.startswith("IMPORTED ")]
419
423
  replayed = set(modules) | {module for module in imported
420
424
  if any((library / (module.replace(".", "/") + ".olean")).is_file() for library in libraries)}
@@ -89,13 +89,13 @@ def _command_sites(source, commands, edit_start, edit_end):
89
89
  yield (cmd["property"], site), cmd, first
90
90
 
91
91
 
92
- def _compare_commands(model, before, mutation, after):
93
- start = mutation.original.index(mutation.old)
92
+ def _compare_commands(model, before, mutation, source, after):
93
+ start = mutation.start
94
94
  end = start + len(mutation.new)
95
95
  originals = {}
96
96
  for site, cmd, _ in _command_sites(mutation.original, before, start, start + len(mutation.old)):
97
97
  originals.setdefault(site, []).append(cmd["statement"])
98
- commands = list(_command_sites(mutation.source, after, start, end))
98
+ commands = list(_command_sites(source, after, start, end))
99
99
  counts = Counter(site for site, _, _ in commands)
100
100
  line_shift = mutation.old.count("\n") - mutation.new.count("\n")
101
101
  edit_line = mutation.original.count("\n", 0, start) + 1
@@ -139,10 +139,9 @@ class OriginalChecks:
139
139
  self._theorems = {(decl["name"], decl["type"]) for decl in theorems}
140
140
  self._commands = original["commands"]
141
141
 
142
- def _theorem_checks(self, declarations, mutation):
143
- start = mutation.original.index(mutation.old)
144
- edit_start = _position(mutation.source, start)
145
- edit_end = _position(mutation.source, start + len(mutation.new))
142
+ def _theorem_checks(self, declarations, mutation, source):
143
+ edit_start = _position(source, mutation.start)
144
+ edit_end = _position(source, mutation.start + len(mutation.new))
146
145
  theorems = [decl for decl in declarations if decl["theorem"]]
147
146
  names = {decl["name"] for decl in theorems}
148
147
  for decl in theorems:
@@ -156,12 +155,12 @@ class OriginalChecks:
156
155
  problem = ""
157
156
  yield _Check(decl["start"], decl["end"], "theorem " + name, problem, _is_witness(name, names))
158
157
 
159
- def broken_checks(self, mutation, copy, analysis):
158
+ def broken_checks(self, mutation, source, copy, analysis):
160
159
  """Return the original checks that fail, or raise ValueError if any error cannot be attributed."""
161
160
  if not analysis["errors"]:
162
161
  return []
163
- theorems = list(self._theorem_checks(analysis["declarations"], mutation))
164
- commands = list(_compare_commands(self._path, self._commands, mutation, analysis["commands"]))
162
+ theorems = list(self._theorem_checks(analysis["declarations"], mutation, source))
163
+ commands = list(_compare_commands(self._path, self._commands, mutation, source, analysis["commands"]))
165
164
  failed = []
166
165
  for error in analysis["errors"]:
167
166
  position = [error["pos"]["line"], error["pos"]["column"]]
@@ -189,7 +188,8 @@ def prepare(model, project):
189
188
 
190
189
  def check(mutation, work):
191
190
  copy = work / model.name
192
- copy.write_text(mutation.source, encoding="utf-8")
193
- return original.broken_checks(mutation, copy, _analyze(copy, project, pin))
191
+ source = mutation.apply()
192
+ copy.write_text(source, encoding="utf-8")
193
+ return original.broken_checks(mutation, source, copy, _analyze(copy, project, pin))
194
194
 
195
195
  return original.targets, check
@@ -93,7 +93,10 @@ class Mutation:
93
93
  old: str
94
94
  new: str
95
95
  original: str
96
- source: str
96
+ start: int
97
+
98
+ def apply(self):
99
+ return "".join((self.original[:self.start], self.new, self.original[self.start + len(self.old):]))
97
100
 
98
101
 
99
102
  class Verdict(Enum):
@@ -135,7 +138,7 @@ def parse(path):
135
138
 
136
139
 
137
140
  def make_mutation(label, directives, model, text, language):
138
- """Check one mutation's directives against its language and apply it to the model's text."""
141
+ """Validate one mutation and locate its edit in the original model."""
139
142
  lines = {keyword: [rest for word, rest in directives if word == keyword] for keyword in DIRECTIVES}
140
143
  for keyword in SINGLE:
141
144
  if len(lines[keyword]) > 1:
@@ -147,17 +150,18 @@ def make_mutation(label, directives, model, text, language):
147
150
  if lines["only"] and not language.takes_only:
148
151
  stop(f"mutation '{label}': {language.name} mutations do not support 'only'")
149
152
  old = "\n".join(lines["-"])
150
- count = text.count(old) if old else 0
151
- if count != 1:
153
+ start = text.find(old) if old else -1
154
+ if start < 0 or text.find(old, start + len(old)) >= 0:
155
+ count = text.count(old) if old else 0
152
156
  stop(f"mutation '{label}': its - text occurs {count} times in {model}, want 1")
153
157
  detects, only = (lines[keyword][0].strip() if lines[keyword] else "" for keyword in SINGLE)
154
158
  new = "\n".join(lines["+"])
155
- return Mutation(label, detects, only, old, new, text, text.replace(old, new))
159
+ return Mutation(label, detects, only, old, new, text, start)
156
160
 
157
161
 
158
162
  def check_tla(plan, checker, mutation, work):
159
163
  try:
160
- detection = plan.check(checker, mutation.detects, mutation.only, mutation.source, work)
164
+ detection = plan.check(checker, mutation.detects, mutation.only, mutation.apply(), work)
161
165
  except ValueError as error:
162
166
  return Result(Verdict.ERROR, str(error))
163
167
  covers = frozenset({mutation.detects})
@@ -178,9 +182,9 @@ def check_lean(broken_checks, mutation, work):
178
182
 
179
183
  def check_rust(model, project, verifier, bounds, sources, mutation, work):
180
184
  """Run Kani on the named harness in a mutated copy of the crate; the mutation covers that harness."""
181
- copy = sources.stage(project, work / "source")
185
+ copy = sources.stage(project, work)
182
186
  covers = frozenset({mutation.detects})
183
- (copy / model.relative_to(project)).write_text(mutation.source, encoding="utf-8")
187
+ (copy / model.relative_to(project)).write_text(mutation.apply(), encoding="utf-8")
184
188
  # Cargo resolves configuration from cwd, including paths outside the copied packages.
185
189
  outcome = kani.verify(copy, work, verifier, mutation.detects, bounds[mutation.detects].unwind, cwd=project)
186
190
  if outcome.verdict is kani.Verdict.PASS:
@@ -370,19 +370,20 @@ def main():
370
370
  print(f"FAIL --source {source} is {path}, which no commit in {root} has")
371
371
  return 1
372
372
  sources.append(str(path.relative_to(root)))
373
- paths = renamed(root, sync, sources)
373
+ source_paths = renamed(root, sync, sources)
374
+ paths = set(source_paths)
374
375
  excluded = [f":(exclude){path}" for path in relative if path not in sources]
375
- suffixes = {Path(path).suffix.lower() for path in paths}
376
+ suffixes = {Path(path).suffix.lower() for path in source_paths}
376
377
  missing = []
377
378
  for name in arguments.name:
378
379
  found = git(root, "grep", "-l", "-z", "-w", "-F", "-e", name, "--", ".", *excluded, check=False)
379
380
  if found.returncode > 1:
380
381
  raise RuntimeError(f"git grep for {name} failed: {found.stderr.strip()}")
381
- roles = {file: role(file, paths, suffixes) for file in found.stdout.split("\0") if file}
382
+ roles = {file: role(file, source_paths, suffixes) for file in found.stdout.split("\0") if file}
382
383
  if not any(kind == "defines" and in_code(root, file, name) for file, kind in roles.items()):
383
384
  missing.append(name)
384
385
  files = [*roles, *held(root, sync, name, [".", *excluded])]
385
- paths.update(file for file in files if role(file, paths, suffixes))
386
+ paths.update(file for file in files if role(file, source_paths, suffixes))
386
387
  for path in sorted(paths):
387
388
  print(f"PATH {path}")
388
389
  for name in missing:
@@ -88,7 +88,11 @@ class Reach:
88
88
  @dataclass(frozen=True)
89
89
  class Run:
90
90
  label: str
91
- constants: str
91
+ bindings: tuple[tuple[str, str], ...]
92
+
93
+ @property
94
+ def constants(self):
95
+ return " ".join(f"{name}={value}" for name, value in self.bindings)
92
96
 
93
97
 
94
98
  @dataclass(frozen=True)
@@ -96,6 +100,16 @@ class Malformed:
96
100
  message: str
97
101
 
98
102
 
103
+ def _parse_run(label, constants):
104
+ bindings = []
105
+ for token in constants.split():
106
+ name, _, value = token.partition("=")
107
+ if not name or not value:
108
+ return Malformed(f"malformed constant {token!r} in run {label!r}: expected Name=Value")
109
+ bindings.append((name, value))
110
+ return Run(label, tuple(bindings))
111
+
112
+
99
113
  def _directives(lines):
100
114
  """Yield each directive of a matrix in file order, with a Malformed in place of a line it rejects."""
101
115
  seen_spec = False
@@ -131,7 +145,7 @@ def _directives(lines):
131
145
  elif not seen_spec:
132
146
  yield Malformed(f"run '{label.rstrip()}' before any spec line")
133
147
  else:
134
- yield Run(label.rstrip(), constants)
148
+ yield _parse_run(label.rstrip(), constants)
135
149
  else:
136
150
  yield Malformed(f"unknown directive: {line}")
137
151
 
@@ -513,7 +527,7 @@ def run_task(checker, matrix_dir, task, work, source=None, traces=False):
513
527
  spec, run = task.spec, task.run
514
528
  operator = task.reach.operator if task.reach else ""
515
529
  name = Path(spec).name.removesuffix(".tla")
516
- run_constants = run.constants.strip()
530
+ run_constants = run.constants
517
531
  run_checks = tuple(check.line for check in task.checks)
518
532
  if not (matrix_dir / spec).is_file():
519
533
  return Result(Outcome.MISSING, name, run.label, detail=spec, constants=run_constants, checks=run_checks)
@@ -525,7 +539,7 @@ def run_task(checker, matrix_dir, task, work, source=None, traces=False):
525
539
  dest.write_text(source, encoding="utf-8")
526
540
  else:
527
541
  dest.write_bytes(module.read_bytes())
528
- constants = "".join(f" {pair.split('=')[0]} = {pair.split('=', 1)[-1]}\n" for pair in run.constants.split())
542
+ constants = "".join(f" {name} = {value}\n" for name, value in run.bindings)
529
543
  config = f"CONSTANTS\n{constants}SPECIFICATION Spec\n"
530
544
  if not task.check_deadlock:
531
545
  config += "CHECK_DEADLOCK FALSE\n"