-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathmain.go
More file actions
1444 lines (1301 loc) · 51.4 KB
/
Copy pathmain.go
File metadata and controls
1444 lines (1301 loc) · 51.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"encoding/json"
"errors"
ast "fizz/proto"
"flag"
"fmt"
"github.com/fizzbee-io/fizzbee/lib"
"github.com/fizzbee-io/fizzbee/modelchecker"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime/pprof"
"slices"
"strings"
"sync/atomic"
"syscall"
"time"
)
var isPlayground bool
var simulation bool
var internalProfile bool
var saveStates bool
var copyAst bool
var outputDir string
var seed int64
var maxRuns int
var simFirstTraces int
var explorationStrategy string
var traceFile string
var preinitHookFile string
var trace string
var preinitHook string
var traceExtend int
var isTest bool
var experimentalProcessedQueue bool
var experimentalNoGraph bool
var experimentalNoStateReturns bool
var noSymmetryReduction bool
func main() {
args := parseFlags()
// Check if the correct number of arguments is provided
if len(args) != 1 {
fmt.Println("Usage:", os.Args[0], "<json_file>")
os.Exit(1)
}
// --experimental_no_graph implies --experimental_processed_queue (the
// drop-graph optimization only makes sense in the queue-of-processed
// model). Auto-enable rather than erroring out.
if experimentalNoGraph && !experimentalProcessedQueue {
fmt.Println("Note: --experimental_no_graph auto-enables --experimental_processed_queue.")
experimentalProcessedQueue = true
}
// Get the input JSON file name from command line argument
jsonFilename := args[0]
dirPath := filepath.Dir(jsonFilename)
f := loadInputJSON(jsonFilename)
// --experimental_no_graph cannot support liveness checks (no graph to
// run SCC/cycle detection on). Refuse upfront if the spec declares any
// always-eventually / eventually-always / eventually invariants.
if experimentalNoGraph {
for _, inv := range f.Invariants {
for _, op := range inv.TemporalOperators {
if op == "eventually" || op == "always-eventually" || op == "eventually-always" {
fmt.Printf("--experimental_no_graph refused: spec declares liveness invariant '%s' (operator '%s'). The no-graph mode keeps no state graph, so cycle-based liveness checks cannot run.\n", inv.Name, op)
os.Exit(1)
}
}
}
}
sourceFileName := filepath.Join(dirPath, f.SourceInfo.GetFileName())
//fmt.Println("dirPath:", dirPath)
// Calculate the relative path
var stateConfig *ast.StateSpaceOptions
if traceFile != "" || trace != "" || traceExtend > 0 {
stateConfig = getStateConfigForTraceChecking(stateConfig)
} else {
stateConfig = loadStateOptions(dirPath, f.GetFrontMatter())
fmt.Printf("StateSpaceOptions: %+v\n", stateConfig)
applyDefaultStateOptions(stateConfig)
}
// no_graph mode cannot drive crash simulation (the crash variants
// rely on the in-memory graph: Attach/visited/Inbound). Warn loudly
// when crash_on_yield is on; the per-yield-point crashProcess /
// crashThread calls are no-oped below in the processor.
if experimentalNoGraph && stateConfig.GetOptions().GetCrashOnYield() {
fmt.Println("WARNING: --experimental_no_graph disables crash-on-yield simulation. Crash variants will NOT be explored. Set crash_on_yield: false to silence this warning, or omit --experimental_no_graph to keep crash simulation.")
}
outDir, err := createOutputDir(dirPath, isTest)
if err != nil {
return
}
err = dumpStateSpaceOptions(stateConfig, outDir)
if err != nil {
fmt.Printf("Error writing state space options: %v\n", err)
return
}
if f.Composition != nil {
runCompositionalModelChecking(f, dirPath, outDir)
} else if len(f.Refinements) > 0 {
if len(f.Refinements) > 1 {
fmt.Println("Multiple refinements found. Only single refinement is supported currently. Contact us if you need support for multiple refinements.")
return
}
runRefinementModelChecking(f, dirPath, outDir, jsonFilename)
} else {
// For single spec model checking, copy AST to the output directory
if copyAst {
err = copyAstToOutputDir(jsonFilename, outDir)
if err != nil {
fmt.Printf("Error copying AST file: %v\n", err)
return
}
}
modelCheckSingleSpec(f, stateConfig, dirPath, outDir, sourceFileName, jsonFilename, nil)
}
}
func dumpStateSpaceOptions(stateConfig *ast.StateSpaceOptions, outDir string) error {
stateConfigJson, err := protojson.MarshalOptions{
Multiline: true,
}.Marshal(stateConfig)
if err != nil {
return err
}
err = os.WriteFile(filepath.Join(outDir, "state_config.json"), stateConfigJson, 0644)
return err
}
func copyAstToOutputDir(jsonFilename string, outDir string) error {
// Read the AST JSON file
astContent, err := os.ReadFile(jsonFilename)
if err != nil {
return fmt.Errorf("failed to read AST file: %w", err)
}
// Create the destination path with fixed name spec_ast.json
destPath := filepath.Join(outDir, "spec_ast.json")
// Write the AST to the output directory
err = os.WriteFile(destPath, astContent, 0644)
if err != nil {
return fmt.Errorf("failed to write AST file: %w", err)
}
return nil
}
func runCompositionalModelChecking(f *ast.File, dirPath string, outDir string) {
if simulation {
fmt.Println("Simulation mode not supported for composition")
return
}
roots := make(map[string]*modelchecker.Node)
rootsList := make([]*modelchecker.Node, len(f.Composition.GetSpecs()))
// create a map to store the interface preserving states
// key is the hash, value is the list of (list of Nodes)
joinHashes := make(modelchecker.JoinHashes)
for i, spec := range f.Composition.GetSpecs() {
fmt.Printf("\nComposed Spec: %s\n", spec.Name)
fileRef, fnRef, err := ParseFunctionRef(spec.Expr.GetPyExpr())
if err != nil {
fmt.Println("Error parsing function reference:", err)
return
} else if fileRef != spec.Name {
fmt.Println("File reference does not match spec name:", fileRef, "!=", spec.Name)
return
}
// Get the new json file name as dirPath + "/" + name + ".json"
composedJsonFileName := filepath.Join(dirPath, spec.Name+".json")
composedFile := loadInputJSON(composedJsonFileName)
composedSourceFileName := filepath.Join(dirPath, composedFile.SourceInfo.GetFileName())
composedStateConfig := loadStateOptions(dirPath, composedFile.GetFrontMatter())
applyDefaultStateOptions(composedStateConfig)
composedOutDir := filepath.Join(outDir, spec.Name)
if err := os.MkdirAll(composedOutDir, 0755); err != nil {
fmt.Println("Error creating directory:", err)
return
}
if copyAst {
err = copyAstToOutputDir(composedJsonFileName, composedOutDir)
if err != nil {
fmt.Printf("Error copying AST file: %v\n", err)
return
}
}
err = dumpStateSpaceOptions(composedStateConfig, composedOutDir)
if err != nil {
fmt.Printf("Error writing state space options: %v\n", err)
return
}
fmt.Println("Model checking composed spec:", composedSourceFileName)
root := modelCheckSingleSpec(composedFile, composedStateConfig, dirPath, composedOutDir, composedSourceFileName, composedJsonFileName, nil)
if root == nil {
fmt.Println("Error in model checking composed spec:", spec.Name, "Aborting")
return
}
roots[spec.Name] = root
rootsList[i] = root
populateJoinHashes(joinHashes, i, root, fileRef, fnRef)
}
err := ComposeTransitions(f, joinHashes, rootsList, outDir)
if err != nil {
fmt.Println("Error composing transitions:", err)
return
}
return
}
func runRefinementModelChecking(f *ast.File, dirPath string, outDir string, jsonFilename string) {
if simulation {
fmt.Println("Simulation mode not supported for refinement")
return
}
if len(f.Refinements) == 0 {
fmt.Println("No refinement specification found")
return
}
// For now, assume only one refinement block
refinement := f.Refinements[0]
// Create map of roots for abstract specs
roots := make(map[string]*modelchecker.Node)
rootsList := make([]*modelchecker.Node, len(refinement.GetSpecs()))
joinHashes := make(modelchecker.JoinHashes)
var implSpecIndex int = -1
// First, run model checking for each abstract spec (not "_")
for i, spec := range refinement.GetSpecs() {
if spec.Name == "_" {
implSpecIndex = i
continue
}
fmt.Printf("\nRefined Spec: %s\n", spec.Name)
fileRef, fnRef, err := ParseFunctionRef(spec.Expr.GetPyExpr())
if err != nil {
fmt.Println("Error parsing function reference:", err)
return
} else if fileRef != spec.Name {
fmt.Println("File reference does not match spec name:", fileRef, "!=", spec.Name)
return
}
abstractJsonFile := filepath.Join(dirPath, spec.Name+".json")
abstractFile := loadInputJSON(abstractJsonFile)
abstractSourceFile := filepath.Join(dirPath, abstractFile.SourceInfo.GetFileName())
stateConfig := loadStateOptions(dirPath, abstractFile.GetFrontMatter())
applyDefaultStateOptions(stateConfig)
abstractOutDir := filepath.Join(outDir, spec.Name)
if err := os.MkdirAll(abstractOutDir, 0755); err != nil {
fmt.Println("Error creating directory:", err)
return
}
if copyAst {
err = copyAstToOutputDir(abstractJsonFile, abstractOutDir)
if err != nil {
fmt.Printf("Error copying AST file: %v\n", err)
return
}
}
err = dumpStateSpaceOptions(stateConfig, abstractOutDir)
if err != nil {
fmt.Printf("Error writing state space options: %v\n", err)
return
}
fmt.Println("Model checking abstract spec:", abstractSourceFile)
root := modelCheckSingleSpec(abstractFile, stateConfig, dirPath, abstractOutDir, abstractSourceFile, abstractJsonFile, nil)
if root == nil {
fmt.Println("Error in model checking abstract spec:", spec.Name)
return
}
roots[spec.Name] = root
rootsList[i] = root
populateJoinHashes(joinHashes, i, root, fileRef, fnRef)
}
if implSpecIndex == -1 {
fmt.Println("Error: no implementation (_) spec found in refinement block")
return
}
// Now run model checking on the implementation (this file), using joinHashes
implOutDir := filepath.Join(outDir, "_")
if err := os.MkdirAll(implOutDir, 0755); err != nil {
fmt.Println("Error creating directory:", err)
return
}
if copyAst {
err := copyAstToOutputDir(jsonFilename, implOutDir)
if err != nil {
fmt.Printf("Error copying AST file: %v\n", err)
return
}
}
fmt.Println("Model checking implementation spec (refined):", f.SourceInfo.GetFileName())
stateConfig := loadStateOptions(dirPath, f.GetFrontMatter())
applyDefaultStateOptions(stateConfig)
err := dumpStateSpaceOptions(stateConfig, implOutDir)
if err != nil {
fmt.Printf("Error writing state space options: %v\n", err)
return
}
root := modelCheckSingleSpec(f, stateConfig, dirPath, implOutDir, f.SourceInfo.GetFileName(), jsonFilename, joinHashes)
if root == nil {
fmt.Println("Error in model checking implementation spec")
return
}
return
}
type ComposedNode = struct {
*modelchecker.Node
Nodes []*modelchecker.Node
}
type ComposedTransition = struct {
From *ComposedNode
To *ComposedNode
}
func cartesianProduct(sets []modelchecker.TransitionSet, handler func(ts []lib.Pair[*modelchecker.Node, *modelchecker.Node]) (
*ComposedNode, *ComposedTransition)) (*ComposedNode, *ComposedTransition) {
var helper func(int, []lib.Pair[*modelchecker.Node, *modelchecker.Node])
var failedNode *ComposedNode
var failedTransition *ComposedTransition
helper = func(depth int, current []lib.Pair[*modelchecker.Node, *modelchecker.Node]) {
if depth == len(sets) {
failedNode, failedTransition = handler(current)
return
}
for t := range sets[depth] {
helper(depth+1, append(current, t))
if failedNode != nil || failedTransition != nil {
return // Stop further processing if a failure is found
}
}
}
helper(0, []lib.Pair[*modelchecker.Node, *modelchecker.Node]{})
if failedTransition != nil {
fmt.Println("Failed Transition:", failedTransition.From.Nodes, "->", failedTransition.To.Nodes)
} else if failedNode != nil {
fmt.Println("Failed Node:", failedNode.Nodes)
}
return failedNode, failedTransition
}
func ComposeTransitions(f *ast.File, joinHashes modelchecker.JoinHashes, roots []*modelchecker.Node, outDir string) error {
hasTransitionInvariant := false
for _, invariant := range f.Invariants {
if invariant.Block != nil && slices.Contains(invariant.TemporalOperators, "transition") {
hasTransitionInvariant = true
break
}
}
for key, sets := range joinHashes {
if len(sets) < 2 {
return fmt.Errorf("need at least 2 transition sets for key %s", key)
}
failedNode, failedTransition := cartesianProduct(sets, func(ts []lib.Pair[*modelchecker.Node, *modelchecker.Node]) (*ComposedNode, *ComposedTransition) {
// Check if all transitions are stuttering
allStuttering := true
for _, t := range ts {
if t.First.Heap.HashCode() != t.Second.Heap.HashCode() {
allStuttering = false
break
}
}
if allStuttering {
return nil, nil // Skip all-stuttering transitions
}
composedFrom := make(map[string]*modelchecker.Heap)
composedTo := make(map[string]*modelchecker.Heap)
from := &ComposedNode{Nodes: make([]*modelchecker.Node, len(ts))}
to := &ComposedNode{Nodes: make([]*modelchecker.Node, len(ts))}
for i, t := range ts {
from.Nodes[i] = t.First
to.Nodes[i] = t.Second
composedFrom[f.Composition.GetSpecs()[i].GetName()] = t.First.Heap
composedTo[f.Composition.GetSpecs()[i].GetName()] = t.Second.Heap
}
composed := &ComposedTransition{From: from, To: to}
// Handle composed transition
processTo := modelchecker.NewProcess("yield", []*ast.File{f}, nil)
processTo.Enable()
processTo.Heap = modelchecker.NewComposedHeap(composedTo)
failedInvariants := modelchecker.CheckInvariants(processTo)
to.Node = modelchecker.NewNode(processTo)
if len(failedInvariants) > 0 && len(failedInvariants[0]) > 0 {
processTo.FailedInvariants = failedInvariants
fmt.Println("Composed state failed invariants:", failedInvariants)
processTo.FailedInvariants = failedInvariants
return to, nil
}
if hasTransitionInvariant {
processFrom := modelchecker.NewProcess("yield", []*ast.File{f}, nil)
processFrom.Enable()
processFrom.Heap = modelchecker.NewComposedHeap(composedFrom)
processTo.Parent = processFrom
failedTransitionInvariants := modelchecker.CheckTransitionInvariants(processTo)
if len(failedTransitionInvariants) > 0 && len(failedTransitionInvariants[0]) > 0 {
//processTo.FailedInvariants = failedInvariants
fmt.Println("Composed transition failed invariants:", failedTransitionInvariants)
link := &modelchecker.Link{
Node: to.Node,
Name: "composed-transition",
FailedInvariants: failedTransitionInvariants,
}
from.Node = modelchecker.NewNode(processFrom)
from.Outbound = append(from.Outbound, link)
to.Inbound = append(to.Inbound, link)
return to, composed
}
}
return nil, nil
})
if failedNode != nil || failedTransition != nil {
if failedTransition != nil {
fmt.Println("Failed Composed Node:", failedTransition)
printComposedTransition(failedTransition)
dumpComposedFailedTransition(failedTransition, f.Composition, roots, outDir)
} else /*if failedNode != nil*/ {
fmt.Println("Failed Composed Node:", failedNode.Nodes)
dumpComposedFailedNode(failedNode, f.Composition, roots, outDir)
}
return fmt.Errorf("failed to compose transitions for key %s", key)
}
}
return nil
}
func printComposedTransition(composed *ComposedTransition) {
fmt.Printf("Composed transition: ")
for i := range composed.From.Nodes {
fmt.Printf("(%s -> %s) ", composed.From.Nodes[i].Heap.String(), composed.To.Nodes[i].Heap.String())
}
fmt.Println()
}
func ParseFunctionRef(input string) (string, string, error) {
input = strings.TrimSpace(input)
if input == "" {
return "", "", errors.New("input is empty")
}
parts := strings.Split(input, ".")
switch len(parts) {
//case 1:
// funcName := strings.TrimSpace(parts[0])
// if funcName == "" {
// return "", "", errors.New("function name is required")
// }
// return "", funcName, nil
case 2:
fileRef := strings.TrimSpace(parts[0])
funcName := strings.TrimSpace(parts[1])
if fileRef == "" || funcName == "" {
return "", "", errors.New("file reference or function name is empty")
}
return fileRef, funcName, nil
default:
return "", "", errors.New("invalid function reference format. Expected format: 'fileName.funcName'")
}
}
func populateJoinHashes(joinHashes modelchecker.JoinHashes, i int, root *modelchecker.Node, fileRef string, fnRef string) {
visited := make(map[*modelchecker.Node]bool)
var dfs func(from *modelchecker.Node, current *modelchecker.Node)
dfs = func(from *modelchecker.Node, current *modelchecker.Node) {
if from != nil && current.IsYieldNode() {
addToJoinHashes(joinHashes, i, from, current, fnRef)
}
if visited[current] {
return
}
visited[current] = true
if current.IsYieldNode() {
// Add stuttering (to, to) link for new Nodes discovered
addToJoinHashes(joinHashes, i, current, current, fnRef)
from = current // update 'from' for child traversal
}
for _, child := range current.Outbound {
if child.Node != nil {
dfs(from, child.Node)
}
}
}
dfs(nil, root)
}
func addToJoinHashes(joinHashes modelchecker.JoinHashes, i int, from, to *modelchecker.Node, fnName string) {
//fmt.Println("Adding to join hashes:", from.Heap.String(), "->", to.Heap.String(), "for function", fnName)
fromState := modelchecker.ExecFunction(from.Process.CloneForAssert(nil, 0), fnName).String()
toState := modelchecker.ExecFunction(to.Process.CloneForAssert(nil, 0), fnName).String()
key := modelchecker.HashKey(fromState + "," + toState)
if _, exists := joinHashes[key]; !exists {
joinHashes[key] = make([]modelchecker.TransitionSet, i+1)
}
for len(joinHashes[key]) <= i {
joinHashes[key] = append(joinHashes[key], make(modelchecker.TransitionSet))
}
if joinHashes[key][i] == nil {
joinHashes[key][i] = make(modelchecker.TransitionSet)
}
pair := lib.NewPair(from, to)
joinHashes[key][i][pair] = true
}
// replayTraceWithFullState writes the action-name path to a trace file
// (so the user has it on disk too) and re-execs the binary with
// --trace-file pointing at it. The replay runs in default mode (with
// graph) so the standard error-report machinery prints the per-step
// state — converting the lightweight no_graph trace into the full
// rich output that the user would have seen without --experimental_no_graph.
// Best-effort: failures to write/exec just print a fallback command.
func replayTraceWithFullState(path []string, outDir, jsonFilename string) {
if len(path) == 0 || jsonFilename == "" {
return
}
traceFile := filepath.Join(outDir, "trace.txt")
body := strings.Join(path, "\n") + "\n"
if err := os.WriteFile(traceFile, []byte(body), 0644); err != nil {
fmt.Printf("(replay skipped: %v)\n", err)
return
}
self, err := os.Executable()
if err != nil {
fmt.Printf("(replay skipped: %v)\nReplay manually with:\n fizz --trace-file %s <spec.fizz>\n", err, traceFile)
return
}
// Preserve flags that change which spec state space the replay sees.
// preinit-hook flags override spec constants; if we drop them the
// replay reads a different spec (different NUM_WRITERS, etc.) and the
// trace won't match anything. Everything else is safe to leave at
// default for the replay — guided trace fixes the path either way.
args := []string{"--trace-file", traceFile}
if preinitHookFile != "" {
args = append(args, "--preinit-hook-file", preinitHookFile)
}
if preinitHook != "" {
args = append(args, "--preinit-hook", preinitHook)
}
args = append(args, jsonFilename)
fmt.Println()
fmt.Println("=== Replaying trace with full per-step state ===")
cmd := exec.Command(self, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
_ = cmd.Run()
}
func modelCheckSingleSpec(f *ast.File, stateConfig *ast.StateSpaceOptions, dirPath string, outDir string, sourceFileName string, jsonFilename string, hashes modelchecker.JoinHashes) *modelchecker.Node {
// Parse trace if provided (either from file or string)
var guidedTrace *modelchecker.GuidedTrace
if traceFile != "" {
var err error
guidedTrace, err = modelchecker.ParseTraceFile(traceFile)
if err != nil {
fmt.Printf("Error parsing trace file: %v\n", err)
return nil
}
fmt.Printf("Loaded trace with %d links\n", len(guidedTrace.LinkNames))
// Trace mode is incompatible with simulation
if simulation {
fmt.Println("Error: --trace-file and --simulation cannot be used together")
return nil
}
} else if trace != "" {
var err error
guidedTrace, err = modelchecker.ParseTraceString(trace)
if err != nil {
fmt.Printf("Error parsing trace string: %v\n", err)
return nil
}
fmt.Printf("Loaded trace with %d links\n", len(guidedTrace.LinkNames))
// Trace mode is incompatible with simulation
if simulation {
fmt.Println("Error: --trace and --simulation cannot be used together")
return nil
}
} else if traceExtend > 0 {
// No trace specified but --trace-extend given: explore traceExtend steps
// from the initial state (empty trace). guidedTrace with no LinkNames but
// ExtendDepth > 0 signals "explore N steps from Init" to ShouldScheduleNode.
if simulation {
fmt.Println("Error: --trace-extend and --simulation cannot be used together")
return nil
}
guidedTrace = &modelchecker.GuidedTrace{}
}
// Set trace extension depth if configured
if guidedTrace != nil && traceExtend > 0 {
guidedTrace.ExtendDepth = traceExtend
fmt.Printf("Trace will extend %d action(s) beyond the guided path\n", traceExtend)
}
// Resolve preinit hook content (either from file or string)
var preinitHookContentResolved string
if preinitHookFile != "" {
content, err := os.ReadFile(preinitHookFile)
if err != nil {
fmt.Printf("Error reading preinit hook file: %v\n", err)
return nil
}
preinitHookContentResolved = string(content)
} else if preinitHook != "" {
preinitHookContentResolved = preinitHook
}
//maxRuns := 10000
if !simulation || seed != 0 {
maxRuns = 1
}
if simulation && seed != 0 {
fmt.Println("Seed:", seed)
}
if simulation && maxRuns == 0 {
fmt.Println("MaxRuns: unlimited")
}
stopped := false
runs := 0
var p1 *modelchecker.Processor
var holder atomic.Pointer[modelchecker.Processor]
var lastRootNode *modelchecker.Node
setupSignalHandler(&holder, &stopped)
// Periodic simulation progress: print "\rSimulated N runs" to stderr
// every 100 runs when stderr is a TTY. Silent otherwise so log files,
// pipes, and parallel-worker captures stay clean. simProgressEmitted
// tracks whether we ever wrote a \r line; if so, callers below must
// emit \n to stderr before any non-progress output so the next message
// doesn't append to the progress line.
simProgressOnTty := false
simProgressEmitted := false
if simulation {
if fi, err := os.Stderr.Stat(); err == nil && (fi.Mode()&os.ModeCharDevice) != 0 {
simProgressOnTty = true
}
}
clearProgressLine := func() {
if simProgressEmitted {
fmt.Fprintln(os.Stderr)
simProgressEmitted = false
}
}
i := 0
for !stopped && (maxRuns <= 0 || i < maxRuns) {
i++
p1 = modelchecker.NewProcessor([]*ast.File{f}, stateConfig, simulation, seed, dirPath, explorationStrategy, isTest, hashes, guidedTrace, preinitHookContentResolved)
p1.SetExperimentalProcessedQueue(experimentalProcessedQueue)
p1.SetExperimentalNoGraph(experimentalNoGraph)
p1.SetExperimentalNoStateReturns(experimentalNoStateReturns)
p1.SetDisableSymmetryReduction(noSymmetryReduction)
holder.Store(p1)
rootNode, failedNode, endTime, err := startModelChecker(p1)
runs++
lastRootNode = rootNode
if simProgressOnTty && runs%100 == 0 {
// \033[K clears any leftover characters from a prior longer
// line (e.g. if maxRuns digit count shrinks across runs).
if maxRuns > 0 {
fmt.Fprintf(os.Stderr, "\r\033[KSimulated %d / %d runs", runs, maxRuns)
} else {
fmt.Fprintf(os.Stderr, "\r\033[KSimulated %d runs", runs)
}
simProgressEmitted = true
}
// Early deadlock detection (NEW path only): startProcessedQueue
// aborts the run on the first detected deadlock and exposes it
// here. Report and exit before any post-run graph traversal — no
// point doing the rest of the work, and dumpFailedNode reads
// node.Inbound which is still populated for this node. In
// no-graph mode the Inbound back-pointer was cleared, so fall
// back to the lightweight pathTail trace.
if earlyDead := p1.GetEarlyDeadlock(); earlyDead != nil && !simulation {
fmt.Println("DEADLOCK detected (early)")
fmt.Println("FAILED: Model checker failed")
if experimentalNoGraph {
path := earlyDead.PathNames()
fmt.Printf("Trace (%d steps):\n", len(path))
for _, step := range path {
fmt.Printf(" %s\n", step)
}
replayTraceWithFullState(path, outDir, jsonFilename)
} else {
dumpFailedNode(sourceFileName, earlyDead, rootNode, outDir)
}
return nil
}
if !simulation && !experimentalNoGraph {
if writeDotFileIfNeeded(p1, rootNode, outDir, "graph.dot") {
return nil
}
} else if i <= simFirstTraces {
// One file per captured run so the first N traces are
// preserved instead of overwriting each other on a shared
// graph.dot path. The "last run" still lands at graph.dot
// below (line 903) so existing tooling reading that canonical
// name keeps working.
writeDotFileIfNeeded(p1, rootNode, outDir, fmt.Sprintf("graph_run_%d.dot", i))
}
if err != nil {
printTraceAndExit(err)
}
// In no-graph mode there's no in-memory state graph to walk for
// dot generation, exists-witness checking, liveness, or deadlock
// detection via traverseBFS. Print a minimal summary and return.
// (Liveness was already refused at startup; deadlock detection in
// no-graph mode happens at expansion time inside startProcessedQueue.)
if experimentalNoGraph {
if failedNode != nil {
if failedNode.FailedInvariants != nil && len(failedNode.FailedInvariants) > 0 && len(failedNode.FailedInvariants[0]) > 0 {
fmt.Println("FAILED: Model checker failed. Invariant:", f.Invariants[failedNode.FailedInvariants[0][0]].Name)
} else {
fmt.Println("FAILED: Model checker failed")
}
path := failedNode.PathNames()
fmt.Printf("Trace (%d steps):\n", len(path))
for _, step := range path {
fmt.Printf(" %s\n", step)
}
replayTraceWithFullState(path, outDir, jsonFilename)
return nil
}
fmt.Printf("Visited entries: %d Unique states: %d\n", p1.GetVisitedNodesCount(), p1.GetUniqueYieldCount())
if p1.Stopped() {
fmt.Println("Model checker stopped")
return nil
}
fmt.Println("PASSED: Model checker completed successfully")
return rootNode
}
// Check if trace was fully executed
if guidedTrace != nil && !guidedTrace.IsExhausted() {
fmt.Printf("WARNING: Trace execution incomplete. Expected %d links, executed %d links.\n",
len(guidedTrace.LinkNames), guidedTrace.GetCurrentIndex())
fmt.Println("The trace may contain links that don't match the model or are unreachable.")
return nil
}
//fmt.Println("root", root)
if failedNode == nil {
var failurePath []*modelchecker.Link
var failedInvariant *modelchecker.InvariantPosition
nodes, messages, deadlock, yieldsCount := modelchecker.GetAllNodes(rootNode, stateConfig.GetOptions().GetMaxActions())
if writeCommunicationFileIfNeeded(messages, outDir) {
return nil
}
if deadlock != nil && stateConfig.GetDeadlockDetection() && !p1.Stopped() && !simulation {
fmt.Println("DEADLOCK detected")
fmt.Println("FAILED: Model checker failed")
if simulation {
fmt.Println("seed:", p1.Seed)
}
dumpFailedNode(sourceFileName, deadlock, rootNode, outDir)
return nil
}
if !simulation {
fmt.Println("Valid Nodes:", len(nodes), "Unique states:", yieldsCount)
// Skip the exists-witness check in trace mode: a guided trace
// only explores a slice of the state space, so `exists`
// invariants legitimately can't be satisfied yet. Letting the
// failure short-circuit here would also skip writing the
// nodes/links pb files, which the trace consumer needs.
if guidedTrace == nil {
invariants := modelchecker.CheckSimpleExistsWitness(nodes)
if len(invariants) > 0 {
fmt.Println("\nFAILED: Expected states never reached")
for i2, invariant := range invariants {
fmt.Printf("Invariant %d: %s\n", i2, f.Invariants[invariant.InvariantIndex].Name)
}
if !isTest {
fmt.Println("Time taken to check invariant: ", time.Now().Sub(endTime))
}
return nil
}
}
}
if !simulation && !p1.Stopped() && guidedTrace == nil {
if stateConfig.GetLiveness() == "" || stateConfig.GetLiveness() == "enabled" || stateConfig.GetLiveness() == "true" || stateConfig.GetLiveness() == "strict" || stateConfig.GetLiveness() == "strict/bfs" {
failurePath, failedInvariant = modelchecker.CheckStrictLiveness(rootNode, nodes)
} else if stateConfig.GetLiveness() == "eventual" || stateConfig.GetLiveness() == "nondeterministic" {
failurePath, failedInvariant = modelchecker.CheckFastLiveness(nodes)
}
fmt.Printf("IsLive: %t\n", failedInvariant == nil)
if !isTest {
fmt.Printf("Time taken to check liveness: %v\n", time.Now().Sub(endTime))
}
}
if failedInvariant == nil && !simulation {
if p1.Stopped() {
fmt.Println("Model checker stopped")
return nil
}
fmt.Println("PASSED: Model checker completed successfully")
//Nodes, _, _ := modelchecker.GetAllNodes(rootNode)
if saveStates || !isPlayground {
nodeFiles, linkFileNames, err := modelchecker.GenerateProtoOfJson(nodes, outDir+"/")
if err != nil {
fmt.Println("Error generating proto files:", err)
return rootNode
}
fmt.Printf("Writen %d node files and %d link files to dir %s\n", len(nodeFiles), len(linkFileNames), outDir)
}
return rootNode
} else if failedInvariant != nil {
fmt.Println("FAILED: Liveness check failed")
if failedInvariant.FileIndex > 0 {
fmt.Printf("Only one file expected. Got %d\n", failedInvariant.FileIndex)
} else {
fmt.Printf("Invariant: %s\n", f.Invariants[failedInvariant.InvariantIndex].Name)
}
GenerateFailurePath(sourceFileName, failurePath, failedInvariant, outDir)
_, _, err = modelchecker.GenerateErrorPathProtoOfJson(failurePath, outDir+"/")
if err != nil {
fmt.Println("Error writing files", err)
}
return nil
}
} else if failedNode != nil {
clearProgressLine()
// Always-assertion failures live on the node's Process.FailedInvariants.
// Transition-assertion failures live on the *inbound link* — see
// processor.go where CheckTransitionInvariants writes to
// node.Inbound[0].FailedInvariants. Without checking the link, a
// transition-assertion failure in simulation falls through to the
// misleading "Deadlock/stuttering" message, and in model-checking
// mode nothing about the failure is printed at all.
if failedNode.FailedInvariants != nil && len(failedNode.FailedInvariants) > 0 && len(failedNode.FailedInvariants[0]) > 0 {
fmt.Println("FAILED: Model checker failed. Invariant: ", f.Invariants[failedNode.FailedInvariants[0][0]].Name)
} else if len(failedNode.Inbound) > 0 && failedNode.Inbound[0].FailedInvariants != nil && len(failedNode.Inbound[0].FailedInvariants[0]) > 0 {
fmt.Println("FAILED: Model checker failed. Transition Invariant:", f.Invariants[failedNode.Inbound[0].FailedInvariants[0][0]].Name)
} else if simulation {
fmt.Println("FAILED: Model checker failed. Deadlock/stuttering detected")
} else {
fmt.Println("FAILED: Model checker failed (no failed-invariant metadata on the failing node; see trace below).")
}
if simulation {
fmt.Println("seed:", p1.Seed)
}
dumpFailedNode(sourceFileName, failedNode, rootNode, outDir)
return nil
}
}
clearProgressLine()
fmt.Println("Stopped after", runs, "runs at ", time.Now())
if simulation && p1 != nil {
if runs-simFirstTraces > 1 {
fmt.Println("Not printing intermediate traces (only the last trace is shown)")
}
// Always write the canonical graph.dot so downstream tooling
// (skills/scripts/docs that grep `out/*/graph.dot`) finds it
// even when --simulation_first_traces >= runs. When the last
// run was also captured as graph_run_<runs>.dot, this is a
// duplicate write — same content under the canonical name.
writeDotFileIfNeeded(p1, lastRootNode, outDir, "graph.dot")
}
return nil
}
func writeCommunicationFileIfNeeded(messages []string, outDir string) bool {
if len(messages) > 0 && !simulation {
graphDot := modelchecker.GenerateCommunicationGraph(messages)
dotFileName := filepath.Join(outDir, "communication.dot")
// Write the content to the file
err := os.WriteFile(dotFileName, []byte(graphDot), 0644)
if err != nil {
fmt.Println("Error writing to file:", err)
return true
}
if !isPlayground {
fmt.Printf("Writen communication diagram dotfile: %s\nTo generate svg, run: \n"+
"dot -Tsvg %s -o communication.svg && open communication.svg\n", dotFileName, dotFileName)
}
}
return false
}
func printTraceAndExit(err error) {
var modelErr *modelchecker.ModelError
if errors.As(err, &modelErr) {
fmt.Println("Stack Trace:")
fmt.Println(modelErr.SprintStackTrace())
} else {
fmt.Println("Error:", err)
}
os.Exit(1)
}
// writeDotFileIfNeeded writes the graph .dot file for the given root node
// to outDir/fileName when the visited-node count is small enough to be
// useful. fileName lets callers separate per-run outputs in simulation
// mode (graph_run_1.dot, graph_run_2.dot, …) from the canonical
// "last result" graph.dot used by the model-check path.
func writeDotFileIfNeeded(p1 *modelchecker.Processor, rootNode *modelchecker.Node, outDir string, fileName string) bool {
if p1.GetVisitedNodesCount() < 250 || (simulation && p1.GetVisitedNodesCount() < 1000) {
dotString := modelchecker.GenerateDotFile(rootNode, make(map[*modelchecker.Node]bool))
dotFileName := filepath.Join(outDir, fileName)
// Write the content to the file
err := os.WriteFile(dotFileName, []byte(dotString), 0644)
if err != nil {
fmt.Println("Error writing to file:", err)
return true
}
if !isPlayground {
fmt.Printf("Writen graph dotfile: %s\nTo generate svg, run: \n"+
"dot -Tsvg %s -o graph.svg && open graph.svg\n", dotFileName, dotFileName)
}
} else if !simulation {
fmt.Printf("Skipping dotfile generation. Too many Nodes: %d\n", p1.GetVisitedNodesCount())
}
return false
}
func setupSignalHandler(holder *atomic.Pointer[modelchecker.Processor], stopped *bool) {
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
fmt.Println("\nInterrupted. Stopping state exploration")
*stopped = true
p1 := holder.Load()
if p1 != nil {
p1.Stop()
}
}()
}
func applyDefaultStateOptions(stateConfig *ast.StateSpaceOptions) {
if stateConfig.Options.MaxActions == 0 {
stateConfig.Options.MaxActions = 100
}
if stateConfig.Options.MaxConcurrentActions == 0 {
stateConfig.Options.MaxConcurrentActions = min(2, stateConfig.Options.MaxActions)
}
if stateConfig.DeadlockDetection == nil {
deadlockDetection := true
stateConfig.DeadlockDetection = &deadlockDetection
}
if stateConfig.Options.CrashOnYield == nil {
crashOnYield := true
stateConfig.Options.CrashOnYield = &crashOnYield