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
package main

// Supervision of the Java solver process.
//
// One worker per model file, kept warm across saves and runs. The JVM costs
// ~0.5s to start and the parser another ~0.3s, so throwing the process away
// after every solve (and paying that again) is exactly what we avoid by keeping
// it alive.
//
// The worker is killed only to cancel a solve. That is unavoidable: a running
// SAT4J solve cannot be interrupted in-process (Thread.interrupt does not abort
// it -- kodkod's SAT4J.solve() is a bare isSatisfiable() with no interrupt
// polling), so the only cancel mechanism that exists is SIGKILL. The Alloy GUI
// solves it the same way, by running solves in a subprocess it can destroy.
//
// Losing the process loses the parsed CompModule, so the next request re-parses.
// That costs ~0.8s and only happens after a user-initiated cancel of a solve
// that was, by definition, taking long enough to be worth cancelling.

import (
	"bufio"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"log"
	"os"
	"os/exec"
	"sync"
)

// solverPathEnv names the environment variable the nix wrapper sets to point at
// the Java half. Without it we fall back to $PATH so a plain `go run` works.
const solverPathEnv = "ALLOY_VIZ_SOLVER"

// workerRequest is one message to the Java worker.
//
// command_index carries no omitempty: 0 is a valid index -- it is the default
// one -- and omitting it makes the Java side's req.get("command_index") return
// null, which NPEs. Running the first command in a file failed outright until
// this was noticed.
type workerRequest struct {
	ID           uint64 `json:"id"`
	Op           string `json:"op"`
	Path         string `json:"path,omitempty"`
	CommandIndex int    `json:"command_index"`
}

// workerFrame is one message from the Java worker. Which fields are populated
// depends on Type; see java/src/de/profpatsch/alloy/Worker.java.
type workerFrame struct {
	ID   uint64 `json:"id"`
	Type string `json:"type"` // "commands" | "progress" | "result" | "error"

	// type=commands
	Commands []CommandInfo `json:"commands,omitempty"`
	Path     string        `json:"path,omitempty"`

	// type=progress
	Phase       string `json:"phase,omitempty"` // "translating" | "solving"
	Solver      string `json:"solver,omitempty"`
	Bitwidth    int    `json:"bitwidth,omitempty"`
	PrimaryVars int    `json:"primary_vars,omitempty"`
	TotalVars   int    `json:"total_vars,omitempty"`
	Clauses     int    `json:"clauses,omitempty"`

	// type=result
	Satisfiable bool   `json:"satisfiable,omitempty"`
	InstanceXML string `json:"instance_xml,omitempty"`
	TraceLength int    `json:"trace_length,omitempty"`
	LoopState   int    `json:"loop_state,omitempty"`
	DurationMs  int64  `json:"duration_ms,omitempty"`

	// type=error
	Kind      string `json:"kind,omitempty"` // "parse" | "type" | "protocol" | "internal" | "no_such_command"
	Message   string `json:"message,omitempty"`
	Filename  string `json:"filename,omitempty"`
	Line      int    `json:"line,omitempty"`
	Column    int    `json:"column,omitempty"`
	Available int    `json:"available,omitempty"`
}

// CommandInfo describes one run/check command in a model.
type CommandInfo struct {
	Index   int    `json:"index"`
	Label   string `json:"label"`
	Kind    string `json:"kind"` // "run" | "check"
	Scope   string `json:"scope"`
	Expects int    `json:"expects"`
}

// isFinal reports whether this frame completes its request. Progress frames are
// the only non-final kind.
func (f *workerFrame) isFinal() bool { return f.Type != "progress" }

// errKilled is returned to any request in flight when the worker process is
// killed, which in practice means the user cancelled.
var errKilled = errors.New("solver process was killed")

