Skip to content

Fix duplicate session race condition (TT-031) - #887

Merged
unjica merged 6 commits into
developfrom
cursor/fix-duplicate-session-race-a93a
Oct 28, 2026
Merged

unjica merged 6 commits into
developfrom
cursor/fix-duplicate-session-race-a93a

Conversation

@unjica

@unjica unjica commented Oct 28, 2026 •

Copy link
Copy Markdown
Collaborator

Base branch: open feature and fix PRs against develop. Milestone releases promote develop → main — see docs/RELEASE.md.

Summary

Fixes duplicate session rows created when calling identify() immediately after init() 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. When init() and identify() send concurrent session creation requests with the same session_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:

  1. Database: Added @@unique([project_id, session_id]) constraint to Session model
  2. Migration: Safe dedupe migration that merges ended_at and deletes duplicates before adding constraint
  3. API: Changed POST /ingest/session from check-then-create to atomic upsert on the unique key
  4. Tests: Added regression tests for concurrent session creation (init + identify pattern)

The SDK behavior is correct — identify() should be callable immediately after init(). The server now handles concurrent session updates atomically.

How to test

pnpm lint && pnpm test && pnpm build

Specifically for the new tests:

cd apps/api && RUN_DB_INTEGRATION_TESTS=true pnpm vitest run src/ingest.integration.test.ts

Code review (Bugbot)

Paused: GitHub bugbot-review is currently a no-op. /review-bugbot is optional.

  • For notification, alert, billing, ingest, or auth changes: considered running /review-bugbot in Cursor (optional while the gate is paused)
  • If Bugbot comments appear anyway: addressed or replied (resolve thread + update .cursor/BUGBOT.md if a finding was a false positive)

Checklist

  • Tests pass (pnpm test; use RUN_DB_INTEGRATION_TESTS=true + Postgres if API integration behavior changed)
  • Lint passes (pnpm lint)
  • Build succeeds (pnpm build)
  • CHANGELOG.md updated under [Unreleased] (if user-facing)
  • Documentation updated (if needed)
  • New code follows the existing style
  • No breaking changes (or called out clearly above)

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.

Open in Web Open in Cursor 

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
unjica merged commit 4639cc5 into develop Oct 28, 2026
8 checks passed
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'.
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