okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
bd0e878f4
main
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 { 22if (read_us .empty ())return 0.0 ; 23 std::vector < float > v (read_us ); 24const 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 ()); 26return 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 { 37uint64_t sets = 0 ; 38uint32_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 42uint64_t used = 0 ; 43 44void init (uint64_t rows ,uint32_t row_bytes = ROW_BYTES ) { 45sets = rows /WAYS ; 46rb = row_bytes ; 47keys .assign (sets * WAYS ,EMPTY ); 48data .assign (sets * WAYS * rb ,0 ); 49next .assign (sets ,0 ); 50used = 0 ; 51 } 52static uint64_t mix (uint32_t r ) { 53uint64_t x = r * 0x9E3779B97F4A7C15ull ; 54return x ^ (x >>29 ); 55 } 56const uint8_t * find (uint32_t row )const { 57if (sets == 0 )return nullptr ; 58const uint64_t s = mix (row ) %sets ; 59for (uint32_t w = 0 ;w < WAYS ;++ w ) 60if (keys [s * WAYS + w ]== row )return & data [(s * WAYS + w )* rb ]; 61return nullptr ; 62 } 63void insert (uint32_t row ,const uint8_t * bytes ) { 64if (sets == 0 || find (row )!= nullptr )return ; 65const uint64_t s = mix (row ) %sets ; 66uint32_t w = next [s ]; 67next [s ]= (uint8_t ) ((w + 1 ) %WAYS ); 68if (keys [s * WAYS + w ]== EMPTY )++ used ; 69keys [s * WAYS + w ]= row ; 70 std::memcpy (& data [(s * WAYS + w )* rb ],bytes ,rb ); 71 } 72}; 73 74struct Use { 75uint32_t row ; 76uint32_t in_page ;// byte offset of the row inside the read buffer 77uint8_t * dst ; 78}; 79 80struct Job { 81uint64_t offset = 0 ;// aligned file offset 82uint32_t length = 0 ;// PAGE or 2 * PAGE (a row that straddles a page boundary) 83uint32_t ticket = 0 ; 84 std::vector < Use > uses ; 85double issued_us = 0 ; 86bool keepalive = false;// no rows and no ticket: it only keeps the SSD awake (`set_keepalive`) 87}; 88 89struct Miss { 90uint64_t first ; 91uint32_t length ; 92uint32_t row ; 93uint32_t in_page ; 94uint32_t order ; 95uint8_t * dst ; 96}; 97 98struct TicketState { 99uint32_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 { 109DirectFile file ; 110uint64_t table_offset = 0 ; 111uint64_t n_rows = 0 ; 112uint32_t row_bytes = ROW_BYTES ; 113uint32_t max_inflight = 0 ; 114uint8_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 ; 120uint32_t next_ticket = 1 ; 121RowCache cache ; 122ReaderStats stats ; 123size_t ring_pos = 0 ; 124double delay_us = 0 ; 125 std::string error ; 126// the keep-alive (`set_keepalive`), steady-clock microseconds; `keep_us` 0 = off 127double keep_us = 0 ; 128double keep_window_us = 0 ; 129double last_issue_us = 0 ;// the last `issue` 130double last_read_us = 0 ;// the last read that went out, rows or keep-alive 131uint64_t rng = 0x9E3779B97F4A7C15ull ; 132 133bool threaded = false; 134bool 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 140uint8_t * slot_buf (uint32_t s ) {return slab + (size_t )s * 2 * PAGE ; } 141bool busy ()const {return free_slots .size ()< max_inflight || !delayed .empty (); } 142 143void cancel_queued () { 144for (const Job & job :queue ) { 145auto it = tickets .find (job .ticket ); 146if (it != tickets .end ()&& it -> second .pending > 0 )-- it -> second .pending ; 147 } 148queue .clear (); 149 } 150 151void record_latency (double us ) { 152stats .read_us_sum += us ; 153if (stats .read_us .size ()< LATENCY_RING )stats .read_us .push_back ((float )us ); 154else stats .read_us [ring_pos ++ %LATENCY_RING ]= (float )us ; 155 } 156 157bool pump () { 158while (!queue .empty ()&& !free_slots .empty ()) { 159const uint32_t s = free_slots .back (); 160free_slots .pop_back (); 161inflight [s ]= std::move (queue .front ()); 162queue .pop_front (); 163Job & j = inflight [s ]; 164j .issued_us = now_us (); 165 std::string kerr ;// a keep-alive read that cannot go out must not fail the reader 166if (!file .submit (j .offset ,slot_buf (s ),j .length ,s ,j .keepalive ?kerr :error )) { 167if (j .keepalive ) {// no more of them: the SSD may sleep as before 168keep_us = 0 ; 169j .keepalive = false; 170free_slots .push_back (s ); 171continue ; 172 } 173j .uses .clear (); 174auto it = tickets .find (j .ticket ); 175if (it != tickets .end ()&& it -> second .pending > 0 )-- it -> second .pending ; 176free_slots .push_back (s ); 177cancel_queued (); 178return false; 179 } 180last_read_us = j .issued_us ; 181if (!j .keepalive ) {// a keep-alive read counts when it completes (`finish`) 182stats .submit_us += now_us ()- j .issued_us ; 183++ stats .reads ; 184 } 185 } 186return 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). 191double keepalive_due (double now )const { 192if (keep_us <=0 || !error .empty ()|| last_issue_us <=0 || now - last_issue_us > keep_window_us )return -1 ; 193return 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). 197void queue_keepalive () { 198rng ^=rng <<13 ; 199rng ^=rng >>7 ; 200rng ^=rng <<17 ; 201const uint64_t first = table_offset /PAGE ,end = (table_offset + n_rows * (uint64_t )row_bytes ) /PAGE ; 202Job j ; 203j .offset = (first + (end > first ?rng % (end - first ) :0 ))* PAGE ; 204j .length = PAGE ; 205j .keepalive = true; 206queue .push_back (std::move (j )); 207 } 208 209bool finish (const Completion & c ) { 210const uint32_t s = (uint32_t )c .tag ; 211if (s >=inflight .size ()) { 212error = "PleReader: invalid table-read completion" ; 213cancel_queued (); 214return false; 215 } 216Job & j = inflight [s ]; 217if (j .keepalive ) {// no rows: it counts once it is done, with how long it took; 218if (c .ok ) {// a failed one turns the keep-alive off, not the reader 219++ stats .keepalive_reads ; 220stats .keepalive_us_max = std::max (stats .keepalive_us_max ,now_us ()- j .issued_us ); 221 }else { 222keep_us = 0 ; 223 } 224j .keepalive = false; 225free_slots .push_back (s ); 226return error .empty () ?pump () : true; 227 } 228if (!c .ok ) { 229error = "PleReader: a table read failed" ; 230cancel_queued (); 231j .uses .clear (); 232auto it = tickets .find (j .ticket ); 233if (it != tickets .end ()&& it -> second .pending > 0 )-- it -> second .pending ; 234free_slots .push_back (s ); 235return false; 236 } 237record_latency (now_us ()- j .issued_us ); 238stats .bytes += c .bytes ; 239const uint8_t * buf = slot_buf (s ); 240for (const Use & u :j .uses ) { 241if (u .in_page + row_bytes > c .bytes ) { 242error = "PleReader: short read inside the table" ; 243cancel_queued (); 244j .uses .clear (); 245auto it = tickets .find (j .ticket ); 246if (it != tickets .end ()&& it -> second .pending > 0 )-- it -> second .pending ; 247free_slots .push_back (s ); 248return false; 249 } 250 } 251for (const Use & u :j .uses ) { 252 std::memcpy (u .dst ,buf + u .in_page ,row_bytes ); 253cache .insert (u .row ,buf + u .in_page ); 254 } 255auto it = tickets .find (j .ticket ); 256if (it != tickets .end ()&& it -> second .pending > 0 )-- it -> second .pending ; 257j .uses .clear (); 258free_slots .push_back (s ); 259return error .empty () ?pump () : true; 260 } 261 262/// Completions (or wake packets) just returned by `file.wait`, applying fault injection. 263bool process (const Completion * got ,int n ) { 264bool ok = true; 265for (int i = 0 ;i < n ;++ i ) { 266if (got [i ].tag == DirectFile ::WAKE_TAG )continue ; 267if (got [i ].tag >=inflight .size ()) { 268error = "PleReader: invalid table-read completion" ; 269cancel_queued (); 270ok = false; 271continue ; 272 } 273if (delay_us > 0 && now_us ()- inflight [(uint32_t )got [i ].tag ].issued_us < delay_us ) { 274delayed .push_back (got [i ]); 275++ stats .late_injected ; 276continue ; 277 } 278if (!finish (got [i ]))ok = false;// drain the rest of this batch so no completed slot is stranded 279 } 280return ok ; 281 } 282 283bool release_delayed () { 284const double now = now_us (); 285for (size_t i = 0 ;i < delayed .size ();) { 286if (now - inflight [(uint32_t )delayed [i ].tag ].issued_us >=delay_us ) { 287const Completion c = delayed [i ]; 288delayed .erase (delayed .begin ()+ (ptrdiff_t )i ); 289if (!finish (c ))return false; 290 }else { 291++ i ; 292 } 293 } 294return true; 295 } 296 297/// Caller-thread mode: process whatever has completed; blocks up to `timeout_ms` for the first completion. 298bool drain (int timeout_ms ) { 299Completion got [64 ]; 300if (!delayed .empty ()) { 301if (!release_delayed ())return false; 302timeout_ms = 0 ;// keep polling the held completions 303 } 304const int n = file .wait (got ,64 ,timeout_ms ); 305return process (got ,n ); 306 } 307 308void worker_loop () { 309 std::unique_lock < std::mutex > lk (mu ); 310for (;;) { 311// Idle: wait for work. While rows are being asked for, the wait ends in time for a keep-alive read. 312while (!(stop || !queue .empty ()|| busy ())) { 313const double now = now_us (); 314const double due = keepalive_due (now ); 315if (due < 0 )cv_work .wait (lk ); 316else if (now >=due )queue_keepalive (); 317else cv_work .wait_for (lk , std::chrono::microseconds (std::max < int64_t > (1000 , (int64_t ) (due - now )))); 318 } 319if (stop && !busy ())break ; 320if (error .empty ()&& !pump ()&& error .empty ())error = "PleReader: submit failed" ; 321if (!delayed .empty ()&& !release_delayed ()&& error .empty ())error = "PleReader: read failed" ; 322if (!error .empty ()) { 323cv_done .notify_all (); 324if (!busy ()) {cv_work .wait (lk , [& ] {return stop ; });break ; } 325 } 326if (!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. 328const int timeout = delayed .empty () ?-1 :0 ; 329lk .unlock (); 330Completion got [64 ]; 331const int n = file .wait (got ,64 ,timeout ); 332lk .lock (); 333if (!process (got ,n )&& error .empty ())error = "PleReader: read failed" ; 334cv_done .notify_all (); 335 } 336 } 337}; 338 339PleReader ::PleReader () :impl_ (new Impl ) {} 340PleReader ::~PleReader () { 341close (); 342delete impl_ ; 343} 344 345bool PleReader ::open (const std::string & path ,uint64_t table_offset ,uint64_t n_rows ,uint32_t max_inflight , 346uint64_t cache_rows , std::string & err ,bool io_thread ,uint32_t row_bytes ) { 347close (); 348if (max_inflight == 0 || max_inflight > 1024 ) {err = "PleReader: max_inflight must be 1..1024" ;return false; } 349if (row_bytes == 0 || row_bytes > PAGE ) {err = "PleReader: row_bytes must be 1..4096" ;return false; } 350if (!impl_ -> file .open (path ,err ))return false; 351impl_ -> row_bytes = row_bytes ; 352if (table_offset + n_rows * (uint64_t )row_bytes > impl_ -> file .size ()) { 353err = "PleReader: the table extends past the end of " + path ; 354close (); 355return false; 356 } 357impl_ -> table_offset = table_offset ; 358impl_ -> n_rows = n_rows ; 359impl_ -> max_inflight = max_inflight ; 360impl_ -> slab = (uint8_t * )DirectFile ::alloc_aligned ((size_t )max_inflight * 2 * PAGE ); 361if (impl_ -> slab == nullptr ) {err = "PleReader: cannot allocate read buffers" ;close ();return false; } 362impl_ -> inflight .assign (max_inflight ,Job {}); 363impl_ -> free_slots .clear (); 364for (uint32_t s = max_inflight ;s -- > 0 ;)impl_ -> free_slots .push_back (s ); 365impl_ -> cache .init (cache_rows ,row_bytes ); 366impl_ -> error .clear (); 367impl_ -> keep_us = 0 ; 368impl_ -> last_issue_us = impl_ -> last_read_us = 0 ; 369impl_ -> rng = 0x9E3779B97F4A7C15ull ^ (uint64_t )now_us (); 370if (impl_ -> rng == 0 )impl_ -> rng = 1 ; 371reset_stats (); 372impl_ -> stop = false; 373impl_ -> threaded = io_thread ; 374if (io_thread ) { 375try { 376impl_ -> worker = std::thread ([this ] { strata::aux_cpus::pin_current_thread ();impl_ -> worker_loop (); }); 377 }catch (const std::exception & e ) { 378err = std::string ("PleReader: cannot create I/O worker: " )+ e .what (); 379close (); 380return false; 381 }catch (...) { 382err = "PleReader: cannot create I/O worker" ; 383close (); 384return false; 385 } 386 } 387return true; 388} 389 390void PleReader ::close () { 391Impl & m = * impl_ ; 392if (m .worker .joinable ()) { 393 { 394 std::lock_guard < std::mutex > lk (m .mu ); 395m .stop = true; 396m .queue .clear ();// unsubmitted work is dropped; in-flight reads still drain 397 } 398m .cv_work .notify_all (); 399m .file .wake (); 400m .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). 404if (m .file .is_open ()) { 405while (m .free_slots .size ()< m .max_inflight ) { 406Completion c [64 ]; 407const int n = m .file .wait (c ,64 ,-1 ); 408if (n == 0 )break ; 409for (int i = 0 ;i < n ;++ i ) 410if (c [i ].tag != DirectFile ::WAKE_TAG )m .free_slots .push_back ((uint32_t )c [i ].tag ); 411 } 412 } 413m .file .close (); 414DirectFile ::free_aligned (m .slab ); 415m .slab = nullptr ; 416m .queue .clear (); 417m .tickets .clear (); 418m .delayed .clear (); 419m .inflight .clear (); 420m .free_slots .clear (); 421m .cache .init (0 ); 422m .threaded = false; 423m .stop = false; 424m .keep_us = 0 ; 425m .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 ) { 432Impl & m = * impl_ ; 433 std::unique_lock < std::mutex > lk (m .mu , std::defer_lock ); 434if (m .threaded )lk .lock (); 435const uint32_t id = m .next_ticket ++ ; 436if (m .next_ticket == 0 )m .next_ticket = 1 ; 437const double now = now_us (); 438const bool rearm = m .keep_us > 0 && (m .last_issue_us <=0 || now - m .last_issue_us > m .keep_window_us ); 439m .last_issue_us = now ; 440TicketState & 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. 444if (!m .error .empty ()) { 445ts .pending = 0 ; 446return 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. 454if (n > UINT32_MAX ) { 455m .error = "PleReader: more than 2^32 rows in one issue" ; 456ts .pending = 0 ; 457return Ticket {id }; 458 } 459constexpr size_t kStackMisses = 64 ; 460uint32_t n_jobs = 0 ; 461if (n <=kStackMisses ) { 462Miss misses [kStackMisses ]; 463size_t n_miss = 0 ; 464const uint32_t rb = m .row_bytes ; 465for (size_t i = 0 ;i < n ;++ i ) { 466uint8_t * dst = out_raw + i * rb ; 467++ m .stats .requests ; 468if (rows [i ] >=m .n_rows ) { 469 std::memset (dst ,0 ,rb ); 470continue ; 471 } 472if (const uint8_t * hit = m .cache .find (rows [i ])) { 473 std::memcpy (dst ,hit ,rb ); 474++ m .stats .cache_hits ; 475continue ; 476 } 477const uint64_t at = m .table_offset + (uint64_t )rows [i ]* rb ; 478const uint64_t first = at /PAGE * PAGE ; 479const uint32_t length = (uint32_t ) ((at + rb - 1 ) /PAGE * PAGE - first + PAGE ); 480misses [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. 483if (n_miss > 1 ) { 484 std::sort (misses ,misses + n_miss , [](const Miss & a ,const Miss & b ) { 485return a .first != b .first ?a .first < b .first :a .order < b .order ; 486 }); 487 } 488for (size_t k = 0 ;k < n_miss ;) { 489const uint64_t first = misses [k ].first ; 490size_t end = k + 1 ; 491uint32_t length = misses [k ].length ; 492while (end < n_miss && misses [end ].first == first ) { 493length = std::max (length ,misses [end ].length ); 494++ m .stats .dedup_rows ; 495++ end ; 496 } 497Job j ; 498j .offset = first ; 499j .length = length ; 500j .ticket = id ; 501j .uses .reserve (end - k ); 502for (;k < end ;++ k )j .uses .push_back (Use {misses [k ].row ,misses [k ].in_page ,misses [k ].dst }); 503m .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 ; 509for (size_t i = 0 ;i < n ;++ i ) { 510const uint32_t rb = m .row_bytes ; 511uint8_t * dst = out_raw + i * rb ; 512++ m .stats .requests ; 513if (rows [i ] >=m .n_rows ) { 514 std::memset (dst ,0 ,rb ); 515continue ; 516 } 517if (const uint8_t * hit = m .cache .find (rows [i ])) { 518 std::memcpy (dst ,hit ,rb ); 519++ m .stats .cache_hits ; 520continue ; 521 } 522const uint64_t at = m .table_offset + (uint64_t )rows [i ]* rb ; 523const uint64_t first = at /PAGE * PAGE ; 524const uint32_t length = (uint32_t ) ((at + rb - 1 ) /PAGE * PAGE - first + PAGE ); 525auto f = by_page .find (first ); 526if (f != by_page .end ()) { 527Job & j = jobs [f -> second ]; 528j .length = std::max (j .length ,length ); 529j .uses .push_back (Use {rows [i ], (uint32_t ) (at - first ),dst }); 530++ m .stats .dedup_rows ; 531continue ; 532 } 533by_page .emplace (first ,jobs .size ()); 534Job j ; 535j .offset = first ; 536j .length = length ; 537j .ticket = id ; 538j .uses .push_back (Use {rows [i ], (uint32_t ) (at - first ),dst }); 539jobs .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 ; }); 543n_jobs = (uint32_t )jobs .size (); 544for (Job & j :jobs )m .queue .push_back (std::move (j )); 545 } 546ts .pending = n_jobs ; 547const bool has_jobs = ts .pending > 0 ; 548if (m .threaded ) { 549lk .unlock (); 550if (has_jobs ) { 551m .cv_work .notify_one (); 552m .file .wake ();// in case the worker is blocked in the port 553 }else if (rearm ) { 554m .cv_work .notify_one ();// the keep-alive had lapsed: start it again 555 } 556 }else if (!m .pump ()&& m .error .empty ()) { 557m .error = "PleReader: submit failed" ; 558 } 559return Ticket {id }; 560} 561 562bool PleReader ::collect (Ticket t , std::string & err ) { 563Impl & m = * impl_ ; 564const double start = now_us (); 565if (m .threaded ) { 566 std::unique_lock < std::mutex > lk (m .mu ); 567auto it = m .tickets .find (t .id ); 568if (it == m .tickets .end ()) {err = "PleReader: unknown ticket" ;return false; } 569m .cv_done .wait (lk , [& ] { 570const auto current = m .tickets .find (t .id ); 571return current == m .tickets .end ()|| current -> second .pending == 0 ; 572 }); 573it = m .tickets .find (t .id ); 574if (it == m .tickets .end ()) {err = "PleReader: unknown ticket" ;return false; } 575if (!m .error .empty ()) {err = m .error ;m .tickets .erase (it );return false; } 576m .stats .wait_us += now_us ()- start ; 577m .tickets .erase (it ); 578return true; 579 } 580auto it = m .tickets .find (t .id ); 581if (it == m .tickets .end ()) {err = "PleReader: unknown ticket" ;return false; } 582while (it -> second .pending > 0 ) { 583const bool drained = m .drain (-1 ); 584if (!drained && m .error .empty ())m .error = "PleReader: read failed" ; 585it = m .tickets .find (t .id ); 586if (it == m .tickets .end ()) {err = "PleReader: unknown ticket" ;return false; } 587 } 588if (!m .error .empty ()) {err = m .error ;m .tickets .erase (it );return false; } 589m .stats .wait_us += now_us ()- start ; 590m .tickets .erase (it ); 591return true; 592} 593 594void PleReader ::set_keepalive (double period_ms ,double window_s ) { 595Impl & m = * impl_ ; 596 { 597 std::lock_guard < std::mutex > lk (m .mu ); 598m .keep_us = m .threaded && period_ms > 0 ?period_ms * 1000.0 :0.0 ; 599m .keep_window_us = window_s > 0 ?window_s * 1e6 :0.0 ; 600 } 601m .cv_work .notify_all (); 602} 603 604void PleReader ::set_injected_delay_us (double delay_us ) { 605 std::lock_guard < std::mutex > lk (impl_ -> mu ); 606impl_ -> delay_us = delay_us < 0 ?0 :delay_us ; 607} 608const ReaderStats & PleReader ::stats ()const {return impl_ -> stats ; } 609ReaderStats PleReader ::snapshot ()const { 610Impl & m = * impl_ ; 611 std::unique_lock < std::mutex > lk (m .mu , std::defer_lock ); 612if (m .threaded )lk .lock (); 613return m .stats ; 614} 615void PleReader ::reset_stats () { 616Impl & m = * impl_ ; 617 std::unique_lock < std::mutex > lk (m .mu , std::defer_lock ); 618if (m .threaded )lk .lock ();// the worker may be counting a keep-alive read 619m .stats = ReaderStats {}; 620m .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