Repository navigation
Expand file tree
/
Copy pathreport_scratch.cpp
More file actions
399 lines (354 loc) · 16 KB
/
Copy pathreport_scratch.cpp
File metadata and controls
399 lines (354 loc) · 16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
#include "report_scratch.hpp"
#include "read_through_window.hpp"
#include <pineforge/run_failure.hpp>
#include <algorithm>
#include <array>
#include <cerrno>
#include <cstring>
#include <limits>
#include <stdexcept>
#include <system_error>
#include <type_traits>
#include <unistd.h>
namespace pineforge {
namespace report_sink {
namespace {
static_assert(std::is_trivially_copyable<pf_equity_point_t>::value,
"scratch points must preserve their complete binary representation");
static_assert(std::numeric_limits<off_t>::is_signed
&& sizeof(off_t) <= sizeof(std::int64_t),
"scratch offsets must fit the P00 signed 64-bit region");
static_assert(kScratchWindowPoints > 0, "scratch window must hold a complete point");
[[noreturn]] void fail_io(int error_number, const char* operation) {
throw detail::ReportScratchIoError(error_number, operation, {{"reason", "scratch_io"}});
}
constexpr std::int64_t maximum_offset() {
return static_cast<std::int64_t>(std::numeric_limits<off_t>::max());
}
void check_span(std::int64_t offset, std::size_t length) {
if (offset < 0 || offset > maximum_offset()
|| static_cast<std::uintmax_t>(length)
> static_cast<std::uintmax_t>(maximum_offset() - offset)) {
throw coded<std::invalid_argument>(RunFailureCode::engine_invariant, {},
"report scratch byte range is invalid");
}
}
void check_region(const metrics::ScratchCurveRegion& region) {
if ((region.point_count != 0 && !region.scratch && region.descriptor < 0)
|| region.byte_offset < 0
|| region.byte_offset > maximum_offset() || region.point_count < 0
|| region.point_count
> (maximum_offset() - region.byte_offset)
/ static_cast<std::int64_t>(sizeof(pf_equity_point_t))) {
throw coded<std::invalid_argument>(RunFailureCode::engine_invariant, {},
"report scratch curve region is invalid");
}
}
void check_buffer(const void* bytes, std::size_t length) {
if (length != 0 && bytes == nullptr) {
throw coded<std::invalid_argument>(RunFailureCode::engine_invariant, {},
"report scratch buffer is null");
}
}
void read_exact(int descriptor, std::int64_t offset, void* bytes, std::size_t length,
ScratchReadStats* inner_reads) {
check_span(offset, length);
check_buffer(bytes, length);
auto* destination = static_cast<unsigned char*>(bytes);
std::size_t received = 0;
while (received < length) {
const std::size_t chunk = std::min(length - received, kScratchWindowBytes);
if (inner_reads) ++inner_reads->calls;
const ssize_t count = ::pread(descriptor, destination + received, chunk,
static_cast<off_t>(offset + static_cast<std::int64_t>(received)));
if (count < 0 && errno == EINTR) continue;
if (count <= 0) fail_io(count < 0 ? errno : EIO, "report scratch read");
if (inner_reads) inner_reads->bytes += static_cast<std::size_t>(count);
received += static_cast<std::size_t>(count);
}
}
} // namespace
ScratchFile::ScratchFile(const std::string& directory, detail::ScratchStore store) {
if (directory.find('\0') != std::string::npos) {
throw coded<std::invalid_argument>(RunFailureCode::engine_invariant, {},
"report scratch directory is invalid");
}
file_.set_store(store);
file_.set_directory(directory);
try {
file_.open("pineforge-scratch");
} catch (const detail::ReportScratchIoError& error) {
// Keep the create prefix, candidate detail and errno. Arena reasons
// and their per-raiser arguments propagate unchanged.
const auto& failure = error.run_failure();
if (failure.args && *failure.args == "{\"reason\":\"scratch_io\"}")
fail_io(error.code().value(), detail::scratch_with_detail("report scratch create", error.what(), error.code().value()).c_str());
throw;
}
}
ScratchFile::~ScratchFile() = default;
int ScratchFile::descriptor() const noexcept {
return file_.descriptor();
}
void ScratchFile::write(std::int64_t byte_offset, const void* bytes, std::size_t length) {
check_span(byte_offset, length);
check_buffer(bytes, length);
if (length == 0) return;
// Reserve the complete requested extent before publishing any of this
// buffer. Both backends use this same end calculation. A refused arena
// claim propagates unchanged.
ensure_size(byte_offset + static_cast<std::int64_t>(length));
const auto* source = static_cast<const unsigned char*>(bytes);
std::size_t written = 0;
while (written < length) {
const std::size_t chunk = std::min(length - written, kScratchWindowBytes);
file_.write(static_cast<std::uint64_t>(byte_offset) + written, source + written, chunk);
written += chunk;
}
}
void ScratchFile::read(std::int64_t byte_offset, void* bytes, std::size_t length) const {
check_span(byte_offset, length);
check_buffer(bytes, length);
if (length == 0) return;
++read_count_;
file_.read(static_cast<std::uint64_t>(byte_offset), bytes, length);
read_bytes_ += length;
}
void ScratchFile::truncate(std::int64_t byte_count) {
check_span(byte_count, 0);
file_.truncate(static_cast<std::uint64_t>(byte_count));
}
void ScratchFile::ensure_size(std::int64_t byte_count) {
check_span(byte_count, 0);
file_.open("pineforge-scratch");
file_.ensure_size(static_cast<std::uint64_t>(byte_count));
}
void ScratchFile::clear() {
truncate(0);
}
void ScratchFile::release() noexcept {
file_.clear();
}
metrics::ScratchCurveRegion ScratchFile::curve_region(
std::int64_t byte_offset, std::int64_t point_count) const {
const metrics::ScratchCurveRegion region{-1, byte_offset, point_count, &file_};
check_region(region);
return region;
}
struct ScratchCurveWriter::State {
ScratchFile file;
std::array<pf_equity_point_t, kScratchWindowPoints> pending{};
std::size_t pending_count = 0;
std::int64_t disk_points = 0;
explicit State(const std::string& directory)
: file(directory, detail::ScratchStore::curve) {}
};
ScratchCurveWriter::ScratchCurveWriter(const std::string& directory)
: state_(std::make_unique<State>(directory)) {}
ScratchCurveWriter::~ScratchCurveWriter() = default;
void ScratchCurveWriter::append(const pf_equity_point_t& point) {
auto& state = *state_;
if (size() == maximum_offset() / static_cast<std::int64_t>(sizeof(point))) {
throw coded<std::overflow_error>(RunFailureCode::engine_invariant, {},
"report scratch curve offset exhausted");
}
if (state.pending_count == state.pending.size()) flush();
std::memcpy(&state.pending[state.pending_count], &point, sizeof(point));
++state.pending_count;
}
void ScratchCurveWriter::replace_last(const pf_equity_point_t& point) {
auto& state = *state_;
if (size() == 0) {
throw coded<std::out_of_range>(RunFailureCode::engine_invariant, {},
"report scratch curve has no last point");
}
if (state.pending_count == 0) {
// Bring the last disk row back into the authoritative RAM batch.
// A partial flush of its replacement is then retryable exactly like
// an append batch, without losing the replacement's complete bytes.
--state.disk_points;
state.pending_count = 1;
}
std::memcpy(&state.pending[state.pending_count - 1], &point, sizeof(point));
}
void ScratchCurveWriter::clear() {
auto& state = *state_;
state.file.clear();
state.disk_points = 0;
state.pending_count = 0;
}
void ScratchCurveWriter::release() noexcept {
auto& state = *state_;
state.file.release();
state.disk_points = 0;
state.pending_count = 0;
}
void ScratchCurveWriter::replace_tail(const pf_equity_point_t* points, std::size_t count) {
auto& state = *state_;
if (count > state.pending.size() || static_cast<std::int64_t>(count) > size()) {
throw coded<std::out_of_range>(RunFailureCode::engine_invariant, {},
"report scratch replacement tail is invalid");
}
check_buffer(points, count * sizeof(*points));
if (count == 0) return;
if (count > state.pending_count) {
// Complete the old batch before changing its authoritative range.
// On failure flush() leaves every old pending point available to retry.
flush();
state.disk_points -= static_cast<std::int64_t>(count);
state.pending_count = count;
}
std::memcpy(state.pending.data() + state.pending_count - count,
points, count * sizeof(*points));
}
void ScratchCurveWriter::flush() const {
auto& state = *state_;
if (state.pending_count == 0) return;
state.file.write(state.disk_points * static_cast<std::int64_t>(sizeof(pf_equity_point_t)),
state.pending.data(), state.pending_count * sizeof(pf_equity_point_t));
state.disk_points += static_cast<std::int64_t>(state.pending_count);
state.pending_count = 0;
}
std::int64_t ScratchCurveWriter::size() const noexcept {
return state_->disk_points + static_cast<std::int64_t>(state_->pending_count);
}
metrics::ScratchCurveRegion ScratchCurveWriter::region() const {
flush();
return state_->file.curve_region(0, state_->disk_points);
}
void read_scratch_points(const metrics::ScratchCurveRegion& region,
std::int64_t first, pf_equity_point_t* points,
std::int64_t count, ScratchReadStats* inner_reads) {
check_region(region);
if (first < 0 || count < 0 || first > region.point_count
|| count > region.point_count - first
|| static_cast<std::uintmax_t>(count)
> std::numeric_limits<std::size_t>::max() / sizeof(pf_equity_point_t)) {
throw coded<std::out_of_range>(RunFailureCode::engine_invariant, {},
"report scratch point range is invalid");
}
const std::int64_t offset =
region.byte_offset + first * static_cast<std::int64_t>(sizeof(pf_equity_point_t));
const auto length = static_cast<std::size_t>(count) * sizeof(pf_equity_point_t);
check_buffer(points, length);
if (length == 0) return;
if (region.scratch) {
if (inner_reads) ++inner_reads->calls;
region.scratch->read(static_cast<std::uint64_t>(offset), points, length);
if (inner_reads) inner_reads->bytes += length;
} else {
read_exact(region.descriptor, offset, points, length, inner_reads);
}
}
struct ScratchCurveWindow::State {
metrics::ScratchCurveRegion region;
ScratchReadStats* inner_reads;
detail::ReadThroughWindow cache;
std::array<pf_equity_point_t, kScratchWindowPoints> window{};
std::int64_t first = 0;
std::int64_t count = 0;
std::int64_t previous_index = -1;
State(const metrics::ScratchCurveRegion& value, std::size_t cache_bytes,
ScratchReadStats* reads)
: State(value, CacheCapacity::from_payload(sizeof(pf_equity_point_t), cache_bytes),
reads) {}
State(const metrics::ScratchCurveRegion& value, CacheCapacity capacity,
ScratchReadStats* reads)
: region(value), inner_reads(reads),
cache(sizeof(pf_equity_point_t), capacity, this, read_backing) {
check_region(region);
}
static void read_backing(void* context, std::uint64_t offset,
void* destination, std::size_t bytes) {
auto& self = *static_cast<State*>(context);
const auto index = static_cast<std::int64_t>(offset / sizeof(pf_equity_point_t));
// The shared cache has already attempted allocation. Its bypass
// must read directly without consulting the fixed block workspace.
if (self.cache.payload_bytes() != 0) {
if ((index < self.first || index - self.first >= self.count)
&& self.previous_index >= 0
&& (index == self.previous_index + 1 || index + 1 == self.previous_index)) {
constexpr auto capacity = static_cast<std::int64_t>(kScratchWindowPoints);
const auto first = index / capacity * capacity;
const auto count = std::min(self.region.point_count - first, capacity);
// A short read can overwrite the old block. Publish its
// replacement only after all requested bytes are available.
self.count = 0;
read_scratch_points(self.region, first, self.window.data(), count, self.inner_reads);
self.first = first;
self.count = count;
}
if (index >= self.first && index - self.first < self.count) {
std::memcpy(destination, &self.window[static_cast<std::size_t>(index - self.first)],
bytes);
return;
}
}
read_scratch_points(self.region, index,
static_cast<pf_equity_point_t*>(destination),
static_cast<std::int64_t>(bytes / sizeof(pf_equity_point_t)), self.inner_reads);
// Retain a lone point until a sequential block replaces it, even
// if a distant probe collides with its shared-cache line.
if (self.cache.payload_bytes() != 0 && self.count == 0) {
std::memcpy(self.window.data(), destination, bytes);
self.first = index;
self.count = 1;
}
}
};
ScratchCurveWindow::ScratchCurveWindow(const metrics::ScratchCurveRegion& region,
std::size_t cache_bytes, ScratchReadStats* inner_reads)
: state_(std::make_unique<State>(region, cache_bytes, inner_reads)) {}
ScratchCurveWindow::ScratchCurveWindow(const metrics::ScratchCurveRegion& region,
CacheCapacity capacity, ScratchReadStats* inner_reads)
: state_(std::make_unique<State>(region, capacity, inner_reads)) {}
ScratchCurveWindow::~ScratchCurveWindow() = default;
std::int64_t ScratchCurveWindow::size() const noexcept {
return state_->region.point_count;
}
std::size_t ScratchCurveWindow::cache_capacity_bytes() const noexcept {
return state_->cache.payload_bytes();
}
detail::ReadThroughCacheStats ScratchCurveWindow::cache_stats() const noexcept {
return state_->cache.stats();
}
std::size_t ScratchCurveWindow::cache_control_bytes() const noexcept {
return sizeof(ScratchCurveWindow) + sizeof(State);
}
pf_equity_point_t ScratchCurveWindow::operator[](std::int64_t index) const {
auto& state = *state_;
if (index < 0 || index >= size()) {
throw coded<std::out_of_range>(RunFailureCode::engine_invariant, {},
"report scratch point index is invalid");
}
pf_equity_point_t point;
state.cache.get(static_cast<std::uint64_t>(index), &point, sizeof(point));
state.previous_index = index;
return point;
}
void check_scratch_equity_extremes(const metrics::ScratchCurveRegion& prefix,
const pf_equity_point_t* held,
double initial_capital,
const double (&expected)[4]) {
ScratchCurveWindow curve(prefix);
double actual[] = {initial_capital, initial_capital, 0.0, 0.0};
const auto fold = [&](double equity) {
if (equity > actual[0]) {
actual[0] = equity;
actual[1] = equity;
}
if (equity < actual[1]) actual[1] = equity;
const double drawdown = actual[0] - equity;
if (drawdown > actual[2]) actual[2] = drawdown;
const double runup = equity - actual[1];
if (runup > actual[3]) actual[3] = runup;
};
for (std::int64_t i = 0; i < curve.size(); ++i) fold(curve[i].equity);
if (held) fold(held->equity);
if (std::memcmp(actual, expected, sizeof(actual)) != 0) {
throw coded<std::logic_error>(RunFailureCode::engine_invariant, {},
"report sink tail fold differs from full scratch equity walk");
}
}
} // namespace report_sink
} // namespace pineforge