Repository navigation
feat: add server-side session management for multi-turn conversations - #51
Conversation
Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
…#5) The server was stateless — the chat TUI worked around this by prepending full conversation history as plaintext into each request, wasting tokens and losing message structure. Now the server maintains per-task conversation sessions using the A2A protocol's taskId. The client detects server-side sessions from the response and stops prepending history. - Add internal/session package with in-memory Store (TTL + reaper) - Update executor to manage session lifecycle (GetOrCreate, Append) - Change MessageProcessor to accept []llm.Message instead of string - Add TaskID to InvokeRequest/InvokeResult for session continuity - Chat TUI stores taskID and skips history prepending when set Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
|
Warning Rate limit exceeded
To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Enterprise Run ID: 📒 Files selected for processing (4)
📝 WalkthroughWalkthroughThis PR implements server-side session management to enable multi-message LLM interactions without per-request full-history tokenization. It introduces an in-memory session store with TTL eviction, updates the client protocol to send session IDs via headers, and modifies the executor to manage session state and message history across requests. ChangesServer-Side Session Management
Sequence DiagramsequenceDiagram
participant Client as Chat Client
participant Server as Server/Executor
participant Store as Session Store
participant LLM as LLM Provider
rect rgba(100, 150, 200, 0.5)
Note over Client,LLM: First Message
Client->>Client: Generate sessionID
Client->>Server: InvokeRequest + x-session-id header
Server->>Store: GetOrCreate(sessionID, systemPrompt)
Store->>Store: Create Session [system message]
Store-->>Server: Session (with system message)
Server->>Server: Append user message
Server->>LLM: ProcessMessage([system, user])
LLM-->>Server: Assistant response
Server->>Store: Append(sessionID, assistant message)
Server-->>Client: Response + set sessionConfirmed
end
rect rgba(150, 200, 100, 0.5)
Note over Client,LLM: Subsequent Messages (Session Active)
Client->>Server: InvokeRequest + sessionID (no history prepended)
Server->>Store: Get(sessionID)
Store-->>Server: Session [system, user₁, assistant₁, ...]
Server->>Server: Append user₂ to message list
Server->>LLM: ProcessMessage([system, user₁, assistant₁, user₂])
LLM-->>Server: Assistant response
Server->>Store: Append(sessionID, assistant₂)
Server-->>Client: Response
end
rect rgba(200, 150, 100, 0.5)
Note over Store: Background TTL Reaper
Store->>Store: Periodically check LastActive
Store->>Store: Delete sessions idle > TTL
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~22 minutes 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
A2A tasks are terminal once completed — reusing taskId for follow-up messages causes "task in terminal state" errors. Switch to a client-generated session ID sent as x-session-id ServiceParam header. Each message creates an independent A2A task but shares a server-side session via the header. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
- Only skip history prepending after first successful response (sessionConfirmed flag), not based on sessionID presence alone. Preserves backward compat with servers without session support. - Add session ID length validation (max 64 chars) in executor - Update design doc to reflect x-session-id implementation Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (7)
internal/session/store.go (2)
88-100: 💤 Low valueReaper ticker interval is hardcoded — consider plumbing through
NewStore.The 60s tick is a reasonable default but unrelated to the configured
ttl. For tests using sub-second TTLs (seeTestStoreReaper), a configurable interval would letStartReaperbe exercised directly instead of having to call the unexporteds.reap().🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/session/store.go` around lines 88 - 100, StartReaper uses a hardcoded 60s ticker which prevents tests with sub-second ttl from exercising the reaper; add a configurable reaper interval to Store (e.g., a reaperInterval time.Duration field) and accept it via NewStore (with a sensible default derived from ttl or a constant) so StartReaper uses s.reaperInterval instead of 60s; update NewStore to set the default interval when not provided and adjust tests to pass a short interval for TestStoreReaper while keeping reap() available for internal calls.
28-33: 🏗️ Heavy liftUnbounded session/message growth is a DoS vector.
Attackers (or buggy clients) can send unlimited unique
x-session-idvalues within a 30-minute window, each creating a session that retains its full message history until idle TTL expires. Similarly, a single long-lived session has no cap on accumulated messages. The TTL alone is not enough back-pressure for an internet-facing endpoint.Recommended phase-1 hardening (also flagged in the design doc's "Future work"):
- Cap total active sessions (e.g.
maxSessions); evict oldest byLastActivewhen exceeded.- Cap messages per session (e.g.
maxMessagesPerSession); drop or compact oldest non-system messages.Not blocking for the chat-TUI proof of concept, but should land before this is exposed beyond trusted callers.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/session/store.go` around lines 28 - 33, NewStore currently creates an unbounded Store (sessions map) which allows unlimited sessions and unlimited messages per session; update the Store and NewStore to accept or embed limits (e.g. maxSessions and maxMessagesPerSession), enforce maxSessions by evicting the oldest session(s) by Session.LastActive when creating a new session or on insertion into Store.sessions, and enforce maxMessagesPerSession inside the Session message append path (e.g. an AddMessage/AppendMessage method) by dropping or compacting the oldest non-system messages until the session is under the limit; ensure these limits are enforced atomically under the Store's mutex where Store.sessions is mutated and reference the NewStore, Store, Session, LastActive, sessions map, and any message-append function to locate and change the code.docs/superpowers/specs/2026-05-04-server-side-sessions-design.md (1)
110-122: 💤 Low valueAdd a language hint to the lifecycle code fence (markdownlint MD040).
Static analysis flags the unlabelled fence. Use ```text (or similar) to silence the warning and improve rendering.
📝 Suggested fix
-``` +```text TUI: "hello" → Server: x-session-id=S1 → create session S1🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/superpowers/specs/2026-05-04-server-side-sessions-design.md` around lines 110 - 122, The lifecycle code fence showing the session flow is an unlabelled markdown fence causing markdownlint MD040; update the opening fence (the block that begins with ```) for the TUI→Server session lifecycle to use a language hint such as ```text (or similar) so the fence is labelled and the linter warning is silenced.internal/session/store_test.go (2)
81-99: 💤 Low valueTTL/reaper tests rely on real wall-clock sleeps; consider a fakeable clock for stability.
TestStoreReaperuses 10ms TTL plus 20ms sleeps, which can be flaky on heavily loaded CI runners. Not blocking, but extracting time via a smallnow func() time.Time(or accepting a clock) would make these deterministic.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/session/store_test.go` around lines 81 - 99, TestStoreReaper is flaky because Store uses real time; change Store to use an injectable clock (e.g., add a now func() time.Time field or accept a Clock interface) so TTL checks and reap() use that instead of time.Now; update NewStore (or add NewStoreWithClock) to set the default now to time.Now, update methods reap, GetOrCreate, Append, and any TTL comparisons to call s.now(), and update the test TestStoreReaper to use a fake clock instance and advance it instead of calling time.Sleep so the test becomes deterministic.
11-118: ⚡ Quick winAdd a
-race-aware concurrent test for the store.The store will be exercised by concurrent
Executecalls keyed on a sharedx-session-id. A small test that runs many parallelGetOrCreate/Append/Getops would catch races inside the store and any future regressions when the executor is reworked to take snapshots under lock (see comment oninternal/bridge/executor.go).🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/session/store_test.go` around lines 11 - 118, Add a new concurrent test (e.g., TestStoreConcurrentRace) that stresses NewStore/GetOrCreate/Append/Get under parallelism: create a store, spawn many goroutines (use sync.WaitGroup) that repeatedly call s.GetOrCreate("x-session-id", "system-prompt"), s.Append("x-session-id", llm.Message{...}) and s.Get("x-session-id") in tight loops (hundreds/thousands of iterations), then wait for all goroutines and assert no panics and that s.Len() == 1 and the session has at least the expected number of messages; this will exercise the same session id concurrently to catch races when running `go test -race`. Ensure the test function name is unique (TestStoreConcurrentRace) and references NewStore, GetOrCreate, Append, and Get so it’s easy to locate.internal/chat/model.go (1)
86-90: 💤 Low valueConsider handling the
crypto/rand.Readerror for defensive session ID generation.If
rand.Readever returns an error,bstays zeroed and every session ID degenerates to the same all-zero UUID, causing all clients to share the same server session. In practicerand.Readis extremely reliable on supported platforms, but a tiny guard avoids that worst-case sharing.♻️ Suggested handling
func generateSessionID() string { b := make([]byte, 16) - _, _ = rand.Read(b) + if _, err := rand.Read(b); err != nil { + // Fall back to time-based ID; collisions still unlikely in single-TUI use. + return fmt.Sprintf("ts-%d", time.Now().UnixNano()) + } return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:]) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/chat/model.go` around lines 86 - 90, generateSessionID currently ignores the error from rand.Read which can produce identical all-zero IDs; modify generateSessionID to check the error returned by rand.Read and handle it defensively (e.g., on err != nil retry rand.Read once, and if it still fails use a secure fallback such as filling b with a math/rand PRNG seeded from time.Now().UnixNano() or composing a timestamp+random nonce) so the function never returns a constant all-zero value; update references in generateSessionID to ensure any fallback still produces a suitably unique hex UUID-like string.internal/bridge/executor.go (1)
97-99: 💤 Low valueSession ID truncation guard is good; consider also rejecting empty/whitespace IDs.
Truncating to 64 chars correctly bounds attacker-influenced input. A trimmed/non-printable check would further prevent edge cases like clients sending whitespace or control characters as the session key, but it's not blocking.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/bridge/executor.go` around lines 97 - 99, The current truncation (sessionID = sessionID[:64]) should be preceded by sanitization: trim surrounding whitespace with strings.TrimSpace, then reject (return an error or nil/unauthorized) if the trimmed sessionID is empty or consists solely of non-printable/control characters (check runes with unicode.IsPrint or similar); after that, enforce the 64-char cap using either rune-aware truncation (slice by runes) or validate utf8 length before slicing. Update the code paths that use the sessionID variable (the sessionID assignment/truncation block) to perform TrimSpace + printable-rune check and return a clear error when invalid, then apply the existing 64-character truncation safely.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@docs/superpowers/specs/2026-05-04-server-side-sessions-design.md`:
- Around line 131-138: Update the PR summary table to reflect the actual
session-id flow: change the bridge/client row to say that InvokeRequest now
carries sessionID which is propagated as the x-session-id header to A2A and note
that InvokeResult is unchanged (no TaskID change), and change the chat/model row
to say the model stores sessionID and gates history prepending on
sessionConfirmed (which is set after the first successful response) rather than
referring to the old TaskID behavior; reference the symbols InvokeRequest,
InvokeResult, sessionID, sessionConfirmed and the x-session-id header to make
locating the code clear.
In `@internal/bridge/executor.go`:
- Around line 100-128: There is a race on the session's mutable fields because
executor reads sess.Messages (via e.Sessions.GetOrCreate -> sess.Messages)
outside the store lock while other goroutines can call e.Sessions.Append; to
fix, add a Store method (e.g., AppendAndSnapshot or Snapshot) that performs the
append (or just snapshot) under the store's mutex and returns a copied
[]llm.Message, then update executor.go to call that new method instead of
reading sess.Messages directly and pass the returned slice into
e.ProcessMessage; ensure you also update the post-processing append path to use
the same atomic AppendAndSnapshot (or a separate Append when appropriate) so no
pointer to the store-owned session is used outside the lock.
In `@internal/session/store.go`:
- Around line 37-57: GetOrCreate currently returns a live *Session that callers
read without the store mutex, causing data races with Append/reap; change the
API so callers get safe snapshots: modify GetOrCreate to return a Session
(value) copy instead of *Session, and add Snapshot(id) (returns []llm.Message,
bool) plus AppendAndSnapshot(id string, msg llm.Message) []llm.Message that
perform all reads/writes under s.mu and return copies of Messages; update
internal callers to use AppendAndSnapshot or Snapshot and remove any direct
pointer reads so no code accesses Session fields outside the mutex.
- Around line 67-77: The Append method on Store silently drops messages if the
session was reaped; update Store.Append to return an error or bool indicating
success (e.g., (bool, error)) instead of void and log a warning when the session
id is missing, so callers like the code path that calls Append after GetOrCreate
(executor.go:126) can detect failure and recreate the session; modify the Append
signature and all callers to handle the returned value, log a descriptive
warning via the existing logger when sess not found, and consider propagating an
error type such as ErrSessionNotFound for callers to react to.
---
Nitpick comments:
In `@docs/superpowers/specs/2026-05-04-server-side-sessions-design.md`:
- Around line 110-122: The lifecycle code fence showing the session flow is an
unlabelled markdown fence causing markdownlint MD040; update the opening fence
(the block that begins with ```) for the TUI→Server session lifecycle to use a
language hint such as ```text (or similar) so the fence is labelled and the
linter warning is silenced.
In `@internal/bridge/executor.go`:
- Around line 97-99: The current truncation (sessionID = sessionID[:64]) should
be preceded by sanitization: trim surrounding whitespace with strings.TrimSpace,
then reject (return an error or nil/unauthorized) if the trimmed sessionID is
empty or consists solely of non-printable/control characters (check runes with
unicode.IsPrint or similar); after that, enforce the 64-char cap using either
rune-aware truncation (slice by runes) or validate utf8 length before slicing.
Update the code paths that use the sessionID variable (the sessionID
assignment/truncation block) to perform TrimSpace + printable-rune check and
return a clear error when invalid, then apply the existing 64-character
truncation safely.
In `@internal/chat/model.go`:
- Around line 86-90: generateSessionID currently ignores the error from
rand.Read which can produce identical all-zero IDs; modify generateSessionID to
check the error returned by rand.Read and handle it defensively (e.g., on err !=
nil retry rand.Read once, and if it still fails use a secure fallback such as
filling b with a math/rand PRNG seeded from time.Now().UnixNano() or composing a
timestamp+random nonce) so the function never returns a constant all-zero value;
update references in generateSessionID to ensure any fallback still produces a
suitably unique hex UUID-like string.
In `@internal/session/store_test.go`:
- Around line 81-99: TestStoreReaper is flaky because Store uses real time;
change Store to use an injectable clock (e.g., add a now func() time.Time field
or accept a Clock interface) so TTL checks and reap() use that instead of
time.Now; update NewStore (or add NewStoreWithClock) to set the default now to
time.Now, update methods reap, GetOrCreate, Append, and any TTL comparisons to
call s.now(), and update the test TestStoreReaper to use a fake clock instance
and advance it instead of calling time.Sleep so the test becomes deterministic.
- Around line 11-118: Add a new concurrent test (e.g., TestStoreConcurrentRace)
that stresses NewStore/GetOrCreate/Append/Get under parallelism: create a store,
spawn many goroutines (use sync.WaitGroup) that repeatedly call
s.GetOrCreate("x-session-id", "system-prompt"), s.Append("x-session-id",
llm.Message{...}) and s.Get("x-session-id") in tight loops (hundreds/thousands
of iterations), then wait for all goroutines and assert no panics and that
s.Len() == 1 and the session has at least the expected number of messages; this
will exercise the same session id concurrently to catch races when running `go
test -race`. Ensure the test function name is unique (TestStoreConcurrentRace)
and references NewStore, GetOrCreate, Append, and Get so it’s easy to locate.
In `@internal/session/store.go`:
- Around line 88-100: StartReaper uses a hardcoded 60s ticker which prevents
tests with sub-second ttl from exercising the reaper; add a configurable reaper
interval to Store (e.g., a reaperInterval time.Duration field) and accept it via
NewStore (with a sensible default derived from ttl or a constant) so StartReaper
uses s.reaperInterval instead of 60s; update NewStore to set the default
interval when not provided and adjust tests to pass a short interval for
TestStoreReaper while keeping reap() available for internal calls.
- Around line 28-33: NewStore currently creates an unbounded Store (sessions
map) which allows unlimited sessions and unlimited messages per session; update
the Store and NewStore to accept or embed limits (e.g. maxSessions and
maxMessagesPerSession), enforce maxSessions by evicting the oldest session(s) by
Session.LastActive when creating a new session or on insertion into
Store.sessions, and enforce maxMessagesPerSession inside the Session message
append path (e.g. an AddMessage/AppendMessage method) by dropping or compacting
the oldest non-system messages until the session is under the limit; ensure
these limits are enforced atomically under the Store's mutex where
Store.sessions is mutated and reference the NewStore, Store, Session,
LastActive, sessions map, and any message-append function to locate and change
the code.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Enterprise
Run ID: 3ed96045-0e68-4eb0-abcb-76541470ac6f
📒 Files selected for processing (8)
CLAUDE.mddocs/superpowers/specs/2026-05-04-server-side-sessions-design.mdinternal/bridge/client.gointernal/bridge/executor.gointernal/chat/model.gointernal/cmd/serve.gointernal/session/store.gointernal/session/store_test.go
| func (s *Store) Append(id string, msg llm.Message) { | ||
| s.mu.Lock() | ||
| defer s.mu.Unlock() | ||
|
|
||
| sess, ok := s.sessions[id] | ||
| if !ok { | ||
| return | ||
| } | ||
| sess.Messages = append(sess.Messages, msg) | ||
| sess.LastActive = time.Now() | ||
| } |
There was a problem hiding this comment.
Append silently drops the message when the session was reaped.
If the reaper deletes a session between GetOrCreate and the post-LLM Append("assistant", …) call (executor.go:126), the assistant turn is lost without any signal to the caller. At minimum, log a warning so this state is observable; ideally return a bool/error so callers can decide to recreate.
📝 Suggested handling
func (s *Store) Append(id string, msg llm.Message) {
s.mu.Lock()
defer s.mu.Unlock()
sess, ok := s.sessions[id]
if !ok {
+ slog.Warn("append to missing session", "session_id", id, "role", msg.Role)
return
}
sess.Messages = append(sess.Messages, msg)
sess.LastActive = time.Now()
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| func (s *Store) Append(id string, msg llm.Message) { | |
| s.mu.Lock() | |
| defer s.mu.Unlock() | |
| sess, ok := s.sessions[id] | |
| if !ok { | |
| return | |
| } | |
| sess.Messages = append(sess.Messages, msg) | |
| sess.LastActive = time.Now() | |
| } | |
| func (s *Store) Append(id string, msg llm.Message) { | |
| s.mu.Lock() | |
| defer s.mu.Unlock() | |
| sess, ok := s.sessions[id] | |
| if !ok { | |
| slog.Warn("append to missing session", "session_id", id, "role", msg.Role) | |
| return | |
| } | |
| sess.Messages = append(sess.Messages, msg) | |
| sess.LastActive = time.Now() | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/session/store.go` around lines 67 - 77, The Append method on Store
silently drops messages if the session was reaped; update Store.Append to return
an error or bool indicating success (e.g., (bool, error)) instead of void and
log a warning when the session id is missing, so callers like the code path that
calls Append after GetOrCreate (executor.go:126) can detect failure and recreate
the session; modify the Append signature and all callers to handle the returned
value, log a descriptive warning via the existing logger when sess not found,
and consider propagating an error type such as ErrSessionNotFound for callers to
react to.
- Add AppendAndSnapshot method that appends + copies under the lock, preventing race between concurrent reads and writes on sess.Messages - Executor uses AppendAndSnapshot instead of reading live session pointer - Add concurrent race test (50 goroutines × 100 ops, passes -race) - Add AppendAndSnapshot unit tests including snapshot isolation - Update design doc tables to match x-session-id implementation - Fix unlabelled markdown code fence (MD040) Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
Summary
internal/sessionpackage with in-memoryStore(map + RWMutex, TTL-based reaper)x-session-idheader as session keyMessageProcessorsignature changes fromfunc(ctx, string)tofunc(ctx, []llm.Message)— server builds conversation history, not the clientEach chat message creates an independent A2A task (respecting the protocol's terminal task states), but the server groups them into a conversation session via the
x-session-idheader. Two terminal sessions get independent conversations. Sessions expire after 30 minutes of idle time.Design
See
docs/superpowers/specs/2026-05-04-server-side-sessions-design.md.Test plan
make testpasses — session store tests cover GetOrCreate, Append, reaper, cancellationmake lintpasses (0 issues)make buildpassesCloses #5 (Phase 1)
🤖 Generated with Claude Code
Summary by CodeRabbit
Release Notes
New Features
Documentation