Skip to content

Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

fix(serve): pin each conversation to a stable KV slot (#634)

JustVugge8580e759a39
diff --git a/c/openai_server.py b/c/openai_server.py
index cf2f5279..5f78eed3 100644
--- a/c/openai_server.py
+++ b/c/openai_server.py
@@ -5,6 +5,7 @@ import argparse
import codecs
import collections
import contextlib
+import hashlib
import json
import math
import mimetypes
@@ -861,6 +862,37 @@ def parse_stop_sequences(body):
return tuple(sequences)
+def conversation_cache_slot(messages, kv_slots):
+ """Stable KV slot for a conversation so its turns reuse the same cached prefix.
+
+ The chat APIs are stateless: every turn resends the whole history, and the engine
+ caches each KV slot's prefix. When the client does not pin a `cache_slot`, the
+ scheduler falls back to `min(free_slots)`, which is blind to which slot already
+ holds this conversation. Under any interleaving of clients a turn can then land on
+ another conversation's slot and force a full re-prefill (#634, Defect 1). Hashing a
+ key that stays constant across a conversation's turns — the leading system messages
+ plus the first user message, which never change once the conversation has started —
+ routes every turn of one conversation to the same slot. Distinct conversations
+ spread across slots; when there are more live conversations than slots, colliding
+ ones degrade to the old re-prefill behaviour rather than to anything worse.
+
+ Returns a slot in [0, kv_slots). Falls back to 0 when there is nothing to key on.
+ """
+ if kv_slots <= 1 or not isinstance(messages, list) or not messages:
+ return 0
+ prefix = []
+ for message in messages:
+ prefix.append(message)
+ if isinstance(message, dict) and message.get("role") == "user":
+ break # first user turn reached: the key is now stable for the whole conversation
+ try:
+ key = json.dumps(prefix, sort_keys=True, default=str)
+ except (TypeError, ValueError):
+ key = repr(prefix)
+ digest = hashlib.sha1(key.encode("utf-8", "replace")).digest()
+ return int.from_bytes(digest[:8], "big") % kv_slots
+
+
def stop_policy(body, chat):
sequences = parse_stop_sequences(body)
ignore_leading = body.get("x_colibri_ignore_leading_stop", False)
@@ -1670,6 +1702,13 @@ class APIHandler(BaseHTTPRequestHandler):
not 0 <= cache_slot < self.server.kv_slots)):
raise APIError(400, f"`cache_slot` must be an integer between 0 and {self.server.kv_slots - 1}.",
"cache_slot")
+ if cache_slot is None and self.server.kv_slots > 1:
+ # #634: pin each conversation to a stable KV slot so multi-turn reuses its
+ # cached prefix instead of re-prefilling. Only when the request carries a
+ # conversation; raw /v1/completions keeps the scheduler's free-slot pick.
+ conversation = body.get("messages")
+ if isinstance(conversation, list) and conversation:
+ cache_slot = conversation_cache_slot(conversation, self.server.kv_slots)
stream = body.get("stream", False)
if not isinstance(stream, bool):
raise APIError(400, "`stream` must be a boolean.", "stream")
@@ -1999,6 +2038,13 @@ class APIHandler(BaseHTTPRequestHandler):
not 0 <= cache_slot < self.server.kv_slots)):
raise APIError(400, f"`cache_slot` must be an integer between 0 and {self.server.kv_slots - 1}.",
"cache_slot")
+ if cache_slot is None and self.server.kv_slots > 1:
+ # #634: pin each conversation to a stable KV slot so multi-turn reuses its
+ # cached prefix instead of re-prefilling. Only when the request carries a
+ # conversation; raw /v1/completions keeps the scheduler's free-slot pick.
+ conversation = body.get("messages")
+ if isinstance(conversation, list) and conversation:
+ cache_slot = conversation_cache_slot(conversation, self.server.kv_slots)
stream = body.get("stream", False)
if not isinstance(stream, bool):
raise APIError(400, "`stream` must be a boolean.", "stream")
diff --git a/c/tests/test_openai_server.py b/c/tests/test_openai_server.py
index fb8235a3..2bda0cc7 100644
--- a/c/tests/test_openai_server.py
+++ b/c/tests/test_openai_server.py
@@ -14,7 +14,8 @@ from pathlib import Path
from openai_server import (APIError, APIHandler, APIServer, ClientCancelled,
DEFAULT_CHAT_STOP_SEQUENCES, END, GenerationScheduler,
READY, Engine, InklingStreamSplit, StopFilter, ThinkingStreamSplit,
- _engine_error, generation_options, parse_tool_calls, read_engine_turn,
+ _engine_error, conversation_cache_slot, generation_options,
+ parse_tool_calls, read_engine_turn,
render_chat, serve, split_thinking_reply, stop_policy)
@@ -1425,5 +1426,47 @@ class KeepAliveFramingTest(unittest.TestCase):
self.assertIsNotNone(conn.sock, "the JSON path should keep the connection open")
+class ConversationCacheSlotTest(unittest.TestCase):
+ """#634 Defect 1: a conversation must map to one stable KV slot across its turns."""
+
+ def _conv(self, *user_and_assistant_turns, system="you are a helpful assistant"):
+ messages = [{"role": "system", "content": system}]
+ for i, text in enumerate(user_and_assistant_turns):
+ messages.append({"role": "user" if i % 2 == 0 else "assistant", "content": text})
+ return messages
+
+ def test_single_slot_is_always_zero(self):
+ self.assertEqual(conversation_cache_slot(self._conv("hi"), 1), 0)
+
+ def test_empty_or_bad_input_is_zero(self):
+ self.assertEqual(conversation_cache_slot(None, 8), 0)
+ self.assertEqual(conversation_cache_slot([], 8), 0)
+
+ def test_slot_is_in_range(self):
+ for kv in (2, 3, 8, 16):
+ slot = conversation_cache_slot(self._conv("solve x"), kv)
+ self.assertTrue(0 <= slot < kv, f"slot {slot} out of range for kv={kv}")
+
+ def test_stable_across_turns_of_one_conversation(self):
+ # The engine caches the prefix; every turn of the same conversation must return
+ # the same slot so it lands on its warm KV instead of re-prefilling.
+ first_turn = self._conv("1+1=")
+ second_turn = self._conv("1+1=", "2", "and 2+2?")
+ third_turn = self._conv("1+1=", "2", "and 2+2?", "4", "thanks")
+ base = conversation_cache_slot(first_turn, 8)
+ self.assertEqual(conversation_cache_slot(second_turn, 8), base)
+ self.assertEqual(conversation_cache_slot(third_turn, 8), base)
+
+ def test_distinct_conversations_can_differ(self):
+ # Not a guarantee for any single pair (hashing collides sometimes), but across a
+ # spread of openings we must see more than one slot used, i.e. not everything on 0.
+ slots = {conversation_cache_slot(self._conv(f"task number {i}"), 8) for i in range(40)}
+ self.assertGreater(len(slots), 1)
+
+ def test_deterministic(self):
+ conv = self._conv("same question", "same answer", "again")
+ self.assertEqual(conversation_cache_slot(conv, 8), conversation_cache_slot(conv, 8))
+
+
if __name__ == "__main__":
unittest.main()