// worker is a running Java solver process bound to a single model file.
//
// Requests are serialized: the Java side is single-threaded and processes one op
// at a time, so sending a second request while a solve is running would just
// queue it behind a potentially multi-minute wait. The caller (*server, via its
// single s.current job) enforces one in-flight request per worker, and cancels
// what is running before it needs the worker for anything else.
type worker struct {
	path string // model file this worker has parsed (or will parse)

	mu    sync.Mutex
	cmd   *exec.Cmd
	stdin io.WriteCloser
	// gen identifies the current process. It is incremented on every spawn so
	// a departing readLoop can tell whether it is cleaning up after itself or
	// would be trampling a process that has already replaced it. Without this,
	// the readLoop of a killed process races the respawn and closes the *new*
	// process's pending requests.
	//
	// kill() is synchronous, so it cannot itself produce that overlap any more,
	// but a JVM that dies on its own still can: nobody is waiting for that
	// readLoop, so a concurrent send() may respawn while it is still unwinding.
	gen uint64
	// done is closed by the readLoop of generation gen once it has finished
	// tearing down, so kill() can wait for the process to be truly gone rather
	// than merely signalled. Replaced on every spawn; nil before the first one.
	done    chan struct{}
	nextID  uint64
	pending map[uint64]chan *workerFrame
	dead    bool // process exited or was killed; needs respawn
	parsed  bool // a successful parse of path has happened in this process
}

func newWorker(path string) *worker {
	return &worker{path: path, pending: make(map[uint64]chan *workerFrame)}
}

// solverBinary resolves the Java worker executable.
func solverBinary() string {
	if p := os.Getenv(solverPathEnv); p != "" {
		return p
	}
	return "alloy-viz-solver"
}

// ensureStarted spawns the process if it is not running. Caller holds w.mu.
//
// It must stay under the *same* acquisition of w.mu as the w.pending
// registration that follows it in send(); see the invariant documented there.
func (w *worker) ensureStarted() error {
	if w.cmd != nil && !w.dead {
		return nil
	}
	bin := solverBinary()
	cmd := exec.Command(bin)
	stdin, err := cmd.StdinPipe()
	if err != nil {
		return fmt.Errorf("solver stdin: %w", err)
	}
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		return fmt.Errorf("solver stdout: %w", err)
	}
	stderr, err := cmd.StderrPipe()
	if err != nil {
		return fmt.Errorf("solver stderr: %w", err)
	}
	if err := cmd.Start(); err != nil {
		return fmt.Errorf("spawn %s: %w", bin, err)
	}

	w.cmd = cmd
	w.stdin = stdin
	w.dead = false
	w.parsed = false
	w.gen++
	// Created only now that the spawn has succeeded: a failed Start must not
	// leave behind a channel that nothing will ever close, which a later kill()
	// would then block on forever.
	done := make(chan struct{})
	w.done = done

	go w.readLoop(w.gen, done, cmd, stdout)
	go relayStderr(stderr)
	return nil
}

// relayStderr forwards the worker's diagnostics to our log. The Java side points
// System.out at stderr, so anything Alloy prints lands here rather than
// corrupting the frame stream.
func relayStderr(r io.ReadCloser) {
	sc := bufio.NewScanner(r)
	sc.Buffer(make([]byte, 0, 8192), 1<<20)
	for sc.Scan() {
		log.Printf("solver: %s", sc.Text())
	}
}

// readLoop decodes NUL-terminated frames and routes them to waiting callers.
// It exits when the process dies, failing every request still in flight.
//
// gen is the generation this loop belongs to; on exit it only tears down shared
// state if it is still the current one.
//
// done is closed last, on every exit path, so a waiter that observes it closed
// knows the process has been reaped and this loop has finished with w's state.
func (w *worker) readLoop(gen uint64, done chan struct{}, cmd *exec.Cmd, stdout io.ReadCloser) {
	defer close(done)

	sc := bufio.NewScanner(stdout)
	sc.Split(scanNulTerminated)
	// Instance XML for a large model comfortably exceeds the 64KB default.
	sc.Buffer(make([]byte, 0, 64*1024), 32*1024*1024)

	for sc.Scan() {
		var f workerFrame
		if err := json.Unmarshal(sc.Bytes(), &f); err != nil {
			log.Printf("solver: undecodable frame: %v", err)
			continue
		}
		w.mu.Lock()
		ch, ok := w.pending[f.ID]
		if ok && f.isFinal() {
			delete(w.pending, f.ID)
		}
		w.mu.Unlock()
		if !ok {
			// A late frame for a request whose caller has gone away (cancel).
			continue
		}
		// Non-blocking: the receiver buffers generously, and a slow consumer
		// must not wedge the reader.
		select {
		case ch <- &f:
		default:
			log.Printf("solver: dropped %s frame for id %d (slow consumer)", f.Type, f.ID)
		}
		if f.isFinal() {
			close(ch)
		}
	}

	_ = cmd.Wait()

	w.mu.Lock()
	// A newer process has already taken over (we were killed and respawned);
	// its readLoop owns the state now, and its pending requests are not ours
	// to fail.
	if w.gen != gen {
		w.mu.Unlock()
		return
	}
	w.dead = true
	w.parsed = false
	for id, ch := range w.pending {
		delete(w.pending, id)
		close(ch)
	}
	w.mu.Unlock()
}

