Coverage for ppedit/_solveproc.py: 85.6%

138 statements  

« prev     ^ index     » next       coverage.py v7.18.0, created at 2026-11-30 17:40 +0000

1"""@private Run a cvxopf solve in a child process that can be stopped (issue #130) 

2 

3`SolveJob` is the handle the server shares between the request that 

4solves and the requests that read progress or stop the solve. `run` solves 

5with `ppedit._cvxopf.runopf` in a child process (a new Python interpreter running `_main`, so 

6it works the same on Linux, macOS and Windows, does not inherit the 

7server's threads and does not import the server's main script), passing 

8the inputs and messages as pickles over its stdin and stdout, relays the child's progress 

9reports to the job, and returns the child's result. `SolveJob.stop()` 

10kills the child: IPOPT, CLARABEL and CVXPY's model building run in C code, 

11which a Python thread cannot interrupt, so a process is the only way to 

12stop a solve at any point. The child runs in its own session (process 

13group) and ignores SIGINT from its first statement, so Ctrl-C in the 

14terminal running the server (or a SIGINT sent to the server's process 

15group) does not interrupt a solve; children still running when the 

16server exits are killed (`_kill_running`, `atexit`). Running in a child also keeps the server alive 

17when a solve runs out of memory (the operating system kills the child) and 

18returns the solver's memory to the system when the solve ends. 

19 

20Progress reports are dicts (see `ppedit._cvxopf.runopf`, `progress`): 

21`phase` (`start`, `build`, `derivatives`, `iterate`, `solve`, `results`), 

22`text` (a short description) and, while IPOPT iterates, `iteration`, 

23`max_iter`, `objective` (IPOPT's internal objective value), 

24`inf_pr` (primal infeasibility) and `inf_du` (dual infeasibility). 

25`SolveJob.status()` adds `running`, `elapsed` (s) and `stopping`. 

26 

27Caveats 

28------- 

29 

30 - The child starts a new Python interpreter and imports cvxopf, which 

31 adds one to a few seconds to every CVXOPF solve run through `run`. 

32 

33 - Python warnings raised in the child outside `runopf` are not relayed; 

34 `runopf` returns its own warnings in its result. 

35 

36 - The solver's own output (`verbose`) reaches the log only when the solve 

37 ends: a stopped solve has the progress reports in its log instead. 

38""" 

39 

40import atexit 

41import io 

42import os 

43import pickle 

44import queue 

45import signal 

46import subprocess 

47import sys 

48import threading 

49import time 

50 

51_CHILD = ("import signal; signal.signal(signal.SIGINT,signal.SIG_IGN); " # first: see _detached 

52 "from ppedit._solveproc import _main; _main()") 

53 

54_RUNNING = set() 

55"""Child processes now solving, killed when the server process exits""" 

56_RUNNING_LOCK = threading.Lock() 

57 

58@atexit.register 

59def _kill_running(): 

60 """Kill the solver processes still running (the server is stopping, e.g. 

61 Ctrl-C), so none is left behind""" 

62 with _RUNNING_LOCK: 

63 procs = list(_RUNNING) 

64 for proc in procs: 

65 if proc.poll() is None: 65 ↛ 64line 65 didn't jump to line 64 because the condition on line 65 was always true

66 proc.kill() 

67 

68def _detached() -> dict: 

69 """`subprocess.Popen` arguments that keep the child out of the 

70 terminal's process group, so Ctrl-C (SIGINT) in the terminal running 

71 the server does not interrupt the solver: only `SolveJob.stop()` ends it""" 

72 if os.name == "nt": 72 ↛ 73line 72 didn't jump to line 73 because the condition on line 72 was never true

73 return {"creationflags":subprocess.CREATE_NEW_PROCESS_GROUP} 

74 return {"start_new_session":True} 

75"""Python code the child process runs""" 

76 

77POLL = 0.25 

78"""Seconds between checks of the child process and the stop request""" 

79 

80class SolveStopped(Exception): 

81 """The solve was stopped by `SolveJob.stop()`""" 

82 

83class SolverProcessError(Exception): 

84 """The solver process failed or ended without a result""" 

85 

86class SolveJob: 

87 """Shared state of one solve: progress reports and the stop request 

88 

89 All methods may be called from any thread.""" 

90 

91 def __init__(self): 

92 self.started = time.time() 

93 """When the job was created (`time.time()`)""" 

94 self.stoppable = False 

95 """Whether the solve runs in a child process that `stop()` can end""" 

96 self.done = False 

97 """Whether the solve has ended""" 

98 self._stop = threading.Event() 

99 self._progress = {} 

100 self._lock = threading.Lock() 

101 

102 def report(self,progress:dict): 

103 """Record the latest progress report `progress`""" 

104 with self._lock: 

105 self._progress = dict(progress) 

106 

107 def stop(self) -> bool: 

108 """Ask for the solve to stop; return whether it can be stopped""" 

109 self._stop.set() 

110 return self.stoppable and not self.done 

111 

112 @property 

113 def stopping(self) -> bool: 

114 """Whether `stop()` was called""" 

115 return self._stop.is_set() 

116 

117 def status(self) -> dict: 

118 """Return the latest progress report with `running`, `elapsed` (s), 

119 `stoppable` and `stopping`""" 

120 with self._lock: 

121 out = dict(self._progress) 

