Repository navigation
relay: sticky routing for KV-cache locality on multi-turn sessions - #321
Conversation
When a request carries a session id (sourced from Options.CacheKey -- the same key OpenAI uses for prompt_cache_key, set to Session.Meta.Id by the agent loop), the queue remembers which worker last served the session and preferentially routes the session's next turn to the same worker. Keeps the model's working state hot in the worker's GPU memory across turns; typically 5-10x speedup on turn 2+ with long contexts (PasClaw's case: MEMORY.md + AGENTS.md + PLAN.md all loaded). Note on tool calls ================== The user's request was "structured tool calls + sticky routing". Structured tool calls already shipped in PR #318's review-fix commit: worker emits a `tool_calls` array in the OpenAI shape, parsed by HandleRelayRespond into TRelayResponse.ToolCalls, copied into TLLMResponse.ToolCalls by DecodeResponse, dispatched by RunToolLoop. So this PR is just sticky routing. Design ====== PopMatchingRequestLocked is now two-pass: Pass 1 -- sticky: scan pending requests for any whose session id is pinned to THIS polling worker. If found, take it. Pass 2 -- FCFS: fall back to the historical first-come-first- served behaviour. After assignment the sticky map is updated to whoever actually took the work, so a session whose preferred worker disappeared gets re- pinned to its new handler. The FCFS fallback means a busy / disconnected preferred worker doesn't starve any session. Cleanup: UnregisterWorker prunes sticky entries pointing at the departing worker so (a) the map stays bounded by # of active workers x active sessions and (b) a fresh worker connecting under the same id doesn't inherit stale stickiness from a previous incarnation. Empty session id (one-shot turns) never enters the map -- no sticky preference, no map pollution from an empty-key entry, no false- positive matches. Wire protocol change ==================== Request envelope gains an OPTIONAL `session_id` field. Emitted only when Options.CacheKey is non-empty. Workers that can do their own KV-cache reuse have a key to work with; workers that don't need the session id just ignore the field. Files ===== MOD src/pkg/gateway/PasClaw.Gateway.RelayQueue.pas - TRelayRequest gains FSessionId field + optional constructor param ASessionId (default '') so existing call sites compile unchanged. - TRelayQueue gains FSessionToWorker: TStringList (Names[]= session id, ValueFromIndex[]=worker id) created in Create and freed in Destroy. - PopMatchingRequestLocked refactored: shared TakeRequest inner procedure + two-pass scan (sticky then FCFS). - UnregisterWorker prunes FSessionToWorker entries pointing at the departing worker. MOD src/pkg/providers/PasClaw.Providers.Relay.pas - Chat() passes Options.CacheKey as the constructor's ASessionId argument. - BuildRelayRequestBody emits `session_id` in the envelope when Options.CacheKey is non-empty. MOD src/tests/relay_queue_tests.pas Four new tests: - TestStickyRoutingPrefersLastWorker - TestStickyRoutingFallsBackOnDisconnect - TestStickyDoesntStarveOtherSessions - TestEmptySessionIdIsNeverSticky Total: 18 cases (was 14). MOD docs/providers-relay.md - Status table refreshed: V1 HTTP endpoints landed, structured tool calls landed (PR #318 review fix), sticky routing now landed. - Request envelope sample shows `session_id` with explanation. - New "Sticky routing (KV-cache locality)" section after the multi-worker semantics block. Tests ===== make clean && make passes. make test-relay-queue passes all 18 cases.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6e2f2e35e9
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| W.Touch; | ||
| Inc(FStats.InflightRequests); | ||
| Dec(FStats.PendingRequests); | ||
| TakeRequestAtLocked(i, R); |
There was a problem hiding this comment.
Preserve stickiness when non-preferred workers wake first
When a session is already pinned to another connected worker, this FCFS fallback still lets the current worker take the request if it happens to acquire the queue lock first. With worker-x and worker-y both blocked in /v1/relay/poll, after worker-x completes session A's first turn, session A's second turn can be stolen by worker-y: pass 1 skips it because Stuck <> W.Id, then this pass takes it and re-pins the session to worker-y. That makes sticky routing depend on scheduler timing rather than KV-cache locality; skip requests pinned to another available worker unless that worker is actually unavailable for fallback.
Useful? React with 👍 / 👎.
Two changes responding to feedback on PR #321: 1. Codex P2 review: strict sticky in the FCFS fallback ============================================================ Reviewer: > With worker-x and worker-y both blocked in /v1/relay/poll, after > worker-x completes session A's first turn, session A's second turn > can be stolen by worker-y: pass 1 skips it because Stuck <> W.Id, > then this pass takes it and re-pins the session to worker-y. That > makes sticky routing depend on scheduler timing rather than > KV-cache locality; skip requests pinned to another available > worker unless that worker is actually unavailable for fallback. The reviewer is right -- the original loose-sticky FCFS undermined the whole point of sticky routing (KV-cache locality) every time a non-preferred worker happened to acquire the queue lock first. Fix: in pass 2 (FCFS), skip requests whose session is pinned to a DIFFERENT currently-connected worker. Take only when the pinned worker has actually disconnected from the registry so sessions don't starve on ghosts. Requests with no sticky entry (one-shot or first-turn-in-session) are taken as before. Test coverage ------------- The original TestStickyDoesntStarveOtherSessions asserted worker-y eventually takes session-A's R2 even when worker-x is still connected -- exactly the loose-sticky behaviour the reviewer flagged. Replaced with TestStrictStickyDoesntStealFromConnectedPreferred: - Session-A turn 1: worker-x. Sticky[A] := worker-x. Respond. - Session-A turn 2 (R2) + session-B (R3) enqueue. - Worker-y polls -- must take R3, MUST skip R2 (pinned to connected worker-x). - Worker-y polls again -- nil (R2 reserved). - Worker-x polls -- takes R2 via sticky pass 1. Locality preserved. Other 17 tests unchanged; all 18 pass. 2. Config knob: Cfg.RelayWaitTimeoutMs ======================================== Surfaces RelayDefaultWaitTimeoutMs as `relay_wait_timeout_ms` in config.json. Pattern matches the existing config field conventions: - TConfig.RelayWaitTimeoutMs: Integer (defaults 0) - 0 = use the Pascal-side default (RelayDefaultWaitTimeoutMs, currently 5 minutes); operators set higher for flaky workers, lower for fast fallback. The sentinel keeps PasClaw on the built-in default so future bumps to the constant flow through without operator action. - SaveConfig emits only when non-default (>0) so a fresh config.json stays tidy. - LoadConfig default-preserves on missing key. Factory wiring -------------- PasClaw.Providers.Factory.NewProviderFromConfig's pfRelay branch now passes Cfg.RelayWaitTimeoutMs to TRelayProvider.Create's AWaitTimeoutMs parameter. The constructor's own `<= 0` branch maps the sentinel to the Pascal default, so the no-config path works identically to before. Docs ==== docs/providers-relay.md updated: - Sticky routing section explains the strict-sticky FCFS rule explicitly (skip pinned-elsewhere requests when their preferred worker is still connected). - New "Tuning the per-Chat wait timeout" section with the config.json example and the sentinel-zero semantics. Tests ===== make clean && make passes. make test-relay-queue passes all 18. make test-config-profile passes (round-trip of the new field covered generically by the existing flip-every-toggle pattern).
…ollow-up) dcc64 rejects the 4-arg call site in PasClaw.Providers.Relay.pas:307 with E2034 "Too many actual parameters" when the optional ASessionId sits behind a `const string = ''` default. FPC accepts it; Delphi does not. Split into two overloaded constructors -- a 3-arg overload that delegates to the 4-arg form with an empty session id -- so both compilers parse the same call shapes. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Summary
When a relay request carries a
session_id, the queue remembers which worker last served that session and preferentially routes the session's next turn to the same worker. Keeps the model's working state hot in the worker's GPU memory across multi-turn conversations — typically 5-10× speedup on turn 2+ with long contexts (PasClaw's typical case with MEMORY.md + AGENTS.md + PLAN.md all loaded).Structured tool calls were already shipped in PR #318's review-fix commit (worker emits a
tool_callsarray in OpenAI shape;HandleRelayRespondparses;RunToolLoopdispatches). So this PR is just the sticky routing piece.Design
The session id source is
Options.CacheKey— the same key OpenAI uses forprompt_cache_key, set toSession.Meta.Idby the agent loop. No new interface, no new field threading through provider configs; the relay just consumes what's already there.PopMatchingRequestLockedis now two-pass:After assignment the sticky map is updated to whoever actually took the work, so a session whose preferred worker disappeared gets re-pinned to its new handler.
Wire protocol change
Request envelope gains an optional
session_idfield. Emitted only whenOptions.CacheKeyis non-empty:{ "id": "req_...", "model": "llama-3.2-3b-instruct", "session_id": "sess_abc123", // ← NEW; optional "messages": [...], "tools": [...], "options": {...} }Workers that can do their own KV-cache reuse have a key to work with; workers that don't need it just ignore the field.
Edge cases handled
session_id) never enter the map. No sticky preference, no map pollution from an empty-key entry, no false-positive matches.UnregisterWorkerprunes sticky entries pointing at the departing worker. Map stays bounded by # of active workers × active sessions. Fresh worker connecting under the same id doesn't inherit stale stickiness.Test plan
make test-relay-queue— 18 hermetic cases (was 14; added):TestStickyRoutingPrefersLastWorker— session A's turn 2 lands on worker X (who handled turn 1) even when worker Y is also matchingTestStickyRoutingFallsBackOnDisconnect— preferred worker disappears between turns → FCFS routes to whoever's connected nextTestStickyDoesntStarveOtherSessions— busy preferred worker doesn't block other sessions from being servedTestEmptySessionIdIsNeverSticky— empty session id (one-shot) never enters the sticky mapmake clean && makepasses. All 18 tests green.Files
src/pkg/gateway/PasClaw.Gateway.RelayQueue.pasTRelayRequest.SessionIdfield + two-passPopMatchingRequestLocked+ sticky-map cleanup onUnregisterWorkersrc/pkg/providers/PasClaw.Providers.Relay.pasChat()passesOptions.CacheKeyas session id;BuildRelayRequestBodyemitssession_idin envelopesrc/tests/relay_queue_tests.pasdocs/providers-relay.mdGenerated by Claude Code