Skip to content

feat(sessions): idempotent /sessions/start via client_session_key - #155

Merged
risjai merged 2 commits into
masterfrom
feat/session-client-key
Apr 28, 2026
Merged

risjai merged 2 commits into
masterfrom
feat/session-client-key

Conversation

@risjai

@risjai risjai commented Apr 28, 2026

Copy link
Copy Markdown
Collaborator

Why

Multi-replica runners (Ray Serve 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 one conversation.

Concrete repro from dev1 today: two sessions named ray-agent-631c6677 appeared 41s apart, both source=api, with different total_steps and questions — clear evidence the same conversation_id was being split across replicas.

What

Add an optional client_session_key field on Session + a UNIQUE WHERE NOT NULL SQLite index, and make POST /api/sessions/start find-or-create on that key.

  • Pre-flight lookup avoids the round trip in the common case.
  • Post-insert UNIQUE-violation handler absorbs the multi-process race window deterministically (try insert; on SQLITE_CONSTRAINT_UNIQUE re-resolve via the same lookup and return the winner).
  • 200 OK on dedup hit (vs 201 CREATED on insert) so callers can branch if they care; response body shape is identical.

SDK side: ExplicitClient.ensure_session 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.

Backward compatibility

  • Callers that don't pass client_session_key get the original "create every time" behavior. Verified with test_start_session_without_key_creates_new_each_time.
  • Older sessions with client_session_key=NULL are unaffected by the unique index (it's WHERE client_session_key IS NOT NULL).
  • row_to_session tolerates the column being absent from a SELECT (defensive Option::ok().flatten()), so no existing code path breaks.

Tests

File Added
crates/rewind-web/tests/recording_api_tests.rs test_start_session_idempotent_returns_existing, test_start_session_distinct_keys_create_distinct_sessions, test_start_session_without_key_creates_new_each_time
python/tests/test_explicit.py test_ensure_session_sends_client_session_key, test_ensure_session_dedups_across_clients_via_server_key

cargo 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:

  • Track 1 (workspace 0.14.0 already released): bumped Cargo.toml + lock + python/rewind_cli.py + python-mcp/{pyproject,rewind_mcp_cli} to 0.14.1 (python-mcp/pyproject.toml from 0.13.0 → 0.13.1).
  • Track 2 (SDK 0.15.0 published): bumped python/{pyproject.toml,rewind_agent/__init__.py} to 0.15.1.

Test plan

  • CI green
  • Smoke deploy in dev1: two queries with same session_id against ray-agent now produce ONE rewind session even though Serve has 2 replicas

Made with Cursor

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
@vercel

vercel Bot commented Apr 28, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
rewind Ready Ready Preview, Comment Apr 28, 2026 3:22pm

@risjai risjai left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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"

Comment thread crates/rewind-web/src/api.rs Outdated
// 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() {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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>,

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Comment thread crates/rewind-web/src/api.rs Outdated
"unique violation but no session found by client_key".to_string(),
)
})?;
let timelines = store.get_timelines(&winner.id).map_err(|e| {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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((

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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
@risjai
risjai merged commit 89e07e6 into master Apr 28, 2026
6 checks passed
@risjai
risjai deleted the feat/session-client-key branch April 28, 2026 16:33
risjai added a commit that referenced this pull request Apr 28, 2026
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

This branch was successfully deployed

1 active deployment
Preview — a5b6dc3b Deployed Apr 28, 2026 by vercel[bot]
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.

1 participant