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
|
package main
// HTTP + SSE frontend.
//
// The browser is a viewer, not an editor: you keep editing the .als in your own
// editor, and every save re-renders here. There is no npm, no bundler and no
// client framework -- the SVG is laid out by graphviz server-side and inlined,
// and the only JavaScript is a few lines of EventSource handling.
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
)
// server owns everything for the one model file being viewed: the solver
// worker, the job in flight, and the connected browsers.
//
// One model per process, deliberately. Watching a second file means running a
// second alloy-viz on another port. An earlier version keyed workers and jobs
// by path to allow several at once; nothing ever used more than one, and the
// job map it needed leaked a full instance XML on every save.
type server struct {
path string // absolute path of the .als being viewed
theme string // absolute path of the sibling .thm, if any
worker *worker // the Java solver holding this model
mu sync.Mutex
commands []CommandInfo
selected int
current *job // the job whose result is displayed, nil before the first run
loadErr *JobError
// subs are the connected SSE clients.
subsMu sync.Mutex
subs map[chan viewState]struct{}
}
// viewState is what the browser renders. It is pushed over SSE on every change,
// and is the only type here that is serialized.
type viewState struct {
Path string `json:"path"`
Commands []CommandInfo `json:"commands"`
Selected int `json:"selected"`
State string `json:"state"`
Label string `json:"label"`
Status string `json:"status"`
ElapsedMs int64 `json:"elapsed_ms"`
SVG string `json:"svg,omitempty"`
XML string `json:"xml,omitempty"`
Error string `json:"error,omitempty"`
ErrorPos string `json:"error_pos,omitempty"`
Running bool `json:"running"`
}
func newServer(path string) *server {
stem := strings.TrimSuffix(path, filepath.Ext(path))
return &server{
path: path,
theme: stem + ".thm",
worker: newWorker(path),
subs: make(map[chan viewState]struct{}),
}
}
// Shutdown kills the solver process. Without this a Ctrl-C would leave a JVM
// behind holding an open SAT solver.
func (s *server) Shutdown() { s.worker.kill() }
// Invalidate marks the parsed model stale, so the next run re-reads the file.
func (s *server) Invalidate() { s.worker.markStale() }
// Reload re-parses the model and starts the selected command. Called at startup
// and on every file change.
//
// Anything in flight is cancelled first. The worker processes one op at a time,
// so without this the parse below would queue behind a running solve and block
// for as long as that solve takes -- up to minutes -- while the user waits for
// the save they just made to show up. A save means the file changed, so a solve
// still running is working on text that no longer exists.
func (s *server) Reload(runIt bool) {
s.cancelCurrent("model changed")
cmds, err := s.parse()
s.mu.Lock()
if err != nil {
s.loadErr = asJobError(err)
s.commands = nil
s.mu.Unlock()
s.broadcast()
return
}
s.loadErr = nil
s.commands = cmds
if s.selected >= len(cmds) {
s.selected = 0
}
sel := s.selected
s.mu.Unlock()
s.broadcast()
if runIt && len(cmds) > 0 {
s.RunCommand(sel)
}
}
// RunCommand starts a job for the given command index and follows it.
//
// Only the selected command is ever run. Running every command in a file is
// what makes the CLI slow (14.7s for ceilingsAndFloors.als's five commands),
// and it is almost never what you want while editing.
//
// A run already in flight is superseded: the user's newest request is the one
// they care about, and the solver is single-threaded, so the old one has to go
// to make room. Superseding marks the old job cancelled *before* killing the
// worker, so its execute goroutine reports "cancelled" rather than mistaking
// the death for a JVM crash.
func (s *server) RunCommand(index int) {
s.mu.Lock()
if index < 0 || index >= len(s.commands) {
s.mu.Unlock()
return
}
s.selected = index
label := s.commands[index].Label
prev := s.current
// markCancelled is the one-shot gate: if the job was already cancelled --
// by Cancel, or by the Reload that led here -- its solver is dead already
// and killing again would hit whatever has replaced it.
superseded := prev != nil && !prev.snapshot().State.terminal() && prev.markCancelled()
j := newJob(index, label)
s.current = j
s.mu.Unlock()
if superseded {
log.Printf("superseding running job: killing solver")
s.worker.kill()
}
go s.execute(j, index)
go s.follow(j)
}
// follow consumes a job's updates and pushes rendered state to the browser.
func (s *server) follow(j *job) {
snap, updates := j.subscribe()
s.publish(j, snap)
if updates == nil {
return
}
for st := range updates {
s.publish(j, st)
}
}
// publish renders a job status into a viewState and broadcasts it to every
// connected browser.
//
// Updates from a job that is no longer the current one are dropped. A
// superseded job still has to wake up and record "cancelled" after its solver
// is killed, and that can happen after its replacement has already reported
// "solving"; since the SSE stream is last-write-wins, publishing it would leave
// the browser showing "cancelled" while a solve is in fact running.
func (s *server) publish(j *job, st JobStatus) {
if !s.isCurrent(j) {
return
}
s.push(s.viewFor(j, st))
}
// isCurrent reports whether j is still the job whose result is displayed.
func (s *server) isCurrent(j *job) bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.current == j
}
// viewFor builds the browser's view of one job status.
//
// This is the single place a JobStatus becomes a viewState; both the broadcast
// path and the seed sent to a newly connected client go through it, so a
// reconnecting browser sees exactly what a fresh one does.
func (s *server) viewFor(j *job, st JobStatus) viewState {
vs := s.baseState()
vs.State = string(st.State)
vs.Label = st.Label
vs.ElapsedMs = st.ElapsedMs
vs.Running = !st.State.terminal()
vs.Status = describeStatus(st)
if st.Err != nil {
vs.Error = st.Err.Message
if st.Err.Line > 0 {
vs.ErrorPos = fmt.Sprintf("%s:%d:%d",
filepath.Base(nonEmpty(st.Err.Filename, s.path)), st.Err.Line, st.Err.Column)
}
}
if st.State == StateDone && st.Result != nil {
if !st.Result.Satisfiable {
vs.Status = "no instance found (unsatisfiable)"
} else {
vs.XML = st.Result.InstanceXML
svg, err := s.render(st.Result.InstanceXML)
if err != nil {
vs.Error = err.Error()
} else {
vs.SVG = svg
}
}
}
return vs
}
// ── solver driving ─────────────────────────────────────────────────────────
// parse sends a parse op and waits for the command list.
//
// Blocking, because parsing is ~0.3-0.8s and every caller needs the answer
// before it can do anything else.
func (s *server) parse() ([]CommandInfo, error) {
ch, err := s.worker.send(workerRequest{Op: "parse", Path: s.path})
if err != nil {
return nil, err
}
for f := range ch {
switch f.Type {
case "commands":
s.worker.markParsed()
return f.Commands, nil
case "error":
return nil, frameError(f)
}
}
return nil, errKilled
}
// execute drives one job to completion on the worker.
func (s *server) execute(j *job, commandIndex int) {
// A fresh or killed process has no CompModule; a changed file has a stale
// one. Either way, re-parse before running.
if s.worker.needsParse() {
if _, err := s.parse(); err != nil {
s.finishErr(j, err)
return
}
}
ch, err := s.worker.send(workerRequest{Op: "run", CommandIndex: commandIndex})
if err != nil {
s.finishErr(j, err)
return
}
for f := range ch {
switch f.Type {
case "progress":
state := StateTranslating
if f.Phase == "solving" {
state = StateSolving
}
j.update(func(st *JobStatus) {
st.State = state
if st.Progress == nil {
st.Progress = &Progress{}
}
if f.Solver != "" {
st.Progress.Solver = f.Solver
}
if f.Bitwidth != 0 {
st.Progress.Bitwidth = f.Bitwidth
}
if f.TotalVars != 0 {
st.Progress.PrimaryVars = f.PrimaryVars
st.Progress.TotalVars = f.TotalVars
st.Progress.Clauses = f.Clauses
}
})
case "result":
j.update(func(st *JobStatus) {
st.State = StateDone
st.Result = &RunResult{
Satisfiable: f.Satisfiable,
InstanceXML: f.InstanceXML,
TraceLength: f.TraceLength,
LoopState: f.LoopState,
DurationMs: f.DurationMs,
}
})
return
case "error":
s.finishErr(j, frameError(f))
return
}
}
// Channel closed with no final frame: the process died. If we asked for
// that -- a cancel, or this job being superseded by a newer one -- it is a
// cancellation; otherwise the JVM crashed.
if j.wasCancelled() {
j.update(func(st *JobStatus) { st.State = StateCancelled })
} else {
s.finishErr(j, errors.New("solver process exited unexpectedly"))
}
}
func (s *server) finishErr(j *job, err error) {
je := asJobError(err)
j.update(func(st *JobStatus) {
st.State = StateError
st.Err = je
})
}
// Cancel stops the job in flight by killing the solver. There is no gentler
// option: SAT4J ignores interrupts entirely.
func (s *server) Cancel() { s.cancelCurrent("cancelling job") }
// cancelCurrent kills the solver if a job is in flight, freeing the worker for
// whatever the caller wants to do next, and reports whether it cancelled
// anything.
//
// The job is marked cancelled *before* the kill so its execute goroutine reads
// the resulting death as a cancellation rather than as a JVM crash. The kill
// itself blocks until the process is reaped, so on return the worker is
// genuinely free.
func (s *server) cancelCurrent(why string) bool {
s.mu.Lock()
j := s.current
s.mu.Unlock()
if j == nil || j.snapshot().State.terminal() || !j.markCancelled() {
return false
}
log.Printf("%s: killing solver for %s", why, s.path)
s.worker.kill()
return true
}
// frameError converts an error frame from the worker into a JobError.
func frameError(f *workerFrame) *JobError {
return &JobError{
Kind: f.Kind, Message: f.Message,
Filename: f.Filename, Line: f.Line, Column: f.Column,
}
}
// render turns instance XML into inline SVG.
func (s *server) render(xml string) (string, error) {
insts, err := ParseInstances(xml)
if err != nil {
return "", err
}
theme, err := LoadTheme(s.theme)
if err != nil {
log.Printf("theme %s: %v (using defaults)", s.theme, err)
theme = DefaultTheme()
}
// Slice 1 renders the first state only. Temporal models carry one instance
// per trace state; stepping through them is slice 2.
dot := RenderDOT(insts[0], theme)
return RenderSVG(context.Background(), dot)
}
func describeStatus(st JobStatus) string {
switch st.State {
case StateParsing:
return "parsing model…"
case StateTranslating:
if st.Progress != nil && st.Progress.Solver != "" {
return fmt.Sprintf("translating (%s, bitwidth %d)…", st.Progress.Solver, st.Progress.Bitwidth)
}
return "translating…"
case StateSolving:
if st.Progress != nil && st.Progress.TotalVars > 0 {
return fmt.Sprintf("solving (%d vars, %d clauses)…", st.Progress.TotalVars, st.Progress.Clauses)
}
return "solving…"
case StateDone:
if st.Result != nil {
return fmt.Sprintf("done in %d ms", st.Result.DurationMs)
}
return "done"
case StateCancelled:
return "cancelled"
case StateError:
return "error"
}
return string(st.State)
}
func (s *server) baseState() viewState {
s.mu.Lock()
defer s.mu.Unlock()
vs := viewState{
Path: s.path,
Commands: s.commands,
Selected: s.selected,
}
if s.loadErr != nil {
vs.State = "error"
vs.Status = "error"
vs.Error = s.loadErr.Message
if s.loadErr.Line > 0 {
vs.ErrorPos = fmt.Sprintf("%s:%d:%d",
filepath.Base(nonEmpty(s.loadErr.Filename, s.path)), s.loadErr.Line, s.loadErr.Column)
}
}
return vs
}
// broadcast pushes the current (job-less) state, e.g. after a parse error.
func (s *server) broadcast() { s.push(s.baseState()) }
func (s *server) push(vs viewState) {
s.subsMu.Lock()
defer s.subsMu.Unlock()
for ch := range s.subs {
select {
case ch <- vs:
default:
// Slow client; it will catch up on the next push.
}
}
}
// ── HTTP ───────────────────────────────────────────────────────────────────
func (s *server) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("/", s.handleIndex)
mux.HandleFunc("/events", s.handleEvents)
mux.HandleFunc("/run", s.handleRun)
mux.HandleFunc("/cancel", s.handleCancel)
return mux
}
func (s *server) handleIndex(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
data := struct {
Path string
Name string
}{s.path, filepath.Base(s.path)}
if err := indexTemplate.Execute(w, data); err != nil {
log.Printf("template: %v", err)
}
}
func (s *server) handleEvents(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
ch := make(chan viewState, 8)
s.subsMu.Lock()
s.subs[ch] = struct{}{}
s.subsMu.Unlock()
defer func() {
s.subsMu.Lock()
delete(s.subs, ch)
s.subsMu.Unlock()
}()
// Send the current state immediately so a fresh page is not blank while a
// long solve is already running, or after a reconnect.
s.mu.Lock()
cur := s.current
s.mu.Unlock()
seed := s.baseState()
if cur != nil {
seed = s.viewFor(cur, cur.snapshot())
}
select {
case ch <- seed:
default:
}
// Keep-alive comments stop intermediaries from dropping an idle stream
// during a multi-minute solve.
ticker := time.NewTicker(25 * time.Second)
defer ticker.Stop()
for {
select {
case <-r.Context().Done():
return
case <-ticker.C:
fmt.Fprint(w, ": keepalive\n\n")
flusher.Flush()
case vs := <-ch:
b, err := json.Marshal(vs)
if err != nil {
continue
}
fmt.Fprintf(w, "data: %s\n\n", b)
flusher.Flush()
}
}
}
func (s *server) handleRun(w http.ResponseWriter, r *http.Request) {
idx, err := strconv.Atoi(r.FormValue("index"))
if err != nil {
http.Error(w, "bad index", http.StatusBadRequest)
return
}
go s.RunCommand(idx)
w.WriteHeader(http.StatusNoContent)
}
func (s *server) handleCancel(w http.ResponseWriter, r *http.Request) {
s.Cancel()
w.WriteHeader(http.StatusNoContent)
}
func nonEmpty(a, b string) string {
if a != "" {
return a
}
return b
}
func asJobError(err error) *JobError {
var je *JobError
if errors.As(err, &je) {
return je
}
return &JobError{Kind: "internal", Message: err.Error()}
}
|