From e745b5ece2d9aa28df13613f50e9005bff44de7c Mon Sep 17 00:00:00 2001 From: Manoel Aranda Neto Date: Thu, 15 Jan 2026 16:24:32 -0300 Subject: [PATCH 1/5] chore: implement setPersonProps method --- .../java/com/posthog/android/PostHogFake.kt | 6 + posthog/src/main/java/com/posthog/PostHog.kt | 72 ++++++ .../main/java/com/posthog/PostHogInterface.kt | 19 ++ .../src/test/java/com/posthog/PostHogTest.kt | 238 ++++++++++++++++++ 4 files changed, 335 insertions(+) diff --git a/posthog-android/src/test/java/com/posthog/android/PostHogFake.kt b/posthog-android/src/test/java/com/posthog/android/PostHogFake.kt index 9e11e6389..813b1bf30 100644 --- a/posthog-android/src/test/java/com/posthog/android/PostHogFake.kt +++ b/posthog-android/src/test/java/com/posthog/android/PostHogFake.kt @@ -74,6 +74,12 @@ public class PostHogFake : PostHogInterface { override fun flush() { } + override fun setPersonProperties( + userPropertiesToSet: Map?, + userPropertiesToSetOnce: Map?, + ) { + } + override fun setPersonPropertiesForFlags( userProperties: Map, reloadFeatureFlags: Boolean, diff --git a/posthog/src/main/java/com/posthog/PostHog.kt b/posthog/src/main/java/com/posthog/PostHog.kt index bb567cb26..2a641d55d 100644 --- a/posthog/src/main/java/com/posthog/PostHog.kt +++ b/posthog/src/main/java/com/posthog/PostHog.kt @@ -54,11 +54,15 @@ public class PostHog private constructor( private val personProcessingLock: Any = Any() private val featureFlagsCalledLock = Any() + private val cachedPersonPropertiesLock = Any() private var remoteConfig: PostHogRemoteConfig? = null private var replayQueue: PostHogQueueInterface? = null private val featureFlagsCalled = mutableMapOf>() + // Used to deduplicate setPersonProperties calls + private var cachedPersonPropertiesHash: String? = null + private var sessionReplayHandler: PostHogSessionReplayHandler? = null private var surveysHandler: PostHogSurveysHandler? = null @@ -720,6 +724,64 @@ public class PostHog private constructor( } } + public override fun setPersonProperties( + userPropertiesToSet: Map?, + userPropertiesToSetOnce: Map?, + ) { + if (!isEnabled()) { + return + } + + if (userPropertiesToSet.isNullOrEmpty() && userPropertiesToSetOnce.isNullOrEmpty()) { + return + } + + if (!requirePersonProcessing("setPersonProperties")) { + return + } + + val currentDistinctId = this.distinctId + + // Calculate hash to deduplicate calls with the same properties + val hash = getPersonPropertiesHash(currentDistinctId, userPropertiesToSet, userPropertiesToSetOnce) + + synchronized(cachedPersonPropertiesLock) { + if (cachedPersonPropertiesHash == hash) { + config?.logger?.log("A duplicate setPersonProperties call was made with the same properties. It has been ignored.") + return + } + cachedPersonPropertiesHash = hash + } + + // Update person properties for flags (setOnce properties are applied first, then set properties override) + val allProperties = mutableMapOf() + userPropertiesToSetOnce?.let { allProperties.putAll(it) } + userPropertiesToSet?.let { allProperties.putAll(it) } + if (allProperties.isNotEmpty()) { + setPersonPropertiesForFlags(allProperties, reloadFeatureFlags = false) + } + + // Send the $set event + capture( + "\$set", + distinctId = currentDistinctId, + userProperties = userPropertiesToSet, + userPropertiesSetOnce = userPropertiesToSetOnce, + ) + } + + /** + * Computes a hash for deduplicating setPersonProperties calls. + */ + private fun getPersonPropertiesHash( + distinctId: String, + userPropertiesToSet: Map?, + userPropertiesToSetOnce: Map?, + ): String { + // Simple hash based on JSON-like string representation + return "$distinctId|${userPropertiesToSet?.entries?.sortedBy { it.key }}|${userPropertiesToSetOnce?.entries?.sortedBy { it.key }}" + } + private fun hasPersonProcessing(): Boolean { return !( config?.personProfiles == PersonProfiles.NEVER || @@ -1045,6 +1107,9 @@ public class PostHog private constructor( getPreferences().clear(except = except.toList()) remoteConfig?.clear() featureFlagsCalled.clear() + synchronized(cachedPersonPropertiesLock) { + cachedPersonPropertiesHash = null + } synchronized(identifiedLock) { isIdentifiedLoaded = false } @@ -1317,6 +1382,13 @@ public class PostHog private constructor( shared.flush() } + public override fun setPersonProperties( + userPropertiesToSet: Map?, + userPropertiesToSetOnce: Map?, + ) { + shared.setPersonProperties(userPropertiesToSet, userPropertiesToSetOnce) + } + public override fun setPersonPropertiesForFlags( userProperties: Map, reloadFeatureFlags: Boolean, diff --git a/posthog/src/main/java/com/posthog/PostHogInterface.kt b/posthog/src/main/java/com/posthog/PostHogInterface.kt index cf948439c..cbf372113 100644 --- a/posthog/src/main/java/com/posthog/PostHogInterface.kt +++ b/posthog/src/main/java/com/posthog/PostHogInterface.kt @@ -187,6 +187,25 @@ public interface PostHogInterface : PostHogCoreInterface { */ public fun getSessionId(): UUID? + /** + * Sets properties on the person profile associated with the current distinct_id. + * Learn more about [identifying users](https://posthog.com/docs/product-analytics/identify) + * + * Updates user properties that are stored with the person profile in PostHog. + * If `personProfiles` is set to `IDENTIFIED_ONLY` and no profile exists, this will create one. + * + * This method sends a `$set` event to PostHog. + * + * @param userPropertiesToSet Optional: Properties to store about the user. These will overwrite existing values. + * @param userPropertiesToSetOnce Optional: Properties to store about the user only if not previously set. + * Note: For feature flag evaluations, if the same key is present in both parameters, + * the value from userPropertiesToSet will take precedence. + */ + public fun setPersonProperties( + userPropertiesToSet: Map? = null, + userPropertiesToSetOnce: Map? = null, + ) + /** * Sets person properties that will be included in feature flag evaluation requests. * diff --git a/posthog/src/test/java/com/posthog/PostHogTest.kt b/posthog/src/test/java/com/posthog/PostHogTest.kt index eeae7eb39..a21df396f 100644 --- a/posthog/src/test/java/com/posthog/PostHogTest.kt +++ b/posthog/src/test/java/com/posthog/PostHogTest.kt @@ -2172,4 +2172,242 @@ internal class PostHogTest { sut.close() http.shutdown() } + + @Test + fun `setPersonProperties captures set event`() { + val http = mockHttp() + val url = http.url("/") + + val sut = getSut(url.toString(), preloadFeatureFlags = false) + + val userPropertiesToSet = mapOf("email" to "user@example.com", "plan" to "premium") + val userPropertiesToSetOnce = mapOf("initial_url" to "/blog") + + sut.setPersonProperties(userPropertiesToSet, userPropertiesToSetOnce) + + queueExecutor.shutdownAndAwaitTermination() + + val request = http.takeRequest() + + assertEquals(1, http.requestCount) + val content = request.body.unGzip() + val batch = serializer.deserialize(content.reader()) + + val theEvent = batch.batch.first() + assertEquals("\$set", theEvent.event) + assertNotNull(theEvent.distinctId) + assertEquals(userPropertiesToSet, theEvent.properties!!["\$set"]) + assertEquals(userPropertiesToSetOnce, theEvent.properties!!["\$set_once"]) + + sut.close() + } + + @Test + fun `setPersonProperties with only userPropertiesToSet`() { + val http = mockHttp() + val url = http.url("/") + + val sut = getSut(url.toString(), preloadFeatureFlags = false) + + val userPropertiesToSet = mapOf("email" to "user@example.com") + + sut.setPersonProperties(userPropertiesToSet) + + queueExecutor.shutdownAndAwaitTermination() + + val request = http.takeRequest() + + assertEquals(1, http.requestCount) + val content = request.body.unGzip() + val batch = serializer.deserialize(content.reader()) + + val theEvent = batch.batch.first() + assertEquals("\$set", theEvent.event) + assertEquals(userPropertiesToSet, theEvent.properties!!["\$set"]) + + sut.close() + } + + @Test + fun `setPersonProperties with only userPropertiesToSetOnce`() { + val http = mockHttp() + val url = http.url("/") + + val sut = getSut(url.toString(), preloadFeatureFlags = false) + + val userPropertiesToSetOnce = mapOf("initial_url" to "/signup") + + sut.setPersonProperties(userPropertiesToSetOnce = userPropertiesToSetOnce) + + queueExecutor.shutdownAndAwaitTermination() + + val request = http.takeRequest() + + assertEquals(1, http.requestCount) + val content = request.body.unGzip() + val batch = serializer.deserialize(content.reader()) + + val theEvent = batch.batch.first() + assertEquals("\$set", theEvent.event) + assertEquals(userPropertiesToSetOnce, theEvent.properties!!["\$set_once"]) + + sut.close() + } + + @Test + fun `setPersonProperties ignores call with empty properties`() { + val http = mockHttp() + val url = http.url("/") + + val sut = getSut(url.toString(), preloadFeatureFlags = false) + + sut.setPersonProperties(emptyMap(), emptyMap()) + + queueExecutor.shutdownAndAwaitTermination() + + assertEquals(0, http.requestCount) + + sut.close() + } + + @Test + fun `setPersonProperties ignores call with null properties`() { + val http = mockHttp() + val url = http.url("/") + + val sut = getSut(url.toString(), preloadFeatureFlags = false) + + sut.setPersonProperties(null, null) + + queueExecutor.shutdownAndAwaitTermination() + + assertEquals(0, http.requestCount) + + sut.close() + } + + @Test + fun `setPersonProperties deduplicates identical calls`() { + val http = mockHttp() + val url = http.url("/") + + val sut = getSut(url.toString(), preloadFeatureFlags = false) + + val userPropertiesToSet = mapOf("email" to "user@example.com") + + // First call should succeed + sut.setPersonProperties(userPropertiesToSet) + + // Second identical call should be ignored + sut.setPersonProperties(userPropertiesToSet) + + queueExecutor.shutdownAndAwaitTermination() + + // Only one event should be sent + assertEquals(1, http.requestCount) + + sut.close() + } + + @Test + fun `setPersonProperties allows different properties after reset`() { + val http = mockHttp() + val url = http.url("/") + + val sut = getSut(url.toString(), preloadFeatureFlags = false, reloadFeatureFlags = false) + + val userPropertiesToSet = mapOf("email" to "user@example.com") + + // First call + sut.setPersonProperties(userPropertiesToSet) + + queueExecutor.awaitExecution() + + assertEquals(1, http.requestCount) + + // Reset clears the cache + sut.reset() + + // Same properties should now be allowed again + sut.setPersonProperties(userPropertiesToSet) + + queueExecutor.shutdownAndAwaitTermination() + + // Should have 2 events now + assertEquals(2, http.requestCount) + + sut.close() + } + + @Test + fun `setPersonProperties allows different properties`() { + val http = mockHttp() + val url = http.url("/") + + val sut = getSut(url.toString(), preloadFeatureFlags = false, flushAt = 2) + + val userPropertiesToSet1 = mapOf("email" to "user@example.com") + val userPropertiesToSet2 = mapOf("email" to "other@example.com") + + sut.setPersonProperties(userPropertiesToSet1) + sut.setPersonProperties(userPropertiesToSet2) + + queueExecutor.shutdownAndAwaitTermination() + + // Both events should be sent + assertEquals(1, http.requestCount) + + val request = http.takeRequest() + val content = request.body.unGzip() + val batch = serializer.deserialize(content.reader()) + + assertEquals(2, batch.batch.size) + + sut.close() + } + + @Test + fun `setPersonProperties is blocked when personProfiles is NEVER`() { + val http = mockHttp() + val url = http.url("/") + + val sut = getSut(url.toString(), preloadFeatureFlags = false, personProfiles = PersonProfiles.NEVER) + + val userPropertiesToSet = mapOf("email" to "user@example.com") + + sut.setPersonProperties(userPropertiesToSet) + + queueExecutor.shutdownAndAwaitTermination() + + assertEquals(0, http.requestCount) + + sut.close() + } + + @Test + fun `setPersonProperties updates person properties for flags`() { + val http = mockHttp(response = MockResponse().setBody(responseFlagsApi)) + val url = http.url("/") + + val cachePreferences = PostHogMemoryPreferences() + val sut = getSut(url.toString(), preloadFeatureFlags = false, cachePreferences = cachePreferences) + + val userPropertiesToSet = mapOf("email" to "user@example.com", "plan" to "premium") + val userPropertiesToSetOnce = mapOf("initial_url" to "/blog") + + sut.setPersonProperties(userPropertiesToSet, userPropertiesToSetOnce) + + queueExecutor.shutdownAndAwaitTermination() + + // Verify person properties for flags were updated + val cachedProps = cachePreferences.getValue(PERSON_PROPERTIES_FOR_FLAGS) as? Map<*, *> + assertNotNull(cachedProps) + assertEquals("user@example.com", cachedProps["email"]) + assertEquals("premium", cachedProps["plan"]) + // setOnce properties should be included too + assertEquals("/blog", cachedProps["initial_url"]) + + sut.close() + http.shutdown() + } } From 3b23214f51d7099365381b89b31014e0487a23e7 Mon Sep 17 00:00:00 2001 From: Manoel Aranda Neto Date: Thu, 15 Jan 2026 16:35:10 -0300 Subject: [PATCH 2/5] fix --- posthog/src/main/java/com/posthog/PostHog.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/posthog/src/main/java/com/posthog/PostHog.kt b/posthog/src/main/java/com/posthog/PostHog.kt index 2a641d55d..14da4d599 100644 --- a/posthog/src/main/java/com/posthog/PostHog.kt +++ b/posthog/src/main/java/com/posthog/PostHog.kt @@ -763,7 +763,7 @@ public class PostHog private constructor( // Send the $set event capture( - "\$set", + PostHogEventName.SET.event, distinctId = currentDistinctId, userProperties = userPropertiesToSet, userPropertiesSetOnce = userPropertiesToSetOnce, From 2937e1acabd5a41a36082760ffd45fd5a1d5ddb5 Mon Sep 17 00:00:00 2001 From: Manoel Aranda Neto Date: Thu, 15 Jan 2026 16:40:42 -0300 Subject: [PATCH 3/5] fix compare --- posthog/src/main/java/com/posthog/PostHog.kt | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/posthog/src/main/java/com/posthog/PostHog.kt b/posthog/src/main/java/com/posthog/PostHog.kt index 14da4d599..7a127126a 100644 --- a/posthog/src/main/java/com/posthog/PostHog.kt +++ b/posthog/src/main/java/com/posthog/PostHog.kt @@ -772,14 +772,20 @@ public class PostHog private constructor( /** * Computes a hash for deduplicating setPersonProperties calls. + * Similar to the JS SDK, this creates a JSON string representation of the properties. */ private fun getPersonPropertiesHash( distinctId: String, userPropertiesToSet: Map?, userPropertiesToSetOnce: Map?, ): String { - // Simple hash based on JSON-like string representation - return "$distinctId|${userPropertiesToSet?.entries?.sortedBy { it.key }}|${userPropertiesToSetOnce?.entries?.sortedBy { it.key }}" + // Create a consistent JSON-like string representation similar to JS SDK's jsonStringify + val hashData = mapOf( + "distinct_id" to distinctId, + "userPropertiesToSet" to userPropertiesToSet, + "userPropertiesToSetOnce" to userPropertiesToSetOnce, + ) + return config?.serializer?.serializeObject(hashData) ?: hashData.toString() } private fun hasPersonProcessing(): Boolean { From 0e5740b87972a856c672dda4f57a67fa241d280d Mon Sep 17 00:00:00 2001 From: Manoel Aranda Neto Date: Fri, 16 Jan 2026 09:43:08 -0300 Subject: [PATCH 4/5] fix --- posthog-android/CHANGELOG.md | 2 + posthog/CHANGELOG.md | 2 + posthog/api/posthog.api | 4 ++ posthog/src/main/java/com/posthog/PostHog.kt | 16 ++++-- .../src/test/java/com/posthog/PostHogTest.kt | 50 +++++++++++++++++++ 5 files changed, 69 insertions(+), 5 deletions(-) diff --git a/posthog-android/CHANGELOG.md b/posthog-android/CHANGELOG.md index b66506a58..c26dbb35d 100644 --- a/posthog-android/CHANGELOG.md +++ b/posthog-android/CHANGELOG.md @@ -1,5 +1,7 @@ ## Next +- feat: implement setPersonProps method ([#369](https://github.com/PostHog/posthog-android/pull/369)) + ## 3.28.1 - 2026-01-09 - fix: Allow flag property overrides via `setPersonPropertiesForFlags`, `setGroupPropertiesForFlags` without person processing ([#365](https://github.com/PostHog/posthog-android/issues/365)) diff --git a/posthog/CHANGELOG.md b/posthog/CHANGELOG.md index a3b886beb..489954ff4 100644 --- a/posthog/CHANGELOG.md +++ b/posthog/CHANGELOG.md @@ -1,5 +1,7 @@ ## Next +- feat: implement setPersonProps method ([#369](https://github.com/PostHog/posthog-android/pull/369)) + ## 6.1.0 - 2025-01-09 - fix: Allow flag property overrides via `setPersonPropertiesForFlags`, `setGroupPropertiesForFlags` without person processing ([#365](https://github.com/PostHog/posthog-android/issues/365)) diff --git a/posthog/api/posthog.api b/posthog/api/posthog.api index 0e7fb14ea..504bcbb29 100644 --- a/posthog/api/posthog.api +++ b/posthog/api/posthog.api @@ -35,6 +35,7 @@ public final class com/posthog/PostHog : com/posthog/PostHogStateless, com/posth public fun resetPersonPropertiesForFlags (Z)V public fun screen (Ljava/lang/String;Ljava/util/Map;)V public fun setGroupPropertiesForFlags (Ljava/lang/String;Ljava/util/Map;Z)V + public fun setPersonProperties (Ljava/util/Map;Ljava/util/Map;)V public fun setPersonPropertiesForFlags (Ljava/util/Map;Z)V public fun setup (Lcom/posthog/PostHogConfig;)V public fun startSession ()V @@ -73,6 +74,7 @@ public final class com/posthog/PostHog$Companion : com/posthog/PostHogInterface public final fun resetSharedInstance ()V public fun screen (Ljava/lang/String;Ljava/util/Map;)V public fun setGroupPropertiesForFlags (Ljava/lang/String;Ljava/util/Map;Z)V + public fun setPersonProperties (Ljava/util/Map;Ljava/util/Map;)V public fun setPersonPropertiesForFlags (Ljava/util/Map;Z)V public fun setup (Lcom/posthog/PostHogConfig;)V public fun startSession ()V @@ -286,6 +288,7 @@ public abstract interface class com/posthog/PostHogInterface : com/posthog/PostH public abstract fun resetPersonPropertiesForFlags (Z)V public abstract fun screen (Ljava/lang/String;Ljava/util/Map;)V public abstract fun setGroupPropertiesForFlags (Ljava/lang/String;Ljava/util/Map;Z)V + public abstract fun setPersonProperties (Ljava/util/Map;Ljava/util/Map;)V public abstract fun setPersonPropertiesForFlags (Ljava/util/Map;Z)V public abstract fun startSession ()V public abstract fun startSessionReplay (Z)V @@ -305,6 +308,7 @@ public final class com/posthog/PostHogInterface$DefaultImpls { public static synthetic fun resetPersonPropertiesForFlags$default (Lcom/posthog/PostHogInterface;ZILjava/lang/Object;)V public static synthetic fun screen$default (Lcom/posthog/PostHogInterface;Ljava/lang/String;Ljava/util/Map;ILjava/lang/Object;)V public static synthetic fun setGroupPropertiesForFlags$default (Lcom/posthog/PostHogInterface;Ljava/lang/String;Ljava/util/Map;ZILjava/lang/Object;)V + public static synthetic fun setPersonProperties$default (Lcom/posthog/PostHogInterface;Ljava/util/Map;Ljava/util/Map;ILjava/lang/Object;)V public static synthetic fun setPersonPropertiesForFlags$default (Lcom/posthog/PostHogInterface;Ljava/util/Map;ZILjava/lang/Object;)V public static synthetic fun startSessionReplay$default (Lcom/posthog/PostHogInterface;ZILjava/lang/Object;)V } diff --git a/posthog/src/main/java/com/posthog/PostHog.kt b/posthog/src/main/java/com/posthog/PostHog.kt index 7a127126a..a7d2adc01 100644 --- a/posthog/src/main/java/com/posthog/PostHog.kt +++ b/posthog/src/main/java/com/posthog/PostHog.kt @@ -773,18 +773,24 @@ public class PostHog private constructor( /** * Computes a hash for deduplicating setPersonProperties calls. * Similar to the JS SDK, this creates a JSON string representation of the properties. + * Keys are sorted to ensure deterministic hashing regardless of map insertion order. */ private fun getPersonPropertiesHash( distinctId: String, userPropertiesToSet: Map?, userPropertiesToSetOnce: Map?, ): String { + // Sort keys to ensure deterministic hashing regardless of map insertion order + val sortedSet = userPropertiesToSet?.toSortedMap() + val sortedSetOnce = userPropertiesToSetOnce?.toSortedMap() + // Create a consistent JSON-like string representation similar to JS SDK's jsonStringify - val hashData = mapOf( - "distinct_id" to distinctId, - "userPropertiesToSet" to userPropertiesToSet, - "userPropertiesToSetOnce" to userPropertiesToSetOnce, - ) + val hashData = + sortedMapOf( + "distinct_id" to distinctId, + "userPropertiesToSet" to sortedSet, + "userPropertiesToSetOnce" to sortedSetOnce, + ) return config?.serializer?.serializeObject(hashData) ?: hashData.toString() } diff --git a/posthog/src/test/java/com/posthog/PostHogTest.kt b/posthog/src/test/java/com/posthog/PostHogTest.kt index a21df396f..59cba8ccd 100644 --- a/posthog/src/test/java/com/posthog/PostHogTest.kt +++ b/posthog/src/test/java/com/posthog/PostHogTest.kt @@ -2410,4 +2410,54 @@ internal class PostHogTest { sut.close() http.shutdown() } + + @Test + fun `setPersonProperties deduplicates calls with same properties in different order`() { + val http = mockHttp() + val url = http.url("/") + + val sut = getSut(url.toString(), preloadFeatureFlags = false) + + // Create two maps with the same data but potentially different insertion order + val userPropertiesToSet1 = linkedMapOf("email" to "user@example.com", "plan" to "premium", "name" to "John") + val userPropertiesToSet2 = linkedMapOf("plan" to "premium", "name" to "John", "email" to "user@example.com") + + // First call + sut.setPersonProperties(userPropertiesToSet1) + + // Second call with same data but different key order - should be deduplicated + sut.setPersonProperties(userPropertiesToSet2) + + queueExecutor.shutdownAndAwaitTermination() + + // Only one event should be sent since the content is the same + assertEquals(1, http.requestCount) + + sut.close() + } + + @Test + fun `setPersonProperties deduplicates calls with same setOnce properties in different order`() { + val http = mockHttp() + val url = http.url("/") + + val sut = getSut(url.toString(), preloadFeatureFlags = false) + + // Create two maps with the same data but potentially different insertion order + val userPropertiesToSetOnce1 = linkedMapOf("initial_url" to "/blog", "referrer" to "google", "campaign" to "summer") + val userPropertiesToSetOnce2 = linkedMapOf("campaign" to "summer", "initial_url" to "/blog", "referrer" to "google") + + // First call + sut.setPersonProperties(userPropertiesToSetOnce = userPropertiesToSetOnce1) + + // Second call with same data but different key order - should be deduplicated + sut.setPersonProperties(userPropertiesToSetOnce = userPropertiesToSetOnce2) + + queueExecutor.shutdownAndAwaitTermination() + + // Only one event should be sent since the content is the same + assertEquals(1, http.requestCount) + + sut.close() + } } From b47b20f321f5848114fbdfd2e4a4151f9c7182f3 Mon Sep 17 00:00:00 2001 From: Manoel Aranda Neto Date: Fri, 16 Jan 2026 10:47:12 -0300 Subject: [PATCH 5/5] fix --- posthog/src/main/java/com/posthog/PostHog.kt | 9 +++--- .../java/com/posthog/internal/PostHogUtils.kt | 29 +++++++++++++++++++ .../src/test/java/com/posthog/PostHogTest.kt | 28 ++++++++++++++++++ 3 files changed, 62 insertions(+), 4 deletions(-) diff --git a/posthog/src/main/java/com/posthog/PostHog.kt b/posthog/src/main/java/com/posthog/PostHog.kt index a7d2adc01..556d82895 100644 --- a/posthog/src/main/java/com/posthog/PostHog.kt +++ b/posthog/src/main/java/com/posthog/PostHog.kt @@ -22,6 +22,7 @@ import com.posthog.internal.PostHogSessionManager import com.posthog.internal.PostHogThreadFactory import com.posthog.internal.personPropertiesContext import com.posthog.internal.replay.PostHogSessionReplayHandler +import com.posthog.internal.sortMapRecursively import com.posthog.internal.surveys.PostHogSurveysHandler import com.posthog.vendor.uuid.TimeBasedEpochGenerator import java.util.Date @@ -773,16 +774,16 @@ public class PostHog private constructor( /** * Computes a hash for deduplicating setPersonProperties calls. * Similar to the JS SDK, this creates a JSON string representation of the properties. - * Keys are sorted to ensure deterministic hashing regardless of map insertion order. + * Keys are sorted recursively to ensure deterministic hashing regardless of map insertion order. */ private fun getPersonPropertiesHash( distinctId: String, userPropertiesToSet: Map?, userPropertiesToSetOnce: Map?, ): String { - // Sort keys to ensure deterministic hashing regardless of map insertion order - val sortedSet = userPropertiesToSet?.toSortedMap() - val sortedSetOnce = userPropertiesToSetOnce?.toSortedMap() + // Sort keys recursively to ensure deterministic hashing regardless of map insertion order + val sortedSet = userPropertiesToSet?.let { sortMapRecursively(it) } + val sortedSetOnce = userPropertiesToSetOnce?.let { sortMapRecursively(it) } // Create a consistent JSON-like string representation similar to JS SDK's jsonStringify val hashData = diff --git a/posthog/src/main/java/com/posthog/internal/PostHogUtils.kt b/posthog/src/main/java/com/posthog/internal/PostHogUtils.kt index dae9079d2..252092bb8 100644 --- a/posthog/src/main/java/com/posthog/internal/PostHogUtils.kt +++ b/posthog/src/main/java/com/posthog/internal/PostHogUtils.kt @@ -7,6 +7,7 @@ import java.io.IOException import java.io.InterruptedIOException import java.net.SocketTimeoutException import java.net.UnknownHostException +import java.util.SortedMap import java.util.concurrent.Executor import java.util.concurrent.ExecutorService @@ -73,3 +74,31 @@ public fun Thread.interruptSafely() { // ignore } } + +/** + * Recursively sorts a map by keys at all levels. + * This is useful for creating deterministic string representations of maps. + */ +internal fun sortMapRecursively(map: Map): SortedMap { + val sortedMap = sortedMapOf() + for ((key, value) in map) { + sortedMap[key] = sortValueRecursively(value) + } + return sortedMap +} + +/** + * Recursively sorts values that are maps, lists, or arrays containing maps. + */ +private fun sortValueRecursively(value: Any?): Any? { + return when (value) { + is Map<*, *> -> { + @Suppress("UNCHECKED_CAST") + val stringKeyMap = value.filterKeys { it is String } as Map + sortMapRecursively(stringKeyMap) + } + is List<*> -> value.map { item -> sortValueRecursively(item) } + is Array<*> -> value.map { item -> sortValueRecursively(item) } + else -> value + } +} diff --git a/posthog/src/test/java/com/posthog/PostHogTest.kt b/posthog/src/test/java/com/posthog/PostHogTest.kt index 59cba8ccd..ae394049d 100644 --- a/posthog/src/test/java/com/posthog/PostHogTest.kt +++ b/posthog/src/test/java/com/posthog/PostHogTest.kt @@ -2460,4 +2460,32 @@ internal class PostHogTest { sut.close() } + + @Test + fun `setPersonProperties deduplicates calls with nested maps in different order`() { + val http = mockHttp() + val url = http.url("/") + + val sut = getSut(url.toString(), preloadFeatureFlags = false) + + // Create two maps with nested maps in different key order + val nested1 = linkedMapOf("city" to "London", "country" to "UK", "zip" to "12345") + val nested2 = linkedMapOf("zip" to "12345", "city" to "London", "country" to "UK") + + val userPropertiesToSet1 = linkedMapOf("name" to "John", "address" to nested1) + val userPropertiesToSet2 = linkedMapOf("address" to nested2, "name" to "John") + + // First call + sut.setPersonProperties(userPropertiesToSet1) + + // Second call with same data but different key order at both levels - should be deduplicated + sut.setPersonProperties(userPropertiesToSet2) + + queueExecutor.shutdownAndAwaitTermination() + + // Only one event should be sent since the content is the same + assertEquals(1, http.requestCount) + + sut.close() + } }