## Session Management & Attribution

Understanding how Alpha Insights manages sessions is crucial for accurate attribution and data analysis. This guide explains session lifecycle, cookie management, timeout handling, and how orders are attributed to traffic sources.

### What is a Session?

A session represents a continuous period of visitor activity on your website. It includes all pages viewed, events triggered, and actions taken from arrival to departure.

Key characteristics:

- Starts when visitor lands on any page of your site
- Continues as long as visitor is active
- Expires after 10 minutes of inactivity
- Each session has a unique ID
- Multiple sessions can belong to same visitor (returning visits)
- Sessions tracked via first-party cookies

Example session:

    10:00 AM - Visitor lands on homepage (session starts)
    10:02 AM - Views product category page
    10:05 AM - Clicks on product
    10:06 AM - Views product page
    10:08 AM - Adds to cart
    10:10 AM - Leaves site
    10:25 AM - Session expires (15 minutes after last activity)

    If visitor returns at 10:30 AM, a NEW session starts.

### Session Lifecycle

#### 1. Session Start (First Page View)

What happens:

1. Visitor lands on your site
2. Alpha Insights checks for existing session cookie
3. No cookie found → New session created
4. Unique session ID generated
5. Three cookies set (10-minute expiry):
   - `wpd_ai_session_id` - Session identifier
   - `wpd_ai_landing_page` - Landing URL with query params
   - `wpd_ai_referral_source` - HTTP referrer
6. Session data written to database (`wp_wpd_ai_session_data` table)
7. Device info captured (browser, OS, device type)
8. Traffic source determined from referrer and query parameters

Database record created:

    {
      "session_id": "wpd5f4dcc3b5aa765a123456789",
      "ip_address": "192.168.1.1",
      "landing_page": "https://store.com/products?utm_source=facebook&utm_campaign=spring",
      "referral_url": "https://www.facebook.com/...",
      "user_id": 0,
      "date_created_gmt": "2024-03-15 10:00:00",
      "date_updated_gmt": "2024-03-15 10:00:00",
      "device_category": "mobile",
      "operating_system": "iOS",
      "browser": "Safari",
      "device": "mobile",
      "additional_data": "{...}"
    }

#### 2. Session Continuation (Subsequent Pages)

What happens:

1. Visitor navigates to another page
2. Alpha Insights checks for session cookie
3. Cookie found → Continue existing session
4. Session ID read from cookie
5. Cookie expiry refreshed (+10 minutes from now)
6. Database record updated:
   - `date_updated_gmt` set to current time
   - Indicates session is still active
7. New event (page view) recorded with same session_id

Important: Landing page and referral URL do NOT change during a session. They're set once at session start.

#### 3. Session Activity

During session, events are tracked:

- Page views
- Product clicks
- Add to cart
- Checkout initiation
- Form submissions
- WooCommerce events

All events share the same session_id:

    // Example events in same session
    session_id: wpd5f4dcc3b5aa765a...
      - page_view (homepage) - 10:00:00
      - page_view (products) - 10:02:15
      - product_click (item 123) - 10:05:22
      - page_view (product 123) - 10:05:23
      - add_to_cart (product 123) - 10:08:14
      - page_view (checkout) - 10:09:45
      - init_checkout - 10:09:45
      - transaction (order 789) - 10:11:30

#### 4. Session End (Expiration)

Session expires when:

- 10 minutes pass with no page loads or activity
- Cookies expire (automatic browser behavior)
- User clears cookies manually
- Browser is closed (depends on browser settings)

What happens at expiration:

- Cookies deleted by browser automatically
- No server action needed (passive expiration)
- Session record remains in database with last `date_updated_gmt`
- Session duration calculated as: `date_updated_gmt - date_created_gmt`

If visitor returns after expiration:

- New session starts (new session ID generated)
- New landing page and referrer captured
- Treated as separate visit
- Both sessions link to same IP (but different session IDs)

### Session Timeout: Why 10 Minutes?

Reasons for 10-minute timeout:

