LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
line_timeout.h
Go to the documentation of this file.
1/*
2 * Copyright (c) 2012-2026, QORE Lab, Imperial College London
3 * All rights reserved.
4 */
5#ifndef LINE_UTIL_LINE_TIMEOUT_H
6#define LINE_UTIL_LINE_TIMEOUT_H
7
8/**
9 * @file
10 * @ingroup line_util
11 * `options.timeout`: one wall-clock budget per top-level solve, on a per-THREAD
12 * deadline stack.
13 *
14 * The C++ twin of MATLAB's `lineTimeoutArm` / `lineTimeoutRemaining` /
15 * `lineTimeoutExceeded` / `lineTimeoutTripped` / `lineTimeoutTrip`, the JAR's
16 * `jline.util.LineTimeout` and Python's `line_solver._timeutil`. The contract:
17 *
18 * - `timeout_arm(budget)` pushes a frame whose budget is
19 * min(budget, the outer frame's remaining time) and returns an RAII scope
20 * that pops it. A non-finite or non-positive budget pushes NOTHING, so an
21 * unbudgeted inner solve keeps reading its caller's frame and never
22 * restarts the clock.
23 * - `timeout_exceeded()` is the CHECKPOINT: true when the top frame's budget
24 * has run out, and it marks that frame TRIPPED as it says so.
25 * - The result flag (`AvgTable::timed_out`, `"timedOut"` on the CLI wire) is
26 * read from the TRIPPED LATCH, never from "elapsed > budget": a run that
27 * finished its loop and then overran in post-processing returned its full
28 * answer and is not flagged.
29 * - Popping a tripped frame trips its parent, so the latch reaches the
30 * outermost scope that reports it.
31 *
32 * THREAD-LOCAL, NOT GLOBAL: two solves on two threads with different budgets
33 * never read each other's deadline (the JAR's static deadline did). A worker
34 * thread a solver spawns starts with an EMPTY stack, so a solver that fans out
35 * hands each worker the remaining budget explicitly (see `ldes_engine_solve`).
36 *
37 * The clock is `steady_clock`, compared as an elapsed double against a double
38 * budget, so neither a clock step nor a huge budget can overflow it.
39 *
40 * `timeout_check(where)` is the raising form, for the computations that have
41 * NO valid partial result -- a state space cut short, an exact recursion
42 * stopped mid-population -- and it raises `LINE:numerical:Timeout`.
43 */
44
45#include <chrono>
46#include <cmath>
47#include <cstdio>
48#include <limits>
49#include <string>
50#include <vector>
51
52#include "line/util/error.h"
53
54namespace line {
55namespace util {
56
57namespace timeout_detail {
58
59struct Frame {
60 std::chrono::steady_clock::time_point start;
61 double budget; ///< seconds, finite and positive
62 bool tripped;
63};
64
65inline std::vector<Frame>& stack() {
66 thread_local std::vector<Frame> s;
67 return s;
68}
69
70inline double elapsed(const Frame& f) {
71 return std::chrono::duration<double>(std::chrono::steady_clock::now() - f.start).count();
72}
73
74} // namespace timeout_detail
75
76/** Seconds left on the innermost armed budget; +Inf when none is armed. */
77inline double timeout_remaining() {
78 const std::vector<timeout_detail::Frame>& s = timeout_detail::stack();
79 if (s.empty()) return std::numeric_limits<double>::infinity();
80 const double r = s.back().budget - timeout_detail::elapsed(s.back());
81 return r > 0.0 ? r : 0.0;
82}
83
84/** Whether any budget is armed on this thread. */
85inline bool timeout_armed() { return !timeout_detail::stack().empty(); }
86
87/**
88 * The checkpoint: true when the innermost budget has run out, marking it
89 * tripped. Cheap (one `steady_clock::now()`), but a tight loop should still
90 * call it on a stride (1024 iterations is the convention here).
91 */
92inline bool timeout_exceeded() {
93 std::vector<timeout_detail::Frame>& s = timeout_detail::stack();
94 if (s.empty()) return false;
95 timeout_detail::Frame& top = s.back();
96 if (top.tripped) return true;
97 if (timeout_detail::elapsed(top) > top.budget) {
98 top.tripped = true;
99 return true;
100 }
101 return false;
102}
103
104/** Whether the innermost budget was tripped by a checkpoint or by `timeout_trip`. */
105inline bool timeout_tripped() {
106 const std::vector<timeout_detail::Frame>& s = timeout_detail::stack();
107 return !s.empty() && s.back().tripped;
108}
109
110/**
111 * Mark the innermost budget tripped without reading the clock: for an external
112 * engine that REPORTS it stopped on the budget (LDES `stoppingReason ==
113 * "max_time"`, a JSIM run given `-maxtime`). A no-op when nothing is armed.
114 */
115inline void timeout_trip() {
116 std::vector<timeout_detail::Frame>& s = timeout_detail::stack();
117 if (!s.empty()) s.back().tripped = true;
118}
119
120/**
121 * The raising checkpoint, for a computation with no valid partial result:
122 * throws `LINE:numerical:Timeout` naming `where` when the budget has run out.
123 */
124inline void timeout_check(const char* where) {
125 if (!timeout_exceeded()) return;
126 throw NumericError(ErrorKind{"Timeout"},
127 std::string(where) +
128 ": the wall-clock time budget (options.timeout) ran out before the "
129 "computation finished, and it has no valid partial result");
130}
131
132/**
133 * The hard kill bound of a child process under the armed budget: the remaining
134 * seconds plus `grace`, rounded up, as MATLAB's `lineTimeoutKillPrefix` builds
135 * `timeout -k 5 ceil(remaining+30)`. 0 (wait indefinitely) when nothing is armed.
136 */
137inline int timeout_kill_seconds(double grace = 30.0) {
138 const double r = timeout_remaining();
139 if (!std::isfinite(r)) return 0;
140 const double s = std::ceil(r + grace);
141 return s < 1.0 ? 1 : (s > 2.0e9 ? 2000000000 : static_cast<int>(s));
142}
143
144/**
145 * The kill bound of a child that also has a bound of its OWN (`explicit_seconds`,
146 * not positive = none): the tighter of the two, 0 when neither is set.
147 */
148inline int timeout_kill_bound(int explicit_seconds, double grace = 30.0) {
149 const int b = timeout_kill_seconds(grace);
150 if (explicit_seconds <= 0) return b;
151 return (b > 0 && b < explicit_seconds) ? b : explicit_seconds;
152}
153
154/**
155 * A child process was killed on its bound: raise `LINE:numerical:Timeout` when
156 * the armed budget is what ran out (a killed child wrote no result, so there is
157 * no partial one), and return otherwise so the caller reports its own bound.
158 */
159inline void timeout_raise_if_killed_on_budget(const std::string& who) {
160 if (!timeout_exceeded()) return;
161 throw NumericError(ErrorKind{"Timeout"},
162 who + " was killed on the wall-clock time budget (options.timeout) "
163 "before it wrote a result, so there is no partial solution to return");
164}
165
166/**
167 * The RAII frame `timeout_arm` returns. Movable, not copyable; an inert scope
168 * (nothing was pushed) pops nothing.
169 */
171 public:
172 TimeoutScope() : depth_(0) {}
173 explicit TimeoutScope(std::size_t depth) : depth_(depth) {}
174 TimeoutScope(TimeoutScope&& o) noexcept : depth_(o.depth_) { o.depth_ = 0; }
176 if (this != &o) {
177 pop();
178 depth_ = o.depth_;
179 o.depth_ = 0;
180 }
181 return *this;
182 }
183 TimeoutScope(const TimeoutScope&) = delete;
186
187 /** Whether this scope pushed a frame. */
188 bool active() const { return depth_ > 0; }
189
190 /**
191 * Pop the frame now (idempotent). A tripped frame, or any tripped frame
192 * above it that an outer pop is unwinding, trips the parent.
193 */
194 void pop() {
195 if (depth_ == 0) return;
196 std::vector<timeout_detail::Frame>& s = timeout_detail::stack();
197 if (s.size() >= depth_) {
198 bool tripped = false;
199 for (std::size_t k = depth_ - 1; k < s.size(); ++k) tripped = tripped || s[k].tripped;
200 s.resize(depth_ - 1);
201 if (tripped && !s.empty()) s.back().tripped = true;
202 }
203 depth_ = 0;
204 }
205
206 private:
207 std::size_t depth_; ///< 1-based stack depth of the frame pushed, 0 = inert
208};
209
210/**
211 * Arm `budget` seconds for the scope's lifetime, capped by the outer frame's
212 * remaining time. A non-finite or non-positive budget arms nothing.
213 */
214inline TimeoutScope timeout_arm(double budget) {
215 if (!(budget > 0.0) || !std::isfinite(budget)) return TimeoutScope();
216 std::vector<timeout_detail::Frame>& s = timeout_detail::stack();
217 const double outer = timeout_remaining();
219 f.start = std::chrono::steady_clock::now();
220 f.budget = budget < outer ? budget : outer;
221 f.tripped = false;
222 s.push_back(f);
223 return TimeoutScope(s.size());
224}
225
226/**
227 * The one warning a solve that stopped on its budget prints, MATLAB's
228 * `flagTimeout` text, on stderr as every other `[LINE] Warning` here.
229 */
230inline void timeout_warn(const std::string& solver, double budget) {
231 std::fprintf(stderr,
232 "[LINE] Warning: %s stopped early on the wall-clock time budget "
233 "(options.timeout=%gs); the returned metrics are the interim solution.\n",
234 solver.c_str(), budget);
235}
236
237} // namespace util
238} // namespace line
239
240#endif // LINE_UTIL_LINE_TIMEOUT_H
NumericError(const std::string &what)
Definition error.h:112
The RAII frame timeout_arm returns.
TimeoutScope & operator=(TimeoutScope &&o) noexcept
void pop()
Pop the frame now (idempotent).
TimeoutScope(std::size_t depth)
TimeoutScope & operator=(const TimeoutScope &)=delete
TimeoutScope(const TimeoutScope &)=delete
TimeoutScope(TimeoutScope &&o) noexcept
bool active() const
Whether this scope pushed a frame.
The exception types the port throws.
double elapsed(const Frame &f)
std::vector< Frame > & stack()
bool timeout_exceeded()
The checkpoint: true when the innermost budget has run out, marking it tripped.
void timeout_trip()
Mark the innermost budget tripped without reading the clock: for an external engine that REPORTS it s...
TimeoutScope timeout_arm(double budget)
Arm budget seconds for the scope's lifetime, capped by the outer frame's remaining time.
int timeout_kill_bound(int explicit_seconds, double grace=30.0)
The kill bound of a child that also has a bound of its OWN (explicit_seconds, not positive = none): t...
double timeout_remaining()
Seconds left on the innermost armed budget; +Inf when none is armed.
int timeout_kill_seconds(double grace=30.0)
The hard kill bound of a child process under the armed budget: the remaining seconds plus grace,...
void timeout_check(const char *where)
The raising checkpoint, for a computation with no valid partial result: throws LINE:numerical:Timeout...
bool timeout_tripped()
Whether the innermost budget was tripped by a checkpoint or by timeout_trip.
bool timeout_armed()
Whether any budget is armed on this thread.
void timeout_warn(const std::string &solver, double budget)
The one warning a solve that stopped on its budget prints, MATLAB's flagTimeout text,...
void timeout_raise_if_killed_on_budget(const std::string &who)
A child process was killed on its bound: raise LINE:numerical:Timeout when the armed budget is what r...
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
std::chrono::steady_clock::time_point start
double budget
seconds, finite and positive