122 out.update(running=not self.done,elapsed=time.time()-self.started, 

123 stoppable=self.stoppable,stopping=self.stopping) 

124 return out 

125 

126def describe(progress:dict) -> str: 

127 """Return a one-line description of the progress report `progress`""" 

128 if progress.get("phase") == "iterate" and progress.get("iteration") is not None: 

129 text = f"IPOPT iteration {progress['iteration']}" 

130 if progress.get("max_iter"): 130 ↛ 132line 130 didn't jump to line 132 because the condition on line 130 was always true

131 text += f" of at most {progress['max_iter']}" 

132 if progress.get("inf_pr") is not None: 132 ↛ 134line 132 didn't jump to line 134 because the condition on line 132 was always true

133 text += f", primal infeasibility {progress['inf_pr']:.2e}" 

134 return text 

135 return progress.get("text") or "" 

136 

137def _main(): 

138 """Child process: read the pickled 

139 `(ppc, formulation, options, series)` from stdin, solve, and write 

140 pickled `("progress", dict)` messages, then `("result", res, log)` or 

141 `("error", message, log)`, to the original stdout. File descriptor 1 

142 is pointed at stderr first, so what the solver prints cannot corrupt 

143 the messages.""" 

144 signal.signal(signal.SIGINT,signal.SIG_IGN) # stopped only by SolveJob.stop() (SIGKILL) 

145 out = os.fdopen(os.dup(1),"wb") 

146 os.dup2(2,1) 

147 sys.stdout = sys.stderr 

148 def send(msg): 

149 pickle.dump(msg,out) 

150 out.flush() 

151 log = io.StringIO() 

152 try: 

153 ppc,formulation,options,series = pickle.load(sys.stdin.buffer) 

154 from ppedit._cvxopf import runopf # pylint: disable=import-outside-toplevel 

155 res = runopf(ppc,formulation,log,options,series,progress=lambda p: send(("progress",p))) 

156 send(("result",res,log.getvalue())) 

157 except Exception as err: # pylint: disable=broad-exception-caught 

158 send(("error",str(err) or type(err).__name__,log.getvalue())) 

159 out.close() 

160 

161def _reader(stream,messages): 

162 """Thread: put each message from the child's `stream` into `messages`, 

163 then `None` at the end of the stream""" 

164 try: 

165 while True: 

166 messages.put(pickle.load(stream)) 

167 except Exception: # pylint: disable=broad-exception-caught 

168 pass # EOFError at the end; anything else means the child died mid-message 

169 messages.put(None) 

170 

171def run(job:SolveJob,ppc:dict,formulation:str,log,options:dict|None=None, 

172 series:dict|None=None) -> dict: 

173 """Solve like `ppedit._cvxopf.runopf(ppc,formulation,log,options,series)` 

174 in a child process, reporting progress to `job` 

175 

176 Exceptions 

177 ---------- 

178 

179 - `SolveStopped`: `job.stop()` was called; the child was killed 

180 

181 - `SolverProcessError`: the solve raised an error (its message) or 

182 the child ended without a result (e.g. killed for lack of memory) 

183 """ 

184 env = dict(os.environ) # find this ppedit even when it is not installed 

185 root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 

186 env["PYTHONPATH"] = root + (os.pathsep + env["PYTHONPATH"] if env.get("PYTHONPATH") else "") 

187 job.report({"phase":"start","text":"starting the solver process"}) 

188 proc = subprocess.Popen([sys.executable,"-c",_CHILD],env=env, # pylint: disable=consider-using-with 

189 stdin=subprocess.PIPE,stdout=subprocess.PIPE,**_detached()) 

190 with _RUNNING_LOCK: 

191 _RUNNING.add(proc) 

192 job.stoppable = True 

193 messages = queue.Queue() 

194 threading.Thread(target=_reader,args=(proc.stdout,messages),daemon=True).start() 

195 last = {} 

196 def where(): 

197 text = describe(last) 

198 return f"after {time.time()-job.started:.0f} s" + (f" ({text})" if text else "") 

199 try: 

200 try: 

201 pickle.dump((ppc,formulation,options,series),proc.stdin) 

202 proc.stdin.close() 

203 except OSError: 

204 pass # the child already ended: reported below 

205 while True: 

206 if job.stopping: 

207 proc.kill() 

208 proc.wait() 

209 log.write(f"\nSolve stopped by the user {where()}\n") 

210 raise SolveStopped(f"stopped by the user {where()}") 

211 try: 

212 msg = messages.get(timeout=POLL) 

213 except queue.Empty: 

214 continue 

215 if msg is None: 

216 code = proc.wait() 

217 log.write(f"\nSolver process ended with exit code {code} {where()}\n") 

218 raise SolverProcessError("the solver process ended without a result " 

219 f"(exit code {code}" + ("; killed by the operating system, possibly for " 

220 "lack of memory" if code < 0 or code == 137 else "") + ")") 

221 if msg[0] == "progress": 

222 last = msg[1] 

223 job.report(last) 

224 elif msg[0] == "result": 

225 log.write(msg[2]) 

226 return msg[1] 

227 else: 

228 log.write(msg[2]) 

229 raise SolverProcessError(msg[1]) 

230 finally: 

231 job.stoppable = False 

232 if proc.poll() is None: 

233 proc.kill() 

234 proc.wait() 

235 proc.stdout.close() 

236 with _RUNNING_LOCK: 

237 _RUNNING.discard(proc) 

238