Skip to content

relay: sticky routing for KV-cache locality on multi-turn sessions - #321

Merged
FMXExpress merged 2 commits into
mainfrom
claude/relay-sticky-routing
Jun 21, 2026
Merged

FMXExpress merged 2 commits into
mainfrom
claude/relay-sticky-routing

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

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_calls array in OpenAI shape; HandleRelayRespond parses; RunToolLoop dispatches). So this PR is just the sticky routing piece.

Design

The session id source is Options.CacheKey — the same key OpenAI uses for prompt_cache_key, set to Session.Meta.Id by the agent loop. No new interface, no new field threading through provider configs; the relay just consumes what's already there.

PopMatchingRequestLocked is now two-pass:

Pass Behavior
Sticky Scan pending requests for any whose session id is pinned to this polling worker. If found, take it.
FCFS (fallback) Historical first-come-first-served behavior. If a session's preferred worker is busy / disconnected, another worker can still pick up the session's request — no starvation.

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_id field. Emitted only when Options.CacheKey is 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

  • One-shot turns (empty session_id) never enter the map. No sticky preference, no map pollution from an empty-key entry, no false-positive matches.
  • Preferred worker disconnects — UnregisterWorker prunes 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.
  • Preferred worker is busy — sticky pass misses (no match for THIS worker), FCFS pass takes the head. Sessions don't wait indefinitely for their KV-warm worker.

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 matching
  • TestStickyRoutingFallsBackOnDisconnect — preferred worker disappears between turns → FCFS routes to whoever's connected next
  • TestStickyDoesntStarveOtherSessions — busy preferred worker doesn't block other sessions from being served
  • TestEmptySessionIdIsNeverSticky — empty session id (one-shot) never enters the sticky map

make clean && make passes. All 18 tests green.

Files

File Change
src/pkg/gateway/PasClaw.Gateway.RelayQueue.pas TRelayRequest.SessionId field + two-pass PopMatchingRequestLocked + sticky-map cleanup on UnregisterWorker
src/pkg/providers/PasClaw.Providers.Relay.pas Chat() passes Options.CacheKey as session id; BuildRelayRequestBody emits session_id in envelope
src/tests/relay_queue_tests.pas 4 new sticky-routing tests
docs/providers-relay.md Status table refreshed; envelope sample updated; new "Sticky routing" section

Generated by Claude Code

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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).
@FMXExpress
FMXExpress merged commit 3283576 into main Jun 21, 2026
khongten001 pushed a commit to khongten001/PasClaw that referenced this pull request Jul 13, 2026
…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants