Archived
server: DELETE /sessions forgets one stored conversation
A client that deleted a conversation, or compacted it past a prefix, knows the
rest is dead before --prefix-cache-ttl does. DELETE /sessions/<label> (or
?label=, ?id=<engine id>) walks the session's chain from the tip inwards like
expiry: VRAM blocks to the pool, the host copy with them, the session's
snapshots to the store. ?keep_tokens=N keeps the chain's start in whole blocks.
Blocks another stored session shares (the system prompt) and blocks a live
request reads stay and are counted apart; the row is cut at the deepest block
that stayed, so a later release reaches it. A request of the same conversation
in flight is 409. IScheduler::release_session beside reset_prefix_cache,
PrefixCache::release_session over the tiers' session table (find_sessions,
shared_prefix_blocks, cut_session). Counters released{entries,snapshots} on
/sessions and /stats, prefix_cache_released_total{what} on /metrics.
This commit is contained in:
1 parent
123c439684
commit
3aded1bbf8
20 files changed
+722
-2
No files matched your search
@@ -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<SessionChain>* 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<BlockHash>& chain,
|
||||
const std::vector<uint64_t>& 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<BlockHash>& 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::SessionInfo> IdleTiers::sessions(Occupancy* occ) const {
|
||||
/* One slice's hold on the lock (YieldingMutex). */
|
||||
struct Slice {
|
||||
|
||||
@@ -246,6 +246,31 @@ public:
|
||||
* microseconds apart. */
|
||||
std::vector<SessionInfo> 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<BlockHash> 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<SessionChain>* 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<BlockHash>& chain,
|
||||
const std::vector<uint64_t>& 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. */
|
||||
|
||||
@@ -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<IdleTiers::SessionChain> rows;
|
||||
tiers_->find_sessions(label, id, &rows);
|
||||
if (rows.empty()) return RAD_E_NOTFOUND;
|
||||
std::vector<uint64_t> 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<int64_t>(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 */
|
||||
@@ -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_; }
|
||||
|
||||
|
||||
@@ -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); }
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<std::mutex> 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<int32_t>& 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;
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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/<label>, "
|
||||
"?label=<label> or ?id=<engine id>"), req.peer);
|
||||
int64_t keep_tokens = 0;
|
||||
const std::string keep_s = req.param("keep_tokens");
|
||||
if (!keep_s.empty()) {
|
||||
if (keep_s.find_first_not_of("0123456789") != std::string::npos || keep_s.size() > 12)
|
||||
return error_response(err_bad("keep_tokens", "expected a non-negative integer: the "
|
||||
"prefix to keep, in tokens"), req.peer);
|
||||
keep_tokens = std::stoll(keep_s);
|
||||
}
|
||||
|
||||
SessionReleased r;
|
||||
const int rc = deps_.sched->release_session(label, id, keep_tokens, &r);
|
||||
if (rc == RAD_E_UNSUPPORTED)
|
||||
return error_response(err_not_implemented(
|
||||
"this engine has no prefix cache (started with --no-prefix-cache, or the model "
|
||||
"declares no cacheable KV group)"), req.peer);
|
||||
const std::string who = label.empty() ? "id " + std::to_string(id) : "'" + label + "'";
|
||||
if (rc == RAD_E_NOTFOUND) {
|
||||
ApiError e;
|
||||
e.status = 404;
|
||||
e.type = "not_found_error";
|
||||
e.param = label.empty() ? "id" : "label";
|
||||
e.message = "no stored session " + who + "; GET /sessions lists them";
|
||||
return error_response(e, req.peer);
|
||||
}
|
||||
if (rc == RAD_E_STATE) {
|
||||
ApiError e;
|
||||
e.status = 409;
|
||||
e.type = "conflict_error";
|
||||
e.code = "session_in_use";
|
||||
e.message = "a request of session " + who + " is queued or running; cancel it or wait "
|
||||
"for it to finish, then release again";
|
||||
return error_response(e, req.peer);
|
||||
}
|
||||
if (rc == RAD_E_INVAL)
|
||||
return error_response(err_bad("keep_tokens", rad_strerror(rc)), req.peer);
|
||||
if (rc < 0) return error_response(err_internal(rad_strerror(rc)), req.peer);
|
||||
|
||||
json o;
|
||||
if (!label.empty()) o["label"] = label;
|
||||
if (id != 0) o["id"] = id;
|
||||
o["keep_tokens"] = keep_tokens;
|
||||
o["sessions"] = r.sessions;
|
||||
o["entries"] = r.entries;
|
||||
o["tokens"] = r.tokens;
|
||||
o["device_bytes"] = r.device_bytes;
|
||||
o["host_bytes"] = r.host_bytes;
|
||||
o["snapshots"] = r.snapshots;
|
||||
o["kept"] = { { "tokens", r.kept_tokens }, { "shared", r.kept_shared },
|
||||
{ "live", r.kept_live } };
|
||||
metrics_.observe_http(200);
|
||||
return HttpResponse::json_body(200, json_dump(o));
|
||||
}
|
||||
|
||||
HttpResponse Server::handle_stats(const HttpRequest&) {
|
||||
json o;
|
||||
o["model"] = opt_.model_id;
|
||||
@@ -222,6 +301,8 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
|
||||
o["ckpt_evictions"] = { { "retention", m.prefix_ckpt_retired },
|
||||
{ "store_full", m.prefix_ckpt_lru } };
|
||||
o["ckpt_refused"] = m.prefix_ckpt_refused;
|
||||
o["released"] = { { "entries", m.prefix_released },
|
||||
{ "snapshots", m.prefix_ckpt_released } };
|
||||
o["hit_cuts"] = { { "no_snapshot", m.hit_cut_no_snapshot },
|
||||
{ "windowed_group", m.hit_cut_window },
|
||||
{ "adopt_failed", m.hit_cut_adopt },
|
||||
|
||||
@@ -78,6 +78,7 @@ struct SchedMetrics {
|
||||
int64_t prefix_restore_cuts = 0;
|
||||
/* Removed by --prefix-cache-ttl, cumulative. Not evictions: nothing wanted the memory. */
|
||||
int64_t prefix_expired = 0, prefix_ckpt_expired = 0;
|
||||
int64_t prefix_released = 0, prefix_ckpt_released = 0;
|
||||
/* Decoupled prefix caching (spec §7.3). `prefix_hit_rate` is the attention hit rate, as in
|
||||
* vLLM. The linear side hits at a different granularity (whole checkpoints, not blocks), so
|
||||
* it is reported separately, with token counts and checkpoints written. */
|
||||
@@ -168,6 +169,17 @@ struct SessionOccupancy {
|
||||
int64_t host_cap_bytes = 0;
|
||||
};
|
||||
|
||||
/* What a release took out of the store and what it left (PrefixCache::release_session). The
|
||||
* kept counts are apart on purpose: `shared` blocks belong to another stored conversation too,
|
||||
* `live` ones to a request still reading them. */
|
||||
struct SessionReleased {
|
||||
int64_t sessions = 0;
|
||||
int64_t entries = 0, tokens = 0;
|
||||
int64_t device_bytes = 0, host_bytes = 0;
|
||||
int64_t snapshots = 0;
|
||||
int64_t kept_tokens = 0, kept_shared = 0, kept_live = 0;
|
||||
};
|
||||
|
||||
/* One in-flight request, for the live request table: shows which request is stuck, e.g. one
|
||||
* waiting on a prompt that will never fit, which no aggregate metric reveals. */
|
||||
struct RequestStat {
|
||||
@@ -225,6 +237,15 @@ public:
|
||||
* allocated), but it takes the scheduler's lock because a step may be inserting into the map. */
|
||||
virtual int64_t reset_prefix_cache() { return RAD_E_UNSUPPORTED; }
|
||||
|
||||
/* Forgets one stored conversation (DELETE /sessions): every row carrying `label`, or with
|
||||
* `id` nonzero the row of that engine id; `keep_tokens` leaves the chain's start standing.
|
||||
* RAD_E_NOTFOUND when nothing matches (404), RAD_E_STATE while a request of that
|
||||
* conversation is queued or running (409), RAD_E_UNSUPPORTED without a prefix cache (501). */
|
||||
virtual int release_session(const std::string& /*label*/, uint64_t /*id*/,
|
||||
int64_t /*keep_tokens*/, SessionReleased* /*out*/) {
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* The live request table, oldest first; returns the count. Default: none kept. */
|
||||
virtual int requests(std::vector<RequestStat>* /*out*/) const { return 0; }
|
||||
|
||||
|
||||
@@ -190,6 +190,8 @@ void Metrics::sample(const SchedMetrics& m) {
|
||||
c_prefix_ckpt_evict_.advance_to(m.prefix_ckpt_evictions);
|
||||
c_prefix_expired_.advance_to(m.prefix_expired);
|
||||
c_prefix_ckpt_expired_.advance_to(m.prefix_ckpt_expired);
|
||||
c_prefix_released_.advance_to(m.prefix_released);
|
||||
c_prefix_ckpt_released_.advance_to(m.prefix_ckpt_released);
|
||||
c_ckpt_retired_.advance_to(m.prefix_ckpt_retired);
|
||||
c_ckpt_lru_.advance_to(m.prefix_ckpt_lru);
|
||||
c_ckpt_refused_.advance_to(m.prefix_ckpt_refused);
|
||||
@@ -447,6 +449,13 @@ std::string Metrics::render() const {
|
||||
c_ckpt_retired_.get());
|
||||
labelled("radiance:prefix_cache_ckpt_evictions_by_reason_total", "reason", "store_full",
|
||||
c_ckpt_lru_.get());
|
||||
w.help("radiance:prefix_cache_released_total",
|
||||
"Prefix-cache entries and linear-state snapshots a client released on purpose "
|
||||
"(DELETE /sessions).", "counter");
|
||||
labelled("radiance:prefix_cache_released_total", "what", "entries",
|
||||
c_prefix_released_.get());
|
||||
labelled("radiance:prefix_cache_released_total", "what", "snapshots",
|
||||
c_prefix_ckpt_released_.get());
|
||||
w.counter("radiance:prefix_cache_ckpt_refused_total",
|
||||
"Checkpoints not written because every snapshot slot was in use by a restore "
|
||||
"in the same step.", L, c_ckpt_refused_.get());
|
||||
|
||||
@@ -152,6 +152,7 @@ private:
|
||||
Counter c_attn_cached_, c_linear_cached_, c_checkpoints_;
|
||||
Counter c_prefix_evict_, c_prefix_ckpt_evict_;
|
||||
Counter c_prefix_expired_, c_prefix_ckpt_expired_;
|
||||
Counter c_prefix_released_, c_prefix_ckpt_released_;
|
||||
Counter c_ckpt_retired_, c_ckpt_lru_, c_ckpt_refused_;
|
||||
Counter c_cut_no_snapshot_, c_cut_window_, c_cut_adopt_, c_cut_resumed_below_, c_cut_tokens_;
|
||||
Counter c_restore_cuts_;
|
||||
|
||||
@@ -210,6 +210,12 @@ void Server::register_routes() {
|
||||
[this](const HttpRequest& q) { return handle_control_vector(q); });
|
||||
router_.post("/admin/control-vector",
|
||||
[this](const HttpRequest& q) { return handle_control_vector(q); });
|
||||
/* Forget one stored conversation: by its client label in the path (or `?label=`, for a
|
||||
* label the path cannot carry), or by engine id with `?id=`. */
|
||||
router_.add ("DELETE", "/sessions/:label",
|
||||
[this](const HttpRequest& q) { return handle_session_release(q); });
|
||||
router_.add ("DELETE", "/sessions",
|
||||
[this](const HttpRequest& q) { return handle_session_release(q); });
|
||||
}
|
||||
|
||||
/* Workers beyond the admission ceiling. A generation holds its connection's worker for its whole
|
||||
|
||||
@@ -329,6 +329,7 @@ private:
|
||||
* {"enabled": bool} sets the default for requests that name no choice. Guarded by the API key
|
||||
* like every other route but the health probes and the page. */
|
||||
HttpResponse handle_control_vector(const HttpRequest& req);
|
||||
HttpResponse handle_session_release(const HttpRequest& req);
|
||||
|
||||
HttpResponse error_response(const ApiError& e, const std::string& peer,
|
||||
ApiShape shape = ApiShape::OpenAI);
|
||||
|
||||
+25
-2
@@ -1214,6 +1214,26 @@ whichever tier holds it (VRAM blocks to the pool, host slot to the arena, snapsh
|
||||
hit or a new turn counts as a use, and a system prompt shared by several conversations stays while
|
||||
any of them is used.
|
||||
|
||||
A client that knows a conversation is dead need not wait for the TTL: `DELETE /sessions/<label>`
|
||||
forgets it now, with `<label>` the `session_id` (or Anthropic `metadata.user_id`) its requests
|
||||
carried, or `DELETE /sessions?id=<id>` by the engine id `GET /sessions` lists (`?label=` works for
|
||||
a label the path cannot carry). `?keep_tokens=N` keeps the first N tokens of the chain, rounded up
|
||||
to whole blocks, for a client that replaced everything past a prefix (a compaction) and wants the
|
||||
prefix to keep hitting. The chain goes from the tip inwards like expiry, host copy and the
|
||||
session's snapshots with it; a block another stored conversation also walks (the shared system
|
||||
prompt) stays, as does one a running request reads. A request of the same conversation in flight
|
||||
is refused with 409: finish or cancel it first. The answer says what went and what stayed:
|
||||
|
||||
```json
|
||||
{"label":"chat-7","keep_tokens":0,"sessions":1,"entries":2048,"tokens":32768,
|
||||
"device_bytes":417792000,"host_bytes":835584000,"snapshots":6,
|
||||
"kept":{"tokens":0,"shared":64,"live":0}}
|
||||
```
|
||||
|
||||
An unknown label or id is 404; an engine without a prefix cache answers 501. `/sessions` and
|
||||
`/stats` count what was released under `released`, `/metrics` as
|
||||
`prefix_cache_released_total{what}`.
|
||||
|
||||
```sh
|
||||
radiance --model m.rad --prefix-cache-mib 8192 --prefix-cache-ttl 3600
|
||||
```
|
||||
@@ -1787,6 +1807,7 @@ flags are refused on it, and so are the pixel bands.
|
||||
| `POST /tokenize`, `POST /detokenize` | vLLM's shape (`prompt` or `messages` in, `prompt` out) and llama-server's (`content` in and out, `with_pieces`) |
|
||||
| `GET /get_tokenizer_info` | the tokeniser's configuration |
|
||||
| `POST /reset_prefix_cache` | drop every cached prefix |
|
||||
| `DELETE /sessions/<label>`, `DELETE /sessions?id=<id>` | forget one stored conversation (§4.8) |
|
||||
| `GET /` or `/dashboard` | the web dashboard |
|
||||
| `GET /stats`, `/graph`, `/sessions` | the JSON the dashboard is drawn from |
|
||||
|
||||
@@ -2134,7 +2155,7 @@ passes but not launches (the UNet runs once per image and branch), so two take t
|
||||
| `stream`, `stream_options.include_usage` | |
|
||||
| `timings_per_token`, `return_progress` | llama-server's: `timings` on every chunk, and `prompt_progress` chunks while the prompt is read |
|
||||
| `samplers` | llama-server's sampler order, names or letters. A stage it leaves out is off. The chain here is penalties, DRY, top-k, top-p, min-p, typical, XTC, with temperature first (the default) or last (llama-server's default), so a list in either order is honoured and any other is refused by name |
|
||||
| `session_id` | OpenRouter's conversation id: labels the conversation on `/sessions` and the dashboard |
|
||||
| `session_id` | OpenRouter's conversation id: labels the conversation on `/sessions` and the dashboard, and names it for `DELETE /sessions/<label>` (§4.8) |
|
||||
| `control_vector` | `true` applies the control vector this deployment found to this request's steps, `false` leaves them on the stock model; absent takes the deployment's runtime default (off unless flipped in the dashboard's Model view). `experimental_speed_projection` is Strata's spelling of the same field and is accepted as an alias. A deployment with no vector refuses `true` by name. On a compatible container (Qwen3.8-Flash-Next), a refusal-direction vector makes the model decline far fewer requests -- that is a safety behaviour removed, and you own what it writes (§4.10, "Control vectors") |
|
||||
| `logprobs`, `top_logprobs`, `n_probs` | each generated token's logprob and up to 20 alternatives (§5.12). Chat: `logprobs: true` with `top_logprobs` alternatives (0 when absent); completions: `logprobs: N`; any endpoint: llama-server's `n_probs: N`, which wins. Not with `echo` (the prompt's logprobs are not computed) |
|
||||
| `tools`, `tool_choice`, `parallel_tool_calls` | chat only. `tool_choice` is `auto`, `none`, `required` or `{"type":"function","function":{"name":...}}`; the last two hold the whole reply to calls (after the reasoning block), the named form to that one function, and cannot be combined with `response_format` or `grammar` |
|
||||
@@ -2338,7 +2359,7 @@ each field is read, taken without effect, or refused by name.
|
||||
| `output_config` | `effort` (`low`, `medium`, `high`, `xhigh`, `max`) is the chat request's `reasoning_effort`, which the template reads in its own level names: a level it does not take is refused with the ones it does, and `--reasoning-effort-map` renames them (§4.9). `format` (`{"type": "json_schema", "schema": ...}`, or the older top-level `output_format`) is a `response_format` (§5.5). `task_budget` is taken |
|
||||
| `context_management` | validated; the conversation is served as sent, and the answer says so: `"context_management": {"applied_edits": []}`, on `message_delta` in a stream |
|
||||
| `thread` | `create` is served as any request; `continue` is refused, since no conversation is stored |
|
||||
| `metadata` | `user_id` is the conversation's label on `/sessions` |
|
||||
| `metadata` | `user_id` is the conversation's label on `/sessions` and its name for `DELETE /sessions/<label>` (§4.8) |
|
||||
| `service_tier`, `inference_geo`, `speed`, `cache_control`, `diagnostics`, `safeguards`, `fallbacks`, `context_hint` | taken; none can change the answer here. `cache_control` on a block is dropped too |
|
||||
| `mcp_servers`, `container` | refused |
|
||||
| anything else | refused: `"<field>: Extra inputs are not permitted ..."`, Anthropic's own words, which Claude Code matches to retry without a beta field it can drop |
|
||||
@@ -2886,6 +2907,7 @@ scheduler clamps reuse to the last linear checkpoint. That verdict is the tab's
|
||||
```sh
|
||||
curl -s localhost:8000/stats | jq # counters, memory, throughput
|
||||
curl -s localhost:8000/sessions | jq # what is stored and where
|
||||
curl -s -X DELETE localhost:8000/sessions/chat-7 | jq # forget one stored conversation (§4.8)
|
||||
curl -s localhost:8000/graph | jq # the resolved kernel graph
|
||||
curl -s localhost:8000/server_info | jq # model, cards, KV, draft depth, wire
|
||||
curl -s localhost:8000/diagnostics | jq # the startup report, hardware read again now (§7.1)
|
||||
@@ -2933,6 +2955,7 @@ there is none.
|
||||
| `prefix_hit_cuts_total{reason}`, `prefix_hit_cut_tokens_total` | admissions whose hit reused nothing (`no_snapshot`, `windowed_group`, `adopt_failed`) or resumed at a snapshot more than one checkpoint interval below it (`resumed_below`), and the checkpoint shortfall: cached prompt tokens computed again because the hit resumed at a snapshot below it. `/stats` and `/sessions` carry the same counts; `RADIANCE_LOG=debug` logs each eviction and each cut hit |
|
||||
| `prefix_restore_cuts_total` | restores from the host tier the pool could not hold whole, even after giving up other conversations' VRAM copies (§4.8) |
|
||||
| `prefix_cache_expired_total`, `prefix_cache_ckpt_expired_total` | what `--prefix-cache-ttl` removed (§4.8) |
|
||||
| `prefix_cache_released_total{what}` | entries and snapshots clients forgot through `DELETE /sessions` (§4.8) |
|
||||
| `num_requests_preempted` | |
|
||||
| `http_queue_depth`, `http_responses_total`, `http_admission_rejected_total` | |
|
||||
| `client_disconnect_total`, `stream_overflow_total` | |
|
||||
|
||||
@@ -56,6 +56,23 @@ struct StatsScheduler : FakeScheduler {
|
||||
occ->host_cap_bytes = 64 << 20;
|
||||
return 1;
|
||||
}
|
||||
/* The one stored conversation is "conv-7" (engine id 7); "busy" has a request in flight. */
|
||||
std::vector<std::pair<std::string, int64_t>> released;
|
||||
int release_session(const std::string& label, uint64_t id, int64_t keep_tokens,
|
||||
SessionReleased* out) override {
|
||||
if (label == "busy") return RAD_E_STATE;
|
||||
if (label != "conv-7" && id != 7) return RAD_E_NOTFOUND;
|
||||
released.push_back({ label.empty() ? "id" : label, keep_tokens });
|
||||
out->sessions = 1;
|
||||
out->entries = 48 - keep_tokens / 16;
|
||||
out->tokens = out->entries * 16;
|
||||
out->device_bytes = out->entries * 4096;
|
||||
out->host_bytes = out->entries * 2048;
|
||||
out->snapshots = 2;
|
||||
out->kept_tokens = keep_tokens;
|
||||
out->kept_shared = 2;
|
||||
return RAD_OK;
|
||||
}
|
||||
TierCounters tier_counters() const override {
|
||||
TierCounters c;
|
||||
c.to_host = 3; c.dropped = 2; c.promoted = 1; c.host_drops = 4; c.failures = 0;
|
||||
@@ -246,6 +263,69 @@ TEST(sessions_lists_each_conversation_and_what_the_tiers_did) {
|
||||
CHECK_EQ(s["linear"].value("hit_cut_tokens", (int64_t)0), (int64_t)9000);
|
||||
}
|
||||
|
||||
/* DELETE /sessions forgets one stored conversation by its label or engine id and answers with
|
||||
* what went and what stayed; an unknown session is 404, one with a request in flight 409, a
|
||||
* malformed count 400, and an engine without a prefix cache 501. */
|
||||
TEST(a_session_is_released_by_label_or_id_and_the_answer_says_what_went) {
|
||||
Dash d(false);
|
||||
HttpResponse r = d.srv->router().call("DELETE", "/sessions/conv-7");
|
||||
CHECK_EQ(r.status, 200);
|
||||
json o = json::parse(r.body, nullptr, false);
|
||||
CHECK_EQ(o.value("label", ""), std::string("conv-7"));
|
||||
CHECK_EQ(o.value("entries", (int64_t)0), (int64_t)48);
|
||||
CHECK_EQ(o.value("tokens", (int64_t)0), (int64_t)768);
|
||||
CHECK_EQ(o.value("snapshots", (int64_t)0), (int64_t)2);
|
||||
CHECK_EQ(o["kept"].value("shared", (int64_t)0), (int64_t)2);
|
||||
CHECK_EQ(o["kept"].value("tokens", (int64_t)0), (int64_t)0);
|
||||
REQUIRE_EQ(d.sched.released.size(), 1u);
|
||||
CHECK_EQ(d.sched.released[0].second, (int64_t)0);
|
||||
|
||||
/* keep_tokens reaches the scheduler and comes back in the answer. */
|
||||
r = d.srv->router().call("DELETE", "/sessions/conv-7?keep_tokens=160");
|
||||
CHECK_EQ(r.status, 200);
|
||||
o = json::parse(r.body, nullptr, false);
|
||||
CHECK_EQ(o.value("keep_tokens", (int64_t)0), (int64_t)160);
|
||||
CHECK_EQ(o.value("entries", (int64_t)0), (int64_t)38);
|
||||
CHECK_EQ(o["kept"].value("tokens", (int64_t)0), (int64_t)160);
|
||||
REQUIRE_EQ(d.sched.released.size(), 2u);
|
||||
CHECK_EQ(d.sched.released[1].second, (int64_t)160);
|
||||
|
||||
/* By engine id, and by a label the path cannot carry. */
|
||||
r = d.srv->router().call("DELETE", "/sessions?id=7");
|
||||
CHECK_EQ(r.status, 200);
|
||||
o = json::parse(r.body, nullptr, false);
|
||||
CHECK_EQ(o.value("id", (int64_t)0), (int64_t)7);
|
||||
CHECK(!o.contains("label"));
|
||||
r = d.srv->router().call("DELETE", "/sessions?label=conv-7");
|
||||
CHECK_EQ(r.status, 200);
|
||||
|
||||
CHECK_EQ(d.srv->router().call("DELETE", "/sessions/conv-8").status, 404);
|
||||
CHECK_EQ(d.srv->router().call("DELETE", "/sessions?id=8").status, 404);
|
||||
CHECK_EQ(d.srv->router().call("DELETE", "/sessions/busy").status, 409);
|
||||
CHECK_EQ(d.srv->router().call("DELETE", "/sessions").status, 400);
|
||||
CHECK_EQ(d.srv->router().call("DELETE", "/sessions?id=seven").status, 400);
|
||||
CHECK_EQ(d.srv->router().call("DELETE", "/sessions/conv-7?keep_tokens=-1").status, 400);
|
||||
CHECK_EQ(d.sched.released.size(), 4u);
|
||||
|
||||
/* The stored-sessions view carries the counters beside the expiry ones. */
|
||||
const json s = d.get("/sessions");
|
||||
CHECK(s.contains("released"));
|
||||
CHECK(s["released"].contains("entries"));
|
||||
CHECK(s["released"].contains("snapshots"));
|
||||
}
|
||||
|
||||
TEST(a_session_release_without_a_prefix_cache_is_not_implemented) {
|
||||
FakeScheduler sched; /* the base: no release_session */
|
||||
FakeTokenizer tok;
|
||||
Deps dd;
|
||||
dd.sched = &sched;
|
||||
dd.tok = &tok;
|
||||
ServerOptions o;
|
||||
o.model_id = "dash";
|
||||
Server srv(dd, o);
|
||||
CHECK_EQ(srv.router().call("DELETE", "/sessions/conv-7").status, 501);
|
||||
}
|
||||
|
||||
/* ================================================================== the page's field contract */
|
||||
|
||||
/* Every field the page's script reads from /stats (in its update and the request table) and from
|
||||
|
||||
@@ -3234,6 +3234,188 @@ TEST(the_tiers_are_told_the_cache_s_block_ids_and_not_the_requests) {
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== release on request
|
||||
*
|
||||
* A client that deleted a conversation, or kept a prefix of it and replaced the rest, forgets it
|
||||
* through the session table: by label, from the tip inwards, host copy and snapshots with it.
|
||||
* What another conversation also walks stays, as does what a live sequence holds.
|
||||
*/
|
||||
|
||||
/* Publishes `tokens` under `id` with a session label, as the scheduler does at a turn's close,
|
||||
* and frees the sequence, as it does right after. */
|
||||
static void publish_turn(Fixture& f, uint64_t id, const std::vector<int32_t>& tokens,
|
||||
const std::string& label) {
|
||||
CHECK_OK(f.kv.add_sequence(id));
|
||||
CHECK_OK(f.kv.ensure(id, (int64_t)tokens.size()));
|
||||
std::vector<std::vector<int32_t>> bt;
|
||||
for (int32_t g : f.pc.cached_groups()) bt.push_back(f.kv.block_table(id, g));
|
||||
CHECK_OK(f.pc.insert(id, tokens, {}, bt, (int64_t)tokens.size(), label));
|
||||
f.kv.free_sequence(id);
|
||||
}
|
||||
|
||||
/* The label's rows in the session table. */
|
||||
static std::vector<IdleTiers::SessionInfo> rows_of(IdleTiers& t, const std::string& label) {
|
||||
std::vector<IdleTiers::SessionInfo> out;
|
||||
for (const IdleTiers::SessionInfo& s : t.sessions())
|
||||
if (s.label == label) out.push_back(s);
|
||||
return out;
|
||||
}
|
||||
|
||||
TEST(a_released_conversation_goes_from_the_tip_down_to_what_another_one_shares) {
|
||||
Fixture f;
|
||||
CHECK_OK(f.build(/*with_linear=*/false, /*ckpt_slots=*/0));
|
||||
IdleTiers t;
|
||||
CHECK_OK(t.configure(tier_config(1 << 20, 1024)));
|
||||
f.pc.set_tiers(&t);
|
||||
|
||||
/* Conversation A over three turns under three request ids: each turn extends the last. The
|
||||
* first two blocks are a system prompt conversation B opens with too. */
|
||||
const auto a1 = tok_run(100, 64); /* 4 blocks */
|
||||
auto a2 = a1; for (int i = 0; i < 32; ++i) a2.push_back(700 + i); /* 6 */
|
||||
auto a3 = a2; for (int i = 0; i < 32; ++i) a3.push_back(800 + i); /* 8 */
|
||||
publish_turn(f, 1, a1, "chat-a");
|
||||
publish_turn(f, 2, a2, "chat-a");
|
||||
publish_turn(f, 3, a3, "chat-a");
|
||||
auto b = tok_run(100, 32); for (int i = 0; i < 64; ++i) b.push_back(900 + i); /* 6 */
|
||||
publish_turn(f, 4, b, "chat-b");
|
||||
CHECK_EQ(f.pc.size(), 12ll); /* 8 + 4 own blocks of B */
|
||||
REQUIRE_EQ(rows_of(t, "chat-a").size(), 1u); /* one row per conversation */
|
||||
CHECK_EQ(rows_of(t, "chat-a")[0].n_tokens, 128ll);
|
||||
/* Every entry has its host copy. */
|
||||
copy_now(t);
|
||||
CHECK_EQ(t.arena().used_slots(), 12);
|
||||
const int64_t pool_before = f.kv.free_blocks(G_FULL);
|
||||
|
||||
SessionRelease r;
|
||||
CHECK_EQ(f.pc.release_session("chat-c", 0, 0, &r), RAD_E_NOTFOUND);
|
||||
CHECK_EQ(f.pc.release_session("", 0, 0, &r), RAD_E_INVAL);
|
||||
|
||||
CHECK_OK(f.pc.release_session("chat-a", 0, 0, &r));
|
||||
CHECK_EQ(r.sessions, 1ll);
|
||||
CHECK_EQ(r.entries, 6ll); /* 8 less the 2 B walks too */
|
||||
CHECK_EQ(r.tokens, 96ll);
|
||||
CHECK_EQ(r.kept_shared, 2ll);
|
||||
CHECK_EQ(r.kept_live, 0ll);
|
||||
CHECK_EQ(r.kept_tokens, 0ll);
|
||||
CHECK(r.device_bytes > 0);
|
||||
CHECK_EQ(r.host_bytes, 6 * 1024ll);
|
||||
/* Pool and arena got the six back; the index holds B's chain and the shared start. */
|
||||
CHECK_EQ(f.kv.free_blocks(G_FULL), pool_before + 6);
|
||||
CHECK_EQ(t.arena().used_slots(), 6);
|
||||
CHECK_EQ(f.pc.size(), 6ll);
|
||||
CHECK_EQ(f.pc.stats().released, 6ll);
|
||||
/* A's next turn hits the shared system prompt and nothing more; B is whole. */
|
||||
CHECK_EQ(f.pc.lookup(a3, {}).n_attn_tokens, 32);
|
||||
CHECK_EQ(f.pc.lookup(b, {}).n_attn_tokens, 80);
|
||||
CHECK_EQ(rows_of(t, "chat-a").size(), 0u);
|
||||
REQUIRE_EQ(rows_of(t, "chat-b").size(), 1u);
|
||||
CHECK_EQ(rows_of(t, "chat-b")[0].n_tokens, 96ll);
|
||||
|
||||
/* Released twice is not found the second time. */
|
||||
CHECK_EQ(f.pc.release_session("chat-a", 0, 0, &r), RAD_E_NOTFOUND);
|
||||
}
|
||||
|
||||
TEST(keep_tokens_leaves_the_chains_start_standing_in_whole_blocks) {
|
||||
Fixture f;
|
||||
CHECK_OK(f.build(/*with_linear=*/false, /*ckpt_slots=*/0));
|
||||
IdleTiers t;
|
||||
CHECK_OK(t.configure(tier_config(1 << 20, 1024)));
|
||||
f.pc.set_tiers(&t);
|
||||
|
||||
auto b = tok_run(100, 32); for (int i = 0; i < 64; ++i) b.push_back(900 + i); /* 6 blocks */
|
||||
publish_turn(f, 4, b, "chat-b");
|
||||
|
||||
/* 40 tokens keep three blocks: the one holding token 40 goes with them. */
|
||||
SessionRelease r;
|
||||
CHECK_OK(f.pc.release_session("chat-b", 0, 40, &r));
|
||||
CHECK_EQ(r.entries, 3ll);
|
||||
CHECK_EQ(r.kept_tokens, 48ll);
|
||||
CHECK_EQ(r.kept_shared, 0ll);
|
||||
CHECK_EQ(f.pc.lookup(b, {}).n_attn_tokens, 48);
|
||||
/* The row stays, cut to the kept prefix: the client extends it again. */
|
||||
REQUIRE_EQ(rows_of(t, "chat-b").size(), 1u);
|
||||
CHECK_EQ(rows_of(t, "chat-b")[0].n_tokens, 48ll);
|
||||
const uint64_t id = rows_of(t, "chat-b")[0].id;
|
||||
|
||||
/* The same by engine id, keeping more than is left: nothing goes, nothing breaks. */
|
||||
CHECK_OK(f.pc.release_session("", id, 200, &r));
|
||||
CHECK_EQ(r.entries, 0ll);
|
||||
CHECK_EQ(r.kept_tokens, 48ll);
|
||||
CHECK_EQ(f.pc.lookup(b, {}).n_attn_tokens, 48);
|
||||
|
||||
/* A later turn extends the stub into a full row again. */
|
||||
publish_turn(f, 5, b, "chat-b");
|
||||
REQUIRE_EQ(rows_of(t, "chat-b").size(), 1u);
|
||||
CHECK_EQ(rows_of(t, "chat-b")[0].n_tokens, 96ll);
|
||||
CHECK_EQ(f.pc.lookup(b, {}).n_attn_tokens, 80);
|
||||
}
|
||||
|
||||
TEST(a_release_takes_the_sessions_snapshots_past_the_kept_prefix_and_leaves_live_blocks) {
|
||||
Fixture f;
|
||||
CHECK_OK(f.build(/*with_linear=*/true, /*ckpt_slots=*/4));
|
||||
IdleTiers t;
|
||||
IdleTiers::Config tc = tier_config(1 << 20, 1024);
|
||||
tc.ckpt_bytes = f.kv.checkpoint_bytes();
|
||||
tc.ckpt_slots = 4;
|
||||
CHECK_OK(t.configure(tc));
|
||||
f.pc.set_tiers(&t);
|
||||
|
||||
const auto a = tok_run(100, 128); /* 8 blocks, checkpoints at 64, 128 */
|
||||
const std::vector<BlockHash> hs = chain_of(a);
|
||||
CHECK_OK(f.kv.add_sequence(3));
|
||||
CHECK_OK(f.kv.ensure(3, 128));
|
||||
ckpt_at(f, 3, hs, 64);
|
||||
ckpt_at(f, 3, hs, 128);
|
||||
f.pc.begin_step();
|
||||
{
|
||||
std::vector<std::vector<int32_t>> bt;
|
||||
for (int32_t g : f.pc.cached_groups()) bt.push_back(f.kv.block_table(3, g));
|
||||
CHECK_OK(f.pc.insert(3, a, {}, bt, 128, "chat-a"));
|
||||
}
|
||||
f.kv.free_sequence(3);
|
||||
CHECK_EQ(f.kv.free_checkpoint_slots(), 2ll);
|
||||
CHECK_EQ(rows_of(t, "chat-a")[0].snapshots, 2ll);
|
||||
|
||||
/* A waiting request restored the chain and holds it; a running one adopted the first
|
||||
* five blocks. Both keep their blocks through a release. */
|
||||
std::vector<std::vector<int32_t>> found;
|
||||
const CacheHit h = f.pc.lookup(a, {}, &found);
|
||||
CHECK_EQ(h.n_attn_tokens, 112);
|
||||
CHECK_OK(f.kv.add_sequence(9));
|
||||
std::vector<int32_t> five(found[0].begin(), found[0].begin() + 5);
|
||||
CHECK_OK(f.kv.adopt(9, f.pc.cached_groups()[0], five, 80));
|
||||
f.pc.begin_step();
|
||||
|
||||
SessionRelease r;
|
||||
CHECK_OK(f.pc.release_session("chat-a", 0, 64, &r));
|
||||
/* Blocks 4..7 are past the kept 64 tokens; block 4 is live, 5..7 go. */
|
||||
CHECK_EQ(r.entries, 3ll);
|
||||
CHECK_EQ(r.kept_live, 1ll);
|
||||
CHECK_EQ(r.kept_tokens, 64ll);
|
||||
/* The snapshot at 128 sat on block 7 and went with it; the one at 64 is on the kept prefix. */
|
||||
CHECK_EQ(r.snapshots, 1ll);
|
||||
CHECK_EQ(f.kv.free_checkpoint_slots(), 3ll);
|
||||
const std::vector<int64_t> left = f.pc.checkpoints(3);
|
||||
REQUIRE_EQ(left.size(), 1u);
|
||||
CHECK_EQ(left[0], 64ll);
|
||||
CHECK_EQ(f.pc.stats().ckpt_released, 1ll);
|
||||
/* The live block is still indexed and the sequence still reads it; the row reaches it. */
|
||||
CHECK_EQ(f.kv.block_refcount(G_FULL, five[4]), 2);
|
||||
REQUIRE_EQ(rows_of(t, "chat-a").size(), 1u);
|
||||
CHECK_EQ(rows_of(t, "chat-a")[0].n_tokens, 80ll);
|
||||
CHECK_EQ(f.pc.lookup(a, {}).n_attn_tokens, 80);
|
||||
CHECK_EQ(f.pc.lookup(a, {}).n_linear_tokens, 64);
|
||||
|
||||
/* The sequence is gone: the block it held goes on the next release. */
|
||||
f.kv.free_sequence(9);
|
||||
CHECK_OK(f.pc.release_session("chat-a", 0, 64, &r));
|
||||
CHECK_EQ(r.entries, 1ll);
|
||||
CHECK_EQ(r.kept_live, 0ll);
|
||||
CHECK_EQ(f.pc.lookup(a, {}).n_attn_tokens, 64);
|
||||
CHECK_EQ(f.pc.lookup(a, {}).n_linear_tokens, 64);
|
||||
CHECK_EQ(rows_of(t, "chat-a")[0].n_tokens, 64ll);
|
||||
}
|
||||
|
||||
/* ================================================================== the pool in bytes
|
||||
*
|
||||
* Blocks and tokens cannot be summed across KV groups: a recurrent group has no token axis and
|
||||
|
||||
@@ -424,6 +424,16 @@ struct FakePC : IPrefixCache {
|
||||
std::vector<uint64_t> holds, releases;
|
||||
void hold(const Request& r) override { holds.push_back(r.id); }
|
||||
void release(const Request& r) override { releases.push_back(r.id); }
|
||||
/* What the scheduler asked to be released, recorded; the answer is canned. */
|
||||
struct Released { std::string label; uint64_t id; int64_t keep_tokens; };
|
||||
std::vector<Released> released_calls;
|
||||
int release_rc = RAD_OK;
|
||||
int release_session(const std::string& label, uint64_t id, int64_t keep_tokens,
|
||||
SessionRelease* out) override {
|
||||
released_calls.push_back({ label, id, keep_tokens });
|
||||
if (out) { *out = SessionRelease{}; out->sessions = 1; out->entries = 5; out->tokens = 80; }
|
||||
return release_rc;
|
||||
}
|
||||
/* What the reserve asked for, call by call. */
|
||||
std::vector<int64_t> trims;
|
||||
int64_t trim(int64_t n) override {
|
||||
|
||||
@@ -1265,6 +1265,49 @@ TEST(cancellation_frees_blocks_immediately) {
|
||||
CHECK_EQ((int)f.sch.find(b)->state, (int)ReqState::Cancelled);
|
||||
}
|
||||
|
||||
/* A release of a conversation with a request of it in flight is refused, whether that request
|
||||
* is queued or running: the cache would skip its blocks as live and the request's close would
|
||||
* publish the whole chain again, so the client would have been told of a release that did not
|
||||
* happen. Once the request is gone the release reaches the cache with what the client asked. */
|
||||
TEST(a_session_release_waits_for_the_conversations_own_request) {
|
||||
Fixture f;
|
||||
f.build(/*blocks=*/40, /*states=*/64);
|
||||
CHECK_OK(f.start());
|
||||
|
||||
auto r = f.request(160, 64);
|
||||
r->session_label = "chat-7";
|
||||
const uint64_t a = f.add(std::move(r));
|
||||
CHECK(a != 0);
|
||||
|
||||
SessionRelease out;
|
||||
/* Queued, not yet admitted. */
|
||||
CHECK_EQ(f.sch.release_session("chat-7", 0, 0, &out), RAD_E_STATE);
|
||||
CHECK_EQ(f.sch.release_session("", a, 0, &out), RAD_E_STATE);
|
||||
CHECK_EQ(f.pc.released_calls.size(), 0u);
|
||||
|
||||
/* Running. */
|
||||
CHECK(f.sch.step() != nullptr);
|
||||
f.commit_plain();
|
||||
CHECK_EQ(f.sch.release_session("chat-7", 0, 32, &out), RAD_E_STATE);
|
||||
/* Another conversation is not in its way. */
|
||||
CHECK_OK(f.sch.release_session("chat-8", 0, 0, &out));
|
||||
REQUIRE_EQ(f.pc.released_calls.size(), 1u);
|
||||
CHECK(f.pc.released_calls[0].label == "chat-8");
|
||||
|
||||
/* Finished: the release goes through with label, id and the kept prefix as given. */
|
||||
CHECK_OK(f.sch.cancel(a));
|
||||
CHECK_OK(f.sch.reap(a));
|
||||
CHECK_OK(f.sch.release_session("chat-7", 0, 48, &out));
|
||||
REQUIRE_EQ(f.pc.released_calls.size(), 2u);
|
||||
CHECK(f.pc.released_calls[1].label == "chat-7");
|
||||
CHECK_EQ(f.pc.released_calls[1].keep_tokens, 48ll);
|
||||
CHECK_EQ(out.entries, 5ll);
|
||||
|
||||
/* Nothing named is a bad request, not a cache call. */
|
||||
CHECK_EQ(f.sch.release_session("", 0, 0, &out), RAD_E_INVAL);
|
||||
CHECK_EQ(f.pc.released_calls.size(), 2u);
|
||||
}
|
||||
|
||||
/* A reap while the step is still on the device. Common: the server reaps as soon as a sink
|
||||
* finishes, and cancelling finishes it, so every mid-decode disconnect lands here. Releasing the
|
||||
* Request now would destroy it under commit(); returning its slot now would let a newly admitted
|
||||
|
||||
Reference in new issue
Block a user