Commit 66c187c0288 for woocommerce

commit 66c187c02888ac3285ae3810bdbf61d2ccb4f493
Author: Chi-Hsuan Huang <chihsuan.tw@gmail.com>
Date:   Wed Dec 2 11:51:35 2026 +0800

    Fix purchases missing from analytics after the session cookie expires (#71598)

    * Give server-side analytics events a session id after the cookie expires

    * Add changelog entry for the analytics session id fallback

    * Limit the analytics session id fallback to visitors with a tk_ai cookie

    * Give events opted into ClickHouse by a filter a fallback session id

    * Set the analytics fallback session id after the event-props filter

    Only the ClickHouse pixel gets the fallback now, so the Tracks pixel matches trunk,
    and a callback's own valid session id is kept. Tests read the queued pixels instead
    of get_properties(), which covers the ClickHouse path a filter can break.

diff --git a/packages/php/woocommerce-analytics/changelog/uni-1117-session-id-fallback b/packages/php/woocommerce-analytics/changelog/uni-1117-session-id-fallback
new file mode 100644
index 00000000000..3e88be06999
--- /dev/null
+++ b/packages/php/woocommerce-analytics/changelog/uni-1117-session-id-fallback
@@ -0,0 +1,4 @@
+Significance: patch
+Type: fixed
+
+Keep purchases and cart events in ClickHouse analytics when the shopper's session cookie has expired before checkout.
diff --git a/packages/php/woocommerce-analytics/src/class-wc-analytics-tracking.php b/packages/php/woocommerce-analytics/src/class-wc-analytics-tracking.php
index 673df2d90b7..7c8f327fa87 100644
--- a/packages/php/woocommerce-analytics/src/class-wc-analytics-tracking.php
+++ b/packages/php/woocommerce-analytics/src/class-wc-analytics-tracking.php
@@ -233,7 +233,12 @@ class WC_Analytics_Tracking {
 		$ch_error = null;
 		if ( Features::is_clickhouse_enabled() || ( isset( $properties['ch'] ) && 1 === (int) $properties['ch'] ) ) {
 			$properties['ch'] = 1;
-			$ch_result        = self::record_ch_event( $properties );
+			// Ingestion drops an event without a session id. Set after the event-props filter, so a
+			// callback's own valid id wins and the Tracks pixel stays as it was.
+			if ( self::needs_fallback_session_id( $properties, $is_client_supplied ) ) {
+				$properties['session_id'] = self::get_fallback_session_id( self::get_visitor_id() );
+			}
+			$ch_result = self::record_ch_event( $properties );
 			if ( is_wp_error( $ch_result ) ) {
 				$ch_error = $ch_result;
 			}
@@ -607,6 +612,52 @@ class WC_Analytics_Tracking {
 		return $all_properties;
 	}

+	/**
+	 * Session id for a server-side event whose request lost the session cookie, which expires
+	 * 30 minutes after the session starts. Same for a visitor all UTC day, so a visitor's late
+	 * events count as one session. Same shape as Woo Ads' `ServerPixel::fallback_session_id()`.
+	 *
+	 * @since 0.19.2
+	 *
+	 * @param string   $visitor_id The event's visitor id (`_ui`).
+	 * @param int|null $now        Unix time; now by default.
+	 * @return string A UUID v5-shaped id.
+	 */
+	private static function get_fallback_session_id( $visitor_id, $now = null ) {
+		$hash = sha1( 'woocommerce-analytics-session:' . $visitor_id . ':' . gmdate( 'Y-m-d', $now ?? time() ) );
+
+		return sprintf(
+			'%s-%s-5%s-%s-%s',
+			substr( $hash, 0, 8 ),
+			substr( $hash, 8, 4 ),
+			substr( $hash, 13, 3 ),
+			dechex( 0x8 | ( hexdec( $hash[16] ) & 0x3 ) ) . substr( $hash, 17, 3 ),
+			substr( $hash, 20, 12 )
+		);
+	}
+
+	/**
+	 * Whether a server-side event lacks a valid session id. Only for a browser that ran the
+	 * client (`tk_ai`): an IP-hash visitor with no cookies is usually a crawler.
+	 *
+	 * @param array $properties         Event properties.
+	 * @param bool  $is_client_supplied Whether the properties came from an untrusted client.
+	 * @return bool
+	 */
+	private static function needs_fallback_session_id( $properties, $is_client_supplied ) {
+		return ! $is_client_supplied && ! empty( $_COOKIE['tk_ai'] ) && ! self::is_uuid( $properties['session_id'] ?? null );
+	}
+
+	/**
+	 * Whether a value is a UUID string.
+	 *
+	 * @param mixed $value Value to check.
+	 * @return bool
+	 */
+	private static function is_uuid( $value ) {
+		return is_string( $value ) && 1 === preg_match( '/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iD', $value );
+	}
+
 	/**
 	 * Get the property names a client may not set.
 	 *
diff --git a/packages/php/woocommerce-analytics/tests/php/WC_Analytics_Tracking_Session_Fallback_Test.php b/packages/php/woocommerce-analytics/tests/php/WC_Analytics_Tracking_Session_Fallback_Test.php
new file mode 100644
index 00000000000..8f9e66184d6
--- /dev/null
+++ b/packages/php/woocommerce-analytics/tests/php/WC_Analytics_Tracking_Session_Fallback_Test.php
@@ -0,0 +1,293 @@
+<?php
+/**
+ * Tests for the fallback session id on server-side events.
+ *
+ * @package automattic/woocommerce-analytics
+ */
+
+namespace Automattic\Woocommerce_Analytics;
+
+use WorDBless\BaseTestCase;
+
+/**
+ * A server-side event whose request lost the session cookie still carries a session id,
+ * because ClickHouse ingestion drops events without one.
+ */
+class WC_Analytics_Tracking_Session_Fallback_Test extends BaseTestCase {
+
+	const VISITOR = 'oEZrV0/o6ozJet++P6UhCuhn';
+
+	const COOKIE_SESSION = 'd58f2527-b6a6-47e3-a27e-95a574a616de';
+
+	const UUID_V5 = '/^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/';
+
+	/**
+	 * Start each test with a visitor cookie, no session cookie and ClickHouse on.
+	 */
+	public function set_up(): void {
+		parent::set_up();
+		$this->reset_visitor_cache();
+		$this->set_pixel_batch_queue( array() );
+		$_COOKIE['tk_ai'] = self::VISITOR;
+		unset( $_COOKIE['woocommerceanalytics_session'] );
+		add_filter( 'woocommerce_analytics_clickhouse_enabled', '__return_true' );
+	}
+
+	/**
+	 * Clean up cookies, filters and the cached visitor id.
+	 */
+	public function tear_down(): void {
+		unset( $_COOKIE['tk_ai'], $_COOKIE['woocommerceanalytics_session'] );
+		remove_all_filters( 'woocommerce_analytics_clickhouse_enabled' );
+		remove_all_filters( 'woocommerce_analytics_experimental_proxy_tracking_enabled' );
+		remove_all_filters( 'jetpack_woocommerce_analytics_event_props' );
+		$this->reset_visitor_cache();
+		$this->set_pixel_batch_queue( array() );
+		parent::tear_down();
+	}
+
+	/**
+	 * Clear the memoized visitor id and IP so each test reads its own request.
+	 */
+	private function reset_visitor_cache(): void {
+		foreach ( array( 'cached_visitor_id', 'cached_ip' ) as $name ) {
+			$property = new \ReflectionProperty( WC_Analytics_Tracking::class, $name );
+			$property->setAccessible( true );
+			$property->setValue( null, null );
+		}
+	}
+
+	/**
+	 * Read or replace the pixels queued for shutdown delivery.
+	 *
+	 * @param array|null $queue Queue to set; null to only read it.
+	 * @return array
+	 */
+	private function set_pixel_batch_queue( ?array $queue = null ): array {
+		$property = new \ReflectionProperty( WC_Analytics_Tracking::class, 'pixel_batch_queue' );
+		$property->setAccessible( true );
+		if ( null !== $queue ) {
+			$property->setValue( null, $queue );
+		}
+		return $property->getValue();
+	}
+
+	/**
+	 * Set the session cookie the way the client writes it.
+	 *
+	 * @param string $session_id Session id to store.
+	 */
+	private function set_session_cookie( string $session_id ): void {
+		$_COOKIE['woocommerceanalytics_session'] = rawurlencode( wp_json_encode( array( 'session_id' => $session_id ) ) );
+	}
+
+	/**
+	 * The fallback session id for a visitor.
+	 *
+	 * @param string   $visitor_id Visitor id.
+	 * @param int|null $now        Unix time.
+	 * @return string
+	 */
+	private function fallback( string $visitor_id, ?int $now = null ): string {
+		$method = new \ReflectionMethod( WC_Analytics_Tracking::class, 'get_fallback_session_id' );
+		$method->setAccessible( true );
+		return $method->invoke( null, $visitor_id, $now );
+	}
+
+	/**
+	 * Record a server-fired purchase and return the query of its queued pixel.
+	 *
+	 * @param string $pixel_url Pixel_Builder::CH_PIXEL_URL or Pixel_Builder::TRACKS_PIXEL_URL.
+	 * @return array|null The pixel's query, or null when none was queued.
+	 */
+	private function record_purchase( string $pixel_url ): ?array {
+		WC_Analytics_Tracking::record_event( 'product_purchase', array( 'pi' => 1 ) );
+
+		return $this->queued_pixel( $pixel_url );
+	}
+
+	/**
+	 * The query of the one queued pixel sent to a URL.
+	 *
+	 * @param string $pixel_url Pixel URL.
+	 * @return array|null The pixel's query, or null when none was queued.
+	 */
+	private function queued_pixel( string $pixel_url ): ?array {
+		$pixels = array_values(
+			array_filter(
+				$this->set_pixel_batch_queue(),
+				static function ( $url ) use ( $pixel_url ) {
+					return 0 === strpos( $url, $pixel_url . '?' );
+				}
+			)
+		);
+		if ( ! $pixels ) {
+			return null;
+		}
+		$this->assertCount( 1, $pixels );
+		parse_str( (string) wp_parse_url( $pixels[0], PHP_URL_QUERY ), $query );
+		return $query;
+	}
+
+	/**
+	 * Assert the ClickHouse purchase carries the visitor's fallback, whichever side of UTC midnight it was built.
+	 */
+	private function assertPurchaseGetsFallback(): void {
+		$before = $this->fallback( self::VISITOR );
+		$actual = $this->record_purchase( Pixel_Builder::CH_PIXEL_URL )['session_id'] ?? null;
+		$after  = $this->fallback( self::VISITOR );
+
+		$this->assertMatchesRegularExpression( self::UUID_V5, (string) $actual );
+		$this->assertContains( $actual, array( $before, $after ) );
+	}
+
+	/**
+	 * Replace the session id an event-props filter returns.
+	 *
+	 * @param string $session_id Session id the filter sets.
+	 */
+	private function filter_session_id( string $session_id ): void {
+		add_filter(
+			'jetpack_woocommerce_analytics_event_props',
+			static function ( $props ) use ( $session_id ) {
+				$props['session_id'] = $session_id;
+				return $props;
+			}
+		);
+	}
+
+	/**
+	 * A purchase after the session cookie expired gets the visitor's fallback session id.
+	 */
+	public function test_event_without_session_cookie_gets_fallback_session_id(): void {
+		$this->assertPurchaseGetsFallback();
+	}
+
+	/**
+	 * The fallback is only for ClickHouse, so the Tracks pixel is sent as before.
+	 */
+	public function test_tracks_pixel_gets_no_fallback_session_id(): void {
+		$this->assertPurchaseGetsFallback();
+
+		$tracks = $this->queued_pixel( Pixel_Builder::TRACKS_PIXEL_URL );
+		$this->assertNotNull( $tracks );
+		$this->assertArrayNotHasKey( 'session_id', $tracks );
+	}
+
+	/**
+	 * The cookie's session id is kept when it is valid.
+	 */
+	public function test_valid_cookie_session_id_is_kept(): void {
+		$this->set_session_cookie( self::COOKIE_SESSION );
+
+		$this->assertSame( self::COOKIE_SESSION, $this->record_purchase( Pixel_Builder::CH_PIXEL_URL )['session_id'] ?? null );
+	}
+
+	/**
+	 * A malformed cookie session id would be dropped by ingestion too, so it is replaced.
+	 */
+	public function test_malformed_cookie_session_id_is_replaced(): void {
+		$this->set_session_cookie( 'not-a-uuid' );
+
+		$this->assertPurchaseGetsFallback();
+	}
+
+	/**
+	 * Tracks-only stores send no ClickHouse pixel, and their Tracks pixel stays as it was.
+	 */
+	public function test_no_fallback_when_clickhouse_is_disabled(): void {
+		remove_all_filters( 'woocommerce_analytics_clickhouse_enabled' );
+
+		$this->assertNull( $this->record_purchase( Pixel_Builder::CH_PIXEL_URL ) );
+		$this->assertArrayNotHasKey( 'session_id', $this->queued_pixel( Pixel_Builder::TRACKS_PIXEL_URL ) );
+	}
+
+	/**
+	 * Events the client sends through the proxy are left as they were.
+	 */
+	public function test_no_fallback_for_client_supplied_events(): void {
+		WC_Analytics_Tracking::record_event( 'page_view', array(), true );
+
+		$ch = $this->queued_pixel( Pixel_Builder::CH_PIXEL_URL );
+		$this->assertNotNull( $ch );
+		$this->assertArrayNotHasKey( 'session_id', $ch );
+	}
+
+	/**
+	 * A cookie-less request with an IP-hash visitor id (proxy tracking) is usually a crawler.
+	 */
+	public function test_no_fallback_without_tk_ai_cookie(): void {
+		unset( $_COOKIE['tk_ai'] );
+		add_filter( 'woocommerce_analytics_experimental_proxy_tracking_enabled', '__return_true' );
+		$server                 = $_SERVER;
+		$_SERVER['REMOTE_ADDR'] = '8.8.8.8';
+		// No user agent: `User_Agent_Info::is_bot()` caches its first answer for the whole run.
+
+		try {
+			$ch = $this->record_purchase( Pixel_Builder::CH_PIXEL_URL );
+		} finally {
+			$_SERVER = $server;
+		}
+
+		$this->assertNotEmpty( $ch['_ui'] ?? null, 'Proxy tracking gives the request an IP-hash visitor id.' );
+		$this->assertArrayNotHasKey( 'session_id', $ch );
+	}
+
+	/**
+	 * A valid session id an event-props callback sets is kept, as Woo Ads sets its own.
+	 */
+	public function test_filter_session_id_is_kept(): void {
+		$this->filter_session_id( self::COOKIE_SESSION );
+
+		$this->assertSame( self::COOKIE_SESSION, $this->record_purchase( Pixel_Builder::CH_PIXEL_URL )['session_id'] ?? null );
+	}
+
+	/**
+	 * A callback that breaks a valid cookie session id does not get the event dropped.
+	 */
+	public function test_filter_that_breaks_session_id_gets_fallback(): void {
+		$this->set_session_cookie( self::COOKIE_SESSION );
+		$this->filter_session_id( 'not-a-uuid' );
+
+		$this->assertPurchaseGetsFallback();
+	}
+
+	/**
+	 * An event a filter opts into ClickHouse on a store with ClickHouse off still gets a session id there.
+	 */
+	public function test_per_event_clickhouse_opt_in_gets_fallback_session_id(): void {
+		remove_all_filters( 'woocommerce_analytics_clickhouse_enabled' );
+		add_filter(
+			'jetpack_woocommerce_analytics_event_props',
+			static function ( $props ) {
+				$props['ch'] = 1;
+				return $props;
+			}
+		);
+
+		$this->assertPurchaseGetsFallback();
+	}
+
+	/**
+	 * One session per visitor per UTC day.
+	 */
+	public function test_fallback_session_id_is_stable_per_visitor_and_utc_day(): void {
+		$morning = gmmktime( 0, 0, 0, 11, 30, 2026 );
+		$night   = gmmktime( 23, 59, 59, 11, 30, 2026 );
+
+		$this->assertSame(
+			$this->fallback( self::VISITOR, $morning ),
+			$this->fallback( self::VISITOR, $night )
+		);
+		$this->assertNotSame(
+			$this->fallback( self::VISITOR, $night ),
+			$this->fallback( self::VISITOR, $night + 1 ),
+			'A new UTC day starts a new session.'
+		);
+		$this->assertNotSame(
+			$this->fallback( self::VISITOR, $morning ),
+			$this->fallback( 'another-visitor', $morning ),
+			'Another visitor gets another session.'
+		);
+	}
+}