Repository navigation
feat(sessions): idempotent /sessions/start via client_session_key - #155
Conversation
Multi-replica runners (Ray Serve with num_replicas>=2, autoscaling worker pools) each keep their own ExplicitClient._session_cache. When two /query calls for the same conversation_id land on different replicas, both miss their local cache and call /sessions/start, producing two duplicate Rewind sessions for what is logically the same conversation. Surfaced today in dev1: two 'ray-agent-631c6677' sessions appeared 41s apart with different total_steps and questions. Fix: add an optional client_session_key field on the Session model + a UNIQUE WHERE NOT NULL index, and make POST /api/sessions/start find-or-create on that key. Pre-flight lookup avoids the round trip in the common case; the post-insert UNIQUE-violation handler absorbs the multi-process race window. Server returns 200 OK on dedup hit (vs 201 CREATED on insert) so callers can branch if they care; the response body shape is identical. SDK: ExplicitClient.ensure_session now passes conversation_id as client_session_key. The in-process cache stays as a fast path so repeat ensure_session calls in the SAME replica never hit the server. The server-side dedup handles the cross-replica case. Tests: 3 new in recording_api_tests.rs (idempotent reuse, distinct keys, no-key backward compat), 2 new in test_explicit.py (SDK sends the key; two ExplicitClient instances converge on one session). 374 rewind-store + rewind-web tests pass; 31 Python explicit tests pass; clippy clean. Versions bumped to 0.14.1 (workspace) and 0.15.1 (Python SDK) per CLAUDE.md release rules. Made-with: Cursor
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
risjai
left a comment
There was a problem hiding this comment.
Review: feat(sessions): idempotent /sessions/start via client_session_key
Clean, well-motivated change that solves a real multi-replica race condition. The TOCTOU → UNIQUE constraint → re-resolve pattern is the right approach for SQLite, and the pre-flight lookup avoids the constraint round-trip in the common case. Test coverage is thorough across both Rust (3 tests covering idempotent reuse, distinct keys, backward compat) and Python (SDK sends the key, two clients converge). Version bumps are correct per CLAUDE.md rules.
One correctness bug to fix before merge, plus a few lower-priority suggestions inline.
Findings summary (details inline)
| # | Severity | Finding |
|---|---|---|
| 1 | Bug | Empty-string client_session_key silently collides — all callers passing "" get routed to the same session |
| 2 | Suggestion | client_session_key leaks into GET /sessions API responses via Serialize derive |
| 3 | Nit | Root-timeline resolution logic duplicated between pre-flight and UNIQUE-recovery paths |
| 4 | Info | No StoreEvent emitted on dedup return paths — SSE/WebSocket listeners won't see "session reused" |
| // Find-or-create when an idempotency key is supplied. Pre-flight | ||
| // lookup avoids the common case of paying the unique-constraint | ||
| // round trip; the post-insert retry handles the race window. | ||
| if let Some(client_key) = body.client_session_key.as_deref() { |
There was a problem hiding this comment.
Bug (medium): If client_session_key is Some("") (empty string), it passes this if let Some(...) gate and is treated as a valid non-NULL key. The first empty-string caller "claims" the slot in the unique index, and all subsequent callers with an empty key silently get routed to that session — corrupting unrelated conversations.
This is a realistic scenario: a Python caller doing conversation_id = get_id() or "" would trigger it.
Suggested fix — normalize at the top of start_session:
let client_session_key = body.client_session_key
.as_deref()
.filter(|k| !k.trim().is_empty())
.map(|k| k.to_string());Then use client_session_key instead of body.client_session_key throughout.
| /// | ||
| /// Database invariant: `UNIQUE WHERE client_session_key IS NOT | ||
| /// NULL` so concurrent inserts collapse via the constraint. | ||
| pub client_session_key: Option<String>, |
There was a problem hiding this comment.
Suggestion (low): Session derives Serialize and is returned directly from list_sessions / get_session (line 65 and 75 of api.rs). This means client_session_key (which carries the caller's conversation_id) is now visible to every dashboard user and API consumer.
Not a security issue per se (the API is local), but it adds a field to the wire format that clients don't need. Consider:
#[serde(skip_serializing_if = "Option::is_none")]
pub client_session_key: Option<String>,Or #[serde(skip_serializing)] if the key should be fully opaque.
| "unique violation but no session found by client_key".to_string(), | ||
| ) | ||
| })?; | ||
| let timelines = store.get_timelines(&winner.id).map_err(|e| { |
There was a problem hiding this comment.
Nit: This root-timeline resolution block (lines 964–975) is a near-exact duplicate of lines 894–905 in the pre-flight path. Consider extracting a helper:
fn resolve_root_timeline_id(
store: &Store,
session_id: &str,
) -> Result<String, (StatusCode, String)> {
let timelines = store.get_timelines(session_id)
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("DB error: {e}")))?;
timelines.iter()
.find(|t| t.parent_timeline_id.is_none())
.map(|t| t.id.clone())
.ok_or_else(|| (
StatusCode::INTERNAL_SERVER_ERROR,
format!("session {session_id} has no root timeline"),
))
}Would DRY both call sites and make the handler easier to read.
| format!("session {} has no root timeline", existing.id), | ||
| ) | ||
| })?; | ||
| return Ok(( |
There was a problem hiding this comment.
Info: Neither this dedup return path nor the UNIQUE-recovery path (line 976) emits a StoreEvent::SessionUpdated. The happy path does at line 990. If SSE/WebSocket listeners track session creation, they won't see sessions that were "reused" by a second replica.
Probably intentional (the session already exists and was announced on first creation), but worth a one-line comment here so a future reader doesn't wonder whether it was forgotten.
…n field Address all four review threads from PR #155: R1 (medium bug): empty/whitespace client_session_key was passing the `if let Some(...)` gate, claiming the UNIQUE-index slot, and routing every subsequent empty-key caller to that single session. Coerce empty/whitespace to None up front so they get fresh sessions like the no-key path. New regression test pins the behavior. R2 (low): mark Session.client_session_key as #[serde(skip_serializing)] so the dashboard-facing `/api/sessions` responses don't leak the caller's conversation_id. Deserialize still works for fixtures / restore. R3 (nit): extract resolve_root_timeline_id helper, eliminating the 12-line duplicate between the pre-flight dedup and the UNIQUE-recovery race-handling paths. R4 (info): add a comment on both dedup return paths explaining why StoreEvent::SessionUpdated is intentionally NOT emitted — the session was announced once at creation and re-broadcasting on every dedup hit would spam SSE/WebSocket consumers. 375 rewind-store + rewind-web tests pass; clippy clean. Made-with: Cursor
Pulls in #156 (replay context cursor fix). v0.14.1 was tagged right after #155 merged and before #156 landed, so the cursor fix needs a fresh GitHub Release to propagate to consumers. Track 1 only (3 files: Cargo.toml + python/rewind_cli.py + python-mcp/rewind_mcp_cli.py + Cargo.lock). Python SDK stays at 0.15.1 and MCP wheel stays at 0.13.1 — neither is on PyPI yet, so the cursor fix rides with those unreleased versions. Made-with: Cursor
Why
Multi-replica runners (Ray Serve
num_replicas>=2, autoscaling worker pools) each keep their ownExplicitClient._session_cache. When two/querycalls for the sameconversation_idland on different replicas, both miss their local cache and call/sessions/start, producing two duplicate Rewind sessions for what is logically one conversation.Concrete repro from dev1 today: two sessions named
ray-agent-631c6677appeared 41s apart, bothsource=api, with differenttotal_stepsand questions — clear evidence the same conversation_id was being split across replicas.What
Add an optional
client_session_keyfield onSession+ aUNIQUE WHERE NOT NULLSQLite index, and makePOST /api/sessions/startfind-or-create on that key.SQLITE_CONSTRAINT_UNIQUEre-resolve via the same lookup and return the winner).SDK side:
ExplicitClient.ensure_sessionpassesconversation_idasclient_session_key. The in-process cache stays as a fast path so repeatensure_sessioncalls in the SAME replica never hit the server.Backward compatibility
client_session_keyget the original "create every time" behavior. Verified withtest_start_session_without_key_creates_new_each_time.client_session_key=NULLare unaffected by the unique index (it'sWHERE client_session_key IS NOT NULL).row_to_sessiontolerates the column being absent from a SELECT (defensiveOption::ok().flatten()), so no existing code path breaks.Tests
crates/rewind-web/tests/recording_api_tests.rstest_start_session_idempotent_returns_existing,test_start_session_distinct_keys_create_distinct_sessions,test_start_session_without_key_creates_new_each_timepython/tests/test_explicit.pytest_ensure_session_sends_client_session_key,test_ensure_session_dedups_across_clients_via_server_keycargo test -p rewind-store -p rewind-web: 374 tests pass.pytest python/tests/test_explicit.py: 31 tests pass.cargo clippy: clean.Versions
Per
CLAUDE.md:python/rewind_cli.py+python-mcp/{pyproject,rewind_mcp_cli}to 0.14.1 (python-mcp/pyproject.tomlfrom 0.13.0 → 0.13.1).python/{pyproject.toml,rewind_agent/__init__.py}to 0.15.1.Test plan
session_idagainst ray-agent now produce ONE rewind session even though Serve has 2 replicasMade with Cursor