1. Industry standard: Google Analytics uses 30 minutes, but 10 is common for eCommerce
2. Balance accuracy and privacy: Long enough to capture shopping journey, short enough to respect privacy
3. Prevents abandoned session inflation: User who leaves for lunch doesn't show 2-hour session
4. Accurate conversion tracking: Clear separation between visits
5. Performance: Shorter sessions = less cookie renewal overhead

What 10 minutes means:

- Active browsing: Session continues indefinitely (cookies refresh each page)
- Idle for 10 minutes: Session expires automatically
- Example: Browse for 30 minutes = 1 session (as long as no 10-minute gaps)

Developer note: Timeout can be customized via filter:

    // Change to 30 minutes
    add_filter('wpd_session_timeout_seconds', function($timeout) {
      return 30 * 60; // 30 minutes
    });

### Cookie Management

#### Cookie Details

1. wpd_ai_session_id

Property | Value
--- | ---
Purpose | Unique session identifier
Format | wpd + MD5 hash + timestamp
Example | wpd5f4dcc3b5aa765a1234567890
Expiry | 10 minutes from last activity
Domain | Your site domain
Path | / (site-wide)
Secure | No (works on HTTP and HTTPS)
HttpOnly | No (accessible to JavaScript)
SameSite | Lax (default)

Generation algorithm:

    function generate_unique_session_id() {
      $random_token = md5($_SERVER['HTTP_USER_AGENT'] . time());
      return 'wpd' . $random_token . time();
    }

2. wpd_ai_landing_page

