FastMM documentation
FastMM C++ API 0.14.0
Public headers, tier 1 and tier 2
Loading...
Searching...
No Matches
param_schedule.hpp
Go to the documentation of this file.
1#pragma once
2// ParamSchedule: parameter updates of a backtest, delivered to the engine at simulated times
3// (ADR-0013). SimDriver hands the earliest update to the engine when its time comes, like any other
4// input, so the journal records it at that time and a replay applies it at the same point.
5//
6// sim::ParamSchedule schedule;
7// schedule.at(start + seconds(1), update); // an update built elsewhere
8// schedule.set_delay(milliseconds(5)); // sink(): 5 ms after the publish
9// ParamPublisher pub(schedule.sink(backend.clock), strategy.params());
10// session.set_param_schedule(&schedule); // bt::BacktestSession
11//
12// Pending updates do not keep a run alive: SimDriver ends when its data does.
13//
14// set_refill() adds a source that knows when its next updates are due (an [ab] test,
15// strategies/ab_test.hpp): it is asked for them one change ahead of the clock, so they are queued
16// before the driver reaches their time.
17//
18// threaded_sink() also accepts updates from other threads (a model thread of a Python strategy):
19// they wait in an inbox until SimDriver next looks at the schedule, and are delivered delay() after
20// the simulated time of that moment, which depends on thread timing.
22#include "fastmm/core/time.hpp"
24
25#include <atomic>
26#include <cstddef>
27#include <cstdint>
28#include <limits>
29#include <map>
30#include <mutex>
31#include <thread>
32#include <vector>
33
34namespace fastmm::sim {
35
36class ParamSchedule {
37 public:
38 // Delivers `m` at `ts`; updates with the same time keep the order they were added in.
39 void at(Timestamp ts, const ParamUpdateMsg& m) { queue_.emplace(ts.ns, m); }
40
41 // Added to the time of updates that arrive through sink() (the slow tier's delay).
42 void set_delay(Duration d) noexcept { delay_ = d; }
43 [[nodiscard]] Duration delay() const noexcept { return delay_; }
44 // A ParamPublisher sink: each update is delivered delay() after `clock`'s time at the publish.
45 [[nodiscard]] ParamSink sink(const SimClock& clock) noexcept {
46 clock_ = &clock;
47 return {this, [](void* c, const ParamUpdateMsg& m) noexcept {
48 auto* self = static_cast<ParamSchedule*>(c);
49 try {
50 self->at(self->clock_->now() + self->delay_, m);
51 return true;
52 } catch (...) {
53 return false;
54 }
55 }};
56 }
57
58 // Like sink(), for a schedule that other threads publish to as well: an update from the thread
59 // that called threaded_sink() (the thread that runs the SimDriver) is delivered delay() after
60 // `clock`'s time; one from another thread goes to the inbox (post()).
61 [[nodiscard]] ParamSink threaded_sink(const SimClock& clock) noexcept {
62 clock_ = &clock;
63 driver_thread_ = std::this_thread::get_id();
64 return {this, [](void* c, const ParamUpdateMsg& m) noexcept {
65 auto* self = static_cast<ParamSchedule*>(c);
66 try {
67 if (std::this_thread::get_id() == self->driver_thread_) {
68 self->at(self->clock_->now() + self->delay_, m);
69 } else {
70 self->post(m);
71 }
72 return true;
73 } catch (...) {
74 return false;
75 }
76 }};
77 }
78
79 // `refill(ctx, due)` adds the updates due at `due` (at() with that time) and returns when the
80 // next ones are due (Timestamp::max(): none). The first call asks for `first`; each later one
81 // comes once `clock` has reached the time the call before it asked for.
82 using Refill = Timestamp (*)(void* ctx, Timestamp due);
83 void set_refill(const SimClock& clock, void* ctx, Refill refill, Timestamp first) noexcept {
84 refill_clock_ = &clock;
85 refill_ctx_ = ctx;
86 refill_ = refill;
87 refill_gate_ = Timestamp{std::numeric_limits<std::int64_t>::min()};
88 refill_next_ = first;
89 }
90
91 // Any thread: holds `m` until the next collect().
92 void post(const ParamUpdateMsg& m) {
93 const std::lock_guard<std::mutex> lock(inbox_mutex_);
94 inbox_.push_back(m);
95 inbox_pending_.store(true, std::memory_order_release);
96 }
97 // Driver thread: schedules the posted updates delay() after the clock's time (the clock passed to
98 // sink() or threaded_sink()). Cheap when nothing was posted.
99 void collect() {
100 if (FASTMM_UNLIKELY(refill_ != nullptr) && refill_next_ != Timestamp::max() &&
101 refill_clock_->now() >= refill_gate_) {
102 refill_gate_ = refill_next_;
103 refill_next_ = refill_(refill_ctx_, refill_next_);
104 }
105 if (FASTMM_LIKELY(!inbox_pending_.load(std::memory_order_acquire))) return;
106 const std::lock_guard<std::mutex> lock(inbox_mutex_);
107 const Timestamp ts = clock_ != nullptr ? clock_->now() + delay_ : Timestamp{};
108 for (const ParamUpdateMsg& m : inbox_) at(ts, m);
109 inbox_.clear();
110 inbox_pending_.store(false, std::memory_order_release);
111 }
112
113 [[nodiscard]] bool empty() const noexcept { return queue_.empty(); }
114 [[nodiscard]] std::size_t size() const noexcept { return queue_.size(); }
115 // The earliest delivery time (Timestamp::max() when empty).
116 [[nodiscard]] Timestamp next_ts() const noexcept {
117 return queue_.empty() ? Timestamp::max() : Timestamp{queue_.begin()->first};
119 // Removes the earliest update; its recv_ts is the delivery time.
120 [[nodiscard]] ParamUpdateMsg pop() noexcept {
121 ParamUpdateMsg m = queue_.begin()->second;
122 m.hdr.recv_ts = Timestamp{queue_.begin()->first};
123 queue_.erase(queue_.begin());
124 return m;
125 }
126
127 private:
128 std::multimap<std::int64_t, ParamUpdateMsg> queue_;
129 Duration delay_{};
130 const SimClock* clock_ = nullptr;
131 std::thread::id driver_thread_{};
132 const SimClock* refill_clock_ = nullptr;
133 void* refill_ctx_ = nullptr;
134 Refill refill_ = nullptr;
135 Timestamp refill_gate_{};
136 Timestamp refill_next_ = Timestamp::max();
137 std::mutex inbox_mutex_;
138 std::vector<ParamUpdateMsg> inbox_;
139 std::atomic<bool> inbox_pending_{false};
140};
141
142} // namespace fastmm::sim
Deterministic clock for sim/backtest/replay. 1 cycle == 1 ns.
Definition time.hpp:338
Timestamp now() const noexcept
Definition time.hpp:342
Definition param_schedule.hpp:38
void set_delay(Duration d) noexcept
Added to the time of updates that arrive through sink() (the slow tier's delay).
Definition param_schedule.hpp:44
Duration delay() const noexcept
Definition param_schedule.hpp:45
Timestamp next_ts() const noexcept
The earliest delivery time (Timestamp::max() when empty).
Definition param_schedule.hpp:118
ParamSink threaded_sink(const SimClock &clock) noexcept
Like sink(), for a schedule that other threads publish to as well: an update from the thread that cal...
Definition param_schedule.hpp:63
void set_refill(const SimClock &clock, void *ctx, Refill refill, Timestamp first) noexcept
Definition param_schedule.hpp:85
void collect()
Driver thread: schedules the posted updates delay() after the clock's time (the clock passed to sink(...
Definition param_schedule.hpp:101
Timestamp(*)(void *ctx, Timestamp due) Refill
refill(ctx, due) adds the updates due at due (at() with that time) and returns when the next ones are...
Definition param_schedule.hpp:84
void post(const ParamUpdateMsg &m)
Any thread: holds m until the next collect().
Definition param_schedule.hpp:94
bool empty() const noexcept
Definition param_schedule.hpp:115
ParamSink sink(const SimClock &clock) noexcept
A ParamPublisher sink: each update is delivered delay() after clock's time at the publish.
Definition param_schedule.hpp:47
ParamUpdateMsg pop() noexcept
Removes the earliest update; its recv_ts is the delivery time.
Definition param_schedule.hpp:122
std::size_t size() const noexcept
Definition param_schedule.hpp:116
void at(Timestamp ts, const ParamUpdateMsg &m)
Delivers m at ts; updates with the same time keep the order they were added in.
Definition param_schedule.hpp:41
Event bus message structs (5.5).
Definition strategy_harness.hpp:40
ParamPublisher: builds ParamUpdate messages for a running engine, off the engine thread (ADR-0013).
Definition time.hpp:22
Timestamp recv_ts
T0 wall-clock (40)
Definition messages.hpp:65
Where a built update goes; push returns false when it was not accepted (full).
Definition param_publisher.hpp:49
New strategy parameter values (ADR-0013): up to kMaxFields (field index, raw value) pairs,...
Definition messages.hpp:795
EventHeader hdr
Definition messages.hpp:813
Definition time.hpp:45
std::int64_t ns
Definition time.hpp:46
static constexpr Timestamp max() noexcept
Definition time.hpp:56
Time primitives.