lumbda/examples/portal-prime.lsp
russell@unturf.com 6b832d5154 Add portal: serialize and resume VM state across machines
Portal saves the full machine state — env chain, compiled procedures,
continuations, frame stack — to a JSON file. Another interpreter
instance loads it and resumes execution from the exact instruction.

Demo: start a primality test on machine A, checkpoint mid-computation,
resume on machine B. 1000000007 prime check: machine B picks up from
i=30000 and finishes in 6% of the original time.

Implementation:
- PortalSerializer: graph-aware with identity tracking for shared env
  references. Handles cycles (closures referencing their own env).
- portal-checkpoint!: triggers mid-execution save from within VM loop.
  Hooks into TAIL_CALL (loop back-edge) for compiled code.
- --portal-resume CLI flag: load .portal file and resume continuation.
- portal-save / portal-resume Scheme builtins.

571 tests green (7 new portal tests: unit + integration + functional).
2026-04-13 19:00:11 -04:00

26 lines
976 B
Text

;;; portal-prime.lsp — portal a primality test between machines
;;;
;;; Machine A: python3 uncommonlisp.py --fast examples/portal-prime.lsp
;;; (starts computing, saves checkpoint to prime-state.portal)
;;;
;;; Machine B: python3 uncommonlisp.py --portal-resume prime-state.portal
;;; (resumes from checkpoint, finishes the computation)
(define (prime? n)
(display "Testing if ") (display n) (display " is prime...") (newline)
(let loop ((i 2) (checks 0))
(cond
((> (* i i) n)
(display " checked ") (display checks) (display " divisors") (newline)
#t)
((= (remainder n i) 0)
(display " found divisor: ") (display i) (newline)
#f)
(else
(when (= (remainder i 10000) 0)
(display " checkpoint at i=") (display i) (newline)
(portal-checkpoint! "prime-state.portal"))
(loop (+ i 1) (+ checks 1))))))
(define result (prime? 1000000007))
(display "Result: ") (display result) (newline)