Repository navigation
Fix duplicate session race condition (TT-031) - #887
Merged
Merged
Conversation
Server-side race condition: when init() and identify() are called in quick succession (common with React Native SDK 1.3.1), both POST /ingest/session requests could arrive concurrently. The endpoint checked for an existing session, then created one if not found - a classic check-then-insert race that created duplicate rows. Root cause: - No unique constraint on (project_id, session_id) - Check-then-create pattern in POST /ingest/session endpoint Fix: 1. Added unique constraint on Session(project_id, session_id) 2. Changed endpoint to use upsert instead of check-then-create 3. Safe migration that dedupes existing duplicate rows first: - Merges ended_at from duplicates into earliest session - Deletes all but the earliest (smallest id) session per key 4. Added regression tests for concurrent session creation The SDK behavior is correct - identify() should be able to update user info immediately after init(). Server now handles this atomically.
…merging, and tests Fixes per review of PR #887 (TT-031, Refs #886): 1. **App dimension in unique key**: Changed from (project_id, session_id) to (project_id, session_id, app) to match findIngestSession's filtering logic. Updated upsert where clause to include app. 2. **Deterministic row selection**: Use ROW_NUMBER() OVER (PARTITION BY ... ORDER BY started_at ASC, id ASC) instead of MIN(id) to ensure earliest session by started_at, then id is kept. 3. **Complete field merging**: Before DELETE, UPDATE merges ALL nullable fields (user_id, user_email, anonymous_id, country, device_browser, device_os, sdk_version, platform, environment, release) using latest non-null values; ended_at uses GREATEST (MAX) of all non-null values. 4. **Transaction**: Wrapped entire migration in BEGIN/COMMIT. 5. **Migration regression test**: Added test that seeds duplicates where identify() row has larger UUID than init() row, verifies kept row has earliest started_at/id with all fields merged, and other apps untouched. Includes second test for multiple duplicates with same started_at. 6. **Bug fix**: Added ended_at to createData in upsert so concurrent requests that win the create race preserve ended_at from the request body. All tests pass (migration test + existing ingest tests).
Only include ended_at and started_at fields in createData when they are provided in the request body, rather than passing undefined which might cause issues in some environments.
…ion creation Prisma's upsert uses SELECT-then-INSERT (not ON CONFLICT) when conditions aren't met, causing P2002 unique violations on concurrent requests in CI. Fix: Native INSERT ... ON CONFLICT (project_id, session_id, app) DO UPDATE with merge semantics matching the migration: - COALESCE to preserve existing non-null fields - GREATEST for ended_at to keep the latest value This ensures truly atomic upsert behavior that handles concurrent init() + identify() calls without race conditions.
- Migration: change ORDER BY to DESC to pick latest non-null values (not oldest) - Migration: flip COALESCE to COALESCE(latest, existing) so latest wins - Ingest ON CONFLICT: use COALESCE(EXCLUDED.x, Session.x) so new non-null wins - Tests: execute actual migration.sql statements (not hand-copied logic) - Tests: verify latest non-null values win, seed later rows with different data - Tests: add upsert test to verify ON CONFLICT preserves existing non-null fields Addresses review feedback on PR #887 (TT-031)
| ) VALUES ( | ||
| gen_random_uuid(), ${projectId}, ${sessionId}, ${app}, | ||
| ${"react-native"}, ${"production"}, ${"2.0.0"}, | ||
| ${"user-2"}, ${"[email protected]"}, ${null}, ${"CA"}, |
| gen_random_uuid(), ${projectId}, ${sessionId}, ${app}, | ||
| ${"react-native"}, ${"production"}, ${"2.0.0"}, | ||
| ${"user-2"}, ${"[email protected]"}, ${null}, ${"CA"}, | ||
| ${null}, ${null}, ${"1.3.1"}, ${startedAt}, ${null} |
| gen_random_uuid(), ${projectId}, ${sessionId}, ${app}, | ||
| ${"react-native"}, ${"production"}, ${"2.0.0"}, | ||
| ${"user-2"}, ${"[email protected]"}, ${null}, ${"CA"}, | ||
| ${null}, ${null}, ${"1.3.1"}, ${startedAt}, ${null} |
| gen_random_uuid(), ${projectId}, ${sessionId}, ${app}, | ||
| ${"react-native"}, ${"production"}, ${"2.0.0"}, | ||
| ${"user-2"}, ${"[email protected]"}, ${null}, ${"CA"}, | ||
| ${null}, ${null}, ${"1.3.1"}, ${startedAt}, ${null} |
| ) VALUES ( | ||
| gen_random_uuid(), ${projectId}, ${sessionId}, ${app}, | ||
| ${"react-native"}, ${"production"}, ${"2.1.0"}, | ||
| ${null}, ${null}, ${null}, ${null}, |
| ) VALUES ( | ||
| gen_random_uuid(), ${projectId}, ${sessionId}, ${app}, | ||
| ${"react-native"}, ${"production"}, ${"2.1.0"}, | ||
| ${null}, ${null}, ${null}, ${null}, |
| ) VALUES ( | ||
| gen_random_uuid(), ${projectId}, ${sessionId}, ${app}, | ||
| ${"react-native"}, ${"production"}, ${"2.1.0"}, | ||
| ${null}, ${null}, ${null}, ${null}, |
| ) VALUES ( | ||
| gen_random_uuid(), ${projectId}, ${sessionId}, ${app}, | ||
| ${"react-native"}, ${"production"}, ${"2.1.0"}, | ||
| ${null}, ${null}, ${null}, ${null}, |
| gen_random_uuid(), ${projectId}, ${sessionId}, ${app}, | ||
| ${"react-native"}, ${"production"}, ${"2.1.0"}, | ||
| ${null}, ${null}, ${null}, ${null}, | ||
| ${null}, ${null}, ${"1.3.1"}, ${startedAt}, ${null} |
| gen_random_uuid(), ${projectId}, ${sessionId}, ${app}, | ||
| ${"react-native"}, ${"production"}, ${"2.1.0"}, | ||
| ${null}, ${null}, ${null}, ${null}, | ||
| ${null}, ${null}, ${"1.3.1"}, ${startedAt}, ${null} |
unjica
added a commit
that referenced
this pull request
Oct 28, 2026
1. Drop started_at fallback: Only use strict-newer comparison when BOTH stored and incoming have timestamps. Requests without identity_updated_at use #887 behavior (new non-null wins). Old SDKs (1.3.1) remain affected until apps upgrade. 2. Migration: Remove backfill, leave identity_updated_at NULL for existing sessions. 3. Timestamp clamping: Clamp client timestamp to LEAST(client_ts, now()) and bound by started_at to prevent future timestamps and ensure logical ordering. 4. Core init() fix: Preserve identity only if set via identify-before-init (no active session). Clear stale identity from previous sessions. Supports identify-before-init pattern while preventing stale user carryover from re-init scenarios. 5. Tests updated: - QA sequence: stale init() first, then identify() - Old-SDK identify mid-session (uses #887 behavior) - Future timestamp clamping - SDK: identify-before-init preservation - SDK: re-init clears stale identity 6. CHANGELOG updated to reflect actual behavior and note that old SDKs stay affected. Root cause confirmed: init() calls startSession() which builds payload with module-level userId before clearing it. With new strict-newer logic and timestamp clamping, this is now properly handled. Refs #886
unjica
added a commit
that referenced
this pull request
Oct 28, 2026
…follow-up) (#890) * Fix stale identity overwrite with timestamp-based protection **Server:** Add identity_updated_at column to Session table. Only update user_id/user_email when incoming timestamp is newer than stored value. Protects against delayed SDK requests overwriting fresher identity data. **SDK:** Track identity timestamps in telemetry-core. When identify() is called, capture current timestamp and send as identity_updated_at. Old SDKs without this field fall back to started_at as the identity timestamp. **Tests:** Added regression tests for: - Stale request arriving after identify() (should be rejected) - Newer identity overwriting older identity (should succeed) - Backward compat: old SDK without identity_updated_at (uses started_at) **Root cause:** RN SDK 1.3.1 sends delayed session requests ~1s after identify(), carrying previous user's ID. With new non-null-wins COALESCE logic from #887, stale requests overwrote correct user. Solution: timestamp-based ordering prevents out-of-order updates. **Versions:** - @telemetry-tracker/core: 1.5.2 → 1.5.3 - @telemetry-tracker/react-native: 1.3.1 → 1.3.2 Refs #886 * Address PR #890 review blockers 1. Drop started_at fallback: Only use strict-newer comparison when BOTH stored and incoming have timestamps. Requests without identity_updated_at use #887 behavior (new non-null wins). Old SDKs (1.3.1) remain affected until apps upgrade. 2. Migration: Remove backfill, leave identity_updated_at NULL for existing sessions. 3. Timestamp clamping: Clamp client timestamp to LEAST(client_ts, now()) and bound by started_at to prevent future timestamps and ensure logical ordering. 4. Core init() fix: Preserve identity only if set via identify-before-init (no active session). Clear stale identity from previous sessions. Supports identify-before-init pattern while preventing stale user carryover from re-init scenarios. 5. Tests updated: - QA sequence: stale init() first, then identify() - Old-SDK identify mid-session (uses #887 behavior) - Future timestamp clamping - SDK: identify-before-init preservation - SDK: re-init clears stale identity 6. CHANGELOG updated to reflect actual behavior and note that old SDKs stay affected. Root cause confirmed: init() calls startSession() which builds payload with module-level userId before clearing it. With new strict-newer logic and timestamp clamping, this is now properly handled. Refs #886 * Fix test timing: use past timestamps to avoid clamping to server time Use timestamps 1 minute in the past for QA sequence test to prevent clamping to server time when test runs close to 'now'.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Base branch: open feature and fix PRs against
develop. Milestone releases promotedevelop→main— see docs/RELEASE.md.Summary
Fixes duplicate session rows created when calling
identify()immediately afterinit()in the React Native SDK 1.3.1 (Refs #886, TT-031).Root cause: Server-side check-then-insert race condition in POST
/ingest/session. Wheninit()andidentify()send concurrent session creation requests with the samesession_id, both checked for an existing session, found none, and created duplicate rows. The Session table had no unique constraint on(project_id, session_id)to prevent this.Fix:
@@unique([project_id, session_id])constraint to Session modelended_atand deletes duplicates before adding constraint/ingest/sessionfrom check-then-create to atomicupserton the unique keyThe SDK behavior is correct —
identify()should be callable immediately afterinit(). The server now handles concurrent session updates atomically.How to test
Specifically for the new tests:
Code review (Bugbot)
/review-bugbotin Cursor (optional while the gate is paused).cursor/BUGBOT.mdif a finding was a false positive)Checklist
pnpm test; useRUN_DB_INTEGRATION_TESTS=true+ Postgres if API integration behavior changed)pnpm lint)pnpm build)[Unreleased](if user-facing)Security / privacy
This change fixes a data integrity issue in the ingest pipeline. The migration safely dedupes existing sessions without data loss. No new PII handling or auth changes.