Property | Value
--- | ---
Purpose | Store first page visited
Format | Full URL including query parameters
Example | https://store.com/shop?utm_source=facebook
Expiry | 10 minutes from last activity
Set once | Yes (only on first page, value doesn't change)
Used for | Order attribution, UTM tracking

Why full URL with query params?

- Captures UTM parameters for campaign tracking
- Captures campaign IDs (meta_cid, google_cid) for profit attribution
- Shows exact entry point with context
- Enables landing page analysis

3. wpd_ai_referral_source

Property | Value
--- | ---
Purpose | Store where visitor came from
Format | Full referrer URL
Example | https://www.google.com/search?q=...
Expiry | 10 minutes from last activity
Set once | Yes (only on first page)
Used for | Traffic source classification

Special handling:

- Own domain referrers ignored (set to empty)
- Empty referrer = Direct traffic
- Captures HTTP_REFERER header from browser
- Social platforms often strip referrers (use UTMs instead)

#### Cookie Lifecycle Example

    10:00:00 - Visitor lands on site
             → Cookies set with expiry 10:10:00

    10:03:00 - Visitor views another page
             → Cookie expiry updated to 10:13:00

    10:07:00 - Visitor adds to cart
             → Cookie expiry updated to 10:17:00

    10:10:00 - Visitor leaves site
             → Cookies still valid until 10:20:00

    10:15:00 - Visitor returns
             → Cookies still exist (within 10 min)
             → SAME session continues
             → Cookie expiry updated to 10:25:00

    10:25:00 - Visitor idle
             → Cookies expire at 10:25:00

    10:30:00 - Visitor returns
             → Cookies gone (expired)
             → NEW session starts

#### Cookie Privacy & Compliance

For complete privacy and GDPR compliance information, see the Privacy & Security guide.

First-party cookies:

- Set by your own domain (not third-party)
- Used for essential site functionality
- Required for accurate analytics
- Generally allowed by privacy laws for analytics

GDPR considerations:

- First-party analytics cookies often exempt from consent (check your jurisdiction)
- No personal data stored in cookies (just IDs)
- IP addresses stored in database (may need consent)
- Consider cookie consent banner if in EU
- Provide opt-out mechanism (exclude user roles)

Best practice:

- Include tracking in privacy policy
- Explain what cookies are set
- Provide opt-out instructions
- Consider cookie consent plugin

### Order Attribution

When a visitor places an order, Alpha Insights permanently links the order to the session's traffic source. This enables profit tracking by source in reports. To understand profit calculations, see How Alpha Insights Works.

#### Attribution Process

Step-by-step:

1. Visitor arrives:
   - Session starts
   - Landing page with UTMs saved to cookie
   - Referrer saved to cookie
2. Visitor browses:
   - Session continues
   - Events tracked
   - Cookies refresh each page
3. Visitor adds to cart:
   - Add to cart event recorded
   - Session ID links event
4. Visitor checks out:
   - Begins checkout process
   - Init checkout event
5. Order created:
   - WooCommerce creates order
   - `woocommerce_checkout_order_processed` hook fires
   - Alpha Insights reads cookies
   - Saves to order meta:
     - `_wpd_ai_landing_page` = landing URL
     - `_wpd_ai_referral_source` = referrer URL
     - `_wpd_ai_meta_campaign_id` = FB campaign ID (if present)
     - `_wpd_ai_google_campaign_id` = Google campaign ID (if present)
6. Transaction event:
   - Order status changes to paid status
   - Transaction event recorded with session_id
   - Links event to session

Result: Order permanently attributed to traffic source, even if cookies expire or session ends.

#### Attribution window

How long does attribution last?

Alpha Insights supports a configurable attribution window (1–30 days). Referral URL and landing page are stored when the visitor first arrives and expire after that many days from first set—they are not updated by later activity. So attribution can extend beyond a single session: if a visitor returns within the window, the original referrer and landing page are still used.

- Setting: Alpha Insights → Settings → General Settings → Attribution Window Timeout (days) (under Alpha Analytics & Event Tracking)
- Default: 3 days
- Effect: Orders and sessions are attributed to the traffic source and landing page until the window expires; after that, a new visit gets a new attribution.

For full details, see Attribution Window.

Example scenarios:

Scenario 1: Quick purchase (within session)

    Day 1, 10:00 AM - Click Facebook ad → Land on product page
    Day 1, 10:05 AM - Add to cart → Checkout → Complete purchase
    Result: Order attributed to Facebook (original landing page)

Scenario 2: Later purchase (session expired)

    Day 1, 10:00 AM - Click Facebook ad → Browse → Leave
    Day 3, 2:00 PM - Direct visit (type URL) → Complete purchase
    Result: Order attributed to Direct (new session, new attribution)

Scenario 3: Multiple sessions

    Day 1, 10:00 AM - Facebook ad → Browse → Leave (session expires)
    Day 1, 3:00 PM - Google search → Browse → Leave (new session, session expires)
    Day 2, 9:00 AM - Direct visit → Purchase (new session)
    Result: Order attributed to Direct (last session wins - last-click attribution)

#### Attribution Model: Last-Click

Alpha Insights uses last-click attribution:

- Order attributed to most recent session's landing page
- Session that contained the purchase gets credit
- Previous sessions and touchpoints not credited

Why last-click?

- Simple and deterministic
- Based on actual cookies at time of purchase
- No complex multi-touch modeling needed
- Matches most analytics platforms' default

Limitations of last-click:

- Doesn't credit awareness channels (Facebook ads that led to later Google search)
- Overvalues direct and branded search (often last touchpoint)
- Undervalues top-of-funnel marketing

Workaround: Multi-session analysis

Use Website Sessions report to see full customer journey:

1. Filter sessions by IP address or customer email
2. View all sessions from same visitor
3. See complete journey across multiple visits
4. Understand which channels assisted conversion

    Example multi-session analysis:

    Session 1 (Day 1):
    - Source: Facebook
    - Landing: product page
    - Events: product_page_view, left site
    - Order: No

    Session 2 (Day 2):
    - Source: Organic (Google search)
    - Landing: product page
    - Events: page_view, add_to_cart, left site
    - Order: No

    Session 3 (Day 3):
    - Source: Direct
    - Landing: cart page
    - Events: viewed_cart, init_checkout, transaction
    - Order: Yes (Order #789)

    Attribution: Direct (last-click)
    Reality: Facebook awareness → Google consideration → Direct conversion

### Only track engaged sessions

When Only Track & Report On Engaged Sessions is enabled (Alpha Insights → Settings → General Settings → Alpha Analytics & Event Tracking), Alpha Insights treats a session as “engaged” only after the visitor has interacted with the page (e.g. click, touch, or scroll). This reduces noise from bots and accidental page loads.

#### What “engaged” means

Engagement is detected on the frontend by the event tracking script:

- Click – Any mouse click on the page
- Pointer/touch – Touch or pointer interaction (improves mobile detection)
- Scroll – User scrolls the page (with a short delay to avoid false triggers)

As soon as one of these occurs, the session is marked as engaged for the rest of that visit.

#### How it affects tracking

- Page views: The first `page_view` event is not sent until the user has engaged. Once they click, touch, or scroll, the page view is sent and the session is marked engaged.
- Cookie: The cookie `wpd_ai_engaged_session` is set when engagement is detected (value `1`).
- Database: The session record has an `engaged_session` flag (0 or 1). It is set when the first page view is stored (after engagement) and can be updated later if engagement is detected on a subsequent request.
- Other events: Product clicks, add to cart, checkout, etc. are still sent as usual; only the initial page view is delayed until engagement.

#### How it affects reporting

When the setting is True:

- Website Traffic / Analytics reports can filter or focus on engaged sessions only (sessions where `engaged_session = 1` or duration > 0).
- Bounce rate and session counts may change because non-engaged single-page visits are excluded or not counted as full sessions.
- Use this when you want metrics that reflect real user interaction rather than all page loads (including bots and quick bounces).

When the setting is False, every page load sends a page view immediately and all sessions are tracked regardless of interaction.

#### Summary

Setting | First page view | Reporting
--- | --- | ---
Only track engaged = False | Sent on page load | All sessions included
Only track engaged = True | Sent after first click/scroll/touch | Only engaged sessions (or sessions with duration > 0) included

### Session Duration Calculation

Formula:

    session_duration = date_updated_gmt - date_created_gmt

Measured in: Seconds (converted to minutes in reports)

Example:

    date_created_gmt: 2024-03-15 10:00:00
    date_updated_gmt: 2024-03-15 10:08:30
    session_duration: 510 seconds (8 minutes 30 seconds)

Important notes:

- Minimum duration: 0 seconds (single page view, immediate exit)
- Maximum practical duration: Limited by 10-minute inactivity timeout
- Last page time unknown: Duration ends at last page load, not when user actually leaves
- Example: User spends 5 minutes on last page → not counted in duration

Calculating average session duration:

    SELECT AVG(TIMESTAMPDIFF(SECOND, date_created_gmt, date_updated_gmt)) as avg_duration_seconds
    FROM wp_wpd_ai_session_data
    WHERE date_created_gmt >= DATE_SUB(NOW(), INTERVAL 30 DAY);

### Session Identification

#### Unique Visitors vs Sessions

Unique visitors (users):

- Counted by unique IP addresses
- Approximate measure (not 100% accurate)
- Same IP = same user (even across sessions)
- Different IPs = different users (even if same person)

Sessions:

- Counted by unique session IDs
- Precise and accurate
- One visitor can have multiple sessions
- Each visit after 10-minute gap = new session

Relationship:

    Users ≤ Sessions

    Example:
    - 1 user visiting 3 times = 3 sessions
    - 10 users visiting once = 10 sessions
    - 5 users visiting twice = 10 sessions

#### Logged-in User Tracking

If user is logged in:

- `user_id` field populated in session data
- Links all sessions to WordPress user account
- Enables cross-device tracking (if same account)
- More accurate user identification

Benefit for repeat customers:

- Track lifetime behavior across sessions
- Link orders to user account
- Calculate customer lifetime value
- Analyze returning customer patterns

#### Cross-Device Tracking

Limitation: Alpha Insights does NOT track cross-device by default

Example:

    User on phone:
    - Session 1 (mobile, IP: 192.168.1.100)
    - Browse, add to cart, leave

    User on laptop:
    - Session 2 (desktop, IP: 10.0.0.50)
    - Different IP, different cookies
    - Treated as separate user

    Result: Two sessions, two "users" - no connection

Exception: Logged-in users

- If user logs in on both devices
- Both sessions link to same user_id
- Can be connected in analysis by user_id
- Still separate sessions, but same user

### Session Data Retention

How long is session data stored?

- Session and event data stored indefinitely by default
- Can configure retention period in settings
- Recommended: 90-365 days for analytics
- Order attribution always preserved (in order meta)

Cleanup strategies:

1. Manual cleanup:

       DELETE FROM wp_wpd_ai_session_data
          WHERE date_created_gmt < DATE_SUB(NOW(), INTERVAL 365 DAY);

2. Automated cleanup: Configure in General Settings (if available)
3. Archive old data: Export to CSV before deletion

What to keep:

- Keep at least 1 year for year-over-year analysis
- Keep sessions with orders (transaction events) indefinitely
- Archive very old data (2+ years) for long-term trends

### Session Filtering in Reports

Available filters:

- Date range: Filter by session start date
- Traffic source: Filter by acquisition source
- Device type: Mobile, desktop, tablet
- Browser: Chrome, Safari, Firefox, etc.
- Operating system: Windows, Mac, iOS, Android, etc.
- Session contains event: Filter sessions with specific events
- Landing page: Filter by entry URL
- UTM parameters: Filter by campaign, source, medium
- IP address: Filter by specific IP (for debugging)
- User ID: Filter by logged-in user

Use cases:

- Analyze mobile vs desktop conversion rates
- Compare traffic sources by device
- Find sessions with checkout errors
- Identify high-value sessions (multiple products viewed)
- Track individual customer journeys

### Technical Details

#### Session Storage

Database table: `wp_wpd_ai_session_data`

Key fields:

    session_id VARCHAR(255) - Unique identifier
    ip_address VARCHAR(100) - Visitor IP
    landing_page TEXT - First page URL
    referral_url TEXT - Where they came from
    user_id BIGINT - WordPress user ID (0 = guest)
    date_created_gmt DATETIME - Session start
    date_updated_gmt DATETIME - Last activity
    device_category VARCHAR(50) - mobile/desktop/tablet
    operating_system VARCHAR(100) - OS name
    browser VARCHAR(100) - Browser name
    additional_data LONGTEXT - JSON metadata

#### Session vs Event Relationship

    One-to-Many relationship:

    Session (1)
      ├── Event 1 (page_view)
      ├── Event 2 (product_click)
      ├── Event 3 (page_view)
      ├── Event 4 (add_to_cart)
      └── Event 5 (transaction)

    All events share same session_id
    JOIN events to sessions via session_id

#### Hooks & Filters

    // Modify session timeout
    add_filter('wpd_session_timeout_seconds', function($timeout) {
      return 30 * 60; // 30 minutes
    });

    // Modify session data before storage
    add_filter('wpd_session_data_before_storage', function($session_data) {
      // Custom modifications
      return $session_data;
    });

    // Action after session created/updated
    add_action('wpd_session_updated', function($session_data) {
      // Custom logic
    });

### Best Practices

- Respect 10-minute timeout: Don't encourage users to stay idle
- Use UTM parameters: Ensure accurate attribution across sessions
- Monitor session duration: Very short = possible UX issues
- Analyze multi-session journeys: Understand full customer path
- Configure data retention: Balance storage and historical analysis
- Test attribution: Place test orders from different sources
- Document custom events: Track important actions within sessions
- Regular cleanup: Archive and delete old sessions
- Privacy compliance: Disclose session tracking in privacy policy

### Troubleshooting Sessions

Sessions not being created:

- Check if analytics is enabled
- Verify cookies are enabled in browser
- Check if user role is excluded from tracking
- Verify bot detection isn't filtering legitimate users

Sessions too short:

- Check site speed (slow pages = users leave)
- Review bounce rate (1 page view = short session)
- Check if timeout is too short (10 minutes default)

Sessions not linking to orders:

- Check if landing page cookie is set
- Verify cookies aren't being cleared prematurely
- Check if purchase happens outside 10-minute window
- Review order meta fields for attribution data

Multiple sessions for same user:

- Expected behavior if 10+ minutes between visits
- Check if user is clearing cookies
- Verify timeout setting
- Consider if browser/device switching

#### Next Steps

- Review Technical Architecture for implementation details
- Read Privacy & Security for GDPR compliance
- Check Troubleshooting Guide for common issues
- See UTM Campaign Tracking for accurate attribution
- Learn about Traffic Source Analysis for optimization strategies
- Understand Website Analytics Overview for tracking basics