// send dispatches a request and returns a channel of frames for it. The channel
// is closed after the final frame, or closed empty if the process died.
//
// Invariant, load-bearing for cancel and supersede: w.mu is held across *both*
// ensureStarted (which may respawn and bump w.gen) and the w.pending
// registration below. A request therefore cannot be registered against a
// generation that is about to change, so a departing readLoop either sees a
// generation mismatch and touches nothing, or runs entirely before the new
// request exists. Splitting this into two acquisitions reintroduces the race
// where a dead process's readLoop closes a live request's channel, which
// presents as the first run after any cancel failing.
//
// w.nextID deliberately survives respawns for the same reason: monotonic IDs
// mean a late frame from a dead process can never alias a live request.
func (w *worker) send(req workerRequest) (<-chan *workerFrame, error) {
	w.mu.Lock()
	defer w.mu.Unlock()

	if err := w.ensureStarted(); err != nil {
		return nil, err
	}
	w.nextID++
	req.ID = w.nextID

	// Buffered so readLoop never blocks: a solve emits at most a couple of
	// progress frames plus one final frame.
	ch := make(chan *workerFrame, 16)
	w.pending[req.ID] = ch

	b, err := json.Marshal(req)
	if err != nil {
		delete(w.pending, req.ID)
		return nil, err
	}
	if _, err := w.stdin.Write(append(b, 0)); err != nil {
		delete(w.pending, req.ID)
		w.dead = true
		return nil, fmt.Errorf("write to solver: %w", err)
	}
	return ch, nil
}

// kill terminates the process and waits for it to be reaped. This is the only
// way to stop a running solve.
//
// The wait matters: without it, a caller that kills and immediately sends again
// can have ensureStarted spawn a replacement before SIGKILL has landed, so two
// JVMs are briefly alive, each holding an open SAT solver. Under a burst of
// saves that fans out. Waiting makes "at most one solver process" structural
// rather than a matter of timing.
//
// w.mu is released before waiting, because the readLoop we are waiting for
// takes it during its own teardown.
func (w *worker) kill() {
	w.mu.Lock()
	cmd := w.cmd
	done := w.done
	w.dead = true
	w.parsed = false
	w.mu.Unlock()

	if cmd == nil || cmd.Process == nil {
		return
	}
	_ = cmd.Process.Kill()
	if done != nil {
		<-done
	}
}

// needsParse reports whether the worker must be (re)sent a parse before a run.
// True after a spawn, a kill, or an edit to the file.
func (w *worker) needsParse() bool {
	w.mu.Lock()
	defer w.mu.Unlock()
	return !w.parsed || w.dead
}

// markStale forces a re-parse on the next request, e.g. after the file changed.
func (w *worker) markStale() {
	w.mu.Lock()
	w.parsed = false
	w.mu.Unlock()
}

func (w *worker) markParsed() {
	w.mu.Lock()
	w.parsed = true
	w.mu.Unlock()
}

// scanNulTerminated is a bufio.SplitFunc for NUL-delimited frames.
func scanNulTerminated(data []byte, atEOF bool) (advance int, token []byte, err error) {
	for i := range data {
		if data[i] == 0 {
			return i + 1, data[0:i], nil
		}
	}
	if atEOF && len(data) > 0 {
		return len(data), data, nil
	}
	return 0, nil, nil
}