LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
ldes_ln_engine.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_SOLVERS_LDES_LDES_LN_ENGINE_H
6#define LINE_SOLVERS_LDES_LDES_LN_ENGINE_H
7
8/**
9 * @file
10 * @ingroup line_solvers
11 * The NATIVE LDES engine for LAYERED (LQN) models, the C++ twin of
12 * `jline/solvers/ldes/handlers/Solver_ssj_ln.java`.
13 *
14 * IT IS A DIFFERENT SIMULATOR FROM THE FLAT ONE, not a wrapper around it. A
15 * layered model has no jobs circulating over a routing matrix: it has
16 * REFERENCE TASKS that think and then invoke an entry, ACTIVITIES that consume
17 * host demand, and CALLS that suspend the caller until the callee replies. The
18 * decomposition into layers that `SolverLN` performs is an APPROXIMATION; this
19 * engine simulates the layered semantics directly and is therefore the
20 * reference the layered solvers are checked against.
21 *
22 * THE TWO RESOURCES ARE HELD AT ONCE, and that is the whole content of a
23 * layered model. An activity needs a THREAD of its task and a SERVER of its
24 * host, and it holds the thread across a synchronous call while the callee runs
25 * on a different host entirely. Releasing the thread during the call would turn
26 * every synchronous call into an asynchronous one and remove the layered
27 * contention the model exists to represent -- the answer stays plausible and
28 * every utilization falls.
29 *
30 * WHAT IT COVERS: reference tasks with think time and multiplicity; task
31 * multiplicity as a thread semaphore, with setup/delay-off power cycling;
32 * host demand on c-server processors under FCFS, LCFS, SIRO, HOL, FCFSPRIO,
33 * LCFSPRIO, FCFSPRPRIO, FCFSPIPRIO, LCFSPRPRIO, LCFSPIPRIO, PS, PSPRIO and INF,
34 * and task queueing under FCFS, LCFS, SIRO, HOL, FCFSPRIO, LCFSPRIO and INF,
35 * each served as Solver_ssj_ln serves it. The priority disciplines order by
36 * `lsn.prio` on the lqns scale, a LARGER number first and the default 0 lowest;
37 * HOL and FCFSPRIO are FIFO within a level, the LCFS variants LIFO; the PR/PI
38 * variants preempt, resuming the residual work (PR) or drawing a fresh demand
39 * (PI); PS is an egalitarian share min(1, c/n) of the c servers and PSPRIO
40 * gives the servers to the levels from the top down; INF never queues, whatever
41 * the multiplicity. Also synchronous calls with a mean call multiplicity,
42 * asynchronous calls and open arrivals (each a request nobody waits on),
43 * activity think times (after the demand, before the calls, holding the thread
44 * but not the processor), REPLICATION of a processor or a task, one queue per
45 * copy, and, as `Solver_ssj_ln` runs them:
46 *
47 * - ACTIVITY GRAPHS walked as graphs, not as a list. An entry starts at its
48 * bound activity and follows `graph`: one successor continues, an OR fork
49 * or a loop exit draws one branch, an AND fork splits the invocation into
50 * concurrent LINES sharing its thread, and an AND join fires on the root
51 * line once every PRE_AND input has arrived, or once `quorum` of them have
52 * on a QUORUM join, whose late inputs still run, holding the thread, and are
53 * discarded at the join. A phase-1 activity followed by phase 2 replies
54 * early, and the thread is held through phase 2; the main line reaching a
55 * leaf replies there even while other lines of the invocation still run.
56 * - FORWARDING: an entry that would reply to a synchronous request hands it,
57 * with the forwarding probability, to the target entry instead, and the
58 * original caller stays blocked until the end of the chain replies.
59 * - CACHE TASKS: one content per task replica, an ItemEntry read drawing an
60 * item from its pmf and continuing on the hit or the miss branch, the
61 * replacement rules RR/FIFO/SFIFO/LRU/HLRU/CLIMB/QLRU over the level lists,
62 * and delayed-hit retrieval (a read of an in-flight item is parked until
63 * the fetcher replies, then continues on the hit branch).
64 * - ADMISSION CONSTRAINTS A n <= b: a host row blocks a host request outside
65 * the processor (thread kept, residence running), a task row blocks a
66 * request before the task (counted nowhere), FIFO release on a departure,
67 * and a run that stops with a blocked request is reported as a deadlock.
68 * - HETEROGENEOUS SERVER POOLS on a processor, served as OI rate sharing: each
69 * pool puts its whole capacity count*rate on the first held job it serves.
70 *
71 * An activity runs its host demand FIRST, then its think time, then its calls,
72 * as LQN2QN builds it and Solver_ssj_ln runs it. An entry's response time is
73 * its service time, from taking a thread of its task to its reply: the wait for
74 * the thread belongs to the caller's call, except a cold start, which is
75 * charged to the request that waited through it. Its occupancy runs from the
76 * same instant to the end of its last phase. Task, entry and activity Util are
77 * DERIVED as Solver_ssj_ln derives them (throughput times host demand, over
78 * the host multiplicity); the measured busy threads are in `UThreadLN`.
79 *
80 * THE RUN IS COUNTED IN ACTIVITY COMPLETIONS and its first 20% are WARMUP, which is
81 * Solver_ssj_ln's rule: the budget `samples` (or `events`) is a number of activity
82 * completions, and at completion floor(0.2*budget) every statistic is reset. A time
83 * integral (QLen, Util) restarts from that instant, so a request straddling the reset
84 * contributes its part after it. A per-observation measure (a completion, a response
85 * time, a host residence, a cache read and its outcome) counts only the observations
86 * of the requests whose ROOT began after the reset: a reference cycle or an open
87 * arrival started after it, and every call, fork branch, forward and asynchronous
88 * request those spawn. A cycle straddling the reset is thus counted nowhere, at its
89 * request and at every one of its activities and calls alike, which keeps the
90 * flow-balance identities (an activity run once per cycle has the cycle's throughput)
91 * exact rather than one cycle off. Every rate is over the measured span.
92 *
93 * PROCESSOR UTIL IS THE TOTAL OVER THE REPLICAS, per server of one replica: the busy
94 * servers of all copies over the multiplicity, so `U = X*D/m` with X the total
95 * throughput. That is Solver_ssj_ln's table and SolverLN's (which scales one
96 * representative replica by REPL), and it exceeds 1 when a replicated processor is
97 * more than 1/REPL busy.
98 *
99 * WHAT IT REFUSES by name: every discipline the Java engine refuses (PS or
100 * preemption on a task, which holds threads and does not divide or preempt
101 * them, and any weighted discipline anywhere), a setup on an infinite-thread
102 * task, server pools on a task (both as the Java engine refuses them), a
103 * partial-quorum join that the main line of the invocation could reach as a
104 * late input, and a cache read whose ItemEntry has no popularity or no hit/miss pair.
105 * Routed call groups (round robin, JSQ) are dispatched as Solver_ssj_ln dispatches them.
106 */
107
108#include <algorithm>
109#include <cctype>
110#include <cmath>
111#include <cstddef>
112#include <cstdint>
113#include <deque>
114#include <functional>
115#include <limits>
116#include <list>
117#include <map>
118#include <queue>
119#include <set>
120#include <string>
121#include <vector>
122
126#include "line/util/error.h"
128#include "line/util/matrix.h"
129
130namespace line {
131namespace ldes {
132namespace engine {
133
134/** One scheduled event of the layered engine. */
135struct LnEvent {
136 double t = 0.0;
137 /**
138 * 0 = host completion (`who` = the LINE), 1 = think completion (`who` = the
139 * reference customer), 2 = a task thread finished its cold start, 3 = an
140 * idle task thread's delay-off countdown expired, 4 = the next completion
141 * on a pooled host replica (`who` = the host slot), 5 = the next completion
142 * on a PS host replica (`who` = the host slot), 6 = line `who` finished the
143 * think time of its activity, 7 = an open arrival at entry `who` on replica
144 * `aux` of its task. A kind-0 event carries the line's host generation, so a
145 * preemption makes it stale.
146 *
147 * For kinds 2 and 3 `who` is the task SLOT and `aux` the thread within it,
148 * and `gen` is the generation the timer was armed with: a countdown caught
149 * by an arriving request is cancelled by bumping the generation, so the
150 * event still fires but finds itself stale and does nothing. Kinds 4 and 5 use the
151 * same device per host slot, since every change of the job set moves the
152 * next completion. The event queue has no removal.
153 */
154 int kind = 0;
155 std::size_t who = 0;
156 std::size_t aux = 0;
157 std::uint64_t gen = 0;
158 std::uint64_t seq = 0;
159};
160
162 bool operator()(const LnEvent& a, const LnEvent& b) const {
163 if (a.t != b.t) return a.t > b.t;
164 if (a.kind != b.kind) return a.kind > b.kind;
165 return a.seq > b.seq;
166 }
167};
168
169/** Index meaning "none" for a line, an invocation or a customer. */
170static const std::size_t LN_NONE = static_cast<std::size_t>(-1);
171
172/**
173 * One LINE of execution: a point in the activity graph of one invocation.
174 *
175 * A sequential invocation has one line, its root. An AND fork gives it one line
176 * per branch, all holding the SAME thread of the invocation, and the join
177 * resumes the root; that is `LNRequest.copyWith` of `Solver_ssj_ln`.
178 */
179struct LnLine {
180 std::size_t inv = LN_NONE; ///< the invocation this line belongs to
181 std::size_t act = 0; ///< current activity, 0 for an entry with none
182 /**
183 * When the current activity began, -1 before it is reached. Its span runs
184 * to its host completion, so it CARRIES THE NESTED CALLS it makes.
185 */
186 double act_t0 = -1.0;
187 std::size_t call_pos = 0; ///< next call index of the current activity
188 /**
189 * Repetitions of the current call still to be made; `NOTDRAWN` until drawn.
190 * `calls-mean` is drawn once when the call is first reached, so a call of
191 * mean 3 blocks three times per execution of the activity.
192 */
193 std::size_t calls_left = static_cast<std::size_t>(-1);
194 double host_t0 = 0.0; ///< when the line asked its processor, queueing included
195 bool branch = false; ///< a line an AND fork created (never the root)
196 /**
197 * The AND fork instance that created this line, from one engine-wide counter; 0 for the root.
198 * A quorum join discards its late inputs by (input activity, fork instance), so the straggler of
199 * one round is never mistaken for an input of the next round of the same join.
200 */
201 std::uint64_t fork_id = 0;
202 int hcol = -1; ///< host admission column held, -1 = none
203 int pcol = -1; ///< operand column at a pooled host
204 double remaining = 0.0; ///< work left at a pooled or PS host
205 double siro_key = 0.0; ///< uniform key in a SIRO host queue; the smallest is served next
206 /**
207 * How far the current activity is before its calls: 0 nothing started, 1 host demand started
208 * or none, 2 think time started or none.
209 */
210 int dem_done = 0;
211 /**
212 * Host service in progress at a queueing host. The completion event carries `host_gen`, drawn
213 * from one engine-wide counter because lines are recycled, so a preemption cancels it by
214 * drawing a new one. `host_rem` is the work left when service (re)starts, negative meaning
215 * "draw the demand": a fresh request or a PI victim.
216 */
217 std::uint64_t host_gen = 0;
218 double host_rem = -1.0;
219 double host_start = 0.0;
220 double host_end = 0.0;
221};
222
223/** Fork instance meaning "any": the late inputs of a join fed by more than one fork instance. */
224static const std::uint64_t LN_ANYFORK = static_cast<std::uint64_t>(-1);
225
226/**
227 * Progress of one AND join within one invocation, `JoinProgress` of the Java engine. `got` holds
228 * the inputs arrived in the current round with the fork instance each came from; `discard` counts
229 * the late inputs of rounds that already fired on a QUORUM, keyed by (input activity, fork
230 * instance), which end their line when they arrive instead of counting towards the next round.
231 */
232struct LnJoin {
233 std::map<std::size_t, std::uint64_t> got;
234 std::map<std::pair<std::size_t, std::uint64_t>, long> discard;
235};
236
237/** One invocation of an entry: what a call or a reference cycle starts. */
238struct LnInv {
239 std::size_t entry = 0, task = 0;
240 std::size_t trep = 0; ///< replica of the task serving it
241 std::size_t ts = 0; ///< task slot of that replica
242 std::size_t th = static_cast<std::size_t>(-1); ///< thread held, NOTHR on an INF task
243 bool has_thread = false;
244 bool started = false; ///< the entry's service has begun (a thread is held)
245 double entry_t0 = 0.0; ///< when the entry took its thread, the start of its service
246 double task_t0 = 0.0; ///< when the request entered its task (admitted)
247 bool cold_wait = false; ///< queued while a thread was free but down: the whole wait is a cold start
248 std::size_t caller = LN_NONE; ///< the line blocked on this call, if synchronous
249 std::size_t cust = LN_NONE; ///< the reference customer, at the top level only
250 std::size_t root = LN_NONE; ///< root line
251 bool replied = false;
252 bool early_reply = false; ///< replied before completing (phase 2 follows)
253 long pending = -1; ///< live lines after a fork, -1 = never forked
254 std::map<std::size_t, LnJoin> joins; ///< join activity -> its progress in this invocation
255 int tcol = -1; ///< task admission column held, -1 = none
256 bool fetching = false; ///< this read is fetching an item (retrieval)
257 std::size_t fetch_cache = 0, fetch_item = 0;
258 double siro_key = 0.0; ///< uniform key in a SIRO thread queue
259 /**
260 * The invocation belongs to a root (reference cycle or open arrival) that began before
261 * the warmup reset, `LNRequest.preWarmup`: none of its observations is counted. Inherited
262 * by every call, forward and asynchronous request it makes.
263 */
264 bool pre = false;
265 /**
266 * The CALL that created this invocation, 1-based into `callpair_dst`, 0 for an entry stream of
267 * its own (a reference cycle, an open arrival or a forwarded request), `LNRequest.callIdx`.
268 * Selects the class its thread hold is charged to in `UCallLN` / `UEntryClassLN`.
269 */
270 std::size_t call_idx = 0;
271 /** When it took its thread, `LNRequest.threadHoldStart`; negative while it holds none. */
272 double hold_t0 = -1.0;
273};
274
275/** A reference-task customer: it thinks, then starts an invocation. */
277 std::size_t ref_task = 0;
278 std::size_t repl = 0; ///< replica of the reference task it belongs to
279 double t_start = 0.0; ///< when the current cycle began
280};
281
282/** Live content of one replica of a cache task, `LNCacheState` of the Java engine. */
284 std::size_t nitems = 0;
285 std::vector<int> cap; ///< per level list
287 std::vector<std::list<std::size_t> > levels; ///< per level, most recent first
288 bool retrieval = false;
289 std::vector<char> inflight; ///< [item] a fetch is in progress
290 std::vector<std::vector<std::pair<std::size_t, std::size_t> > > held; ///< (line, access)
291 long long reads = 0, hits = 0, misses = 0, delayed = 0;
292};
293
294/** One ItemEntry read: its driver activity, its item law and its two branches. */
296 std::vector<std::size_t> caches; ///< cache state per replica of the cache task
297 std::vector<double> cdf;
298 std::size_t hit = 0, miss = 0, entry = 0;
299};
300
301/** Thread index meaning "no thread held", also used for an infinite-thread task. */
302static const std::size_t NOTHR = static_cast<std::size_t>(-1);
303
304/** `LnJob::calls_left` before the repetition count of a call has been drawn. */
305static const std::size_t NOTDRAWN = static_cast<std::size_t>(-1);
306
307/** Power state of one task thread, mirroring Solver_ssj_ln's THREAD_* constants. */
308enum class ThreadState { ACTIVE, DELAYOFF, OFF, SETUP };
309
310/** The layered result: per element, the mean measures. */
311struct LnResult {
312 std::size_t nidx = 0;
314 /**
315 * Busy THREADS of each task over its thread capacity (threads times replicas), the integral
316 * of the threads held, and 0 at every other element. It is NOT the task's `ULN`: since
317 * 2026-10-03 that is the derived figure `Solver_ssj_ln` reports, the sum over the task's
318 * activities of throughput times host demand, over the host processor's multiplicity. A
319 * thread held across a nested call or a phase-2 tail is busy here and contributes nothing
320 * there; this field keeps the measured occupancy of the thread pool for whoever needs it.
321 */
323 /**
324 * Arrival rate per element, `Solver_ssj_ln`'s ALN: an entry's request rate (its throughput, since
325 * the engine loses no request) and 0 at every other element.
326 */
328 /**
329 * Think time per element, `Solver_ssj_ln`'s ZLN: Little's law on a task's thread pool read
330 * backwards, Z = (N - B) / X with N the threads times replicas, B the mean busy threads and X the
331 * task throughput. 0 at a task with an unbounded pool (no pool to close the law on), at a task
332 * with no completions, and at every non-task element.
333 */
335 /**
336 * Residence time per element, the ResidT column: the time an activity holds
337 * ITS HOST PROCESSOR per visit of the request stream driving its task, and
338 * for a task the sum over its activities.
339 *
340 * NOT the response time RLN, which also carries the nested synchronous
341 * calls the activity makes. NaN at the element kinds that have no residence
342 * -- processors and entries -- because a zero residence is a claim (nothing
343 * is held there) and this is the absence of one, the same convention
344 * SolverLN and LQNS report.
345 */
347 /**
348 * Every per-request ENTRY response time observed, one vector per entry in
349 * LOCAL index space (0..nentries-1). `RLN` at the entry indices is their
350 * mean; these are the observations themselves, which is what an empirical
351 * CDF has to be built from -- a law fitted to the mean says nothing about
352 * the tail, and the tail is the reason to ask a simulator at all.
353 */
354 std::vector<std::vector<double> > entry_resp_samples;
355 /** Length of the MEASURED span, from the end of warmup to the end of the run. */
356 double simulated_time = 0.0;
357 /** Simulation time at which warmup ended and the statistics were reset. */
358 double warmup_time = 0.0;
359 /** Reference-task cycles completed in the measured span. */
360 long long completions = 0;
361 /** Activity completions over the whole run, warmup included: what the budget counts. */
362 long long events = 0;
363 /**
364 * Cache measures, one row per ItemEntry that was read, pooled over the
365 * replicas of its cache task as `Solver_ssj_ln` pools them: element indices
366 * of the task and of the entry, the hit, miss and delayed-hit probabilities
367 * per read, and the read rate. Hit + miss + delayed = 1.
368 */
369 std::vector<std::size_t> cache_task, cache_entry;
371 /**
372 * Per-CLASS occupancy of the task thread pools, `Solver_ssj_ln`'s UCallLN and UEntryClassLN:
373 * the mean number of threads held by the requests a call creates (`UCallLN[c-1]`, call c of
374 * `callpair_dst`) or by an entry stream of its own, a reference cycle, an open arrival or a
375 * forwarded request (`UEntryClassLN[e]`, LOCAL entry index). A hold straddling the end of
376 * warmup counts from that instant, as the busy-thread integrator counts it, so over the
377 * classes of a task these sum to its `UThreadLN` times its thread capacity.
378 */
379 std::vector<double> UCallLN, UEntryClassLN;
380 /**
381 * Dispatches of each call per unit time, counted where the CALLER issues it (`TCallLN[c-1]`),
382 * so an asynchronous call registers too; a caller of a pre-warmup root is not counted.
383 */
384 std::vector<double> TCallLN;
385 /** The run stopped on its wall-clock budget (`LdesOptions::timeout`) before `max_events`. */
386 bool timed_out = false;
387};
388
389/** One entry's empirical response-time CDF: F[j] = P(R <= t[j]). */
391 std::vector<double> t;
392 std::vector<double> F;
393};
394
395/**
396 * The empirical response time CDF of every ENTRY, the `getCdfRespTLN` of the
397 * other codebases: one [F(t), t] table per entry in the LOCAL index space,
398 * empty where the run observed nothing.
399 *
400 * The ecdf of each entry's observations: sort, step by 1/n, and collapse ties
401 * keeping the LARGEST value at each distinct time, so an interpolating reader
402 * cannot land on a multivalued point.
403 */
404inline std::vector<LnEntryCdf> ldes_ln_cdf_respt(const LnResult& r, std::size_t nentries) {
405 std::vector<LnEntryCdf> out(nentries);
406 for (std::size_t e = 0; e < nentries; ++e) {
407 if (e >= r.entry_resp_samples.size()) continue;
408 std::vector<double> x = r.entry_resp_samples[e];
409 if (x.empty()) continue;
410 std::sort(x.begin(), x.end());
411 const double n = static_cast<double>(x.size());
412 for (std::size_t i = 0; i < x.size(); ++i) {
413 if (i + 1 < x.size() && x[i + 1] == x[i]) continue;
414 out[e].t.push_back(x[i]);
415 out[e].F.push_back(static_cast<double>(i + 1) / n);
416 }
417 }
418 return out;
419}
420
421/** A column of the shared layered average table, as `line-cli` prints it. */
422enum class LnColumn { QLen, Util, RespT, ResidT, Tput };
423
424/**
425 * Does the element at `i` HAVE the quantity in column `c`?
426 *
427 * THE MASK BELONGS TO THE TABLE, not to whichever engine filled it. A NaN there
428 * is not a failed computation: it says the quantity is not defined for that
429 * element kind, and SolverLN and LQNS report the same one --
430 *
431 * Processor QLen no, Util yes, RespT no, ResidT no, Tput no
432 * Task QLen yes, Util yes, RespT no, ResidT yes, Tput yes
433 * Entry QLen yes, Util yes, RespT yes, ResidT no, Tput yes
434 * Activity all five
435 *
436 * -- so a reader can diff the arms row by row. This engine MEASURES more than
437 * that: a processor's completion rate is sitting in `TLN` and an entry's
438 * occupancy in `QLN`, both perfectly well defined as sample-path quantities.
439 * Reporting them where every other solver says NaN would make one column mean
440 * different things depending on who filled it, which is the divergence the JAR
441 * removed from `getLNAvgTable` on 2026-08-21. Nothing is discarded: the caller
442 * still has the whole `LnResult`; only the SHARED TABLE is masked.
443 *
444 * ResidT needs no rule of its own here because the engine already applies it:
445 * `WLN` starts at NaN and only activities and their tasks are written, so a
446 * task with no activity at all keeps its NaN rather than claiming a residence
447 * of zero (which would say something is held there for no time, not that
448 * nothing is held).
449 *
450 * Twin of the mask `jline.solvers.ldes.SolverLDES.getLNAvgTable` applies and of
451 * the `defined_*` flags of `ln::LnSolution`; the three are pinned against each
452 * other by `cpp/tests/test_lqn_nan_mask_parity.cpp`.
453 */
454template <class T>
455inline bool ln_defined(const lqn::LqnStruct<T>& lsn, const LnResult& r, std::size_t i,
456 LnColumn c) {
457 if (i < 1 || i > r.nidx || i >= lsn.type.size()) return false;
458 const bool host = lsn.type[i] == line::lang::LqnElement::HOST;
459 switch (c) {
460 case LnColumn::QLen: return !host;
461 case LnColumn::Util: return true;
462 case LnColumn::RespT:
463 return lsn.type[i] == line::lang::LqnElement::ENTRY ||
465 case LnColumn::ResidT: return !std::isnan(r.WLN(i, 0));
466 case LnColumn::Tput: return !host;
467 }
468 return false;
469}
470
471/**
472 * The generator of one LN stream, seeded from a HASH of (run seed, offset).
473 *
474 * The MRG32k3a stream is `rng::SeedHash`'s, exactly as the flat engine seeds
475 * its streams (equally spaced seed vectors are linearly dependent and had
476 * biased every AND join by 1-2%, see `rng_ssj.h`); the same hash then goes on
477 * to seed the java.util.Random and the McRng. Solver_ssj_ln draws everything
478 * from ONE java.util.Random, so the layered reference has no stream layout to
479 * reproduce bit for bit, only a law: the offsets keep naming the streams.
480 */
481inline Rng ln_rng(long long seed, long long offset) {
482 rng::SeedHash h(seed, offset);
483 long long s[6];
484 h.mrg_seeds(s);
485 Rng g(seed, offset);
486 g.stream.set_seed(s);
487 g.aux = rng::JavaRandom(static_cast<long long>(h.next() >> 1));
488 g.mc = pfqn::McRng(h.next());
489 return g;
490}
491
492} // namespace engine
493
494/**
495 * Port of `ldes_ln_refusal`: why `SolverLDES.supports` declines a layered model, or an empty
496 * string when it does not.
497 *
498 * A host or task with a load-dependent (`lldscaling`), class-dependent (`cdscaling`) or
499 * joint-dependent (`jdscaling`) rate is served by this engine at its NOMINAL rate, as by
500 * Solver_ssj_ln, so the facade refuses it by name and points at SolverLN. The ENGINE itself does
501 * not call this: `ldes_ln_engine_solve` keeps the CLI's behaviour, which is the JAR's, of
502 * running such a model at the nominal rate rather than refusing it.
503 */
504template <class T>
506 const std::size_t last = lsn.tshift + lsn.ntasks;
507 for (std::size_t i = 1; i <= last; ++i) {
508 const std::string nm = i < lsn.names.size() ? lsn.names[i] : std::to_string(i);
509 if (i < lsn.lldscaling.size() && !lsn.lldscaling[i].empty())
510 return "SolverLDES does not simulate the load-dependent rate of '" + nm +
511 "' (setLoadDependence): the layered engine serves it at its nominal rate. Use SolverLN.";
512 if ((i < lsn.cdscaling.size() && static_cast<bool>(lsn.cdscaling[i])) ||
513 (i < lsn.jdscaling.size() && static_cast<bool>(lsn.jdscaling[i])))
514 return "SolverLDES does not simulate the class- or joint-dependent rate of '" + nm +
515 "' (setClassDependence/setJointDependence): the layered engine serves it at its "
516 "nominal rate. Use SolverLN.";
517 }
518 return std::string();
519}
520
521/**
522 * Simulate a layered model in process.
523 *
524 * The budget is ACTIVITY COMPLETIONS, Solver_ssj_ln's `totalEventCount`: a layered
525 * model has no single notion of "a job leaving", and the reference sets both its
526 * horizon and its warmup (the first 20%) on the activities completed.
527 */
528template <class T>
530 using namespace engine;
532
533 const std::size_t nidx = lsn.nidx;
534 if (nidx == 0) throw InputError("SolverLDES (native LN engine): empty layered model");
535
536 // ---- refuse what the engine does not simulate ---------------------------
537 // The disciplines Solver_ssj_ln.assertSchedulingIsSupported admits, refused by name otherwise:
538 // a discipline quietly served as another returns plausible numbers for a model nobody described.
539 for (std::size_t k = 1; k <= nidx && k < lsn.sched.size(); ++k) {
540 const bool is_host = k > lsn.hshift && k <= lsn.hshift + lsn.nhosts;
541 const bool is_task = k > lsn.tshift && k <= lsn.tshift + lsn.ntasks;
542 if (!is_host && !is_task) continue;
543 const SchedStrategy sc = lsn.sched[k];
544 const bool ok = sc == SchedStrategy::FCFS || sc == SchedStrategy::INF ||
545 sc == SchedStrategy::LCFS || sc == SchedStrategy::SIRO ||
546 sc == SchedStrategy::HOL || sc == SchedStrategy::REF ||
547 sc == SchedStrategy::LCFSPRIO ||
548 (is_host && (sc == SchedStrategy::PS || sc == SchedStrategy::PSPRIO ||
549 sc == SchedStrategy::FCFSPRPRIO ||
550 sc == SchedStrategy::FCFSPIPRIO ||
551 sc == SchedStrategy::LCFSPRPRIO ||
552 sc == SchedStrategy::LCFSPIPRIO));
553 if (ok) continue;
554 std::string scname = lang::sched_to_text(sc);
555 for (std::size_t c = 0; c < scname.size(); ++c)
556 scname[c] = static_cast<char>(std::toupper(static_cast<unsigned char>(scname[c])));
557 throw UnsupportedError(ErrorKind{"SchedStrategy"},
558 "SolverLDES (native LN engine) does not simulate " + scname + " scheduling at " +
559 (is_host ? "processor" : "task") + " '" + lsn.names[k] +
560 "'. The layered engine implements " +
561 (is_host ? "FCFS, LCFS, SIRO, HOL, FCFSPRIO, LCFSPRIO, FCFSPRPRIO, FCFSPIPRIO, "
562 "LCFSPRPRIO, LCFSPIPRIO, PS, PSPRIO and INF"
563 : "FCFS, LCFS, SIRO, HOL, FCFSPRIO, LCFSPRIO and INF (a task holds threads, "
564 "it does not divide or preempt them)") +
565 "; a weighted discipline would additionally need the per-task shares the layered "
566 "struct does not carry.");
567 }
568 for (std::size_t t = lsn.tshift + 1; t <= lsn.tshift + lsn.ntasks; ++t) {
569 // A setup IS simulated, except on an infinite-thread task, which holds
570 // no thread to power down. Same rule as the Java engine.
571 if (t < lsn.hassetup.size() && lsn.hassetup[t]) {
572 const double m = (t < lsn.mult.size()) ? lsn.mult[t] : 1.0;
573 if (!std::isfinite(m) || (t < lsn.sched.size() && lsn.sched[t] == lang::SchedStrategy::INF))
574 throw UnsupportedError(ErrorKind{"SetupDelayOff"}, "SolverLDES (native LN engine): task '" + lsn.names[t] +
575 "' declares a setup time on an infinite-server task, which "
576 "holds no thread to power down; give it a finite "
577 "multiplicity");
578 }
579 // Server pools on a TASK: the Java engine holds pools on processors only
580 // and throws here, so this does too rather than pick a reading of its own.
581 if (t < lsn.pools.size() && lsn.pools[t].npools() > 0)
582 throw UnsupportedError(ErrorKind{"HeteroServers"}, "SolverLDES (native LN engine): task '" + lsn.names[t] +
583 "' declares heterogeneous server pools; LDES holds server "
584 "pools on processors only");
585 }
586
587 for (const lqn::LqnCallGroup& grp : lsn.callgroups)
589 throw UnsupportedError(ErrorKind{"CallGroup"},
590 "SolverLDES (native LN engine) dispatches call groups round robin or JSQ only (activity '" +
591 lsn.names[grp.caller] + "')");
592
593 const std::uint64_t max_events =
594 static_cast<std::uint64_t>(o.events > 0 ? o.events : o.samples);
595 // The wall-clock budget, `options.timeout` as Solver_ssj_ln reads it through LineTimeout: a
596 // run over budget stops between two events with the statistics gathered so far.
598 bool time_stopped = false;
599 const std::uint64_t base =
600 (o.seed >= 0) ? static_cast<std::uint64_t>(o.seed) : std::random_device{}();
601 /**
602 * ONE STREAM PER ACTIVITY, named by an offset built from the activity
603 * index: host demands in the service band (+1000) and think times in the
604 * arrival band. The offset only NAMES the stream; `engine::ln_rng` hashes it
605 * into the seed, because equally spaced MRG32k3a seed vectors give linearly
606 * dependent streams and biased every AND join. Solver_ssj_ln draws from a
607 * single java.util.Random, so agreement with it is in law, not sample path.
608 */
609 const long long ln_seed = static_cast<long long>(base);
610 std::vector<Rng> g_host, g_think;
611 g_host.reserve(nidx + 1);
612 g_think.reserve(nidx + 1);
613 for (std::size_t k = 0; k <= nidx; ++k) {
614 g_host.push_back(engine::ln_rng(ln_seed, static_cast<long long>(k) * 10 + 1000));
615 g_think.push_back(engine::ln_rng(ln_seed, static_cast<long long>(k) * 10));
616 }
617 Rng g_call = engine::ln_rng(ln_seed, 900000);
618
619 // ---- resolved model -----------------------------------------------------
620 std::vector<Sampler> hostdem(nidx + 1), think(nidx + 1), actthink(nidx + 1);
621 std::vector<bool> has_hostdem(nidx + 1, false), has_think(nidx + 1, false),
622 has_actthink(nidx + 1, false);
623 // ACTIVITY think time (`Activity.setThinkTime`, .lqnx `think-time` on an activity): an
624 // off-processor delay after the demand and before the calls, on its own offset block (6000).
625 std::vector<Rng> g_actthink;
626 g_actthink.reserve(nidx + 1);
627 for (std::size_t k = 0; k <= nidx; ++k)
628 g_actthink.push_back(engine::ln_rng(ln_seed, static_cast<long long>(k) * 10 + 6000));
629 for (std::size_t a = lsn.ashift + 1; a <= lsn.ashift + lsn.nacts && a < lsn.actthink.size(); ++a) {
630 if (!lsn.actthink[a].disabled && num_traits<T>::to_double(lsn.actthink[a].mean) > 0.0) {
631 actthink[a] = Sampler(lsn.actthink[a], "the think time of activity '" + lsn.names[a] + "'");
632 has_actthink[a] = true;
633 }
634 }
635 for (std::size_t k = 1; k <= nidx; ++k) {
636 if (k < lsn.hostdem.size() && !lsn.hostdem[k].disabled &&
637 num_traits<T>::to_double(lsn.hostdem[k].mean) > 0.0) {
638 hostdem[k] = Sampler(lsn.hostdem[k], "the host demand of '" + lsn.names[k] + "'");
639 has_hostdem[k] = true;
640 }
641 if (k < lsn.think.size() && !lsn.think[k].disabled &&
642 num_traits<T>::to_double(lsn.think[k].mean) > 0.0) {
643 think[k] = Sampler(lsn.think[k], "the think time of '" + lsn.names[k] + "'");
644 has_think[k] = true;
645 }
646 }
647
648 // Host servers and task threads: the two resources an activity holds.
649 std::vector<std::size_t> host_servers(nidx + 1, 1), task_threads(nidx + 1, 1);
650 std::vector<SchedStrategy> host_sched(nidx + 1, SchedStrategy::FCFS);
651 std::vector<SchedStrategy> task_sched(nidx + 1, SchedStrategy::FCFS);
652 // An INF host or task never queues, whatever multiplicity it declares, which is how
653 // Solver_ssj_ln serves it (startHostService / enterTask branch on the discipline alone).
654 for (std::size_t h = lsn.hshift + 1; h <= lsn.hshift + lsn.nhosts; ++h) {
655 const double m = (h < lsn.mult.size()) ? lsn.mult[h] : 1.0;
656 if (h < lsn.sched.size()) host_sched[h] = lsn.sched[h];
657 host_servers[h] = (std::isfinite(m) && host_sched[h] != SchedStrategy::INF)
658 ? std::max<std::size_t>(1, static_cast<std::size_t>(m + 0.5))
659 : std::numeric_limits<std::size_t>::max();
660 }
661 for (std::size_t t = lsn.tshift + 1; t <= lsn.tshift + lsn.ntasks; ++t) {
662 const double m = (t < lsn.mult.size()) ? lsn.mult[t] : 1.0;
663 if (t < lsn.sched.size()) task_sched[t] = lsn.sched[t];
664 task_threads[t] = (std::isfinite(m) && task_sched[t] != SchedStrategy::INF)
665 ? static_cast<std::size_t>(m + 0.5)
666 : std::numeric_limits<std::size_t>::max();
667 }
668
669 /**
670 * REPLICATION. A processor or task declared with replication r is r
671 * identical copies of itself, and a copy is a server of its own: pooling
672 * them into one server of r times the capacity would let one queue absorb
673 * what r separate queues cannot. So the host state below is indexed by a
674 * SLOT -- the processor plus its replica -- while what the copies share by
675 * definition (servers per copy, scheduling) stays indexed by the element.
676 * The reported measures are summed over the copies, which keeps throughput
677 * conserved across a call and utilization a fraction of the total capacity.
678 */
679 std::vector<std::size_t> repl(nidx + 1, 1);
680 for (std::size_t k = 1; k < lsn.repl.size() && k <= nidx; ++k) {
681 const double r = lsn.repl[k];
682 repl[k] = (r > 1.0) ? static_cast<std::size_t>(r + 0.5) : 1;
683 }
684 std::vector<std::size_t> host_slot0(nidx + 1, 0);
685 std::size_t nhost_slots = 0;
686 for (std::size_t h = lsn.hshift + 1; h <= lsn.hshift + lsn.nhosts; ++h) {
687 host_slot0[h] = nhost_slots;
688 nhost_slots += repl[h];
689 }
690 if (nhost_slots == 0) nhost_slots = 1;
691
692 /** Slot of the processor replica running replica trep of one of its tasks. */
693 auto host_slot = [&](std::size_t host, std::size_t trep) {
694 return host_slot0[host] + (trep % repl[host]);
695 };
696
697 // Task replicas get their own slots for exactly the reason processors do: r
698 // copies are r thread pools, not one pool of r times the size.
699 std::vector<std::size_t> task_slot0(nidx + 1, 0);
700 std::size_t ntask_slots = 0;
701 for (std::size_t t = lsn.tshift + 1; t <= lsn.tshift + lsn.ntasks; ++t) {
702 task_slot0[t] = ntask_slots;
703 ntask_slots += repl[t];
704 }
705 if (ntask_slots == 0) ntask_slots = 1;
706 auto task_slot = [&](std::size_t task, std::size_t trep) {
707 return task_slot0[task] + (trep % repl[task]);
708 };
709
710 /**
711 * Replica of the callee reached by one call of replica `crep` of the caller.
712 * An unset fan-out is the smallest value consistent with
713 * repl(caller)*fanout = repl(callee)*fanin, and the caller reaches the block
714 * {(i*f+k) mod r}. A call is one indivisible unit of work, so it goes to one
715 * member of that block drawn uniformly: over many calls each member carries
716 * the 1/f share that LQN2QN splits the call mean into. This is deterministic
717 * pairing at f=1 and a uniform spread over every replica at f=r.
718 */
719 auto callee_replica = [&](std::size_t caller_task, std::size_t crep,
720 std::size_t callee_task) -> std::size_t {
721 const std::size_t rb = repl[callee_task];
722 if (rb <= 1) return 0;
723 std::size_t f = static_cast<std::size_t>(lsn.fanout_at(caller_task, callee_task) + 0.5);
724 if (f == 0) {
725 const std::size_t ra = repl[caller_task];
726 f = (rb > ra) ? std::max<std::size_t>(1, rb / ra) : 1;
727 }
728 f = std::min(std::max<std::size_t>(1, f), rb);
729 const std::size_t k =
730 (f > 1) ? static_cast<std::size_t>(uniform01(g_call) * static_cast<double>(f)) : 0;
731 return ((crep * f) + std::min(k, f - 1)) % rb;
732 };
733
734 // ---- the activity graph, as buildActivityGraph builds it -----------------
735 const std::size_t a_lo = lsn.ashift + 1, a_hi = lsn.ashift + lsn.nacts;
736 auto is_act = [&](std::size_t k) { return k >= a_lo && k <= a_hi; };
737 auto wgt = [&](std::size_t i, std::size_t j) {
738 return num_traits<T>::to_double(lsn.graph.get(i, j));
739 };
740 auto pretype = [&](std::size_t a) {
741 return a < lsn.actpretype.size() ? lsn.actpretype[a] : lang::PrecedenceType::NONE;
742 };
743 auto posttype = [&](std::size_t a) {
744 return a < lsn.actposttype.size() ? lsn.actposttype[a] : lang::PrecedenceType::NONE;
745 };
746 auto phase_of = [&](std::size_t a) -> int {
747 const std::size_t k = a - lsn.ashift;
748 return (k < lsn.actphase.size() && lsn.actphase[k] > 0) ? lsn.actphase[k] : 1;
749 };
750 // Successors of an activity are the ACTIVITIES it precedes, ascending: the
751 // element graph also carries its call edges, which are not precedence.
752 std::vector<std::vector<std::size_t> > succ_act(nidx + 1);
753 for (std::size_t a = a_lo; a <= a_hi; ++a)
754 for (std::size_t s : lsn.graph.succ(a))
755 if (is_act(s)) succ_act[a].push_back(s);
756 /**
757 * A multi-successor activity CHOOSES one branch when it is an OR fork or a
758 * loop decision (its own post type, the first test of `buildActivityGraph`)
759 * or when any branch weight is a probability (w != 1, the lazy test of
760 * `completeActivity`); otherwise it FORKS every branch. The weights are
761 * renormalised when they do not sum to one, and the draw is `u <= cum`.
762 */
763 std::vector<std::vector<double> > or_prob(nidx + 1);
764 for (std::size_t a = a_lo; a <= a_hi; ++a) {
765 const std::vector<std::size_t>& sc = succ_act[a];
766 if (sc.size() < 2) continue;
767 bool prob = posttype(a) == lang::PrecedenceType::POST_OR ||
768 posttype(a) == lang::PrecedenceType::POST_LOOP;
769 for (std::size_t s : sc) {
770 const double w = wgt(a, s);
771 if (w != 1.0 && w > 0.0) prob = true;
772 }
773 if (!prob) continue;
774 double tot = 0.0;
775 for (std::size_t s : sc) tot += wgt(a, s);
776 for (std::size_t s : sc) {
777 const double w = wgt(a, s);
778 or_prob[a].push_back((tot > 0.0 && tot != 1.0) ? w / tot : w);
779 }
780 }
781 // An AND join waits for as many inputs as there are PRE_AND activities whose
782 // first successor it is, joinRequiredCount of the Java engine.
783 std::vector<std::size_t> join_required(nidx + 1, 0);
784 for (std::size_t a = a_lo; a <= a_hi; ++a)
785 if (pretype(a) == lang::PrecedenceType::PRE_AND && !succ_act[a].empty())
786 ++join_required[succ_act[a][0]];
787 /**
788 * QUORUM. A join with quorum k of n fires on the k-th input of a round, the k-th order
789 * statistic SolverLN's fj_quorum_moments takes. The n-k late inputs still run to completion,
790 * holding the thread, and are DISCARDED when they reach the join: the invocation completes
791 * only once they have drained, as lqsim keeps a task busy until every forked thread is done.
792 * `join_quorum` is n where no quorum is declared, so a full join is unchanged.
793 */
794 std::vector<std::size_t> join_quorum(nidx + 1, 0);
795 std::vector<std::vector<std::size_t> > join_inputs(nidx + 1);
796 for (std::size_t a = a_lo; a <= a_hi; ++a)
797 if (pretype(a) == lang::PrecedenceType::PRE_AND && !succ_act[a].empty())
798 join_inputs[succ_act[a][0]].push_back(a);
799 for (std::size_t j = a_lo; j <= a_hi; ++j) {
800 if (join_required[j] == 0) continue;
801 const std::size_t q = j < lsn.actquorum.size() ? lsn.actquorum[j] : 0;
802 join_quorum[j] = (q >= 1 && q < join_required[j]) ? q : join_required[j];
803 }
804 /**
805 * A partial quorum is refused where the MAIN LINE of the invocation can be one of the inputs,
806 * i.e. an input reachable from an earlier join's output without passing an AND fork. The join
807 * resumes the main line, and a main line still running as a late input could not also
808 * continue past the join. Same rule as Solver_ssj_ln.assertQuorumJoinsAreForked.
809 */
810 {
811 std::vector<char> seen(nidx + 1, 0), root_input(nidx + 1, 0);
812 std::deque<std::size_t> todo;
813 for (std::size_t j = a_lo; j <= a_hi; ++j)
814 if (join_required[j] > 0) todo.push_back(j);
815 while (!todo.empty()) {
816 const std::size_t a = todo.front();
817 todo.pop_front();
818 if (seen[a]) continue;
819 seen[a] = 1;
820 if (pretype(a) == lang::PrecedenceType::PRE_AND && !succ_act[a].empty()) {
821 root_input[a] = 1;
822 continue;
823 }
824 const std::vector<std::size_t>& sc = succ_act[a];
825 const bool choose = sc.size() == 1 || !or_prob[a].empty() ||
826 posttype(sc.empty() ? a : sc[0]) == lang::PrecedenceType::POST_CACHE;
827 if (choose)
828 for (std::size_t s : sc) todo.push_back(s);
829 }
830 for (std::size_t j = a_lo; j <= a_hi; ++j) {
831 if (join_quorum[j] >= join_required[j]) continue;
832 for (std::size_t a : join_inputs[j])
833 if (root_input[a])
834 throw UnsupportedError(ErrorKind{"JoinPartial"},
835 "SolverLDES (native LN engine): the AND join into '" + lsn.names[j] +
836 "' declares a quorum of " + std::to_string(join_quorum[j]) + " of " +
837 std::to_string(join_required[j]) + " inputs, but its input '" +
838 lsn.names[a] + "' follows an earlier join without an AND fork in between, "
839 "so the main line of the invocation could arrive late; a quorum join must "
840 "be fed by forked branches only");
841 }
842 }
843 /**
844 * The activity an entry starts at: the one the entry's own graph edge names,
845 * else the first predecessor-free sequential activity of its task, else the
846 * first activity, which is `findBoundActivityForEntry`. 0 means none.
847 */
848 std::vector<std::size_t> bound(nidx + 1, 0);
849 for (std::size_t e = lsn.eshift + 1; e <= lsn.eshift + lsn.nentries; ++e) {
850 const std::size_t t = lsn.parent[e];
851 const std::vector<std::size_t>& acts =
852 (t < lsn.actsof.size()) ? lsn.actsof[t] : std::vector<std::size_t>();
853 for (std::size_t a : acts)
854 if (wgt(e, a) > 0.0) {
855 bound[e] = a;
856 break;
857 }
858 if (bound[e] != 0 || acts.empty()) continue;
859 for (std::size_t a : acts) {
860 const lang::PrecedenceType pt = pretype(a);
862 bool haspred = false;
863 for (std::size_t o2 : acts)
864 if (o2 != a && wgt(o2, a) > 0.0) {
865 haspred = true;
866 break;
867 }
868 if (!haspred) {
869 bound[e] = a;
870 break;
871 }
872 }
873 if (bound[e] == 0) bound[e] = acts[0];
874 }
875
876 // ---- cache tasks: one content per replica, one access per ItemEntry -------
877 std::vector<LnCacheState> caches;
878 std::vector<std::size_t> cache_of_slot(ntask_slots, LN_NONE);
879 for (std::size_t t = lsn.tshift + 1; t <= lsn.tshift + lsn.ntasks; ++t) {
880 if (t >= lsn.iscache.size() || !lsn.iscache[t]) continue;
881 const std::size_t n = t < lsn.nitems.size() ? lsn.nitems[t] : 0;
882 if (n == 0) continue;
883 std::vector<int> cap = (t < lsn.itemcap.size()) ? lsn.itemcap[t] : std::vector<int>();
884 if (cap.empty()) cap.assign(1, 1);
885 for (std::size_t m = 0; m < repl[t]; ++m) {
886 LnCacheState cs;
887 cs.nitems = n;
888 cs.cap = cap;
889 cs.rs = (t < lsn.replacestrat.size()) ? lsn.replacestrat[t]
891 cs.levels.assign(cap.size(), std::list<std::size_t>());
892 cs.retrieval = t < lsn.hasretrieval.size() && lsn.hasretrieval[t];
893 if (cs.retrieval) {
894 cs.inflight.assign(n, 0);
895 cs.held.assign(n, {});
896 }
897 cache_of_slot[task_slot(t, m)] = caches.size();
898 caches.push_back(cs);
899 }
900 }
901 std::vector<LnCacheAccess> accesses;
902 std::vector<std::size_t> access_of_driver(nidx + 1, LN_NONE);
903 std::vector<std::size_t> branch_reply(nidx + 1, 0); ///< hit/miss activity -> its ItemEntry
904 for (std::size_t e = lsn.eshift + 1; e <= lsn.eshift + lsn.nentries; ++e) {
905 const std::size_t t = lsn.parent[e];
906 if (t <= lsn.tshift || t > lsn.tshift + lsn.ntasks) continue;
907 if (cache_of_slot[task_slot(t, 0)] == LN_NONE) continue;
908 const std::size_t drv = bound[e];
909 const bool is_item = e < lsn.itemproc.size() && !lsn.itemproc[e].empty();
910 // An entry of a cache task that is not an ItemEntry runs as an ordinary
911 // entry, as it does in the Java engine.
912 if (!is_item) continue;
913 if (drv == 0 || succ_act[drv].size() < 2)
914 throw UnsupportedError(ErrorKind{"ItemEntry"}, "SolverLDES (native LN engine): ItemEntry '" + lsn.names[e] +
915 "' has no cache access with a hit and a miss branch");
916 LnCacheAccess ca;
917 for (std::size_t m = 0; m < repl[t]; ++m) ca.caches.push_back(cache_of_slot[task_slot(t, m)]);
918 ca.hit = succ_act[drv][0];
919 ca.miss = succ_act[drv][1];
920 ca.entry = e;
921 std::size_t card = e < lsn.nitems.size() ? lsn.nitems[e] : 0;
922 if (card == 0) card = caches[ca.caches[0]].nitems;
923 double sum = 0.0;
924 for (std::size_t i = 0; i < card; ++i) {
925 const double v = (i < lsn.itemproc[e].size())
926 ? num_traits<T>::to_double(lsn.itemproc[e][i]) : 0.0;
927 if (std::isnan(v) || v < 0.0)
928 throw InputError("SolverLDES (native LN engine): ItemEntry '" + lsn.names[e] +
929 "' has a popularity that is not a pmf");
930 sum += v;
931 ca.cdf.push_back(sum);
932 }
933 if (!(sum > 0.0))
934 throw InputError("SolverLDES (native LN engine): ItemEntry '" + lsn.names[e] +
935 "' has a popularity of zero total mass");
936 for (double& c : ca.cdf) c /= sum;
937 access_of_driver[drv] = accesses.size();
938 branch_reply[ca.hit] = e;
939 branch_reply[ca.miss] = e;
940 accesses.push_back(ca);
941 }
942 // A POST_CACHE branch with no resolvable read would otherwise run as an AND
943 // fork of the hit AND the miss branch, which is not a cache at all.
944 for (std::size_t a = a_lo; a <= a_hi; ++a) {
945 if (access_of_driver[a] != LN_NONE) continue;
946 for (std::size_t s : succ_act[a])
947 if (posttype(s) == lang::PrecedenceType::POST_CACHE)
948 throw UnsupportedError(ErrorKind{"Cache"}, "SolverLDES (native LN engine): activity '" + lsn.names[a] +
949 "' reads a cache, but no ItemEntry of a cache task with "
950 "a popularity is bound to it");
951 }
952
953 // ---- admission constraints A n <= b --------------------------------------
954 /**
955 * The rows are declared once per element and hold separately inside each
956 * replica, so A and b are per element and the occupancy per slot. A host's
957 * columns are its tasks (`tasksof`), a task's its entries (`entriesof`).
958 */
959 struct Lincon {
960 std::vector<std::vector<double> > A;
961 std::vector<double> b;
962 std::map<std::size_t, int> col;
963 };
964 std::vector<Lincon> lincon(nidx + 1);
965 std::vector<bool> has_lincon(nidx + 1, false);
966 for (std::size_t k = 1; k < lsn.lincon_A.size() && k <= nidx; ++k) {
967 const Matrix<T>& A = lsn.lincon_A[k];
968 if (A.rows() == 0) continue;
969 const bool host = k > lsn.hshift && k <= lsn.hshift + lsn.nhosts;
970 const std::vector<std::size_t>* ops = nullptr;
971 if (host && k < lsn.tasksof.size()) ops = &lsn.tasksof[k];
972 if (!host && k < lsn.entriesof.size()) ops = &lsn.entriesof[k];
973 const std::size_t ncols = ops ? ops->size() : 0;
974 if (A.cols() != ncols)
975 throw InputError("SolverLDES (native LN engine): the admission constraint on '" +
976 lsn.names[k] + "' has " + std::to_string(A.cols()) +
977 " columns but the server has " + std::to_string(ncols) + " operands");
978 if (ncols == 0) continue;
979 Lincon lc;
980 lc.A.assign(A.rows(), std::vector<double>(ncols, 0.0));
981 for (std::size_t r = 0; r < A.rows(); ++r)
982 for (std::size_t c = 0; c < ncols; ++c) lc.A[r][c] = num_traits<T>::to_double(A(r, c));
983 for (std::size_t r = 0; r < A.rows(); ++r)
984 lc.b.push_back((k < lsn.lincon_b.size() && r < lsn.lincon_b[k].size())
985 ? num_traits<T>::to_double(lsn.lincon_b[k][r])
986 : std::numeric_limits<double>::infinity());
987 for (std::size_t c = 0; c < ncols; ++c) lc.col[(*ops)[c]] = static_cast<int>(c);
988 lincon[k] = lc;
989 has_lincon[k] = true;
990 }
991 auto lincon_col = [&](std::size_t elem, std::size_t operand) -> int {
992 if (!has_lincon[elem]) return -1;
993 const std::map<std::size_t, int>::const_iterator it = lincon[elem].col.find(operand);
994 return it == lincon[elem].col.end() ? -1 : it->second;
995 };
996 /** True when one more job in column `col` still satisfies every row. */
997 auto admits = [&](std::size_t elem, const std::vector<int>& occ, int col) {
998 const Lincon& lc = lincon[elem];
999 for (std::size_t r = 0; r < lc.A.size(); ++r) {
1000 double lhs = lc.A[r][static_cast<std::size_t>(col)];
1001 for (std::size_t k = 0; k < occ.size(); ++k) lhs += lc.A[r][k] * occ[k];
1002 if (lhs > lc.b[r] + 1e-9) return false;
1003 }
1004 return true;
1005 };
1006
1007 // ---- heterogeneous server pools on processors ----------------------------
1008 /**
1009 * The pools ARE the servers of the host, so their counts must add up to its
1010 * multiplicity. An INF host ignores them, as the Java engine's service path
1011 * does. The operand column of a job is its task's position in `tasksof`.
1012 */
1013 std::vector<bool> pooled(nidx + 1, false);
1014 std::vector<std::vector<double> > pool_capacity(nidx + 1);
1015 std::vector<std::vector<std::vector<bool> > > pool_serves(nidx + 1);
1016 std::vector<std::map<std::size_t, int> > pool_col(nidx + 1);
1017 for (std::size_t h = lsn.hshift + 1; h <= lsn.hshift + lsn.nhosts; ++h) {
1018 if (h >= lsn.pools.size() || lsn.pools[h].npools() == 0) continue;
1019 if (host_sched[h] == SchedStrategy::INF) continue; // the INF path ignores pools
1020 const lqn::ServerPools<T>& P = lsn.pools[h];
1021 const std::size_t np = P.npools(), nc = P.compat.cols();
1022 std::size_t declared = 0;
1023 for (std::size_t p = 0; p < np; ++p) {
1024 const double cnt = (p < P.counts.size()) ? P.counts[p] : 0.0;
1025 const std::size_t c = cnt > 0.0 ? static_cast<std::size_t>(cnt) : 0;
1026 const double r = (p < P.rates.size()) ? num_traits<T>::to_double(P.rates[p]) : 1.0;
1027 pool_capacity[h].push_back(static_cast<double>(c) * (r > 0.0 ? r : 1.0));
1028 declared += c;
1029 std::vector<bool> sv(nc, false);
1030 for (std::size_t j = 0; j < nc; ++j)
1031 sv[j] = num_traits<T>::to_double(P.compat(p, j)) != 0.0;
1032 pool_serves[h].push_back(sv);
1033 }
1034 if (declared != host_servers[h])
1035 throw InputError("SolverLDES (native LN engine): processor '" + lsn.names[h] +
1036 "' declares server pools holding " + std::to_string(declared) +
1037 " servers but has multiplicity " +
1038 (host_servers[h] == std::numeric_limits<std::size_t>::max()
1039 ? std::string("Inf") : std::to_string(host_servers[h])) +
1040 "; the pools must partition the servers");
1041 const std::vector<std::size_t>& ops =
1042 (h < lsn.tasksof.size()) ? lsn.tasksof[h] : std::vector<std::size_t>();
1043 for (std::size_t j = 0; j < ops.size() && j < nc; ++j) pool_col[h][ops[j]] = static_cast<int>(j);
1044 pooled[h] = true;
1045 }
1046
1047 // ---- live state ---------------------------------------------------------
1048 double now = 0.0;
1049 std::priority_queue<LnEvent, std::vector<LnEvent>, LnEventLater> evq;
1050 std::uint64_t seq = 0;
1051 // Lines and invocations live in deques, whose elements do not move when
1052 // another is added, and are recycled through free lists.
1053 std::deque<LnLine> lines;
1054 std::deque<LnInv> invs;
1055 std::vector<std::size_t> free_lines, free_invs;
1056 std::vector<LnCustomer> custs;
1057
1058 // Busy servers and waiting lines of ONE processor replica, addressed by slot.
1059 std::vector<std::size_t> host_busy(nhost_slots, 0);
1060 std::vector<std::deque<std::size_t>> host_queue(nhost_slots);
1061 // A pooled replica holds its lines in arrival order, the order the pools scan.
1062 std::vector<std::vector<std::size_t> > pool_jobs(nhost_slots);
1063 std::vector<double> pool_last(nhost_slots, 0.0), pool_rate(nhost_slots, 0.0);
1064 std::vector<std::uint64_t> pool_gen(nhost_slots, 0);
1065 std::vector<std::size_t> host_of_slot(nhost_slots, 0);
1066 for (std::size_t h = lsn.hshift + 1; h <= lsn.hshift + lsn.nhosts; ++h)
1067 for (std::size_t m = 0; m < repl[h]; ++m) host_of_slot[host_slot0[h] + m] = h;
1068 // Admission occupancy and blocked requests, per slot.
1069 std::vector<std::vector<int> > hocc(nhost_slots), tocc(ntask_slots);
1070 std::vector<std::deque<std::size_t> > hadm(nhost_slots), tadm(ntask_slots);
1071 for (std::size_t h = lsn.hshift + 1; h <= lsn.hshift + lsn.nhosts; ++h)
1072 if (has_lincon[h])
1073 for (std::size_t m = 0; m < repl[h]; ++m)
1074 hocc[host_slot0[h] + m].assign(lincon[h].A[0].size(), 0);
1075
1076 // Task threads of ONE task replica, addressed by slot. An invocation that
1077 // finds every thread taken waits in thr_queue, holding no resource meanwhile.
1078 std::vector<std::vector<bool>> thr_held(ntask_slots);
1079 std::vector<std::vector<ThreadState>> thr_state(ntask_slots);
1080 std::vector<std::vector<double>> thr_setup_t0(ntask_slots);
1081 std::vector<std::vector<std::uint64_t>> thr_gen(ntask_slots);
1082 std::vector<std::deque<std::size_t>> thr_queue(ntask_slots);
1083 std::vector<std::size_t> thr_owner(ntask_slots, 0); ///< task index of each slot
1084 for (std::size_t t = lsn.tshift + 1; t <= lsn.tshift + lsn.ntasks; ++t) {
1085 const std::size_t n = (task_threads[t] == std::numeric_limits<std::size_t>::max())
1086 ? 0 : task_threads[t];
1087 for (std::size_t m = 0; m < repl[t]; ++m) {
1088 const std::size_t ts = task_slot(t, m);
1089 thr_owner[ts] = t;
1090 thr_held[ts].assign(n, false);
1091 thr_state[ts].assign(n, ThreadState::ACTIVE);
1092 thr_setup_t0[ts].assign(n, 0.0);
1093 thr_gen[ts].assign(n, 0);
1094 if (has_lincon[t]) tocc[ts].assign(lincon[t].A[0].size(), 0);
1095 }
1096 }
1097
1098 // A SetupTask's two clocks, per task. Both must be positive for the power
1099 // cycle to exist: a setup with no delay-off would never fire, because nothing
1100 // would ever power a thread down.
1101 std::vector<Sampler> setupd(nidx + 1), delayoffd(nidx + 1);
1102 std::vector<bool> has_setup(nidx + 1, false);
1103 std::vector<Rng> g_setup, g_doff;
1104 g_setup.reserve(nidx + 1);
1105 g_doff.reserve(nidx + 1);
1106 for (std::size_t k = 0; k <= nidx; ++k) {
1107 g_setup.push_back(engine::ln_rng(ln_seed, static_cast<long long>(k) * 10 + 2000));
1108 g_doff.push_back(engine::ln_rng(ln_seed, static_cast<long long>(k) * 10 + 3000));
1109 }
1110 for (std::size_t t = lsn.tshift + 1; t <= lsn.tshift + lsn.ntasks; ++t) {
1111 if (t >= lsn.hassetup.size() || !lsn.hassetup[t]) continue;
1112 const bool su = t < lsn.setuptime.size() && !lsn.setuptime[t].disabled &&
1113 num_traits<T>::to_double(lsn.setuptime[t].mean) > 0.0;
1114 const bool df = t < lsn.delayofftime.size() && !lsn.delayofftime[t].disabled &&
1115 num_traits<T>::to_double(lsn.delayofftime[t].mean) > 0.0;
1116 if (!su || !df) continue;
1117 setupd[t] = Sampler(lsn.setuptime[t], "the setup time of '" + lsn.names[t] + "'");
1118 delayoffd[t] = Sampler(lsn.delayofftime[t], "the delay-off time of '" + lsn.names[t] + "'");
1119 has_setup[t] = true;
1120 }
1121
1122 /**
1123 * The new features draw on streams of their own, in blocks above every
1124 * existing offset, so that a model without them keeps its seeded sample
1125 * path: branch choices per activity (940000), item draws per cache replica
1126 * (950000) and random replacement per cache replica (960000). 910000 and
1127 * 920000 are the SIRO keys of hosts and tasks.
1128 */
1129 std::vector<Rng> g_route, g_item, g_rr;
1130 g_route.reserve(nidx + 1);
1131 for (std::size_t k = 0; k <= nidx; ++k)
1132 g_route.push_back(engine::ln_rng(ln_seed, 940000 + static_cast<long long>(k) * 10));
1133 for (std::size_t c = 0; c < caches.size(); ++c) {
1134 g_item.push_back(engine::ln_rng(ln_seed, 950000 + static_cast<long long>(c) * 10));
1135 g_rr.push_back(engine::ln_rng(ln_seed, 960000 + static_cast<long long>(c) * 10));
1136 }
1137
1138 /**
1139 * FORWARDING, `buildForwardingMap`: a FWD call names a source ENTRY, a target entry and a
1140 * probability. A synchronous request the source entry would reply to is, with that
1141 * probability, handed to the target instead; the caller stays blocked until the end of the
1142 * chain replies. One draw per reply on a stream per source entry (block 970000), so a model
1143 * without forwarding keeps its seeded sample path.
1144 */
1145 std::vector<std::vector<std::size_t> > fwd_dst(nidx + 1);
1146 std::vector<std::vector<double> > fwd_prob(nidx + 1);
1147 for (std::size_t c = 1; c <= lsn.ncalls && c < lsn.calltype.size(); ++c) {
1148 if (lsn.calltype[c] != lang::CallType::FWD) continue;
1149 const std::size_t src = lsn.callpair_src[c], dst = lsn.callpair_dst[c];
1150 if (src == 0 || dst == 0 || src > nidx || dst > nidx) continue;
1151 fwd_dst[src].push_back(dst);
1152 fwd_prob[src].push_back(c < lsn.callproc_mean.size()
1153 ? num_traits<T>::to_double(lsn.callproc_mean[c])
1154 : 1.0);
1155 }
1156 std::vector<Rng> g_fwd;
1157 g_fwd.reserve(nidx + 1);
1158 for (std::size_t k = 0; k <= nidx; ++k)
1159 g_fwd.push_back(engine::ln_rng(ln_seed, 970000 + static_cast<long long>(k) * 10));
1160
1161 /// Lines woken by a release, continued after the current walk returns.
1162 /// Waking them inside the walk would re-enter it on another line.
1163 std::deque<std::size_t> runnable;
1164
1165 /**
1166 * PRIORITY ORDER, as Solver_ssj_ln orders it: a LARGER `lsn.prio` first (the lqns convention),
1167 * FIFO within one level under HOL/FCFSPRIO and the FCFS preemptive variants, LIFO under the
1168 * LCFS ones. A host request carries the priority of the task whose activity it is; a task
1169 * request that of its CALLER, since every request at one task belongs to that task, and one
1170 * with no caller (a reference task's own cycle, an open arrival, an asynchronous call) takes
1171 * 0, the lowest.
1172 */
1173 auto task_prio = [&](std::size_t task) -> int {
1174 return (task < lsn.prio.size()) ? lsn.prio[task] : 0;
1175 };
1176 auto host_req_prio = [&](std::size_t lid) -> int { return task_prio(lsn.parent[lines[lid].act]); };
1177 auto task_req_prio = [&](std::size_t vi) -> int {
1178 const std::size_t c = invs[vi].caller;
1179 return c == LN_NONE ? 0 : task_prio(invs[lines[c].inv].task);
1180 };
1181 // SIRO keys, one stream per resource kind on the engine's own offsets, so a SIRO queue does
1182 // not shift the demand, think or call variates of any other element.
1183 Rng g_siro_host = engine::ln_rng(ln_seed, 910000);
1184 Rng g_siro_task = engine::ln_rng(ln_seed, 920000);
1185 auto fcfs_prio = [](SchedStrategy sc) {
1186 // FCFSPRIO has no enumerator of its own here: it is MATLAB's alias for HOL.
1187 return sc == SchedStrategy::HOL || sc == SchedStrategy::FCFSPRPRIO ||
1188 sc == SchedStrategy::FCFSPIPRIO;
1189 };
1190 auto lcfs_prio = [](SchedStrategy sc) {
1191 return sc == SchedStrategy::LCFSPRIO || sc == SchedStrategy::LCFSPRPRIO ||
1192 sc == SchedStrategy::LCFSPIPRIO;
1193 };
1194 auto preemptive = [](SchedStrategy sc) {
1195 return sc == SchedStrategy::FCFSPRPRIO || sc == SchedStrategy::FCFSPIPRIO ||
1196 sc == SchedStrategy::LCFSPRPRIO || sc == SchedStrategy::LCFSPIPRIO;
1197 };
1198 auto is_ps = [](SchedStrategy sc) {
1199 return sc == SchedStrategy::PS || sc == SchedStrategy::PSPRIO;
1200 };
1201 /**
1202 * Queue `id` behind every request of a higher priority and, within its own level, behind the
1203 * ones FIFO (or, `lifo`, LIFO) puts first. `key_of` is the arrival instant a level is ordered
1204 * by; a task queue passes none and relies on requests joining it in arrival order.
1205 */
1206 auto prio_enqueue = [](std::deque<std::size_t>& q, std::size_t id,
1207 const std::function<int(std::size_t)>& prio_of, bool lifo,
1208 const std::function<double(std::size_t)>* key_of) {
1209 const int prio = prio_of(id);
1210 const double key = key_of ? (*key_of)(id) : 0.0;
1211 std::deque<std::size_t>::iterator it = q.end();
1212 while (it != q.begin()) {
1213 const std::size_t o = *(it - 1);
1214 const int po = prio_of(o);
1215 if (po > prio) break;
1216 if (po == prio) {
1217 if (!lifo && (!key_of || (*key_of)(o) <= key)) break;
1218 if (lifo && key_of && (*key_of)(o) > key) break;
1219 }
1220 --it;
1221 }
1222 q.insert(it, id);
1223 };
1224 /**
1225 * Queue `id` under `sc`, the order Solver_ssj_ln's comparators impose: FCFS by arrival, LCFS
1226 * newest first, SIRO by a uniform key drawn now, the priority disciplines by `prio` then
1227 * arrival (`key_of`, the host residence start, when given).
1228 */
1229 auto enqueue = [&](std::deque<std::size_t>& q, std::size_t id, SchedStrategy sc,
1230 const std::function<int(std::size_t)>& prio_of, double& key, Rng& g_siro,
1231 const std::function<double(std::size_t)>* key_of) {
1232 if (fcfs_prio(sc) || lcfs_prio(sc)) {
1233 prio_enqueue(q, id, prio_of, lcfs_prio(sc), key_of);
1234 } else if (sc == SchedStrategy::LCFS) {
1235 q.push_front(id);
1236 } else {
1237 if (sc == SchedStrategy::SIRO) key = uniform01(g_siro);
1238 q.push_back(id);
1239 }
1240 };
1241 /** Take the request `sc` serves next: the head, or under SIRO the smallest key. */
1242 auto dequeue = [&](std::deque<std::size_t>& q, SchedStrategy sc,
1243 const std::function<double(std::size_t)>& key_of) -> std::size_t {
1244 std::deque<std::size_t>::iterator best = q.begin();
1245 if (sc == SchedStrategy::SIRO)
1246 for (std::deque<std::size_t>::iterator it = q.begin(); it != q.end(); ++it)
1247 if (key_of(*it) < key_of(*best)) best = it;
1248 const std::size_t id = *best;
1249 q.erase(best);
1250 return id;
1251 };
1252 const std::function<double(std::size_t)> line_key = [&](std::size_t lid) {
1253 return lines[lid].siro_key;
1254 };
1255 const std::function<double(std::size_t)> inv_key = [&](std::size_t vi) {
1256 return invs[vi].siro_key;
1257 };
1258 const std::function<double(std::size_t)> host_key = [&](std::size_t lid) {
1259 return lines[lid].host_t0;
1260 };
1261
1262 /**
1263 * PROCESSOR SHARING on a host replica, Solver_ssj_ln's startPSJob / advancePSService: every line
1264 * present is served at min(1, c/n) of a server, and the next completion is re-read whenever the
1265 * set changes. The event queue has no removal, so a stale completion is recognised by its
1266 * generation (event kind 5).
1267 */
1268 std::vector<std::vector<std::size_t> > ps_jobs(nhost_slots);
1269 std::vector<double> ps_last(nhost_slots, 0.0);
1270 std::vector<std::uint64_t> ps_gen(nhost_slots, 0);
1271 /**
1272 * The share of each line of slot `hs`: min(1, c/n) under PS; under PSPRIO, Solver_ssj_ln's
1273 * psprioJobRates, the levels served from the largest task priority down, each taking
1274 * min(servers left, its lines) servers split evenly. Either way the shares sum to min(n, c).
1275 */
1276 auto ps_rates = [&](std::size_t hs) -> std::vector<double> {
1277 const std::vector<std::size_t>& pj = ps_jobs[hs];
1278 const std::size_t n = pj.size();
1279 const std::size_t host = host_of_slot[hs];
1280 const double c = static_cast<double>(host_servers[host]);
1281 if (host_sched[host] != SchedStrategy::PSPRIO || static_cast<double>(n) <= c)
1282 return std::vector<double>(n, n == 0 ? 0.0 : std::min(1.0, c / static_cast<double>(n)));
1283 std::vector<double> rate(n, 0.0);
1284 std::vector<int> pr(n);
1285 for (std::size_t i = 0; i < n; ++i) pr[i] = task_prio(lsn.parent[lines[pj[i]].act]);
1286 std::vector<int> levels(pr);
1287 std::sort(levels.begin(), levels.end(), std::greater<int>());
1288 levels.erase(std::unique(levels.begin(), levels.end()), levels.end());
1289 double left = c;
1290 for (std::size_t l = 0; l < levels.size() && left > 0.0; ++l) {
1291 std::size_t cnt = 0;
1292 for (std::size_t i = 0; i < n; ++i) cnt += (pr[i] == levels[l]) ? 1 : 0;
1293 const double alloc = std::min(left, static_cast<double>(cnt));
1294 for (std::size_t i = 0; i < n; ++i)
1295 if (pr[i] == levels[l]) rate[i] = alloc / static_cast<double>(cnt);
1296 left -= alloc;
1297 }
1298 return rate;
1299 };
1300 /** Serve every line of slot `hs` up to now at the shares in force since the last change. */
1301 auto ps_advance = [&](std::size_t hs) {
1302 const double dt = now - ps_last[hs];
1303 if (dt > 0.0) {
1304 const std::vector<double> rate = ps_rates(hs);
1305 for (std::size_t i = 0; i < ps_jobs[hs].size(); ++i) {
1306 LnLine& L = lines[ps_jobs[hs][i]];
1307 L.remaining = std::max(0.0, L.remaining - dt * rate[i]);
1308 }
1309 }
1310 ps_last[hs] = now;
1311 };
1312 /** Busy servers of a PS slot holding n lines, the min(n, c) Solver_ssj_ln.updateHostStats counts. */
1313 auto ps_busy = [&](std::size_t hs, std::size_t n) -> double {
1314 return static_cast<double>(std::min(n, host_servers[host_of_slot[hs]]));
1315 };
1316
1317 // Time integrals per element.
1318 std::vector<double> tot_q(nidx + 1, 0.0), tot_u(nidx + 1, 0.0);
1319 std::vector<double> cur_q(nidx + 1, 0.0), cur_u(nidx + 1, 0.0);
1320 std::vector<double> last_upd(nidx + 1, 0.0);
1321 std::vector<double> completions(nidx + 1, 0.0), resp_sum(nidx + 1, 0.0),
1322 resp_cnt(nidx + 1, 0.0);
1323 // The observations behind `resp_sum` at the ENTRY indices, kept for
1324 // get_cdf_respt. Only entries: an activity's and a task's response times are
1325 // means the layered table reports, with no distributional getter on them.
1326 std::vector<std::vector<double> > entry_resp_samples(lsn.nentries);
1327 // Thread time held per call (1-based, slot 0 unused) and per local entry stream, and the
1328 // dispatches of each call at its caller: the UCallLN / UEntryClassLN / TCallLN accumulators.
1329 std::vector<double> call_busy(lsn.ncalls + 1, 0.0), call_disp(lsn.ncalls + 1, 0.0);
1330 std::vector<double> ecls_busy(lsn.nentries, 0.0);
1331 // Total time the executions of an activity spend AT ITS HOST PROCESSOR --
1332 // queueing there plus running. Over the elapsed time this is the mean
1333 // occupancy at the host, which is what ResidT is built from below.
1334 // MEASURED rather than derived from the nominal `hostdem` mean: that mean is
1335 // the SERVICE time, and on a contended processor the residence is that plus
1336 // the wait, so a derived figure would report an uncontended residence at
1337 // exactly the models where it matters.
1338 std::vector<double> act_host_resid(nidx + 1, 0.0);
1339
1340 // ONE STREAM PER CALL for the repetition count, on the engine's own offset
1341 // block (4000), so that adding a call does not shift the variates of the
1342 // think times or the host demands and re-baseline every seeded result.
1343 std::vector<Rng> g_callmult;
1344 g_callmult.reserve(lsn.ncalls + 1);
1345 for (std::size_t c = 0; c <= lsn.ncalls; ++c)
1346 g_callmult.push_back(engine::ln_rng(ln_seed, static_cast<long long>(c) * 10 + 4000));
1347
1348 /*
1349 * Routed call groups (synchCallRoundRobin, synchCallJSQ), Solver_ssj_ln.buildCallGroups.
1350 * Group g makes cg_mean[g] calls per execution, the sum of its member calls' means, drawn
1351 * at its first member in the caller's call order (the lead; the other members are then
1352 * skipped), and each call goes to a member when it is made: the next in the order of the
1353 * group's targets (round robin, one pointer per caller replica) or the member whose callee
1354 * replica holds the fewest requests (JSQ, ties uniform). A group that resolves to fewer
1355 * than two calls is dropped, as SolverLN drops it.
1356 */
1357 std::vector<std::vector<std::size_t> > cg_members;
1358 std::vector<lang::RoutingStrategy> cg_strategy;
1359 std::vector<double> cg_mean;
1360 std::vector<std::vector<std::size_t> > cg_next;
1361 std::vector<long> cg_of(lsn.ncalls + 1, -1);
1362 std::vector<bool> cg_lead(lsn.ncalls + 1, false);
1363 for (const lqn::LqnCallGroup& grp : lsn.callgroups) {
1364 if (grp.caller >= lsn.callsof.size()) continue;
1365 const std::vector<std::size_t>& calls = lsn.callsof[grp.caller];
1366 std::vector<std::size_t> members;
1367 double mean = 0.0;
1368 for (std::size_t target : grp.targets) {
1369 for (std::size_t cidx : calls) {
1370 if (lsn.calltype[cidx] == lang::CallType::SYNC && lsn.callpair_dst[cidx] == target &&
1371 cg_of[cidx] < 0 && std::find(members.begin(), members.end(), cidx) == members.end()) {
1372 members.push_back(cidx);
1373 mean += (cidx < lsn.callproc_mean.size()) ? num_traits<T>::to_double(lsn.callproc_mean[cidx]) : 1.0;
1374 break;
1375 }
1376 }
1377 }
1378 if (members.size() < 2) continue;
1379 const long g = static_cast<long>(cg_members.size());
1380 for (std::size_t cidx : members) cg_of[cidx] = g;
1381 for (std::size_t cidx : calls)
1382 if (cg_of[cidx] == g) {
1383 cg_lead[cidx] = true;
1384 break;
1385 }
1386 cg_members.push_back(members);
1387 cg_strategy.push_back(grp.strategy);
1388 cg_mean.push_back(mean);
1389 cg_next.push_back(std::vector<std::size_t>(std::max<std::size_t>(1, repl[lsn.parent[grp.caller]]), 0));
1390 }
1391 // The groups' call counts and JSQ ties on blocks of their own (930000, 980000)
1392 std::vector<Rng> g_cgcount;
1393 for (std::size_t g = 0; g < cg_members.size(); ++g)
1394 g_cgcount.push_back(engine::ln_rng(ln_seed, 930000 + static_cast<long long>(g)));
1395 Rng g_cgtie = engine::ln_rng(ln_seed, 980000);
1396 // Requests at each task replica, queued or in service: what JSQ compares
1397 std::vector<std::size_t> tslot_q(ntask_slots, 0);
1398
1399 /**
1400 * How many times one execution of the caller makes call `cidx`.
1401 *
1402 * `floor(mean)` calls plus one more with probability equal to the fraction,
1403 * which is `Solver_ssj_ln.sampleCallCount` exactly. It is DETERMINISTIC at
1404 * an integer mean, which is what `calls-mean="3"` asks for: three calls
1405 * every time, not three on average.
1406 */
1407 auto sample_call_count = [&](std::size_t cidx) -> std::size_t {
1408 const double m = (cidx < lsn.callproc_mean.size())
1409 ? num_traits<T>::to_double(lsn.callproc_mean[cidx])
1410 : 1.0;
1411 if (!(m > 0.0)) return 0;
1412 std::size_t n = static_cast<std::size_t>(std::floor(m));
1413 const double frac = m - static_cast<double>(n);
1414 if (frac > 0.0 && cidx < g_callmult.size() && uniform01(g_callmult[cidx]) < frac) ++n;
1415 return n;
1416 };
1417 // The same law for the calls of group g
1418 auto sample_group_count = [&](std::size_t g) -> std::size_t {
1419 const double m = cg_mean[g];
1420 if (!(m > 0.0)) return 0;
1421 std::size_t n = static_cast<std::size_t>(std::floor(m));
1422 const double frac = m - static_cast<double>(n);
1423 if (frac > 0.0 && uniform01(g_cgcount[g]) < frac) ++n;
1424 return n;
1425 };
1426 // The member call the next call of group g goes to, made by replica crep of caller_task; its
1427 // callee replica in rep
1428 auto dispatch_group = [&](std::size_t g, std::size_t caller_task, std::size_t crep,
1429 std::size_t& rep) -> std::size_t {
1430 const std::vector<std::size_t>& members = cg_members[g];
1431 if (cg_strategy[g] == lang::RoutingStrategy::RROBIN) {
1432 std::vector<std::size_t>& next = cg_next[g];
1433 std::size_t& ptr = next[std::min(crep, next.size() - 1)];
1434 const std::size_t cidx = members[ptr];
1435 ptr = (ptr + 1) % members.size();
1436 rep = callee_replica(caller_task, crep, lsn.parent[lsn.callpair_dst[cidx]]);
1437 return cidx;
1438 }
1439 std::size_t best = members.front(), ties = 0, best_len = std::numeric_limits<std::size_t>::max();
1440 for (std::size_t cidx : members) {
1441 const std::size_t t = lsn.parent[lsn.callpair_dst[cidx]];
1442 const std::size_t r = callee_replica(caller_task, crep, t);
1443 const std::size_t len = tslot_q[task_slot(t, r)];
1444 if (len < best_len) {
1445 best = cidx;
1446 rep = r;
1447 best_len = len;
1448 ties = 1;
1449 } else if (len == best_len && uniform01(g_cgtie) * static_cast<double>(++ties) < 1.0) {
1450 best = cidx;
1451 rep = r;
1452 }
1453 }
1454 return best;
1455 };
1456
1457 auto touch = [&](std::size_t k) {
1458 const double dt = now - last_upd[k];
1459 if (dt > 0.0) {
1460 tot_q[k] += cur_q[k] * dt;
1461 tot_u[k] += cur_u[k] * dt;
1462 }
1463 last_upd[k] = now;
1464 };
1465 auto push_ev = [&](LnEvent e) {
1466 e.seq = seq++;
1467 evq.push(e);
1468 };
1469
1470 // THE BUDGET AND THE WARMUP COUNT ACTIVITY COMPLETIONS, Solver_ssj_ln's totalEventCount and
1471 // checkEventCountStop: the run stops once `max_events` activities have completed, and when
1472 // floor(0.2*max_events) have, every statistic is reset (`reset_stats`, resetStatistics).
1473 // WARMUP ENDS AT WHICHEVER BUDGET IS 20% SPENT FIRST: with a wall-clock budget (the armed
1474 // timeout, `--maxtime` included) the reset also fires at the first activity completion once
1475 // 20% of that budget has elapsed, so a run its clock cuts short still measures the last 80%
1476 // of what it simulated instead of reporting zeros. Without one the event rule is unchanged.
1477 std::uint64_t done = 0;
1478 const std::uint64_t warm_events =
1479 static_cast<std::uint64_t>(static_cast<double>(max_events) * 0.2);
1480 const double clock_budget = util::timeout_remaining();
1481 const bool has_warm_deadline = std::isfinite(clock_budget);
1482 const auto warm_deadline = std::chrono::steady_clock::now() +
1483 std::chrono::duration_cast<std::chrono::steady_clock::duration>(std::chrono::duration<double>(
1484 has_warm_deadline ? 0.2 * std::max(clock_budget, 0.0) : 0.0));
1485 std::uint64_t warm_done_at = 0; ///< `done` at the reset: completions after it are measured
1486 bool warm = false;
1487 double warm_t = 0.0;
1488 long long cycles = 0; ///< reference cycles completed since the reset
1489 /**
1490 * The end of warmup, Solver_ssj_ln.resetStatistics: every time integral is closed at `now`
1491 * and restarts from zero in the state the model is in, and every count, sum and sample so
1492 * far is dropped. Nothing in flight needs marking: every invocation alive now was created
1493 * with `pre` set, and only invocations created from here on by a new root count.
1494 */
1495 auto reset_stats = [&]() {
1496 warm = true;
1497 warm_t = now;
1498 warm_done_at = done;
1499 for (std::size_t k = 0; k <= nidx; ++k) {
1500 touch(k);
1501 tot_q[k] = 0.0;
1502 tot_u[k] = 0.0;
1503 completions[k] = 0.0;
1504 resp_sum[k] = 0.0;
1505 resp_cnt[k] = 0.0;
1506 act_host_resid[k] = 0.0;
1507 }
1508 for (std::size_t e = 0; e < entry_resp_samples.size(); ++e) entry_resp_samples[e].clear();
1509 std::fill(call_busy.begin(), call_busy.end(), 0.0);
1510 std::fill(call_disp.begin(), call_disp.end(), 0.0);
1511 std::fill(ecls_busy.begin(), ecls_busy.end(), 0.0);
1512 for (std::size_t ci = 0; ci < caches.size(); ++ci) {
1513 caches[ci].reads = 0;
1514 caches[ci].hits = 0;
1515 caches[ci].misses = 0;
1516 caches[ci].delayed = 0;
1517 }
1518 cycles = 0;
1519 };
1520
1521 /**
1522 * Charge the post-warmup part of invocation `vi`'s thread hold to its class,
1523 * `Solver_ssj_ln.releaseThreadHold` (`end`) and `flushThreadHold` (the run stops with the
1524 * hold still open, which keeps it open from `now`). A call is charged to its call index,
1525 * anything else to the local index of its entry; nothing is charged before warmup ends.
1526 */
1527 auto charge_hold = [&](std::size_t vi, bool end) {
1528 LnInv& v = invs[vi];
1529 const double start = v.hold_t0;
1530 v.hold_t0 = end ? -1.0 : now;
1531 if (!warm || start < 0.0) return;
1532 const double held = now - std::max(start, warm_t);
1533 if (!(held > 0.0)) return;
1534 if (v.call_idx >= 1 && v.call_idx <= lsn.ncalls) {
1535 call_busy[v.call_idx] += held;
1536 } else if (v.entry > lsn.eshift && v.entry <= lsn.eshift + lsn.nentries) {
1537 ecls_busy[v.entry - lsn.eshift - 1] += held;
1538 }
1539 };
1540 /** One dispatch of call `cidx` by invocation `vi`, `Solver_ssj_ln.countCallDispatch`. */
1541 auto count_dispatch = [&](std::size_t vi, std::size_t cidx) {
1542 if (!invs[vi].pre && cidx >= 1 && cidx <= lsn.ncalls) call_disp[cidx] += 1.0;
1543 };
1544
1545 // ---- lines and invocations ------------------------------------------------
1546 auto new_line = [&](std::size_t inv, std::size_t act, bool branch) -> std::size_t {
1547 std::size_t id;
1548 if (!free_lines.empty()) {
1549 id = free_lines.back();
1550 free_lines.pop_back();
1551 lines[id] = LnLine();
1552 } else {
1553 id = lines.size();
1554 lines.push_back(LnLine());
1555 }
1556 lines[id].inv = inv;
1557 lines[id].act = act;
1558 lines[id].calls_left = NOTDRAWN;
1559 lines[id].branch = branch;
1560 return id;
1561 };
1562 auto free_line = [&](std::size_t id) { free_lines.push_back(id); };
1563 /** Move a line to activity `a`, not yet begun. */
1564 auto set_act = [&](std::size_t lid, std::size_t a) {
1565 LnLine& L = lines[lid];
1566 L.act = a;
1567 L.act_t0 = -1.0;
1568 L.call_pos = 0;
1569 L.calls_left = NOTDRAWN;
1570 L.dem_done = 0;
1571 };
1572 auto new_inv =[&](std::size_t entry, std::size_t trep, std::size_t caller,
1573 std::size_t cust) -> std::size_t {
1574 // A call or forward belongs to its caller's root; a new root counts once warmup is over.
1575 const bool pre = !warm || (caller != LN_NONE && invs[lines[caller].inv].pre);
1576 std::size_t id;
1577 if (!free_invs.empty()) {
1578 id = free_invs.back();
1579 free_invs.pop_back();
1580 invs[id] = LnInv();
1581 } else {
1582 id = invs.size();
1583 invs.push_back(LnInv());
1584 }
1585 LnInv& v = invs[id];
1586 v.entry = entry;
1587 v.task = lsn.parent[entry];
1588 v.trep = trep;
1589 v.ts = task_slot(v.task, trep);
1590 v.th = NOTHR;
1591 v.caller = caller;
1592 v.cust = cust;
1593 v.pre = pre;
1594 const std::size_t root = new_line(id, bound[entry], false);
1595 invs[id].root = root;
1596 return id;
1597 };
1598
1599 /**
1600 * Enter the task: the invocation now counts at the task. It counts at its ENTRY only once it
1601 * holds a thread (see `advance`), since the entry's service starts there.
1602 */
1603 auto enter_task = [&](std::size_t vi) {
1604 LnInv& v = invs[vi];
1605 v.task_t0 = now;
1606 touch(v.task);
1607 cur_q[v.task] += 1.0;
1608 ++tslot_q[v.ts];
1609 };
1610 /**
1611 * Arrive at the task, through its admission constraint when it has one. A
1612 * blocked request holds neither a thread nor a place in the task's queue,
1613 * so it is counted nowhere while it waits, as `arriveAtTask` has it.
1614 */
1615 auto arrive_at_task = [&](std::size_t vi) -> bool {
1616 LnInv& v = invs[vi];
1617 const int col = lincon_col(v.task, v.entry);
1618 if (col >= 0) {
1619 v.tcol = col;
1620 if (!admits(v.task, tocc[v.ts], col)) {
1621 tadm[v.ts].push_back(vi);
1622 return false;
1623 }
1624 ++tocc[v.ts][static_cast<std::size_t>(col)];
1625 }
1626 enter_task(vi);
1627 return true;
1628 };
1629
1630 // ---- the activity walk --------------------------------------------------
1631 std::function<void(std::size_t)> advance;
1632 /** Continue every line a release woke, and every line those wake. */
1633 auto drain = [&]() {
1634 while (!runnable.empty()) {
1635 const std::size_t id = runnable.front();
1636 runnable.pop_front();
1637 advance(id);
1638 }
1639 };
1640
1641 /** Put line `lid` into service at its host replica. */
1642 std::function<void(std::size_t)> advance_pool;
1643 auto pool_rates = [&](std::size_t hs) {
1644 const std::size_t h = host_of_slot[hs];
1645 const std::vector<std::size_t>& jobs = pool_jobs[hs];
1646 std::vector<double> rate(jobs.size(), 0.0);
1647 for (std::size_t p = 0; p < pool_capacity[h].size(); ++p)
1648 for (std::size_t i = 0; i < jobs.size(); ++i) {
1649 const int j = lines[jobs[i]].pcol;
1650 if (j >= 0 && static_cast<std::size_t>(j) < pool_serves[h][p].size() &&
1651 pool_serves[h][p][static_cast<std::size_t>(j)]) {
1652 rate[i] += pool_capacity[h][p];
1653 break;
1654 }
1655 }
1656 return rate;
1657 };
1658 /** Serve every job of a pooled replica up to now at the rates in force. */
1659 advance_pool = [&](std::size_t hs) {
1660 const std::vector<double> r = pool_rates(hs);
1661 const double dt = now - pool_last[hs];
1662 for (std::size_t i = 0; i < pool_jobs[hs].size(); ++i) {
1663 LnLine& L = lines[pool_jobs[hs][i]];
1664 L.remaining = std::max(0.0, L.remaining - dt * r[i]);
1665 }
1666 pool_last[hs] = now;
1667 };
1668 /**
1669 * Re-read the delivered rate after the job set changed, and arm the next
1670 * completion. A pooled host's Util integrates the DELIVERED rate, which is
1671 * `hostBusyTime += delivered*dt` of `advancePSService`.
1672 */
1673 auto rearm_pool = [&](std::size_t hs) {
1674 const std::size_t h = host_of_slot[hs];
1675 const std::vector<double> r = pool_rates(hs);
1676 double tot = 0.0, tmin = std::numeric_limits<double>::infinity();
1677 for (std::size_t i = 0; i < r.size(); ++i) {
1678 tot += r[i];
1679 if (r[i] > 0.0) tmin = std::min(tmin, lines[pool_jobs[hs][i]].remaining / r[i]);
1680 }
1681 touch(h);
1682 pool_rate[hs] = tot;
1683 double u = 0.0;
1684 for (std::size_t m = 0; m < repl[h]; ++m) u += pool_rate[host_slot0[h] + m];
1685 cur_u[h] = u;
1686 const std::uint64_t g = ++pool_gen[hs];
1687 if (std::isfinite(tmin)) {
1688 LnEvent e;
1689 e.t = now + tmin;
1690 e.kind = 4;
1691 e.who = hs;
1692 e.gen = g;
1693 push_ev(e);
1694 }
1695 };
1696 /** Arm the next completion of PS slot `hs` under the shares that hold from now on. */
1697 auto ps_schedule = [&](std::size_t hs) {
1698 ++ps_gen[hs];
1699 if (ps_jobs[hs].empty()) return;
1700 const std::vector<double> rate = ps_rates(hs);
1701 double tmin = std::numeric_limits<double>::infinity();
1702 for (std::size_t i = 0; i < ps_jobs[hs].size(); ++i)
1703 if (rate[i] > 0.0) tmin = std::min(tmin, lines[ps_jobs[hs][i]].remaining / rate[i]);
1704 LnEvent e;
1705 e.t = now + tmin;
1706 e.kind = 5;
1707 e.who = hs;
1708 e.gen = ps_gen[hs];
1709 push_ev(e);
1710 };
1711
1712 /// Lines in service on a host slot under a preemptive discipline, the candidates to preempt.
1713 std::vector<std::vector<std::size_t> > in_service(nhost_slots);
1714 std::uint64_t host_gen_ctr = 0;
1715 /// AND fork instances, numbered from 1 so that 0 marks the root line, which no fork created.
1716 std::uint64_t fork_ctr = 0;
1717 /**
1718 * Put line `lid` on a server of queueing host slot `hs` for the work it has left, drawing the
1719 * demand when it has none yet (a fresh request, or a PI victim resuming).
1720 */
1721 auto begin_host = [&](std::size_t lid, std::size_t hs) {
1722 LnLine& L = lines[lid];
1723 if (L.host_rem < 0.0) L.host_rem = hostdem[L.act].next(g_host[L.act]);
1724 L.host_start = now;
1725 L.host_end = now + L.host_rem;
1726 if (preemptive(host_sched[host_of_slot[hs]])) in_service[hs].push_back(lid);
1727 L.host_gen = ++host_gen_ctr;
1728 LnEvent e;
1729 e.t = L.host_end;
1730 e.kind = 0;
1731 e.who = lid;
1732 e.gen = L.host_gen;
1733 push_ev(e);
1734 };
1735 /**
1736 * Preempt a line in service on full slot `hs` for `lid`, Solver_ssj_ln.preemptFor: FCFSPR/PIPRIO
1737 * take only a STRICTLY lower priority, the lowest in service and the latest started among ties;
1738 * LCFSPR/PIPRIO take the lowest strictly lower one (earliest arrival among ties), else the equal
1739 * one that started earliest. The victim rejoins the queue at its original arrival, keeping its
1740 * residual work under PR and drawing afresh under PI. Returns whether `lid` took a server.
1741 */
1742 auto preempt_for = [&](std::size_t lid, std::size_t hs) -> bool {
1743 const SchedStrategy sc = host_sched[host_of_slot[hs]];
1744 const bool lifo = lcfs_prio(sc);
1745 const int pa = host_req_prio(lid);
1746 std::vector<std::size_t>& ins = in_service[hs];
1747 std::size_t vi = ins.size();
1748 int pv = 0;
1749 for (std::size_t i = 0; i < ins.size(); ++i) {
1750 const int pr = host_req_prio(ins[i]);
1751 if (pr >= pa) continue;
1752 bool better = vi == ins.size() || pr < pv;
1753 if (!better && pr == pv) {
1754 const LnLine& r = lines[ins[i]];
1755 const LnLine& v = lines[ins[vi]];
1756 better = lifo ? r.host_t0 < v.host_t0 : r.host_start > v.host_start;
1757 }
1758 if (better) {
1759 vi = i;
1760 pv = pr;
1761 }
1762 }
1763 if (vi == ins.size() && lifo)
1764 for (std::size_t i = 0; i < ins.size(); ++i)
1765 if (host_req_prio(ins[i]) == pa &&
1766 (vi == ins.size() || lines[ins[i]].host_start < lines[ins[vi]].host_start))
1767 vi = i;
1768 if (vi == ins.size()) return false;
1769 const std::size_t victim = ins[vi];
1770 ins.erase(ins.begin() + static_cast<std::ptrdiff_t>(vi));
1771 LnLine& v = lines[victim];
1772 v.host_gen = ++host_gen_ctr; // its pending completion is now stale
1773 const bool resume = sc == SchedStrategy::FCFSPRPRIO || sc == SchedStrategy::LCFSPRPRIO;
1774 v.host_rem = resume ? std::max(0.0, v.host_end - now) : -1.0;
1775 enqueue(host_queue[hs], victim, sc, host_req_prio, v.siro_key, g_siro_host, &host_key);
1776 begin_host(lid, hs);
1777 return true;
1778 };
1779
1780 auto start_host_service = [&](std::size_t lid) {
1781 LnLine& L = lines[lid];
1782 const std::size_t act = L.act;
1783 const std::size_t host = lsn.host_of(act);
1784 const std::size_t hs = host_slot(host, invs[L.inv].trep);
1785 touch(host);
1786 cur_q[host] += 1.0;
1787 if (pooled[host]) {
1788 advance_pool(hs);
1789 const std::size_t t = lsn.parent[act];
1790 const std::map<std::size_t, int>::const_iterator it = pool_col[host].find(t);
1791 if (it == pool_col[host].end())
1792 throw InputError("SolverLDES (native LN engine): activity '" + lsn.names[act] +
1793 "' runs on a host whose pool declaration does not name its "
1794 "task, so no server can be assigned");
1795 lines[lid].pcol = it->second;
1796 lines[lid].remaining = hostdem[act].next(g_host[act]);
1797 pool_jobs[hs].push_back(lid);
1798 rearm_pool(hs);
1799 return;
1800 }
1801 lines[lid].host_rem = -1.0;
1802 if (is_ps(host_sched[host])) {
1803 // Charge the interval that just ended at the share in force during it, then admit.
1804 ps_advance(hs);
1805 const std::size_t n0 = ps_jobs[hs].size();
1806 lines[lid].remaining = hostdem[act].next(g_host[act]);
1807 ps_jobs[hs].push_back(lid);
1808 ++host_busy[hs];
1809 cur_u[host] += ps_busy(hs, n0 + 1) - ps_busy(hs, n0);
1810 ps_schedule(hs);
1811 return;
1812 }
1813 if (host_busy[hs] < host_servers[host]) {
1814 ++host_busy[hs];
1815 cur_u[host] += 1.0;
1816 begin_host(lid, hs);
1817 } else if (!(preemptive(host_sched[host]) && preempt_for(lid, hs))) {
1818 enqueue(host_queue[hs], lid, host_sched[host], host_req_prio, lines[lid].siro_key,
1819 g_siro_host, &host_key);
1820 }
1821 };
1822 /**
1823 * Ask the host for service. The residence starts HERE, when the line asks,
1824 * whether it then queues at the processor or waits outside it for a host
1825 * admission token; a blocked line keeps its thread, being still inside
1826 * its activity, but holds no server.
1827 */
1828 auto request_host = [&](std::size_t lid) {
1829 LnLine& L = lines[lid];
1830 const std::size_t act = L.act;
1831 const std::size_t host = lsn.host_of(act);
1832 const std::size_t hs = host_slot(host, invs[L.inv].trep);
1833 L.host_t0 = now;
1834 const int col = lincon_col(host, lsn.parent[act]);
1835 if (col >= 0) {
1836 L.hcol = col;
1837 if (!admits(host, hocc[hs], col)) {
1838 hadm[hs].push_back(lid);
1839 return;
1840 }
1841 ++hocc[hs][static_cast<std::size_t>(col)];
1842 }
1843 start_host_service(lid);
1844 };
1845 /** Give back a host admission token and admit the blocked head while it fits. */
1846 auto release_host_admission = [&](std::size_t lid) {
1847 LnLine& L = lines[lid];
1848 if (L.hcol < 0) return;
1849 const std::size_t host = lsn.host_of(L.act);
1850 const std::size_t hs = host_slot(host, invs[L.inv].trep);
1851 --hocc[hs][static_cast<std::size_t>(L.hcol)];
1852 L.hcol = -1;
1853 while (!hadm[hs].empty()) {
1854 const std::size_t head = hadm[hs].front();
1855 const int c = lines[head].hcol;
1856 if (!admits(host, hocc[hs], c)) return;
1857 hadm[hs].pop_front();
1858 ++hocc[hs][static_cast<std::size_t>(c)];
1859 start_host_service(head);
1860 }
1861 };
1862
1863 /** Arm THREAD's cold start; the request that woke it waits in thr_queue. */
1864 auto start_setup = [&](std::size_t ts, std::size_t th) {
1865 const std::size_t task = thr_owner[ts];
1866 thr_state[ts][th] = ThreadState::SETUP;
1867 thr_setup_t0[ts][th] = now;
1868 LnEvent e;
1869 e.t = now + setupd[task].next(g_setup[task]);
1870 e.kind = 2;
1871 e.who = ts;
1872 e.aux = th;
1873 e.gen = ++thr_gen[ts][th];
1874 push_ev(e);
1875 };
1876
1877 /** Arm THREAD's idle countdown; when it expires the thread is OFF. */
1878 auto start_delayoff = [&](std::size_t ts, std::size_t th) {
1879 const std::size_t task = thr_owner[ts];
1880 thr_state[ts][th] = ThreadState::DELAYOFF;
1881 LnEvent e;
1882 e.t = now + delayoffd[task].next(g_doff[task]);
1883 e.kind = 3;
1884 e.who = ts;
1885 e.aux = th;
1886 e.gen = ++thr_gen[ts][th];
1887 push_ev(e);
1888 };
1889
1890 /**
1891 * Give invocation `vi` a thread of its task.
1892 *
1893 * Returns false when it could not proceed: either every thread is taken, or
1894 * the only thread available was powered off and is now warming up. Either
1895 * way it is parked in thr_queue and continued by whoever frees or finishes
1896 * warming a thread. An infinite-thread task never blocks and holds no
1897 * identified thread.
1898 */
1899 auto acquire_thread = [&](std::size_t vi) -> bool {
1900 LnInv& v = invs[vi];
1901 const std::size_t task = v.task;
1902 const std::size_t ts = v.ts;
1903 touch(task);
1904 if (task_threads[task] == std::numeric_limits<std::size_t>::max()) {
1905 cur_u[task] += 1.0;
1906 v.has_thread = true;
1907 v.hold_t0 = now;
1908 v.th = NOTHR;
1909 return true;
1910 }
1911 std::vector<bool>& held = thr_held[ts];
1912 std::vector<ThreadState>& st = thr_state[ts];
1913 // An ACTIVE idle thread first, then one still counting down -- caught
1914 // before it powers off, it serves having paid nothing -- and only then a
1915 // thread that is already OFF, which must warm up first.
1916 for (std::size_t th = 0; th < held.size(); ++th) {
1917 if (!held[th] && st[th] == ThreadState::ACTIVE) {
1918 held[th] = true;
1919 cur_u[task] += 1.0;
1920 v.has_thread = true;
1921 v.hold_t0 = now;
1922 v.th = th;
1923 return true;
1924 }
1925 }
1926 for (std::size_t th = 0; th < held.size(); ++th) {
1927 if (!held[th] && st[th] == ThreadState::DELAYOFF) {
1928 ++thr_gen[ts][th]; // cancel the countdown
1929 st[th] = ThreadState::ACTIVE;
1930 held[th] = true;
1931 cur_u[task] += 1.0;
1932 v.has_thread = true;
1933 v.hold_t0 = now;
1934 v.th = th;
1935 return true;
1936 }
1937 }
1938 // a thread is free but down or powering up: this wait is a cold start, not contention
1939 v.cold_wait = static_cast<std::size_t>(std::count(held.begin(), held.end(), true)) < held.size();
1940 enqueue(thr_queue[ts], vi, task_sched[task], task_req_prio, invs[vi].siro_key, g_siro_task,
1941 nullptr);
1942 for (std::size_t th = 0; th < held.size(); ++th) {
1943 if (!held[th] && st[th] == ThreadState::OFF) {
1944 start_setup(ts, th);
1945 break;
1946 }
1947 }
1948 return false;
1949 };
1950
1951 /** Free the thread invocation `vi` holds and hand it to the next one waiting. */
1952 auto release_thread = [&](std::size_t vi) {
1953 LnInv& v = invs[vi];
1954 const std::size_t ts = v.ts;
1955 const std::size_t th = v.th;
1956 const std::size_t task = thr_owner[ts];
1957 touch(task);
1958 cur_u[task] -= 1.0;
1959 charge_hold(vi, true);
1960 v.has_thread = false;
1961 v.th = NOTHR;
1962 if (th == NOTHR) return; // an infinite-thread task holds nothing
1963 thr_held[ts][th] = false;
1964 if (!thr_queue[ts].empty()) {
1965 const std::size_t nxt = dequeue(thr_queue[ts], task_sched[task], inv_key);
1966 thr_held[ts][th] = true;
1967 cur_u[task] += 1.0;
1968 invs[nxt].has_thread = true;
1969 invs[nxt].hold_t0 = now;
1970 invs[nxt].th = th;
1971 // a freed thread can end a cold wait before its setup does: charged from arrival
1972 if (invs[nxt].cold_wait && !invs[nxt].started) {
1973 LnInv& w = invs[nxt];
1974 w.started = true;
1975 w.entry_t0 = w.task_t0;
1976 touch(w.entry);
1977 tot_q[w.entry] += now - std::max(w.entry_t0, warm_t);
1978 cur_q[w.entry] += 1.0;
1979 }
1980 runnable.push_back(invs[nxt].root);
1981 } else if (has_setup[task]) {
1982 start_delayoff(ts, th);
1983 }
1984 };
1985
1986 /**
1987 * One execution of the line's activity has finished.
1988 *
1989 * ITS RESPONSE TIME CARRIES THE CALLS IT MADE, which is what separates it
1990 * from the residence `act_host_resid` accumulates: on an activity that calls
1991 * a server three times, the response is its own demand plus the three
1992 * replies and the residence is its own demand alone. The occupancy is closed
1993 * off through `cur_q` at the same instant, so QLen, RespT and Tput satisfy
1994 * Little's law by construction rather than by three separate estimators
1995 * happening to agree.
1996 */
1997 auto finish_act = [&](LnLine& L) {
1998 const std::size_t act = L.act;
1999 const bool seen = !invs[L.inv].pre;
2000 if (seen) completions[act] += 1.0;
2001 if (L.act_t0 >= 0.0) {
2002 if (seen) {
2003 resp_sum[act] += now - L.act_t0;
2004 resp_cnt[act] += 1.0;
2005 }
2006 touch(act);
2007 cur_q[act] -= 1.0;
2008 }
2009 L.act_t0 = -1.0;
2010 };
2011
2012 /**
2013 * The entry replies: its throughput and response time are recorded, and the
2014 * synchronous caller is released. `direct` is a reply at completion, whose
2015 * caller the walk continues itself; an early reply (phase 2 follows, or a
2016 * cache branch replied) wakes the caller through `runnable`.
2017 *
2018 * AN ENTRY'S RESPONSE TIME IS THE LQN ENTRY SERVICE TIME, from the instant it
2019 * took a thread of its task to the reply, and so carries every nested call its
2020 * activities made. The wait for the thread belongs to the caller's call, as
2021 * lqns, lqsim, SolverLN and Solver_ssj_ln.sendEntryReply all count it.
2022 */
2023 auto send_reply = [&](std::size_t vi, bool direct) {
2024 LnInv& v = invs[vi];
2025 if (v.replied) return;
2026 v.replied = true;
2027 v.early_reply = !direct;
2028 if (!v.pre) {
2029 completions[v.entry] += 1.0;
2030 const double r = now - v.entry_t0;
2031 resp_sum[v.entry] += r;
2032 resp_cnt[v.entry] += 1.0;
2033 // 1-BASED element indices in this engine, unlike the JAR and python
2034 // ports: entries are eshift+1 .. eshift+nentries, so the local index is
2035 // one less than the difference.
2036 if (v.entry > lsn.eshift && v.entry <= lsn.eshift + lsn.nentries)
2037 entry_resp_samples[v.entry - lsn.eshift - 1].push_back(r);
2038 }
2039 // FORWARDING, Solver_ssj_ln.sendEntryReply: the entry has served its part (its throughput
2040 // and response time are recorded above), and with the forwarding probability the request
2041 // goes on to the target entry carrying the SAME caller, who stays blocked. The forwarding
2042 // invocation gives up its caller, so its own completion releases nobody.
2043 if (v.caller != LN_NONE && !fwd_dst[v.entry].empty()) {
2044 const double u = uniform01(g_fwd[v.entry]);
2045 double cum = 0.0;
2046 for (std::size_t k = 0; k < fwd_dst[v.entry].size(); ++k) {
2047 cum += fwd_prob[v.entry][k];
2048 if (u < cum) {
2049 const std::size_t tgt = fwd_dst[v.entry][k];
2050 const std::size_t caller = v.caller;
2051 // The forwarding entry is the caller of the entry it forwards to.
2052 const std::size_t rep = callee_replica(v.task, v.trep, lsn.parent[tgt]);
2053 v.caller = LN_NONE;
2054 const std::size_t child = new_inv(tgt, rep, caller, LN_NONE);
2055 if (arrive_at_task(child)) runnable.push_back(invs[child].root);
2056 return;
2057 }
2058 }
2059 }
2060 if (!direct && v.caller != LN_NONE) runnable.push_back(v.caller);
2061 };
2062
2063 // ---- cache content -------------------------------------------------------
2064 /** `cacheMiss`: insert into the entry list, evicting by the policy's rule. */
2065 auto cache_insert = [&](std::size_t ci, std::size_t item) {
2066 LnCacheState& cs = caches[ci];
2067 std::list<std::size_t>& lst = cs.levels[0];
2068 const std::size_t cap = static_cast<std::size_t>(std::max(0, cs.cap[0]));
2069 if (cs.rs == lang::ReplacementStrategy::RR) {
2070 if (lst.size() >= cap && !lst.empty()) {
2071 std::size_t r = static_cast<std::size_t>(uniform01(g_rr[ci]) *
2072 static_cast<double>(lst.size()));
2073 r = std::min(r, lst.size() - 1);
2074 std::list<std::size_t>::iterator it = lst.begin();
2075 std::advance(it, static_cast<long>(r));
2076 *it = item;
2077 } else {
2078 lst.push_front(item);
2079 }
2080 } else {
2081 lst.push_front(item);
2082 if (lst.size() > cap) lst.pop_back();
2083 }
2084 };
2085 /** `cacheHit`: refresh or promote the item one list up, demoting the displaced one. */
2086 auto cache_promote = [&](std::size_t ci, std::size_t item, std::size_t level) {
2087 LnCacheState& cs = caches[ci];
2088 const lang::ReplacementStrategy rs = cs.rs;
2089 const std::size_t inew = std::min(level + 1, cs.levels.size() - 1);
2090 const bool front_rule = rs == lang::ReplacementStrategy::LRU ||
2093 if (inew <= level) {
2094 if (front_rule) {
2095 cs.levels[level].remove(item);
2096 cs.levels[level].push_front(item);
2097 }
2098 return;
2099 }
2100 std::list<std::size_t>& lo = cs.levels[level];
2101 std::list<std::size_t>& hi = cs.levels[inew];
2102 std::size_t kpos = 0;
2103 for (std::list<std::size_t>::iterator it = lo.begin(); it != lo.end(); ++it, ++kpos)
2104 if (*it == item) break;
2105 lo.remove(item);
2106 if (hi.size() < static_cast<std::size_t>(std::max(0, cs.cap[inew]))) {
2107 hi.push_front(item);
2108 return;
2109 }
2110 std::size_t demoted;
2112 std::size_t r = static_cast<std::size_t>(uniform01(g_rr[ci]) *
2113 static_cast<double>(hi.size()));
2114 r = std::min(r, hi.size() - 1);
2115 std::list<std::size_t>::iterator it = hi.begin();
2116 std::advance(it, static_cast<long>(r));
2117 demoted = *it;
2118 *it = item;
2119 } else {
2120 demoted = hi.back();
2121 hi.pop_back();
2122 hi.push_front(item);
2123 }
2124 if (front_rule || rs == lang::ReplacementStrategy::SFIFO) {
2125 lo.push_front(demoted);
2126 } else {
2127 std::list<std::size_t>::iterator it = lo.begin();
2128 std::advance(it, static_cast<long>(std::min(kpos, lo.size())));
2129 lo.insert(it, demoted);
2130 }
2131 };
2132 static const std::size_t HELD = static_cast<std::size_t>(-2);
2133 /**
2134 * One read of an ItemEntry, `accessCache`: draw the item, look it up in the
2135 * live content of the replica serving the request, update the content, and
2136 * return the branch to continue on -- or HELD, when retrieval parks a read
2137 * of an item that is already being fetched.
2138 */
2139 auto access_cache = [&](std::size_t ai, std::size_t lid) -> std::size_t {
2140 const LnCacheAccess& ca = accesses[ai];
2141 LnInv& v = invs[lines[lid].inv];
2142 const std::size_t ci = ca.caches[std::min(v.trep, ca.caches.size() - 1)];
2143 LnCacheState& cs = caches[ci];
2144 // A read, its hit or miss and its delayed hit all count, or none does, by its root.
2145 const bool seen = !v.pre;
2146 if (seen) ++cs.reads;
2147 const double u = uniform01(g_item[ci]);
2148 std::size_t item = ca.cdf.size() - 1;
2149 for (std::size_t i = 0; i < ca.cdf.size(); ++i)
2150 if (u <= ca.cdf[i]) {
2151 item = i;
2152 break;
2153 }
2154 for (std::size_t l = 0; l < cs.levels.size(); ++l)
2155 if (std::find(cs.levels[l].begin(), cs.levels[l].end(), item) != cs.levels[l].end()) {
2156 if (seen) ++cs.hits;
2157 cache_promote(ci, item, l);
2158 return ca.hit;
2159 }
2160 if (cs.retrieval) {
2161 if (item < cs.inflight.size() && cs.inflight[item]) {
2162 cs.held[item].push_back(std::make_pair(lid, ai));
2163 return HELD;
2164 }
2165 if (seen) ++cs.misses;
2166 cs.inflight[item] = 1;
2167 v.fetching = true;
2168 v.fetch_cache = ci;
2169 v.fetch_item = item;
2170 return ca.miss;
2171 }
2172 if (seen) ++cs.misses;
2173 cache_insert(ci, item);
2174 return ca.miss;
2175 };
2176 /** The fetch completed: insert the item and let every parked read hit it. */
2177 auto release_fetch = [&](std::size_t vi) {
2178 LnInv& v = invs[vi];
2179 if (!v.fetching) return;
2180 v.fetching = false;
2181 LnCacheState& cs = caches[v.fetch_cache];
2182 const std::size_t item = v.fetch_item;
2183 cs.inflight[item] = 0;
2184 cache_insert(v.fetch_cache, item);
2185 std::vector<std::pair<std::size_t, std::size_t> > held;
2186 held.swap(cs.held[item]);
2187 // A parked read counts its delayed hit only if its read was counted: a read parked
2188 // before the reset belongs to a pre-warmup root, so hit + miss + delayed stays one per read.
2189 for (std::size_t k = 0; k < held.size(); ++k) {
2190 if (!invs[lines[held[k].first].inv].pre) ++caches[v.fetch_cache].delayed;
2191 set_act(held[k].first, accesses[held[k].second].hit);
2192 runnable.push_back(held[k].first);
2193 }
2194 };
2195
2196 /**
2197 * The invocation is complete, `completeRequest`: reply if it has not, leave
2198 * the entry and the task, free the thread and the task admission token, and
2199 * return the line to continue -- the synchronous caller, when the reply was
2200 * made just now -- or LN_NONE. A top-level invocation sends its customer
2201 * back to think.
2202 */
2203 auto complete_request = [&](std::size_t vi) -> std::size_t {
2204 send_reply(vi, true);
2205 release_fetch(vi);
2206 LnInv& v = invs[vi];
2207 touch(v.entry);
2208 cur_q[v.entry] -= 1.0;
2209 const bool seen = !v.pre;
2210 if (seen) completions[v.task] += 1.0;
2211 touch(v.task);
2212 cur_q[v.task] -= 1.0;
2213 --tslot_q[v.ts];
2214 release_thread(vi);
2215 if (v.tcol >= 0) {
2216 const std::size_t ts = v.ts, task = v.task;
2217 --tocc[ts][static_cast<std::size_t>(v.tcol)];
2218 v.tcol = -1;
2219 while (!tadm[ts].empty()) {
2220 const std::size_t head = tadm[ts].front();
2221 const int c = invs[head].tcol;
2222 if (!admits(task, tocc[ts], c)) break;
2223 tadm[ts].pop_front();
2224 ++tocc[ts][static_cast<std::size_t>(c)];
2225 enter_task(head);
2226 runnable.push_back(invs[head].root);
2227 }
2228 }
2229 LnInv& w = invs[vi];
2230 const std::size_t caller = w.caller, cust = w.cust;
2231 const bool early = w.early_reply;
2232 free_line(w.root);
2233 free_invs.push_back(vi);
2234 if (cust != LN_NONE) {
2235 // THE COMPLETION IS NOT COUNTED HERE: the reference task's own entry
2236 // just replied and `completions[task]` above is this task already.
2237 // `resp_sum` is the CYCLE response time and is the task's own.
2238 const std::size_t rt = custs[cust].ref_task;
2239 if (seen) {
2240 resp_sum[rt] += now - custs[cust].t_start;
2241 resp_cnt[rt] += 1.0;
2242 ++cycles;
2243 }
2244 LnEvent e;
2245 e.t = now + (has_think[rt] ? think[rt].next(g_think[rt]) : 0.0);
2246 e.kind = 1;
2247 e.who = cust;
2248 push_ev(e);
2249 return LN_NONE;
2250 }
2251 return (caller != LN_NONE && !early) ? caller : LN_NONE;
2252 };
2253
2254 /** A line reached an activity with no successor, `finishLine`. */
2255 auto finish_line = [&](std::size_t lid) -> std::size_t {
2256 const std::size_t vi = lines[lid].inv;
2257 LnInv& v = invs[vi];
2258 const bool br = lines[lid].branch;
2259 if (v.pending < 0) return complete_request(vi);
2260 const long rem = v.pending - 1;
2261 if (br) free_line(lid);
2262 if (rem <= 0) {
2263 invs[vi].pending = -1;
2264 return complete_request(vi);
2265 }
2266 invs[vi].pending = rem;
2267 return LN_NONE;
2268 };
2269
2270 /**
2271 * The line's activity is complete, `completeActivity`: a cache read picks
2272 * its branch; an AND-join input is recorded and the join fires on the ROOT
2273 * once all have arrived; a phase-1 activity entering phase 2, or a cache
2274 * branch of the entry, replies; then one successor continues, an OR or loop
2275 * decision draws one, and an AND fork starts every branch. Returns the line
2276 * to continue, or LN_NONE.
2277 */
2278 auto complete_activity = [&](std::size_t lid) -> std::size_t {
2279 finish_act(lines[lid]);
2280 // One event of the budget, counted where Solver_ssj_ln.completeActivity counts it: after
2281 // the activity's own measures and before anything it releases.
2282 ++done;
2283 if (!warm && (done >= warm_events ||
2284 (has_warm_deadline && std::chrono::steady_clock::now() >= warm_deadline)))
2285 reset_stats();
2286 const std::size_t act = lines[lid].act;
2287 const std::size_t vi = lines[lid].inv;
2288 if (access_of_driver[act] != LN_NONE) {
2289 const std::size_t nx = access_cache(access_of_driver[act], lid);
2290 if (nx == HELD) return LN_NONE;
2291 set_act(lid, nx);
2292 return lid;
2293 }
2294 const std::vector<std::size_t>& sc = succ_act[act];
2295 const bool br = lines[lid].branch;
2296 if ((br || invs[vi].pending >= 0) && pretype(act) == lang::PrecedenceType::PRE_AND &&
2297 !sc.empty()) {
2298 const std::size_t j = sc[0];
2299 const std::uint64_t fid = lines[lid].fork_id;
2300 {
2301 // A late input of a round that already fired on its quorum: it is discarded
2302 // here and its line ends, which is what lets the invocation drain.
2303 LnJoin& jn = invs[vi].joins[j];
2304 std::map<std::pair<std::size_t, std::uint64_t>, long>::iterator it =
2305 jn.discard.find(std::make_pair(act, fid));
2306 if (it == jn.discard.end()) it = jn.discard.find(std::make_pair(act, LN_ANYFORK));
2307 if (it != jn.discard.end()) {
2308 if (--it->second <= 0) jn.discard.erase(it);
2309 if (jn.got.empty() && jn.discard.empty()) invs[vi].joins.erase(j);
2310 return finish_line(lid);
2311 }
2312 }
2313 LnJoin& jn = invs[vi].joins[j];
2314 jn.got[act] = fid;
2315 if (br) free_line(lid);
2316 const std::size_t req = join_quorum[j] > 0 ? join_quorum[j] : 1;
2317 if (jn.got.size() >= req) {
2318 // The inputs still missing are this round's late inputs. They came from the
2319 // same fork instance as the ones that arrived, unless those disagree.
2320 std::uint64_t rf = jn.got.begin()->second;
2321 for (const std::pair<const std::size_t, std::uint64_t>& g : jn.got)
2322 if (g.second != rf) rf = LN_ANYFORK;
2323 for (std::size_t in : join_inputs[j])
2324 if (jn.got.find(in) == jn.got.end()) ++jn.discard[std::make_pair(in, rf)];
2325 jn.got.clear();
2326 if (jn.discard.empty()) invs[vi].joins.erase(j);
2327 if (invs[vi].pending >= 0) invs[vi].pending -= static_cast<long>(req - 1);
2328 set_act(invs[vi].root, j);
2329 return invs[vi].root;
2330 }
2331 return LN_NONE;
2332 }
2333 if (!invs[vi].replied && !br) {
2334 bool reply = branch_reply[act] != 0 && branch_reply[act] == invs[vi].entry;
2335 if (!reply && phase_of(act) == 1)
2336 for (std::size_t s : sc)
2337 if (phase_of(s) == 2) {
2338 reply = true;
2339 break;
2340 }
2341 // The main line reaching a leaf while other lines of the invocation still run (the
2342 // late inputs of a quorum join, a branch that joins nothing): the leaf is the reply
2343 // activity getStruct infers, and Solver_ssj_ln replies there, not when the rest drain.
2344 if (!reply && sc.empty() && invs[vi].pending > 1) reply = true;
2345 if (reply) send_reply(vi, false);
2346 }
2347 if (invs[vi].replied && invs[vi].fetching) release_fetch(vi);
2348 if (sc.empty()) return finish_line(lid);
2349 if (sc.size() == 1) {
2350 set_act(lid, sc[0]);
2351 return lid;
2352 }
2353 if (!or_prob[act].empty()) {
2354 const double u = uniform01(g_route[act]);
2355 double cum = 0.0;
2356 std::size_t pick = sc.back();
2357 for (std::size_t k = 0; k < sc.size(); ++k) {
2358 cum += or_prob[act][k];
2359 if (u <= cum) {
2360 pick = sc[k];
2361 break;
2362 }
2363 }
2364 set_act(lid, pick);
2365 return lid;
2366 }
2367 // AND fork: one line becomes |sc| concurrent lines. The forking line goes
2368 // dormant (the root) or retires (a branch); the join resumes the root.
2369 invs[vi].pending = (invs[vi].pending < 0 ? 1 : invs[vi].pending) +
2370 static_cast<long>(sc.size()) - 1;
2371 if (br) free_line(lid);
2372 const std::uint64_t fork = ++fork_ctr;
2373 std::vector<std::size_t> kids;
2374 for (std::size_t k = 0; k < sc.size(); ++k) {
2375 kids.push_back(new_line(vi, sc[k], true));
2376 lines[kids.back()].fork_id = fork;
2377 }
2378 for (std::size_t k = kids.size(); k-- > 1;) runnable.push_front(kids[k]);
2379 return kids[0];
2380 };
2381
2382 /**
2383 * A request at `entry` on task replica `rep` that nobody waits on: an asynchronous callee or
2384 * an open arrival. It runs as an invocation with no caller and no customer, so it just ends.
2385 */
2386 auto spawn_request = [&](std::size_t entry, std::size_t rep, bool pre, std::size_t cidx) {
2387 const std::size_t vi = new_inv(entry, rep, LN_NONE, LN_NONE);
2388 // An asynchronous callee belongs to the root of the request that sent it.
2389 if (pre) invs[vi].pre = true;
2390 invs[vi].call_idx = cidx;
2391 if (arrive_at_task(vi)) runnable.push_back(invs[vi].root);
2392 };
2393
2394 /**
2395 * Continue line `lid` from wherever it is: take a thread, begin the current
2396 * activity, ask its host, think, issue its next call, or complete it.
2397 */
2398 advance = [&](std::size_t lid) {
2399 while (lid != LN_NONE) {
2400 const std::size_t vi = lines[lid].inv;
2401 // An invocation holds a THREAD of its task for the whole entry,
2402 // across its calls, and waits outside when none is free.
2403 if (!invs[vi].has_thread) {
2404 if (!acquire_thread(vi)) return;
2405 }
2406 // The entry's service starts with its thread; its occupancy runs from here to the
2407 // end of its last phase, Solver_ssj_ln's entryResidenceTime from serviceStartTime.
2408 if (!invs[vi].started) {
2409 LnInv& v = invs[vi];
2410 v.started = true;
2411 v.entry_t0 = now;
2412 touch(v.entry);
2413 cur_q[v.entry] += 1.0;
2414 }
2415 LnLine& L = lines[lid];
2416 const std::size_t act = L.act;
2417 if (act == 0) { // an entry with no activity replies at once
2418 lid = complete_request(vi);
2419 continue;
2420 }
2421 if (L.act_t0 < 0.0) {
2422 L.act_t0 = now;
2423 touch(act);
2424 cur_q[act] += 1.0;
2425 L.dem_done = 0;
2426 }
2427 // THE HOST DEMAND RUNS FIRST, THEN THE THINK TIME, THEN THE CALLS: the order LQN2QN
2428 // builds (the demand step, then one step per call stage) and Solver_ssj_ln runs.
2429 if (L.dem_done == 0) {
2430 L.dem_done = 1;
2431 if (has_hostdem[act]) {
2432 request_host(lid);
2433 return;
2434 }
2435 }
2436 // The activity's think time, Solver_ssj_ln.proceedAfterHost: it holds the thread but
2437 // not the processor, so it adds to the activity's response and not to host busy.
2438 if (L.dem_done == 1) {
2439 L.dem_done = 2;
2440 if (has_actthink[act]) {
2441 LnEvent e;
2442 e.t = now + actthink[act].next(g_actthink[act]);
2443 e.kind = 6;
2444 e.who = lid;
2445 push_ev(e);
2446 return;
2447 }
2448 }
2449 const std::vector<std::size_t>& calls =
2450 (act < lsn.callsof.size()) ? lsn.callsof[act] : std::vector<std::size_t>();
2451 if (L.call_pos < calls.size()) {
2452 // A pending call of the current activity, made `calls-mean` times
2453 // per execution, drawn once when it is first reached.
2454 const std::size_t cidx = calls[L.call_pos];
2455 const long grp = cg_of[cidx];
2456 if (grp >= 0 && !cg_lead[cidx]) {
2457 // A group's calls are drawn and made at its lead member
2458 ++L.call_pos;
2459 continue;
2460 }
2461 if (L.calls_left == NOTDRAWN)
2462 L.calls_left = (grp >= 0) ? sample_group_count(static_cast<std::size_t>(grp)) : sample_call_count(cidx);
2463 if (L.calls_left == 0) {
2464 ++L.call_pos;
2465 L.calls_left = NOTDRAWN;
2466 continue;
2467 }
2468 --L.calls_left;
2469 if (L.calls_left == 0) {
2470 ++L.call_pos;
2471 L.calls_left = NOTDRAWN;
2472 }
2473 // `rcidx` is the call actually made: a group resolves to one of its members.
2474 std::size_t rcidx = cidx;
2475 std::size_t rep;
2476 if (grp >= 0)
2477 rcidx = dispatch_group(static_cast<std::size_t>(grp), invs[vi].task, invs[vi].trep, rep);
2478 const std::size_t callee = lsn.callpair_dst[rcidx];
2479 if (grp < 0) rep = callee_replica(invs[vi].task, invs[vi].trep, lsn.parent[callee]);
2480 count_dispatch(vi, rcidx);
2481 if (lsn.calltype[cidx] == lang::CallType::SYNC) {
2482 // THE CALLER KEEPS ITS THREAD across the call. That is the
2483 // layered contention the model exists to represent.
2484 const std::size_t child = new_inv(callee, rep, lid, LN_NONE);
2485 invs[child].call_idx = rcidx;
2486 if (!arrive_at_task(child)) return;
2487 lid = invs[child].root;
2488 continue;
2489 }
2490 // Asynchronous: the callee runs as a request of its own, the caller
2491 // does not wait, and the reply is never collected.
2492 spawn_request(callee, rep, invs[vi].pre, rcidx);
2493 continue;
2494 }
2495 // The demand, the think time and the calls are done: the activity
2496 // completes, its response time carrying all three.
2497 L.call_pos = 0;
2498 L.calls_left = NOTDRAWN;
2499 lid = complete_activity(lid);
2500 }
2501 };
2502
2503 // ---- reference tasks ----------------------------------------------------
2504 // Each reference task runs `mult` independent customers, which is what makes
2505 // the closed population of a layered model.
2506 auto start_cycle = [&](std::size_t c) {
2507 const std::size_t t = custs[c].ref_task;
2508 custs[c].t_start = now;
2509 const std::size_t vi = new_inv(lsn.entriesof[t][0], custs[c].repl, LN_NONE, c);
2510 if (arrive_at_task(vi)) advance(invs[vi].root);
2511 };
2512 bool any_ref = false;
2513 for (std::size_t t = lsn.tshift + 1; t <= lsn.tshift + lsn.ntasks; ++t) {
2514 if (t >= lsn.isref.size() || !lsn.isref[t]) continue;
2515 any_ref = true;
2516 const std::size_t n = (task_threads[t] == std::numeric_limits<std::size_t>::max())
2517 ? 1
2518 : task_threads[t];
2519 const std::vector<std::size_t>& es =
2520 (t < lsn.entriesof.size()) ? lsn.entriesof[t] : std::vector<std::size_t>();
2521 if (es.empty())
2522 throw InputError("SolverLDES (native LN engine): reference task '" + lsn.names[t] +
2523 "' declares no entry to invoke");
2524 // A replicated reference task is r separate populations of `mult`
2525 // customers, not one population of r*mult sharing a queue.
2526 for (std::size_t m = 0; m < repl[t]; ++m) {
2527 for (std::size_t k = 0; k < n; ++k) {
2528 LnCustomer cu;
2529 cu.ref_task = t;
2530 cu.repl = m;
2531 custs.push_back(cu);
2532 start_cycle(custs.size() - 1);
2533 }
2534 }
2535 }
2536 // ---- open arrivals --------------------------------------------------------
2537 // Each replica of the entry's task receives its own stream, as Solver_ssj_ln.startOpenArrivals
2538 // gives it: the declared rate is what one replica sees. Offset block 5000, per entry.
2539 std::vector<Sampler> arrival(nidx + 1);
2540 bool any_arrival = false;
2541 std::vector<Rng> g_arr;
2542 g_arr.reserve(nidx + 1);
2543 for (std::size_t k = 0; k <= nidx; ++k)
2544 g_arr.push_back(engine::ln_rng(ln_seed, static_cast<long long>(k) * 10 + 5000));
2545 for (std::size_t e = lsn.eshift + 1; e <= lsn.eshift + lsn.nentries; ++e) {
2546 if (e >= lsn.has_arrival.size() || !lsn.has_arrival[e] || e >= lsn.arrival.size() ||
2547 lsn.arrival[e].disabled)
2548 continue;
2549 arrival[e] = Sampler(lsn.arrival[e], "the open arrivals at '" + lsn.names[e] + "'");
2550 any_arrival = true;
2551 for (std::size_t m = 0; m < repl[lsn.parent[e]]; ++m) {
2552 LnEvent ev;
2553 ev.t = now + arrival[e].next(g_arr[e]);
2554 ev.kind = 7;
2555 ev.who = e;
2556 ev.aux = m;
2557 push_ev(ev);
2558 }
2559 }
2560 drain();
2561 // Open arrivals drive a model on their own, as Solver_ssj_ln.startOpenArrivals does: only a
2562 // model with neither a reference task nor an open stream has nothing to simulate.
2563 if (!any_ref && !any_arrival)
2564 throw InputError("SolverLDES (native LN engine): the model has no reference task and no "
2565 "open arrival, so nothing drives it");
2566
2567 // ---- the event loop -----------------------------------------------------
2568 std::uint32_t wall_tick = 0;
2569 while (!evq.empty() && done < max_events) {
2570 // checkEventCountStop reads the budget every 256 events
2571 if ((++wall_tick & 255u) == 0 && util::timeout_exceeded()) {
2572 time_stopped = true;
2573 break;
2574 }
2575 const LnEvent ev = evq.top();
2576 evq.pop();
2577 now = ev.t;
2578
2579 if (ev.kind == 1) {
2580 // A reference customer finished thinking: start the next cycle on the
2581 // replica it belongs to.
2582 start_cycle(ev.who);
2583 drain();
2584 continue;
2585 }
2586
2587 if (ev.kind == 2 || ev.kind == 3) {
2588 const std::size_t ts = ev.who, th = ev.aux;
2589 if (ev.gen != thr_gen[ts][th]) continue; // the timer was cancelled
2590 if (ev.kind == 3) {
2591 if (thr_state[ts][th] == ThreadState::DELAYOFF)
2592 thr_state[ts][th] = ThreadState::OFF;
2593 continue;
2594 }
2595 // A cold start finished: the thread is up and takes the head of the
2596 // queue it was woken for.
2597 thr_state[ts][th] = ThreadState::ACTIVE;
2598 if (!thr_held[ts][th] && !thr_queue[ts].empty()) {
2599 const std::size_t nxt = dequeue(thr_queue[ts], task_sched[thr_owner[ts]], inv_key);
2600 thr_held[ts][th] = true;
2601 touch(thr_owner[ts]);
2602 cur_u[thr_owner[ts]] += 1.0;
2603 invs[nxt].has_thread = true;
2604 invs[nxt].hold_t0 = now;
2605 invs[nxt].th = th;
2606 // THE SETUP IS CHARGED TO THE REQUEST THAT WAITED THROUGH IT, as
2607 // Solver_ssj_ln.TaskSetupComplete dates its service: from the later of its
2608 // arrival and the cold start, not from now. It is not contention -- nobody else
2609 // was served meanwhile -- so it belongs to the entry, not to the caller's wait.
2610 // The entry's occupancy is back-dated to the same instant.
2611 if (!invs[nxt].started) {
2612 LnInv& w = invs[nxt];
2613 w.started = true;
2614 w.entry_t0 = w.cold_wait ? w.task_t0 : std::max(w.task_t0, thr_setup_t0[ts][th]);
2615 touch(w.entry);
2616 // Back-dated, but never into the warmup the integral has discarded.
2617 tot_q[w.entry] += now - std::max(w.entry_t0, warm_t);
2618 cur_q[w.entry] += 1.0;
2619 }
2620 advance(invs[nxt].root);
2621 drain();
2622 }
2623 continue;
2624 }
2625
2626 if (ev.kind == 4) {
2627 // The next completion at a pooled replica, unless the job set moved it.
2628 const std::size_t hs = ev.who;
2629 if (ev.gen != pool_gen[hs]) continue;
2630 const std::size_t host = host_of_slot[hs];
2631 advance_pool(hs);
2632 std::vector<std::size_t> finished, keep;
2633 for (std::size_t lid : pool_jobs[hs])
2634 (lines[lid].remaining <= 1e-9 ? finished : keep).push_back(lid);
2635 pool_jobs[hs].swap(keep);
2636 rearm_pool(hs);
2637 for (std::size_t lid : finished) {
2638 touch(host);
2639 cur_q[host] -= 1.0;
2640 if (!invs[lines[lid].inv].pre) {
2641 completions[host] += 1.0;
2642 act_host_resid[lines[lid].act] += now - lines[lid].host_t0;
2643 }
2644 release_host_admission(lid);
2645 advance(lid); // on to its think time and calls
2646 drain();
2647 }
2648 continue;
2649 }
2650
2651 if (ev.kind == 5) {
2652 // A PS host replica's next completion: every line whose work is done leaves together.
2653 const std::size_t hs = ev.who;
2654 if (ev.gen != ps_gen[hs]) continue; // the job set changed since this was armed
2655 const std::size_t host = host_of_slot[hs];
2656 ps_advance(hs);
2657 std::vector<std::size_t> finished, keep;
2658 for (std::size_t lid : ps_jobs[hs])
2659 (lines[lid].remaining <= 1e-9 ? finished : keep).push_back(lid);
2660 const std::size_t n0 = ps_jobs[hs].size();
2661 ps_jobs[hs].swap(keep);
2662 touch(host);
2663 cur_u[host] -= ps_busy(hs, n0) - ps_busy(hs, ps_jobs[hs].size());
2664 ps_schedule(hs);
2665 for (std::size_t lid : finished) {
2666 cur_q[host] -= 1.0;
2667 --host_busy[hs];
2668 if (!invs[lines[lid].inv].pre) {
2669 completions[host] += 1.0;
2670 act_host_resid[lines[lid].act] += now - lines[lid].host_t0;
2671 }
2672 release_host_admission(lid);
2673 advance(lid); // on to its think time and calls
2674 drain();
2675 }
2676 continue;
2677 }
2678
2679 if (ev.kind == 6) {
2680 // A line finished its activity's think time and goes on to its calls.
2681 advance(ev.who);
2682 drain();
2683 continue;
2684 }
2685
2686 if (ev.kind == 7) {
2687 // An open arrival: a request nobody waits on, then the next arrival of the stream.
2688 spawn_request(ev.who, ev.aux, false, 0);
2689 LnEvent nx = ev;
2690 nx.t = now + arrival[ev.who].next(g_arr[ev.who]);
2691 push_ev(nx);
2692 drain();
2693 continue;
2694 }
2695
2696 // A host completion at a c-server (or INF) processor, unless a preemption made it stale.
2697 const std::size_t lid = ev.who;
2698 if (ev.gen != lines[lid].host_gen) continue;
2699 const std::size_t act = lines[lid].act;
2700 const std::size_t host = lsn.host_of(act);
2701 // The demand ran on the processor replica paired with the task replica
2702 // that holds the request, and that pairing is fixed for the invocation.
2703 const std::size_t hs = host_slot(host, invs[lines[lid].inv].trep);
2704 touch(host);
2705 cur_q[host] -= 1.0;
2706 cur_u[host] -= 1.0;
2707 --host_busy[hs];
2708 if (!invs[lines[lid].inv].pre) {
2709 completions[host] += 1.0;
2710 act_host_resid[act] += now - lines[lid].host_t0;
2711 }
2712 if (preemptive(host_sched[host]))
2713 in_service[hs].erase(std::find(in_service[hs].begin(), in_service[hs].end(), lid));
2714 if (!host_queue[hs].empty()) {
2715 const std::size_t nxt = dequeue(host_queue[hs], host_sched[host], line_key);
2716 ++host_busy[hs];
2717 cur_u[host] += 1.0;
2718 begin_host(nxt, hs);
2719 }
2720 release_host_admission(lid);
2721 // The demand is the FIRST thing an activity does: it goes on to its think
2722 // time and its calls, and advance() completes it once they are done.
2723 advance(lid);
2724 drain();
2725 }
2726
2727 // A run that stops early with a request still blocked by an admission
2728 // constraint did not finish its budget: the constraint deadlocked it, and
2729 // the measures so far describe a model that has stopped moving.
2730 if (!time_stopped && done < max_events && evq.empty()) {
2731 for (std::size_t s = 0; s < nhost_slots; ++s)
2732 if (!hadm[s].empty())
2733 throw InputError("SolverLDES (native LN engine): the admission constraint on "
2734 "host '" + lsn.names[host_of_slot[s]] + "' deadlocked the model: " +
2735 std::to_string(hadm[s].size()) +
2736 " request(s) are blocked with no event left");
2737 for (std::size_t s = 0; s < ntask_slots; ++s)
2738 if (!tadm[s].empty())
2739 throw InputError("SolverLDES (native LN engine): the admission constraint on "
2740 "task '" + lsn.names[thr_owner[s]] + "' deadlocked the model: " +
2741 std::to_string(tadm[s].size()) +
2742 " request(s) are blocked with no event left");
2743 }
2744
2745 // A run its wall-clock budget stopped before any activity completed past the warmup reset
2746 // has nothing to report: all-zero measures read as a converged answer. Solver_ssj_ln's
2747 // assertMeasuredSpan raises the same error, the one a budget that leaves no valid partial
2748 // result raises (_kb/17).
2749 if (time_stopped && (!warm || done <= warm_done_at || !(now - warm_t > 0.0)))
2750 throw NumericError(ErrorKind{"Timeout"},
2751 "SolverLDES (layered engine): the wall-clock budget ran out after " + std::to_string(done) +
2752 " activity completions, before any were measured past the warmup; no valid partial "
2753 "result exists. Raise the budget (--maxtime / options.timeout).");
2754
2755 // ---- result -------------------------------------------------------------
2756 for (std::size_t k = 1; k <= nidx; ++k) touch(k);
2757 // Every rate is over the MEASURED span, Solver_ssj_ln's `ssjSim.time() - warmupEndTime`.
2758 const double span = now - warm_t;
2759 LnResult res;
2760 res.nidx = nidx;
2761 res.QLN = Matrix<double>(nidx + 1, 1, 0.0);
2762 res.ULN = Matrix<double>(nidx + 1, 1, 0.0);
2763 res.RLN = Matrix<double>(nidx + 1, 1, 0.0);
2764 res.TLN = Matrix<double>(nidx + 1, 1, 0.0);
2765 res.UThreadLN = Matrix<double>(nidx + 1, 1, 0.0);
2766 res.ALN = Matrix<double>(nidx + 1, 1, 0.0);
2767 res.ZLN = Matrix<double>(nidx + 1, 1, 0.0);
2768 // Residence starts at NaN everywhere and is written only where it exists:
2769 // activities and their tasks. See LnResult::WLN.
2770 res.WLN = Matrix<double>(nidx + 1, 1, std::numeric_limits<double>::quiet_NaN());
2771 for (std::size_t k = 1; k <= nidx; ++k) {
2772 if (span > 0.0) {
2773 res.QLN(k, 0) = tot_q[k] / span;
2774 // A host's utilization is its busy servers over its capacity; an
2775 // infinite server has no capacity to be busy against, so the
2776 // integral itself is the answer.
2777 // A REPLICATED PROCESSOR REPORTS THE TOTAL OVER ITS COPIES, per server of
2778 // one copy: the integral runs over the busy servers of all r copies and is
2779 // divided by the multiplicity c alone, so U = X*D/c with X the total
2780 // throughput, the per-server figure SolverLN gets by scaling its one
2781 // representative replica by r, and the one Solver_ssj_ln's table reports.
2782 // Dividing by r*c as well (until 2026-10-03) gave the per-copy fraction,
2783 // which broke U = X*D against the totalled throughput.
2784 // A task's busy-thread fraction (UThreadLN) is a fraction of its whole
2785 // pool, threads times replicas, and is not the Util column.
2786 const bool is_task = (k > lsn.tshift && k <= lsn.tshift + lsn.ntasks);
2787 const std::size_t cap_k = is_task ? task_threads[k] : host_servers[k];
2788 double c = (cap_k == std::numeric_limits<std::size_t>::max())
2789 ? 1.0
2790 : static_cast<double>(is_task ? cap_k * repl[k] : cap_k);
2791 // A host divides by the servers its work can reach, lsn.maxmult, as SolverLN does (P150).
2792 if (!is_task && k < lsn.maxmult.size() && lsn.maxmult[k] > 0.0 && lsn.maxmult[k] < c)
2793 c = lsn.maxmult[k];
2794 res.ULN(k, 0) = tot_u[k] / (span * c);
2795 if (is_task) res.UThreadLN(k, 0) = res.ULN(k, 0);
2796 // TASK QLEN IS THE THREAD-HOLDING OCCUPANCY (BUG-109): the busy-thread
2797 // integral tot_u, totalled over the replicas, not tot_q, which also counts
2798 // the requests waiting for a thread. That wait is charged to the caller,
2799 // as SolverLN, lqns, lqsim and this engine's own entry QLen do, so a
2800 // task's QLen is the sum of its entries'. Twin of Solver_ssj_ln.
2801 if (is_task) res.QLN(k, 0) = tot_u[k] / span;
2802 res.TLN(k, 0) = completions[k] / span;
2803 // Z = (N - B) / X on a bounded pool, B = tot_u/span in threads, as Solver_ssj_ln.
2804 if (is_task && cap_k != std::numeric_limits<std::size_t>::max() && res.TLN(k, 0) > 0.0) {
2805 const double pool = static_cast<double>(cap_k * repl[k]);
2806 res.ZLN(k, 0) = std::max(0.0, (pool - tot_u[k] / span) / res.TLN(k, 0));
2807 }
2808 if (k > lsn.eshift && k <= lsn.eshift + lsn.nentries) res.ALN(k, 0) = res.TLN(k, 0);
2809 }
2810 if (resp_cnt[k] > 0.0) res.RLN(k, 0) = resp_sum[k] / resp_cnt[k];
2811 }
2812 res.entry_resp_samples.swap(entry_resp_samples);
2813
2814 // Per-class thread occupancy and call rates. The requests still holding a thread are charged
2815 // what they have held so far (flushThreadHold), so over the classes of a task the occupancies
2816 // still add up to its busy-thread integral. Sized max(1, n) as Solver_ssj_ln sizes them.
2817 for (std::size_t vi = 0; vi < invs.size(); ++vi)
2818 if (invs[vi].has_thread) charge_hold(vi, false);
2819 res.UCallLN.assign(std::max<std::size_t>(1, lsn.ncalls), 0.0);
2820 res.TCallLN.assign(std::max<std::size_t>(1, lsn.ncalls), 0.0);
2821 res.UEntryClassLN.assign(std::max<std::size_t>(1, lsn.nentries), 0.0);
2822 if (span > 0.0) {
2823 for (std::size_t c = 1; c <= lsn.ncalls; ++c) {
2824 res.UCallLN[c - 1] = call_busy[c] / span;
2825 res.TCallLN[c - 1] = call_disp[c] / span;
2826 }
2827 for (std::size_t e = 0; e < lsn.nentries; ++e) res.UEntryClassLN[e] = ecls_busy[e] / span;
2828 }
2829
2830 // ResidT, per activity and summed onto its task. SolverLN builds
2831 // residt(aidx) as QN(host)/TN_ref, and TN_ref -- the reference of the
2832 // activity's layer -- is the completion rate of the activity's TASK: the
2833 // cycle rate of a reference task, the request rate into a called one,
2834 // TLN(task) either way. QN(host) is the mean occupancy at the host, which
2835 // is the total host time over the run divided by it, so
2836 //
2837 // ResidT = QN(host) / X_task = (total host time) / (elapsed * X_task)
2838 //
2839 // i.e. host time accumulated per driving visit. An activity executing once
2840 // per request reports its host residence, one inside a loop the loop's
2841 // total, and neither reading needs a visit count of its own. Accumulated
2842 // aside so a task with no activity at all keeps its NaN instead of 0.
2843 if (span > 0.0) {
2844 std::vector<double> task_resid(nidx + 1, 0.0);
2845 std::vector<bool> task_has_act(nidx + 1, false);
2846 for (std::size_t a = lsn.ashift + 1; a <= lsn.ashift + lsn.nacts && a <= nidx; ++a) {
2847 const std::size_t task = lsn.parent[a];
2848 const double x_task = (task >= 1 && task <= nidx) ? res.TLN(task, 0) : 0.0;
2849 const double resid = (x_task > 0.0) ? act_host_resid[a] / (span * x_task) : 0.0;
2850 res.WLN(a, 0) = resid;
2851 if (task >= 1 && task <= nidx) {
2852 task_resid[task] += resid;
2853 task_has_act[task] = true;
2854 }
2855 }
2856 for (std::size_t t = lsn.tshift + 1; t <= lsn.tshift + lsn.ntasks && t <= nidx; ++t)
2857 if (task_has_act[t]) res.WLN(t, 0) = task_resid[t];
2858 }
2859
2860 // TASK, ENTRY AND ACTIVITY UTILIZATION ARE DERIVED, the way `Solver_ssj_ln`
2861 // derives them and `SolverLDES.getLNAvgTable` reports them: the utilization an
2862 // activity causes at its host is its throughput times its host demand, a
2863 // task's is the sum over its activities, an entry's the sum over the
2864 // activities bound under it, and an activity's own figure is that product
2865 // itself. Each is then divided by the reachable multiplicity of the host
2866 // processor (lsn.maxmult; 1 for an infinite one), the per-server convention of the table.
2867 //
2868 // A TASK IS NOT ITS BUSY THREADS here. Until 2026-10-03 this port reported
2869 // the integral of the threads held, which counts a thread blocked in a
2870 // nested call or in a phase-2 tail as busy; the JAR, which MATLAB calls for
2871 // layered LDES, reports X*D and the two disagreed by exactly the nested
2872 // waits. That integral is kept in `UThreadLN`. The PROCESSOR column is not
2873 // touched: it is the integral of busy servers in both engines.
2874 if (span > 0.0) {
2875 // The reachable multiplicity of the processor hosting element `k` (P150).
2876 auto host_mult = [&](std::size_t k) -> double { return lsn.host_reach_mult(k); };
2877 std::vector<double> proc_util(nidx + 1, 0.0), task_proc_util(nidx + 1, 0.0);
2878 for (std::size_t a = lsn.ashift + 1; a <= lsn.ashift + lsn.nacts && a <= nidx; ++a) {
2879 const double d = (a < lsn.hostdem.size() && !lsn.hostdem[a].disabled)
2880 ? num_traits<T>::to_double(lsn.hostdem[a].mean)
2881 : 0.0;
2882 proc_util[a] = res.TLN(a, 0) * d;
2883 const std::size_t task = lsn.parent[a];
2884 if (task >= 1 && task <= nidx) task_proc_util[task] += proc_util[a];
2885 }
2886 for (std::size_t t = lsn.tshift + 1; t <= lsn.tshift + lsn.ntasks && t <= nidx; ++t)
2887 res.ULN(t, 0) = task_proc_util[t] / host_mult(t);
2888 for (std::size_t e = lsn.eshift + 1; e <= lsn.eshift + lsn.nentries && e <= nidx; ++e) {
2889 double u = 0.0;
2890 const std::vector<std::size_t>& acts =
2891 (e < lsn.actsof.size()) ? lsn.actsof[e] : std::vector<std::size_t>();
2892 for (std::size_t i = 0; i < acts.size(); ++i)
2893 if (acts[i] <= nidx) u += proc_util[acts[i]];
2894 res.ULN(e, 0) = u / host_mult(e);
2895 }
2896 // An activity reports its OWN share of its host, X(a)*D(a), as SolverLN (UN of its
2897 // class at the host) and LQNS (proc-utilization) do. The ratio to its task's load
2898 // that used to be written here read 1 for every activity alone on its task.
2899 for (std::size_t a = lsn.ashift + 1; a <= lsn.ashift + lsn.nacts && a <= nidx; ++a)
2900 res.ULN(a, 0) = proc_util[a] / host_mult(a);
2901 }
2902
2903 // Cache measures per ItemEntry, pooled over the replicas of its cache task.
2904 for (std::size_t ai = 0; ai < accesses.size(); ++ai) {
2905 long long reads = 0, hits = 0, misses = 0, delayed = 0;
2906 for (std::size_t ci : accesses[ai].caches) {
2907 reads += caches[ci].reads;
2908 hits += caches[ci].hits;
2909 misses += caches[ci].misses;
2910 delayed += caches[ci].delayed;
2911 }
2912 if (reads <= 0 || !(span > 0.0)) continue;
2913 const double n = static_cast<double>(reads);
2914 res.cache_task.push_back(lsn.parent[accesses[ai].entry]);
2915 res.cache_entry.push_back(accesses[ai].entry);
2916 res.cache_hit.push_back(static_cast<double>(hits) / n);
2917 res.cache_miss.push_back(static_cast<double>(misses) / n);
2918 res.cache_delayed.push_back(static_cast<double>(delayed) / n);
2919 res.cache_read_rate.push_back(n / span);
2920 }
2921
2922 res.simulated_time = span;
2923 res.warmup_time = warm_t;
2924 res.completions = cycles;
2925 res.events = static_cast<long long>(done);
2926 res.timed_out = time_stopped;
2927 return res;
2928}
2929
2930} // namespace ldes
2931} // namespace line
2932
2933#endif // LINE_SOLVERS_LDES_LDES_LN_ENGINE_H
InputError(const std::string &what)
Definition error.h:105
std::size_t cols() const
Definition matrix.h:90
std::size_t rows() const
Definition matrix.h:89
NumericError(const std::string &what)
Definition error.h:112
UnsupportedError(const std::string &what)
Definition error.h:119
java.util.Random, the 48-bit LCG of the Java Language Specification.
Definition rng_ssj.h:219
void set_seed(const long long s[6])
SSJ's setSeed(long[6]).
Definition rng_ssj.h:125
splitmix64 keyed by (run seed, stream offset): where every LDES stream's seeds come from.
Definition rng_ssj.h:79
std::uint64_t next()
The next splitmix64 output.
Definition rng_ssj.h:85
void mrg_seeds(long long s[6])
Six MRG32k3a seeds: the first three in [1, m1), the last three in [1, m2), so neither component can s...
Definition rng_ssj.h:97
The RAII frame timeout_arm returns.
The exception types the port throws.
The option and result records of SolverLDES, the discrete-event simulator.
The variate generators of the native LDES engine.
options.timeout: one wall-clock budget per top-level solve, on a per-THREAD deadline stack.
LayeredNetworkStruct, the flattened description of a layered queueing network.
Dense matrix and non-owning view.
SchedStrategy
Scheduling disciplines, with the values of MATLAB SchedStrategy.
Definition lang_types.h:194
PrecedenceType
Activity precedence kinds, with the values of MATLAB ActivityPrecedenceType.
Definition lang_types.h:511
const char * sched_to_text(SchedStrategy s)
Definition lang_types.h:248
ReplacementStrategy
Cache replacement policies, with the values of MATLAB ReplacementStrategy.
Definition lang_types.h:419
@ HLRU
h-LRU / LRU(m): h lists, promote i -> i+1 on a hit
Definition lang_types.h:424
@ QLRU
q-LRU: LRU with probabilistic admission on a miss
Definition lang_types.h:426
@ LRU
least recently used
Definition lang_types.h:423
LnColumn
A column of the shared layered average table, as line-cli prints it.
static const std::size_t LN_NONE
Index meaning "none" for a line, an invocation or a customer.
static const std::size_t NOTHR
Thread index meaning "no thread held", also used for an infinite-thread task.
static const std::size_t NOTDRAWN
LnJob::calls_left before the repetition count of a call has been drawn.
ThreadState
Power state of one task thread, mirroring Solver_ssj_ln's THREAD_* constants.
static const std::uint64_t LN_ANYFORK
Fork instance meaning "any": the late inputs of a join fed by more than one fork instance.
bool ln_defined(const lqn::LqnStruct< T > &lsn, const LnResult &r, std::size_t i, LnColumn c)
Does the element at i HAVE the quantity in column c?
Rng ln_rng(long long seed, long long offset)
The generator of one LN stream, seeded from a HASH of (run seed, offset).
std::vector< LnEntryCdf > ldes_ln_cdf_respt(const LnResult &r, std::size_t nentries)
The empirical response time CDF of every ENTRY, the getCdfRespTLN of the other codebases: one [F(t),...
engine::LnResult ldes_ln_engine_solve(const lqn::LqnStruct< T > &lsn, const LdesOptions &o)
Simulate a layered model in process.
std::string ldes_ln_refusal(const lqn::LqnStruct< T > &lsn)
Port of ldes_ln_refusal: why SolverLDES.supports declines a layered model, or an empty string when it...
std::mt19937_64 McRng
The generator type every Monte Carlo entry point in this tree accepts.
bool timeout_exceeded()
The checkpoint: true when the innermost budget has run out, marking it tripped.
TimeoutScope timeout_arm(double budget)
Arm budget seconds for the scope's lifetime, capped by the outer frame's remaining time.
double timeout_remaining()
Seconds left on the innermost armed budget; +Inf when none is armed.
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
The knobs of one LDES run.
long seed
–seed; -1 requests a random stream
std::size_t events
0 = not given; overrides samples when set
std::size_t samples
-s, service-completion budget
double timeout
–maxtime, a COOPERATIVE wall-clock budget the event loop polls; the wrapper caps it by any options....
One ItemEntry read: its driver activity, its item law and its two branches.
std::vector< std::size_t > caches
cache state per replica of the cache task
Live content of one replica of a cache task, LNCacheState of the Java engine.
lang::ReplacementStrategy rs
std::vector< int > cap
per level list
std::vector< std::vector< std::pair< std::size_t, std::size_t > > > held
(line, access)
std::vector< char > inflight
[item] a fetch is in progress
std::vector< std::list< std::size_t > > levels
per level, most recent first
A reference-task customer: it thinks, then starts an invocation.
double t_start
when the current cycle began
std::size_t repl
replica of the reference task it belongs to
One entry's empirical response-time CDF: F[j] = P(R <= t[j]).
bool operator()(const LnEvent &a, const LnEvent &b) const
One scheduled event of the layered engine.
int kind
0 = host completion (who = the LINE), 1 = think completion (who = the reference customer),...
One invocation of an entry: what a call or a reference cycle starts.
std::size_t caller
the line blocked on this call, if synchronous
std::size_t th
thread held, NOTHR on an INF task
std::size_t root
root line
std::size_t cust
the reference customer, at the top level only
std::size_t ts
task slot of that replica
int tcol
task admission column held, -1 = none
long pending
live lines after a fork, -1 = never forked
double entry_t0
when the entry took its thread, the start of its service
std::map< std::size_t, LnJoin > joins
join activity -> its progress in this invocation
bool pre
The invocation belongs to a root (reference cycle or open arrival) that began before the warmup reset...
std::size_t call_idx
The CALL that created this invocation, 1-based into callpair_dst, 0 for an entry stream of its own (a...
bool started
the entry's service has begun (a thread is held)
bool early_reply
replied before completing (phase 2 follows)
bool fetching
this read is fetching an item (retrieval)
std::size_t trep
replica of the task serving it
bool cold_wait
queued while a thread was free but down: the whole wait is a cold start
double hold_t0
When it took its thread, LNRequest.threadHoldStart; negative while it holds none.
double siro_key
uniform key in a SIRO thread queue
double task_t0
when the request entered its task (admitted)
Progress of one AND join within one invocation, JoinProgress of the Java engine.
std::map< std::pair< std::size_t, std::uint64_t >, long > discard
std::map< std::size_t, std::uint64_t > got
One LINE of execution: a point in the activity graph of one invocation.
double act_t0
When the current activity began, -1 before it is reached.
int dem_done
How far the current activity is before its calls: 0 nothing started, 1 host demand started or none,...
int hcol
host admission column held, -1 = none
std::size_t act
current activity, 0 for an entry with none
std::uint64_t fork_id
The AND fork instance that created this line, from one engine-wide counter; 0 for the root.
double host_t0
when the line asked its processor, queueing included
std::size_t call_pos
next call index of the current activity
int pcol
operand column at a pooled host
std::size_t calls_left
Repetitions of the current call still to be made; NOTDRAWN until drawn.
std::size_t inv
the invocation this line belongs to
double remaining
work left at a pooled or PS host
std::uint64_t host_gen
Host service in progress at a queueing host.
double siro_key
uniform key in a SIRO host queue; the smallest is served next
bool branch
a line an AND fork created (never the root)
The layered result: per element, the mean measures.
std::vector< double > cache_read_rate
Matrix< double > ZLN
Think time per element, Solver_ssj_ln's ZLN: Little's law on a task's thread pool read backwards,...
bool timed_out
The run stopped on its wall-clock budget (LdesOptions::timeout) before max_events.
std::vector< double > cache_miss
Matrix< double > ALN
Arrival rate per element, Solver_ssj_ln's ALN: an entry's request rate (its throughput,...
std::vector< double > UEntryClassLN
Matrix< double > UThreadLN
Busy THREADS of each task over its thread capacity (threads times replicas), the integral of the thre...
Matrix< double > WLN
Residence time per element, the ResidT column: the time an activity holds ITS HOST PROCESSOR per visi...
std::vector< std::size_t > cache_entry
std::vector< double > cache_hit
std::vector< std::vector< double > > entry_resp_samples
Every per-request ENTRY response time observed, one vector per entry in LOCAL index space (0....
std::vector< std::size_t > cache_task
Cache measures, one row per ItemEntry that was read, pooled over the replicas of its cache task as So...
double simulated_time
Length of the MEASURED span, from the end of warmup to the end of the run.
double warmup_time
Simulation time at which warmup ended and the statistics were reset.
long long events
Activity completions over the whole run, warmup included: what the budget counts.
std::vector< double > TCallLN
Dispatches of each call per unit time, counted where the CALLER issues it (TCallLN[c-1]),...
std::vector< double > cache_delayed
std::vector< double > UCallLN
Per-CLASS occupancy of the task thread pools, Solver_ssj_ln's UCallLN and UEntryClassLN: the mean num...
long long completions
Reference-task cycles completed in the measured span.
The engine's randomness, in the SHAPE the Java engine uses it.
rng::JavaRandom aux
java.util.Random: the Markovian samplers
rng::Mrg32k3a stream
SSJ MRG32k3a: every renewal family.
pfqn::McRng mc
the residual RAP/ME path, not yet aligned
One routed call group: an activity, the strategy that picks among its targets, and the target ENTRIES...
Definition lqn_struct.h:200
std::vector< std::size_t > targets
absolute entry indices, in declaration order
Definition lqn_struct.h:203
lang::RoutingStrategy strategy
Definition lqn_struct.h:202
std::size_t caller
absolute index of the dispatching activity
Definition lqn_struct.h:201
Heterogeneous server pools declared on a layer server, the twin of the nservertypes / servertypenames...
Definition lqn_struct.h:78