| 952 | } |
| 953 | |
| 954 | bool Dflash2Drafter::begin_request(const int32_t* ids, int64_t n, int64_t resume, bool* cold) { |
| 955 | resume = std::max<int64_t>(0, std::min(resume, n)); |
| 956 | if (cold) *cold = false; |
| 957 | ++ring_stats.requests; |
| 958 | last_rebuilt = last_missing = 0; |
| 959 | last_ms = 0; |
| 960 | last_swapped = false; |
| 961 | std::string err; |
| 962 | (void) context_wait(err); |
| 963 | const Clock::time_point t0 = Clock::now(); |
| 964 | auto lcp_of = [&](const std::vector<int32_t>& h) { |
| 965 | int64_t l = 0; |
| 966 | const int64_t lim = std::min<int64_t>((int64_t) h.size(), resume); |
| 967 | while (l < lim && h[(size_t) l] == ids[l]) ++l; |
| 968 | return l; |
| 969 | }; |
| 970 | if (!log_on_) { // the pre-log rule: a history that does not cover the resumed prefix starts the ring over |
| 971 | const int64_t lcp = lcp_of(cur_.hist); |
| 972 | const bool stale = ring_hi_ > lcp && lcp < resume; |
| 973 | if (stale) { ++epoch_; ring_hi_ = 0; } |
| 974 | if (cold) *cold = stale; |
| 975 | cur_.hist.assign(ids, ids + resume); |
| 976 | return true; |
| 977 | } |
| 978 | bool covered = lcp_of(cur_.hist) >= resume; |
| 979 | bool swapped = false; |
| 980 | if (!covered) { // a parked lineage may be the one this request resumes |
| 981 | for (size_t i = stash_.size(); i-- > 0;) { |
| 982 | if (lcp_of(stash_[i].hist) < resume) continue; |
| 983 | Lineage got = std::move(stash_[i]); |
| 984 | stash_.erase(stash_.begin() + (std::ptrdiff_t) i); |
| 985 | stash_push(std::move(cur_)); |
| 986 | cur_ = std::move(got); |
| 987 | invalidate_ring(); |
| 988 | covered = swapped = true; |
| 989 | ++ring_stats.stash_hits; |
| 990 | break; |
| 991 | } |
| 992 | } |
| 993 | if (!covered) { // another conversation: the live lineage is parked, this one starts empty |
| 994 | stash_push(std::move(cur_)); |
| 995 | cur_ = Lineage{}; |
| 996 | invalidate_ring(); |
| 997 | ++ring_stats.cold_starts; |
| 998 | } else if ((int64_t) cur_.hist.size() >= resume + 128) { |
| 999 | // the rows past `resume` are about to be rewritten (a rewound or branching request): keep the old branch as it is, sharing the log's chunks |
| 1000 | Lineage copy; |
| 1001 | copy.hist = cur_.hist; |
| 1002 | copy.chunks = cur_.chunks; |
| 1003 | stash_push(std::move(copy)); |
| 1004 | } |
| 1005 | if ((int64_t) cur_.hist.size() > resume) { cur_.hist.resize((size_t) resume); cur_.truncate(resume); } |
| 1006 | if (!covered) cur_.hist.assign(ids, ids + resume); |
| 1007 | // the window the first draft reads, below `resume` (the prompt's own taps cover [resume, n)): every slot that does not hold its row is rebuilt from the log |
| 1008 | int64_t rebuilt = 0, missing = 0; |
| 1009 | const int64_t lo = std::max<int64_t>(0, n - (window_ - 1)), hi = resume; |
| 1010 | if (hi > lo) { |
| 1011 | if (!rebuild(lo, hi, &rebuilt, &missing, err)) { |