okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0216-core into f-0216-allbd0e878f4

main
24.4 KiB625 linesraw
1// src/ngram/ple_reader.cpp - see include/strata/ngram/ple_reader.hpp.
2#include "strata/ngram/ple_reader.hpp"
3#include "strata/platform/aux_cpus.hpp"
4
5#include <algorithm>
6#include <chrono>
7#include <condition_variable>
8#include <cstring>
9#include <deque>
10#include <exception>
11#include <mutex>
12#include <thread>
13#include <unordered_map>
14
15namespace strata::ngram {
16
17using platform::Completion;
18using platform::DirectFile;
19using platform::now_us;
20
21double ReaderStats::percentile(double q) const {
22    if (read_us.empty()) return 0.0;
23    std::vector<float> v(read_us);
24    const size_t k = std::min(v.size() - 1, (size_t) (q * (double) (v.size() - 1) + 0.5));
25    std::nth_element(v.begin(), v.begin() + (ptrdiff_t) k, v.end());
26    return v[k];
27}
28
29namespace {
30
31constexpr size_t LATENCY_RING = 65536;
32constexpr uint32_t WAYS = 8;
33constexpr uint32_t EMPTY = 0xFFFFFFFFu;
34
35/// Set-associative row cache: 8 ways per set, round-robin replacement inside a set. Bounded by construction.
36struct RowCache {
37    uint64_t sets = 0;
38    uint32_t rb = ROW_BYTES;        // bytes per row
39    std::vector<uint32_t> keys;     // sets * WAYS
40    std::vector<uint8_t> data;      // sets * WAYS * rb
41    std::vector<uint8_t> next;      // per-set replacement pointer
42    uint64_t used = 0;
43
44    void init(uint64_t rows, uint32_t row_bytes = ROW_BYTES) {
45        sets = rows / WAYS;
46        rb = row_bytes;
47        keys.assign(sets * WAYS, EMPTY);
48        data.assign(sets * WAYS * rb, 0);
49        next.assign(sets, 0);
50        used = 0;
51    }
52    static uint64_t mix(uint32_t r) {
53        uint64_t x = r * 0x9E3779B97F4A7C15ull;
54        return x ^ (x >> 29);
55    }
56    const uint8_t* find(uint32_t row) const {
57        if (sets == 0) return nullptr;
58        const uint64_t s = mix(row) % sets;
59        for (uint32_t w = 0; w < WAYS; ++w)
60            if (keys[s * WAYS + w] == row) return &data[(s * WAYS + w) * rb];
61        return nullptr;
62    }
63    void insert(uint32_t row, const uint8_t* bytes) {
64        if (sets == 0 || find(row) != nullptr) return;
65        const uint64_t s = mix(row) % sets;
66        uint32_t w = next[s];
67        next[s] = (uint8_t) ((w + 1) % WAYS);
68        if (keys[s * WAYS + w] == EMPTY) ++used;
69        keys[s * WAYS + w] = row;
70        std::memcpy(&data[(s * WAYS + w) * rb], bytes, rb);
71    }
72};
73
74struct Use {
75    uint32_t row;
76    uint32_t in_page;      // byte offset of the row inside the read buffer
77    uint8_t* dst;
78};
79
80struct Job {
81    uint64_t offset = 0;   // aligned file offset
82    uint32_t length = 0;   // PAGE or 2 * PAGE (a row that straddles a page boundary)
83    uint32_t ticket = 0;
84    std::vector<Use> uses;
85    double issued_us = 0;
86    bool keepalive = false;// no rows and no ticket: it only keeps the SSD awake (`set_keepalive`)
87};
88
89struct Miss {
90    uint64_t first;
91    uint32_t length;
92    uint32_t row;
93    uint32_t in_page;
94    uint32_t order;
95    uint8_t* dst;
96};
97
98struct TicketState {
99    uint32_t pending = 0;  // jobs not yet completed
100};
101
102}  // namespace
103
104// THREADING. With `io_thread` (the default) one worker thread owns every DirectFile call: it submits queued jobs
105// and reaps completions, so `issue` on the caller's thread only builds jobs and wakes it (~11 us per ReadFile
106// no longer lands on the host loop). `mu` guards everything below except `file`, which only the worker touches
107// (plus `wake`, which is thread-safe). Without `io_thread` the caller does all of it, as before.
108struct PleReader::Impl {
109    DirectFile file;
110    uint64_t table_offset = 0;
111    uint64_t n_rows = 0;
112    uint32_t row_bytes = ROW_BYTES;
113    uint32_t max_inflight = 0;
114    uint8_t* slab = nullptr;              // max_inflight slots of 2 pages
115    std::vector<uint32_t> free_slots;
116    std::vector<Job> inflight;            // indexed by slot
117    std::vector<Completion> delayed;      // completed but held back by fault injection
118    std::deque<Job> queue;                // not yet submitted
119    std::unordered_map<uint32_t, TicketState> tickets;
120    uint32_t next_ticket = 1;
121    RowCache cache;
122    ReaderStats stats;
123    size_t ring_pos = 0;
124    double delay_us = 0;
125    std::string error;
126    // the keep-alive (`set_keepalive`), steady-clock microseconds; `keep_us` 0 = off
127    double keep_us = 0;
128    double keep_window_us = 0;
129    double last_issue_us = 0;             // the last `issue`
130    double last_read_us = 0;              // the last read that went out, rows or keep-alive
131    uint64_t rng = 0x9E3779B97F4A7C15ull;
132
133    bool threaded = false;
134    bool stop = false;
135    std::mutex mu;
136    std::condition_variable cv_work;      // worker: there is something to submit
137    std::condition_variable cv_done;      // collectors: a ticket may have completed
138    std::thread worker;
139
140    uint8_t* slot_buf(uint32_t s) { return slab + (size_t) s * 2 * PAGE; }
141    bool busy() const { return free_slots.size() < max_inflight || !delayed.empty(); }
142
143    void cancel_queued() {
144        for (const Job& job : queue) {
145            auto it = tickets.find(job.ticket);
146            if (it != tickets.end() && it->second.pending > 0) --it->second.pending;
147        }
148        queue.clear();
149    }
150
151    void record_latency(double us) {
152        stats.read_us_sum += us;
153        if (stats.read_us.size() < LATENCY_RING) stats.read_us.push_back((float) us);
154        else stats.read_us[ring_pos++ % LATENCY_RING] = (float) us;
155    }
156
157    bool pump() {
158        while (!queue.empty() && !free_slots.empty()) {
159            const uint32_t s = free_slots.back();
160            free_slots.pop_back();
161            inflight[s] = std::move(queue.front());
162            queue.pop_front();
163            Job& j = inflight[s];
164            j.issued_us = now_us();
165            std::string kerr;             // a keep-alive read that cannot go out must not fail the reader
166            if (!file.submit(j.offset, slot_buf(s), j.length, s, j.keepalive ? kerr : error)) {
167                if (j.keepalive) {                 // no more of them: the SSD may sleep as before
168                    keep_us = 0;
169                    j.keepalive = false;
170                    free_slots.push_back(s);
171                    continue;
172                }
173                j.uses.clear();
174                auto it = tickets.find(j.ticket);
175                if (it != tickets.end() && it->second.pending > 0) --it->second.pending;
176                free_slots.push_back(s);
177                cancel_queued();
178                return false;
179            }
180            last_read_us = j.issued_us;
181            if (!j.keepalive) {                    // a keep-alive read counts when it completes (`finish`)
182                stats.submit_us += now_us() - j.issued_us;
183                ++stats.reads;
184            }
185        }
186        return true;
187    }
188
189    /// When the next keep-alive read is due, or < 0 when none is: it is off, the reader failed, or no rows
190    /// were asked for within the window (then the SSD may sleep; the next `issue` re-arms it).
191    double keepalive_due(double now) const {
192        if (keep_us <= 0 || !error.empty() || last_issue_us <= 0 || now - last_issue_us > keep_window_us) return -1;
193        return last_read_us + keep_us;
194    }
195
196    /// One page of the table, a different one each time, so the SSD really reads (not its controller's buffer).
197    void queue_keepalive() {
198        rng ^= rng << 13;
199        rng ^= rng >> 7;
200        rng ^= rng << 17;
201        const uint64_t first = table_offset / PAGE, end = (table_offset + n_rows * (uint64_t) row_bytes) / PAGE;
202        Job j;
203        j.offset = (first + (end > first ? rng % (end - first) : 0)) * PAGE;
204        j.length = PAGE;
205        j.keepalive = true;
206        queue.push_back(std::move(j));
207    }
208
209    bool finish(const Completion& c) {
210        const uint32_t s = (uint32_t) c.tag;
211        if (s >= inflight.size()) {
212            error = "PleReader: invalid table-read completion";
213            cancel_queued();
214            return false;
215        }
216        Job& j = inflight[s];
217        if (j.keepalive) {                         // no rows: it counts once it is done, with how long it took;
218            if (c.ok) {                            // a failed one turns the keep-alive off, not the reader
219                ++stats.keepalive_reads;
220                stats.keepalive_us_max = std::max(stats.keepalive_us_max, now_us() - j.issued_us);
221            } else {
222                keep_us = 0;
223            }
224            j.keepalive = false;
225            free_slots.push_back(s);
226            return error.empty() ? pump() : true;
227        }
228        if (!c.ok) {
229            error = "PleReader: a table read failed";
230            cancel_queued();
231            j.uses.clear();
232            auto it = tickets.find(j.ticket);
233            if (it != tickets.end() && it->second.pending > 0) --it->second.pending;
234            free_slots.push_back(s);
235            return false;
236        }
237        record_latency(now_us() - j.issued_us);
238        stats.bytes += c.bytes;
239        const uint8_t* buf = slot_buf(s);
240        for (const Use& u : j.uses) {
241            if (u.in_page + row_bytes > c.bytes) {
242                error = "PleReader: short read inside the table";
243                cancel_queued();
244                j.uses.clear();
245                auto it = tickets.find(j.ticket);
246                if (it != tickets.end() && it->second.pending > 0) --it->second.pending;
247                free_slots.push_back(s);
248                return false;
249            }
250        }
251        for (const Use& u : j.uses) {
252            std::memcpy(u.dst, buf + u.in_page, row_bytes);
253            cache.insert(u.row, buf + u.in_page);
254        }
255        auto it = tickets.find(j.ticket);
256        if (it != tickets.end() && it->second.pending > 0) --it->second.pending;
257        j.uses.clear();
258        free_slots.push_back(s);
259        return error.empty() ? pump() : true;
260    }
261
262    /// Completions (or wake packets) just returned by `file.wait`, applying fault injection.
263    bool process(const Completion* got, int n) {
264        bool ok = true;
265        for (int i = 0; i < n; ++i) {
266            if (got[i].tag == DirectFile::WAKE_TAG) continue;
267            if (got[i].tag >= inflight.size()) {
268                error = "PleReader: invalid table-read completion";
269                cancel_queued();
270                ok = false;
271                continue;
272            }
273            if (delay_us > 0 && now_us() - inflight[(uint32_t) got[i].tag].issued_us < delay_us) {
274                delayed.push_back(got[i]);
275                ++stats.late_injected;
276                continue;
277            }
278            if (!finish(got[i])) ok = false;   // drain the rest of this batch so no completed slot is stranded
279        }
280        return ok;
281    }
282
283    bool release_delayed() {
284        const double now = now_us();
285        for (size_t i = 0; i < delayed.size();) {
286            if (now - inflight[(uint32_t) delayed[i].tag].issued_us >= delay_us) {
287                const Completion c = delayed[i];
288                delayed.erase(delayed.begin() + (ptrdiff_t) i);
289                if (!finish(c)) return false;
290            } else {
291                ++i;
292            }
293        }
294        return true;
295    }
296
297    /// Caller-thread mode: process whatever has completed; blocks up to `timeout_ms` for the first completion.
298    bool drain(int timeout_ms) {
299        Completion got[64];
300        if (!delayed.empty()) {
301            if (!release_delayed()) return false;
302            timeout_ms = 0;                        // keep polling the held completions
303        }
304        const int n = file.wait(got, 64, timeout_ms);
305        return process(got, n);
306    }
307
308    void worker_loop() {
309        std::unique_lock<std::mutex> lk(mu);
310        for (;;) {
311            // Idle: wait for work. While rows are being asked for, the wait ends in time for a keep-alive read.
312            while (!(stop || !queue.empty() || busy())) {
313                const double now = now_us();
314                const double due = keepalive_due(now);
315                if (due < 0) cv_work.wait(lk);
316                else if (now >= due) queue_keepalive();
317                else cv_work.wait_for(lk, std::chrono::microseconds(std::max<int64_t>(1000, (int64_t) (due - now))));
318            }
319            if (stop && !busy()) break;
320            if (error.empty() && !pump() && error.empty()) error = "PleReader: submit failed";
321            if (!delayed.empty() && !release_delayed() && error.empty()) error = "PleReader: read failed";
322            if (!error.empty()) {
323                cv_done.notify_all();
324                if (!busy()) { cv_work.wait(lk, [&] { return stop; }); break; }
325            }
326            if (!busy()) { cv_done.notify_all(); continue; }
327            // Block in the port WITHOUT the lock, so `issue` can queue work; `issue` wakes us with a packet.
328            const int timeout = delayed.empty() ? -1 : 0;
329            lk.unlock();
330            Completion got[64];
331            const int n = file.wait(got, 64, timeout);
332            lk.lock();
333            if (!process(got, n) && error.empty()) error = "PleReader: read failed";
334            cv_done.notify_all();
335        }
336    }
337};
338
339PleReader::PleReader() : impl_(new Impl) {}
340PleReader::~PleReader() {
341    close();
342    delete impl_;
343}
344
345bool PleReader::open(const std::string& path, uint64_t table_offset, uint64_t n_rows, uint32_t max_inflight,
346                     uint64_t cache_rows, std::string& err, bool io_thread, uint32_t row_bytes) {
347    close();
348    if (max_inflight == 0 || max_inflight > 1024) { err = "PleReader: max_inflight must be 1..1024"; return false; }
349    if (row_bytes == 0 || row_bytes > PAGE) { err = "PleReader: row_bytes must be 1..4096"; return false; }
350    if (!impl_->file.open(path, err)) return false;
351    impl_->row_bytes = row_bytes;
352    if (table_offset + n_rows * (uint64_t) row_bytes > impl_->file.size()) {
353        err = "PleReader: the table extends past the end of " + path;
354        close();
355        return false;
356    }
357    impl_->table_offset = table_offset;
358    impl_->n_rows = n_rows;
359    impl_->max_inflight = max_inflight;
360    impl_->slab = (uint8_t*) DirectFile::alloc_aligned((size_t) max_inflight * 2 * PAGE);
361    if (impl_->slab == nullptr) { err = "PleReader: cannot allocate read buffers"; close(); return false; }
362    impl_->inflight.assign(max_inflight, Job{});
363    impl_->free_slots.clear();
364    for (uint32_t s = max_inflight; s-- > 0;) impl_->free_slots.push_back(s);
365    impl_->cache.init(cache_rows, row_bytes);
366    impl_->error.clear();
367    impl_->keep_us = 0;
368    impl_->last_issue_us = impl_->last_read_us = 0;
369    impl_->rng = 0x9E3779B97F4A7C15ull ^ (uint64_t) now_us();
370    if (impl_->rng == 0) impl_->rng = 1;
371    reset_stats();
372    impl_->stop = false;
373    impl_->threaded = io_thread;
374    if (io_thread) {
375        try {
376            impl_->worker = std::thread([this] { strata::aux_cpus::pin_current_thread(); impl_->worker_loop(); });
377        } catch (const std::exception& e) {
378            err = std::string("PleReader: cannot create I/O worker: ") + e.what();
379            close();
380            return false;
381        } catch (...) {
382            err = "PleReader: cannot create I/O worker";
383            close();
384            return false;
385        }
386    }
387    return true;
388}
389
390void PleReader::close() {
391    Impl& m = *impl_;
392    if (m.worker.joinable()) {
393        {
394            std::lock_guard<std::mutex> lk(m.mu);
395            m.stop = true;
396            m.queue.clear();                       // unsubmitted work is dropped; in-flight reads still drain
397        }
398        m.cv_work.notify_all();
399        m.file.wake();
400        m.worker.join();
401    }
402    // Outstanding reads must finish before their buffers are released (caller-thread mode, or a worker that
403    // stopped on an error).
404    if (m.file.is_open()) {
405        while (m.free_slots.size() < m.max_inflight) {
406            Completion c[64];
407            const int n = m.file.wait(c, 64, -1);
408            if (n == 0) break;
409            for (int i = 0; i < n; ++i)
410                if (c[i].tag != DirectFile::WAKE_TAG) m.free_slots.push_back((uint32_t) c[i].tag);
411        }
412    }
413    m.file.close();
414    DirectFile::free_aligned(m.slab);
415    m.slab = nullptr;
416    m.queue.clear();
417    m.tickets.clear();
418    m.delayed.clear();
419    m.inflight.clear();
420    m.free_slots.clear();
421    m.cache.init(0);
422    m.threaded = false;
423    m.stop = false;
424    m.keep_us = 0;
425    m.last_issue_us = m.last_read_us = 0;
426}
427
428bool PleReader::is_open() const { return impl_->file.is_open(); }
429uint32_t PleReader::row_bytes() const { return impl_->row_bytes; }
430
431PleReader::Ticket PleReader::issue(const uint32_t* rows, size_t n, uint8_t* out_raw) {
432    Impl& m = *impl_;
433    std::unique_lock<std::mutex> lk(m.mu, std::defer_lock);
434    if (m.threaded) lk.lock();
435    const uint32_t id = m.next_ticket++;
436    if (m.next_ticket == 0) m.next_ticket = 1;
437    const double now = now_us();
438    const bool rearm = m.keep_us > 0 && (m.last_issue_us <= 0 || now - m.last_issue_us > m.keep_window_us);
439    m.last_issue_us = now;
440    TicketState& ts = m.tickets[id];
441    // After a failed read the reader stays failed (`collect` reports `error` until the next `open`) and its worker has
442    // parked (worker_loop). A ticket queued now would never be read and `collect` would wait for it for ever, so it
443    // is not queued: it has no jobs, and `collect` returns the error at once.
444    if (!m.error.empty()) {
445        ts.pending = 0;
446        return Ticket{id};
447    }
448    // The common batches -- a decode step's 1..16 rows, the prefetch of PLE_N_HEADS = 16 -- are folded in a fixed stack
449    // buffer: no hash table, no temporary job vector, sorted by page offset and merged in one pass straight into the
450    // queue.  A batch above kStackMisses (a prompt chunk's thousands of rows) takes the general path below: a hash by page,
451    // as before.  Measured, the sort of every miss loses to the hash there when many rows share a page, so the stack path is
452    // kept to the size it wins at.  Nothing here outlives the call, so concurrent issuers (they hold m.mu when threaded)
453    // share no scratch.
454    if (n > UINT32_MAX) {
455        m.error = "PleReader: more than 2^32 rows in one issue";
456        ts.pending = 0;
457        return Ticket{id};
458    }
459    constexpr size_t kStackMisses = 64;
460    uint32_t n_jobs = 0;
461    if (n <= kStackMisses) {
462        Miss misses[kStackMisses];
463        size_t n_miss = 0;
464        const uint32_t rb = m.row_bytes;
465        for (size_t i = 0; i < n; ++i) {
466            uint8_t* dst = out_raw + i * rb;
467            ++m.stats.requests;
468            if (rows[i] >= m.n_rows) {
469                std::memset(dst, 0, rb);
470                continue;
471            }
472            if (const uint8_t* hit = m.cache.find(rows[i])) {
473                std::memcpy(dst, hit, rb);
474                ++m.stats.cache_hits;
475                continue;
476            }
477            const uint64_t at = m.table_offset + (uint64_t) rows[i] * rb;
478            const uint64_t first = at / PAGE * PAGE;
479            const uint32_t length = (uint32_t) ((at + rb - 1) / PAGE * PAGE - first + PAGE);
480            misses[n_miss++] = Miss{first, length, rows[i], (uint32_t) (at - first), (uint32_t) i, dst};
481        }
482        // Sorted by offset: prefill chunks then read the SSD in near-sequential order, and equal pages sit adjacent.
483        if (n_miss > 1) {
484            std::sort(misses, misses + n_miss, [](const Miss& a, const Miss& b) {
485                return a.first != b.first ? a.first < b.first : a.order < b.order;
486            });
487        }
488        for (size_t k = 0; k < n_miss;) {
489            const uint64_t first = misses[k].first;
490            size_t end = k + 1;
491            uint32_t length = misses[k].length;
492            while (end < n_miss && misses[end].first == first) {
493                length = std::max(length, misses[end].length);
494                ++m.stats.dedup_rows;
495                ++end;
496            }
497            Job j;
498            j.offset = first;
499            j.length = length;
500            j.ticket = id;
501            j.uses.reserve(end - k);
502            for (; k < end; ++k) j.uses.push_back(Use{misses[k].row, misses[k].in_page, misses[k].dst});
503            m.queue.push_back(std::move(j));
504            ++n_jobs;
505        }
506    } else {
507        std::unordered_map<uint64_t, size_t> by_page;     // aligned offset -> index in `jobs`
508        std::vector<Job> jobs;
509        for (size_t i = 0; i < n; ++i) {
510            const uint32_t rb = m.row_bytes;
511            uint8_t* dst = out_raw + i * rb;
512            ++m.stats.requests;
513            if (rows[i] >= m.n_rows) {
514                std::memset(dst, 0, rb);
515                continue;
516            }
517            if (const uint8_t* hit = m.cache.find(rows[i])) {
518                std::memcpy(dst, hit, rb);
519                ++m.stats.cache_hits;
520                continue;
521            }
522            const uint64_t at = m.table_offset + (uint64_t) rows[i] * rb;
523            const uint64_t first = at / PAGE * PAGE;
524            const uint32_t length = (uint32_t) ((at + rb - 1) / PAGE * PAGE - first + PAGE);
525            auto f = by_page.find(first);
526            if (f != by_page.end()) {
527                Job& j = jobs[f->second];
528                j.length = std::max(j.length, length);
529                j.uses.push_back(Use{rows[i], (uint32_t) (at - first), dst});
530                ++m.stats.dedup_rows;
531                continue;
532            }
533            by_page.emplace(first, jobs.size());
534            Job j;
535            j.offset = first;
536            j.length = length;
537            j.ticket = id;
538            j.uses.push_back(Use{rows[i], (uint32_t) (at - first), dst});
539            jobs.push_back(std::move(j));
540        }
541        // Sorted by offset: prefill chunks then read the SSD in near-sequential order.
542        std::sort(jobs.begin(), jobs.end(), [](const Job& a, const Job& b) { return a.offset < b.offset; });
543        n_jobs = (uint32_t) jobs.size();
544        for (Job& j : jobs) m.queue.push_back(std::move(j));
545    }
546    ts.pending = n_jobs;
547    const bool has_jobs = ts.pending > 0;
548    if (m.threaded) {
549        lk.unlock();
550        if (has_jobs) {
551            m.cv_work.notify_one();
552            m.file.wake();                         // in case the worker is blocked in the port
553        } else if (rearm) {
554            m.cv_work.notify_one();                // the keep-alive had lapsed: start it again
555        }
556    } else if (!m.pump() && m.error.empty()) {
557        m.error = "PleReader: submit failed";
558    }
559    return Ticket{id};
560}
561
562bool PleReader::collect(Ticket t, std::string& err) {
563    Impl& m = *impl_;
564    const double start = now_us();
565    if (m.threaded) {
566        std::unique_lock<std::mutex> lk(m.mu);
567        auto it = m.tickets.find(t.id);
568        if (it == m.tickets.end()) { err = "PleReader: unknown ticket"; return false; }
569        m.cv_done.wait(lk, [&] {
570            const auto current = m.tickets.find(t.id);
571            return current == m.tickets.end() || current->second.pending == 0;
572        });
573        it = m.tickets.find(t.id);
574        if (it == m.tickets.end()) { err = "PleReader: unknown ticket"; return false; }
575        if (!m.error.empty()) { err = m.error; m.tickets.erase(it); return false; }
576        m.stats.wait_us += now_us() - start;
577        m.tickets.erase(it);
578        return true;
579    }
580    auto it = m.tickets.find(t.id);
581    if (it == m.tickets.end()) { err = "PleReader: unknown ticket"; return false; }
582    while (it->second.pending > 0) {
583        const bool drained = m.drain(-1);
584        if (!drained && m.error.empty()) m.error = "PleReader: read failed";
585        it = m.tickets.find(t.id);
586        if (it == m.tickets.end()) { err = "PleReader: unknown ticket"; return false; }
587    }
588    if (!m.error.empty()) { err = m.error; m.tickets.erase(it); return false; }
589    m.stats.wait_us += now_us() - start;
590    m.tickets.erase(it);
591    return true;
592}
593
594void PleReader::set_keepalive(double period_ms, double window_s) {
595    Impl& m = *impl_;
596    {
597        std::lock_guard<std::mutex> lk(m.mu);
598        m.keep_us = m.threaded && period_ms > 0 ? period_ms * 1000.0 : 0.0;
599        m.keep_window_us = window_s > 0 ? window_s * 1e6 : 0.0;
600    }
601    m.cv_work.notify_all();
602}
603
604void PleReader::set_injected_delay_us(double delay_us) {
605    std::lock_guard<std::mutex> lk(impl_->mu);
606    impl_->delay_us = delay_us < 0 ? 0 : delay_us;
607}
608const ReaderStats& PleReader::stats() const { return impl_->stats; }
609ReaderStats PleReader::snapshot() const {
610    Impl& m = *impl_;
611    std::unique_lock<std::mutex> lk(m.mu, std::defer_lock);
612    if (m.threaded) lk.lock();
613    return m.stats;
614}
615void PleReader::reset_stats() {
616    Impl& m = *impl_;
617    std::unique_lock<std::mutex> lk(m.mu, std::defer_lock);
618    if (m.threaded) lk.lock();                     // the worker may be counting a keep-alive read
619    m.stats = ReaderStats{};
620    m.ring_pos = 0;
621}
622uint64_t PleReader::cache_capacity() const { return impl_->cache.sets * WAYS; }
623uint64_t PleReader::cache_size() const { return impl_->cache.used; }
624
625}  // namespace strata::ngram