diff --git a/core/mem/kvtier.cpp b/core/mem/kvtier.cpp index b39144e5..3d1face9 100644 --- a/core/mem/kvtier.cpp +++ b/core/mem/kvtier.cpp @@ -606,6 +606,51 @@ void IdleTiers::drop_session(uint64_t id) { sessions_.erase(it); } +void IdleTiers::find_sessions(const std::string& label, uint64_t id, + std::vector* out) const { + out->clear(); + std::lock_guard lk(mu_); + for (const auto& kv : sessions_) { + const bool hit = id != 0 ? kv.first == id : (!label.empty() && kv.second.label == label); + if (!hit) continue; + SessionChain c; + c.id = kv.first; + c.label = kv.second.label; + c.chain = kv.second.chain; + out->push_back(std::move(c)); + } +} + +int64_t IdleTiers::shared_prefix_blocks(const std::vector& chain, + const std::vector& except) const { + if (chain.empty()) return 0; + std::lock_guard lk(mu_); + auto ro = roots_.find(chain[0]); + if (ro == roots_.end()) return 0; + int64_t most = 0; + for (uint64_t sid : ro->second) { + if (std::find(except.begin(), except.end(), sid) != except.end()) continue; + auto it = sessions_.find(sid); + if (it == sessions_.end()) continue; + const std::vector& other = it->second.chain; + size_t n = 0; + while (n < chain.size() && n < other.size() && chain[n] == other[n]) ++n; + if ((int64_t)n > most) most = (int64_t)n; + } + return most; +} + +void IdleTiers::cut_session(uint64_t id, int64_t keep_blocks, int64_t keep_tokens) { + std::lock_guard lk(mu_); + if (keep_blocks <= 0) { drop_session(id); return; } + auto it = sessions_.find(id); + if (it == sessions_.end()) return; + Session& s = it->second; + if ((int64_t)s.chain.size() <= keep_blocks) return; + s.chain.resize((size_t)keep_blocks); + s.n_tokens = keep_tokens; +} + std::vector IdleTiers::sessions(Occupancy* occ) const { /* One slice's hold on the lock (YieldingMutex). */ struct Slice { diff --git a/core/mem/kvtier.h b/core/mem/kvtier.h index 20eccac2..cdb79a5a 100644 --- a/core/mem/kvtier.h +++ b/core/mem/kvtier.h @@ -246,6 +246,31 @@ public: * microseconds apart. */ std::vector sessions(Occupancy* occ = nullptr) const; + /* ---------------- a release names a session ---------------- + * + * The cache keys by block and knows no conversation; the rows here are what a client can + * name. PrefixCache::release_session asks for the rows, walks their chains itself and + * reports back what is left of each. */ + struct SessionChain { + uint64_t id = 0; + std::string label; + std::vector chain; + }; + /* Every row carrying `label`, or with `id` nonzero the one row of that id. A label is the + * client's and may stand on several leaves (a conversation branched and both ends were + * served); a release by label means all of them. */ + void find_sessions(const std::string& label, uint64_t id, + std::vector* out) const; + /* How many blocks at the start of `chain` another stored session walks too: the longest + * common prefix with any row at the same root whose id is not in `except`. Those blocks + * belong to the other conversation as much as to this one. */ + int64_t shared_prefix_blocks(const std::vector& chain, + const std::vector& except) const; + /* The release is done: the row keeps its first `keep_blocks` (covering `keep_tokens`), + * which is the kept prefix or, beyond it, the deepest block a live request held back; it + * goes when that is zero. A kept stub is a leaf again until a later turn extends it. */ + void cut_session(uint64_t id, int64_t keep_blocks, int64_t keep_tokens); + struct Stats { /* `to_host` counts copies to host memory (link traffic); `dropped` counts VRAM copies * then given up. An entry can be copied and never dropped. */ diff --git a/core/mem/prefix.cpp b/core/mem/prefix.cpp index a2a418d8..957da514 100644 --- a/core/mem/prefix.cpp +++ b/core/mem/prefix.cpp @@ -981,4 +981,83 @@ int64_t PrefixCache::expire(uint64_t now_ns, uint64_t ttl_ns) { stats_.ckpt_expired += (int64_t)gone.size(); return n; } + +/* ------------------------------------------------------------------ release on request */ + +int PrefixCache::release_session(const std::string& label, uint64_t id, int64_t keep_tokens, + SessionRelease* out) { + if (!out) return RAD_E_INVAL; + *out = SessionRelease{}; + if (!enabled_ || !tiers_ || block_size_ <= 0) return RAD_E_UNSUPPORTED; + if (label.empty() && id == 0) return RAD_E_INVAL; + if (keep_tokens < 0) return RAD_E_INVAL; + + std::vector rows; + tiers_->find_sessions(label, id, &rows); + if (rows.empty()) return RAD_E_NOTFOUND; + std::vector ids; + for (const IdleTiers::SessionChain& r : rows) ids.push_back(r.id); + + /* A kept token keeps its whole block: the block holding it is what the next turn hits. */ + const int64_t keep_blocks = (keep_tokens + block_size_ - 1) / block_size_; + int64_t entry_bytes = 0; + for (int32_t g : groups_) { + const KVGroupPlan* p = kv_->plan(g); + if (p) entry_bytes += p->bytes_per_block; + } + + for (const IdleTiers::SessionChain& row : rows) { + const int64_t n = (int64_t)row.chain.size(); + const int64_t shared = tiers_->shared_prefix_blocks(row.chain, ids); + const int64_t floor = std::max(keep_blocks, shared); + ++out->sessions; + out->kept_tokens += std::min(keep_blocks, n) * block_size_; + out->kept_shared += std::max(0, std::min(shared, n) - keep_blocks); + + /* Tip inwards, as expire() and the host tier's pressure do: what is left is still a + * prefix a lookup reaches. `live_upto` is one past the deepest block a request kept: + * the row is cut there, not at the kept prefix, so a later release reaches it. */ + int64_t live_upto = 0; + for (int64_t b = n - 1; b >= floor; --b) { + const BlockHash& h = row.chain[(size_t)b]; + auto it = map_.find(h); + if (it != map_.end()) { + Entry& e = it->second; + /* A sequence reads it, or a waiting request restored it and holds it against + * drop_clean: releasing would free nothing and lose the entry under them. Its + * snapshot stays with it; that request most likely resumes from it. */ + if (e.in_lru && (shared_with_live(e) || held_.count(h) > 0)) { + ++out->kept_live; + if (live_upto == 0) live_upto = b + 1; + continue; + } + if (e.in_lru) { + lru_.erase(e.lru); + e.in_lru = false; + release_blocks(e); + out->device_bytes += entry_bytes; + } + /* The host copy goes with the entry (forget), so count it before. */ + if (tiers_->resident_off_device(h) || tiers_->droppable(h)) + out->host_bytes += tiers_->entry_bytes(); + tiers_->forget(h); + map_.erase(it); + ++out->entries; + } + auto ck = ck_by_prefix_.find(h); + if (ck != ck_by_prefix_.end() && ck->second.valid && !handed(h) && !reserved(h)) { + const uint64_t session = ck->second.session; + retire_ckpt(ck); + unindex_ckpt(session, h); + ++out->snapshots; + } + } + const int64_t cut = std::min(n, std::max(keep_blocks, live_upto)); + tiers_->cut_session(row.id, cut, cut * block_size_); + } + out->tokens = out->entries * block_size_; + stats_.released += out->entries; + stats_.ckpt_released += out->snapshots; + return RAD_OK; +} } /* namespace rad */ diff --git a/core/mem/prefix.h b/core/mem/prefix.h index c88c405a..cea7f4b7 100644 --- a/core/mem/prefix.h +++ b/core/mem/prefix.h @@ -174,6 +174,23 @@ CheckpointSlots checkpoint_slots_auto(const CheckpointPolicy& policy, int64_t ma int64_t ctx, int64_t interval, int64_t slot_bytes, int64_t share_bytes, int64_t room_bytes); +/* ------------------------------------------------------------------ a release */ +/* What PrefixCache::release_session took out and what it left. Blocks are left for three + * reasons, counted apart so a caller can tell a half-shared conversation from a busy one: the + * caller asked for them (`keep_tokens`), another stored session's chain runs through them (a + * system prompt two conversations open with belongs to both), or a live sequence holds them. */ +struct SessionRelease { + int64_t sessions = 0; /* rows the label or id named */ + int64_t entries = 0; /* blocks forgotten, from VRAM or the host tier */ + int64_t tokens = 0; /* entries x block size */ + int64_t device_bytes = 0; /* pool bytes given back */ + int64_t host_bytes = 0; /* host-tier slots given back */ + int64_t snapshots = 0; + int64_t kept_tokens = 0; /* the chain's start, as asked, whole blocks */ + int64_t kept_shared = 0; /* blocks beyond that on another stored session's chain */ + int64_t kept_live = 0; /* blocks a running or waiting request holds */ +}; + /* ------------------------------------------------------------------ the cache */ class PrefixCache { public: @@ -315,6 +332,21 @@ public: * than what follows it: conversations expire from the tip inwards and a shared system prompt * outlives its readers. Returns how many entries went. */ int64_t expire(uint64_t now_ns, uint64_t ttl_ns); + + /* ---------------- release on request ---------------- + * + * Forget one stored conversation now instead of at the TTL: a client that deleted it, or + * replaced everything past a prefix (a compaction) and knows the rest is dead. `label` names + * every row carrying it, `id` (nonzero) one row by its engine id (IdleTiers::SessionInfo). + * The chain goes from the tip inwards like expire(): VRAM blocks to the pool, the host copy + * with them, the session's snapshots on the released blocks to the store. `keep_tokens` + * leaves the chain's first blocks standing (rounded up to whole blocks), so the prefix the + * client kept still hits. A block another stored session's chain shares stays, as does one a + * live sequence holds or a waiting request has restored; snapshots handed out or reserved + * this step stay too. RAD_E_NOTFOUND when nothing matches, RAD_E_UNSUPPORTED without the + * session table (no tiers attached). */ + int release_session(const std::string& label, uint64_t id, int64_t keep_tokens, + SessionRelease* out); /* ---------------- linear checkpoints ---------------- */ /* The next position strictly after `pos` at which the scheduler must split a chunk so that a * checkpoint lands on a boundary (spec §7.1, §7.3). */ @@ -359,6 +391,8 @@ public: int64_t expired = 0, ckpt_expired = 0; /* Restores from the host tier cut short because the pool could not hold the chain. */ int64_t restore_cuts = 0; + /* Entries and snapshots a client released (release_session). */ + int64_t released = 0, ckpt_released = 0; }; const Stats& stats() const { return stats_; } diff --git a/core/sched/mem_iface.h b/core/sched/mem_iface.h index 05934b33..1b2e6531 100644 --- a/core/sched/mem_iface.h +++ b/core/sched/mem_iface.h @@ -173,6 +173,16 @@ struct IPrefixCache { /* Restores the pool could not hold whole (PrefixCache::Stats::restore_cuts). */ virtual int64_t restore_cuts() const { return 0; } virtual int64_t ckpt_expired() const { return 0; } + /* Entries and snapshots a client released on purpose (release_session). */ + virtual int64_t released() const { return 0; } + virtual int64_t ckpt_released() const { return 0; } + + /* Forget one stored conversation now, by the client's label or the engine's session id + * (PrefixCache::release_session). RAD_E_UNSUPPORTED from a cache without a session table. */ + virtual int release_session(const std::string& /*label*/, uint64_t /*id*/, + int64_t /*keep_tokens*/, SessionRelease* /*out*/) { + return RAD_E_UNSUPPORTED; + } /* Tokens of context held only by the cache right now. Blocks a running sequence also reads * are excluded. Separates a working cache from a leak in the pool figures. */ @@ -424,6 +434,12 @@ struct PCBinding final : IPrefixCache { int64_t expired() const override { return m->stats().expired; } int64_t restore_cuts() const override { return m->stats().restore_cuts; } int64_t ckpt_expired() const override { return m->stats().ckpt_expired; } + int64_t released() const override { return m->stats().released; } + int64_t ckpt_released() const override { return m->stats().ckpt_released; } + int release_session(const std::string& label, uint64_t id, int64_t keep_tokens, + SessionRelease* out) override { + return m->release_session(label, id, keep_tokens, out); + } int64_t held_tokens() const override { return m->unshared_tokens(); } int64_t next_checkpoint_after(int64_t p) const override { return m->next_checkpoint_after(p); } diff --git a/core/sched/metrics.h b/core/sched/metrics.h index a4aa80cf..1c808cfb 100644 --- a/core/sched/metrics.h +++ b/core/sched/metrics.h @@ -92,6 +92,7 @@ struct SchedMetrics { * and reservations that went without a snapshot. */ int64_t prefix_ckpt_retired = 0, prefix_ckpt_lru = 0, prefix_ckpt_refused = 0; int64_t prefix_expired = 0, prefix_ckpt_expired = 0; /* --prefix-cache-ttl */ + int64_t prefix_released = 0, prefix_ckpt_released = 0; /* DELETE /sessions */ /* Admissions whose attention hit was cut to nothing: no snapshot at or below it (recurrent * state or a window snapshot), a windowed trunk group no window snapshot covers, or blocks * that could not be adopted. `hit_cut_resumed_below` counts those that resumed at a diff --git a/core/sched/scheduler.cpp b/core/sched/scheduler.cpp index 7a5667db..aec80fef 100644 --- a/core/sched/scheduler.cpp +++ b/core/sched/scheduler.cpp @@ -385,6 +385,40 @@ int64_t Scheduler::reset_prefix_cache() { return dropped; } +int Scheduler::release_session(const std::string& label, uint64_t id, int64_t keep_tokens, + SessionRelease* out) { + std::lock_guard lk(mu_); + if (!pc_ || !cfg_.prefix_cache) return RAD_E_UNSUPPORTED; + if (label.empty() && id == 0) return RAD_E_INVAL; + for (const auto& p : reqs_) { + if (!p || !p->req) continue; + const Request& r = *p->req; + if (r.state == ReqState::Finished || r.state == ReqState::Failed || + r.state == ReqState::Cancelled) + continue; + if ((id != 0 && r.id == id) || (!label.empty() && r.session_label == label)) + return RAD_E_STATE; + } + const int rc = pc_->release_session(label, id, keep_tokens, out); + if (rc == RAD_OK && out) { + if (label.empty()) + RAD_INFO("prefix cache: session %llu released: %lld entries (%lld tokens), %lld " + "snapshots; kept %lld tokens as asked, %lld blocks shared, %lld live", + (unsigned long long)id, (long long)out->entries, (long long)out->tokens, + (long long)out->snapshots, (long long)out->kept_tokens, + (long long)out->kept_shared, (long long)out->kept_live); + else + RAD_INFO("prefix cache: session '%s' released (%lld rows): %lld entries (%lld " + "tokens), %lld snapshots; kept %lld tokens as asked, %lld blocks shared, " + "%lld live", + label.c_str(), (long long)out->sessions, (long long)out->entries, + (long long)out->tokens, (long long)out->snapshots, + (long long)out->kept_tokens, (long long)out->kept_shared, + (long long)out->kept_live); + } + return rc; +} + void Scheduler::trim_prefix_cache() { if (!pc_ || !cfg_.prefix_cache) return; const std::vector& cg = pc_->cached_groups(); @@ -2632,6 +2666,8 @@ SchedMetrics Scheduler::metrics_locked() const { m.prefix_expired = pc_->expired(); m.prefix_ckpt_expired = pc_->ckpt_expired(); m.prefix_restore_cuts = pc_->restore_cuts(); + m.prefix_released = pc_->released(); + m.prefix_ckpt_released = pc_->ckpt_released(); m.prefix_held_tokens = pc_->held_tokens(); } m.attn_hit_rate = m.prompt_tokens ? (float)((double)m.attn_cached_tokens / (double)m.prompt_tokens) : 0.0f; diff --git a/core/sched/scheduler.h b/core/sched/scheduler.h index d89c323e..9d46691a 100644 --- a/core/sched/scheduler.h +++ b/core/sched/scheduler.h @@ -254,6 +254,13 @@ public: * cache. Takes the step lock because the step path inserts into the map (live sequences hold * their own block references). See IScheduler::reset_prefix_cache. */ int64_t reset_prefix_cache(); + /* Forget one stored conversation, by label or engine id, keeping its first `keep_tokens` + * (IPrefixCache::release_session). Refused with RAD_E_STATE while a request of that + * conversation is queued or running: its blocks would be skipped as live and its close + * would publish the chain again, so the release would be half done and undone at once. + * Takes the step lock like reset_prefix_cache. */ + int release_session(const std::string& label, uint64_t id, int64_t keep_tokens, + SessionRelease* out); /* ---------------------------------------------------------- the step path */ /* One decision, one batch. Null when there is nothing to run, which is not an error. */ diff --git a/core/server/adapters.h b/core/server/adapters.h index a624d5e7..440f19bd 100644 --- a/core/server/adapters.h +++ b/core/server/adapters.h @@ -107,6 +107,8 @@ inline SchedMetrics bridge_metrics(const rad::SchedMetrics& m) { o.hit_cut_tokens = m.hit_cut_tokens; o.prefix_expired = m.prefix_expired; o.prefix_ckpt_expired = m.prefix_ckpt_expired; + o.prefix_released = m.prefix_released; + o.prefix_ckpt_released = m.prefix_ckpt_released; o.prefill_tps = m.prefill_tps; o.decode_tps = m.decode_tps; @@ -202,6 +204,24 @@ public: int64_t reset_prefix_cache() override { return s_->reset_prefix_cache(); } + int release_session(const std::string& label, uint64_t id, int64_t keep_tokens, + SessionReleased* out) override { + SessionRelease r; + const int rc = s_->release_session(label, id, keep_tokens, &r); + if (out) { + out->sessions = r.sessions; + out->entries = r.entries; + out->tokens = r.tokens; + out->device_bytes = r.device_bytes; + out->host_bytes = r.host_bytes; + out->snapshots = r.snapshots; + out->kept_tokens = r.kept_tokens; + out->kept_shared = r.kept_shared; + out->kept_live = r.kept_live; + } + return rc; + } + /* The stored conversations. The tiers keep monotonic timestamps; idle and age are converted * to "seconds ago" here, so only the monotonic clock is authoritative. */ TierCounters tier_counters() const override { diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index 53b976ba..bdd6dc40 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -138,6 +138,8 @@ HttpResponse Server::handle_sessions(const HttpRequest&) { o["snapshot_store"] = { { "bytes_each", c.ck_bytes }, { "slots", c.ck_slots } }; /* Entries and snapshots removed by --prefix-cache-ttl, from whichever tier held them. */ o["expired"] = { { "entries", sm.prefix_expired }, { "snapshots", sm.prefix_ckpt_expired } }; + /* And the ones a client gave up on purpose (DELETE /sessions). */ + o["released"] = { { "entries", sm.prefix_released }, { "snapshots", sm.prefix_ckpt_released } }; /* Step-thread time spent on tier moves; every request waits through it. */ o["stall"] = { { "restores", c.restores }, { "restore_ms", (double)c.restore_ns / 1e6 }, { "flushes", c.flushes }, { "flush_ms", (double)c.flush_ns / 1e6 } }; @@ -167,6 +169,83 @@ HttpResponse Server::handle_sessions(const HttpRequest&) { return HttpResponse::json_body(200, json_dump(o)); } +/* ------------------------------------------------------------------ DELETE /sessions + * + * A client that deletes a conversation, or replaces everything past a prefix of it, knows the + * rest is dead before the TTL does. Named by the label it sent (`session_id`, or Anthropic's + * `metadata.user_id`), or by the engine id `/sessions` shows. `keep_tokens` keeps the chain's + * start. Shared blocks and blocks a live request reads stay; a request of the same conversation + * in flight is a 409, since its close would publish the chain again. */ +HttpResponse Server::handle_session_release(const HttpRequest& req) { + if (!deps_.sched) + return error_response(err_not_implemented("the server has no engine attached"), req.peer); + + const std::string label = req.param("label"); + uint64_t id = 0; + const std::string id_s = req.param("id"); + if (!id_s.empty()) { + if (id_s.find_first_not_of("0123456789") != std::string::npos || id_s.size() > 19) + return error_response(err_bad("id", "expected the session's engine id, a decimal " + "integer as /sessions reports it"), req.peer); + id = std::stoull(id_s); + if (id == 0) return error_response(err_bad("id", "0 names no session"), req.peer); + } + if (label.empty() && id == 0) + return error_response(err_bad("label", "name the session: DELETE /sessions/