From 3dffbef0d888d5ba7312159fd501628f47c8e47b Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Mon, 9 Nov 2026 15:55:42 -0500 Subject: [PATCH 1/2] fix: skip the person-properties hash for maybe-personless updates and fill $lib as a pair The hash guard read only the process_person_profile option, but a registered or legacy $process_person_profile false is hoisted into options later, at send. Such a $set recorded a hash it couldn't apply, so the same update sent after unregistering was dropped as a duplicate. Resolve the setting the way it's sent (non-null option, then the legacy property) and record a hash only when it's missing or a Boolean true. Fill the SDK's $lib and $lib_version as a pair after the caller's properties, per sdk-specs #146: another library's $lib never gets this SDK's version, and a $lib_version without a $lib is replaced. Co-Authored-By: Claude Opus 5.5 --- .changeset/v4-major-release.md | 1 + MIGRATION.md | 4 ++ PostHog/PostHogSDK.swift | 34 +++++++++-- PostHogTests/PostHogCaptureV1Test.swift | 76 +++++++++++++++++++++++++ 4 files changed, 109 insertions(+), 6 deletions(-) diff --git a/.changeset/v4-major-release.md b/.changeset/v4-major-release.md index 4674b1b75..23ff6d668 100644 --- a/.changeset/v4-major-release.md +++ b/.changeset/v4-major-release.md @@ -33,6 +33,7 @@ PostHog iOS 4.0: see the [migration guide](https://github.com/PostHog/posthog-io - **Breaking:** pause sending for at most 30 seconds on `Retry-After`, including session replay and logs - **Breaking:** send `$process_person_profile`, `$cookieless_mode`, `$ignore_sent_at` and `$product_tour_id` as capture options, so PostHog drops an event whose option value it can't read - **Breaking:** let registered super properties override SDK properties such as `$os`, and let super and event properties override `$is_identified`, `$process_person_profile`, `$geoip_disable` and the session replay debug values +- **Breaking:** fill `$lib` and `$lib_version` as a pair after your properties, so a `$lib` you pass without `$lib_version` is sent without one and a `$lib_version` without `$lib` is replaced - **Breaking:** let `userProperties`, `userPropertiesSetOnce` and `groups` win key by key over `$set`, `$set_once` and `$groups` passed in the same call's properties - **Breaking:** rename `maxRetries` to `pushNotificationSubscriptionMaxRetries` - **Breaking:** send `$session_id` and `$window_id` as top-level `session_id` and `window_id` fields, and drop a value that isn't a string diff --git a/MIGRATION.md b/MIGRATION.md index 0c97d3150..487f85700 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -232,6 +232,10 @@ If you also pass `$set`, `$set_once` or `$groups` in the properties, the per-cal In 3.x, the SDK's own values won over super properties, and `$is_identified`, `$process_person_profile`, `$geoip_disable` and the session replay debug properties also won over the properties you pass. In 4.0 a value you register or pass wins, for example `capture("signed_up", properties: ["$geoip_disable": false])` sends that event with GeoIP enabled even when `disableGeoIp` is on. +`$lib` and `$lib_version` are the exception: the SDK fills them as a pair after all of the above, before `beforeSend`. +If `$lib` is missing or empty, the SDK sets both, replacing a `$lib_version` you passed on its own. +If `$lib` names another library, the SDK leaves both as you set them and doesn't add its own version. + ### Session and window IDs Capture v1 sends `$session_id` and `$window_id` as top-level `session_id` and `window_id` fields, not as properties. diff --git a/PostHog/PostHogSDK.swift b/PostHog/PostHogSDK.swift index c923f238f..eff4194d2 100644 --- a/PostHog/PostHogSDK.swift +++ b/PostHog/PostHogSDK.swift @@ -683,6 +683,28 @@ let maxRetryDelay = 30.0 value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } + /// Whether the event is sure to update the person profile. The setting is read as it is sent: a + /// non-null option wins over the legacy `$process_person_profile` property. Only a missing setting + /// or a Boolean `true` counts, so a value PostHog might read as false never records a hash. + private static func surelyProcessesPersonProfile(_ event: PostHogEvent) -> Bool { + let option = event.options["process_person_profile"] + let value = isNullValue(option) ? event.properties["$process_person_profile"] : option + return isNullValue(value) || value as? Bool == true + } + + /// Fills the SDK's own `$lib` and `$lib_version` as a pair, so another library's `$lib` never + /// gets this SDK's version and a `$lib_version` without a `$lib` is replaced. + private static func fillLibraryIdentity(_ props: inout [String: Any], sdkInfo: [String: Any]) { + guard let sdkLib = sdkInfo["$lib"] as? String else { return } + let lib = props["$lib"] as? String + if lib.isNilOrEmpty { + props["$lib"] = sdkLib + props["$lib_version"] = sdkInfo["$lib_version"] + } else if lib == sdkLib, (props["$lib_version"] as? String).isNilOrEmpty { + props["$lib_version"] = sdkInfo["$lib_version"] + } + } + private static func isReplayDebugEvent(_ event: String?) -> Bool { guard let event else { return false } return event.hasPrefix("$") @@ -792,11 +814,6 @@ let maxRetryDelay = 30.0 } } - let sdkInfo = context?.sdkInfo() - if sdkInfo != nil { - props = props.merging(sdkInfo ?? [:]) { current, _ in current } - } - if let sessionId { if propSessionId.isNilOrEmpty { props["$session_id"] = sessionId @@ -895,6 +912,11 @@ let maxRetryDelay = 30.0 } props.merge(callerProps) { _, new in new } + // The SDK's own library identity fills last, after every caller layer. + if let sdkInfo = context?.sdkInfo() { + Self.fillLibraryIdentity(&props, sdkInfo: sdkInfo) + } + return props } @@ -2682,7 +2704,7 @@ let maxRetryDelay = 30.0 // A personless event doesn't update the person, so it neither marks nor matches a hash. if event.event == PostHogKnownUnsafeEditableEvent.set.rawValue || event.event == PostHogKnownUnsafeEditableEvent.identify.rawValue, userProperties != nil || userPropertiesSetOnce != nil, - event.options["process_person_profile"] as? Bool != false, + Self.surelyProcessesPersonProfile(event), let storageManager = config.storageManager { let hash = getPersonPropertiesHash( diff --git a/PostHogTests/PostHogCaptureV1Test.swift b/PostHogTests/PostHogCaptureV1Test.swift index b4024f323..f66510750 100644 --- a/PostHogTests/PostHogCaptureV1Test.swift +++ b/PostHogTests/PostHogCaptureV1Test.swift @@ -769,6 +769,82 @@ final class PostHogCaptureV1OptionsTest { #expect(events.last?.options["process_person_profile"] == nil) } + /// `beforeSend` edits only the first `$set`, tagged with `first`, and removes the tag so both + /// updates hash the same. + private static func editFirstSet(_ edit: @escaping @Sendable (PostHogEvent) -> Void) -> BeforeSendBlock { + { event in + guard var set = event.properties["$set"] as? [String: Any], set.removeValue(forKey: "first") != nil else { return event } + event.properties["$set"] = set + edit(event) + return event + } + } + + @Test("a $set whose legacy or non-Boolean setting may be personless doesn't suppress the same properties later", + arguments: ["registered false", "string false option", "legacy false under a null option"]) + func maybePersonlessSetDoesNotDeduplicate(setup: String) async throws { + let legacyFalse = Self.editFirstSet { + $0.properties["$process_person_profile"] = false + $0.options["process_person_profile"] = NSNull() + } + let sut = makeSDK(personProfiles: .always, flushAt: 2, beforeSend: setup == "legacy false under a null option" ? legacyFalse : nil) + defer { sut.close() } + + server.reset(batchCount: 1) + switch setup { + case "registered false": + sut.register(["$process_person_profile": false]) + sut.setPersonProperties(userPropertiesToSet: ["plan": "pro"]) + sut.unregister("$process_person_profile") + case "string false option": + sut.setPersonProperties(userPropertiesToSet: ["plan": "pro"], options: ["process_person_profile": "false"]) + default: + sut.setPersonProperties(userPropertiesToSet: ["plan": "pro", "first": true]) + } + sut.setPersonProperties(userPropertiesToSet: ["plan": "pro"]) + let events = try await getServerEvents(server) + + #expect(events.map(\.event) == ["$set", "$set"]) + #expect(events.last?.options["process_person_profile"] == nil) + } + + @Test("an explicit true option beats a legacy false, so the same properties set later are deduplicated") + func explicitTrueOptionDeduplicates() async throws { + let sut = makeSDK(personProfiles: .always, flushAt: 2, beforeSend: Self.editFirstSet { + $0.properties["$process_person_profile"] = false + $0.options["process_person_profile"] = true + }) + defer { sut.close() } + + server.reset(batchCount: 1) + sut.setPersonProperties(userPropertiesToSet: ["plan": "pro", "first": true]) + sut.setPersonProperties(userPropertiesToSet: ["plan": "pro"]) + sut.capture("after") + let events = try await getServerEvents(server) + + #expect(events.map(\.event) == ["$set", "after"]) + } + + @Test("the SDK fills $lib and $lib_version as a pair after the caller's properties", + arguments: [ + ([:], postHogSdkName, postHogVersion), + (["$lib": "custom-lib", "$lib_version": "9.9.9"], "custom-lib", "9.9.9"), + (["$lib": "custom-lib"], "custom-lib", nil), + (["$lib": "", "$lib_version": "9.9.9"], postHogSdkName, postHogVersion), + (["$lib_version": "9.9.9"], postHogSdkName, postHogVersion), + (["$lib": postHogSdkName], postHogSdkName, postHogVersion), + ] as [([String: String], String, String?)]) + func libraryIdentityPair(properties: [String: String], lib: String, version: String?) async throws { + let sut = makeSDK() + defer { sut.close() } + + let sent = try await captureAndSend(sut) { $0.capture("test", properties: properties) } + + let sentProperties = try #require(sent["properties"] as? [String: Any]) + #expect(sentProperties["$lib"] as? String == lib) + #expect(sentProperties["$lib_version"] as? String == version) + } + @Test("a blank distinctId argument uses the current distinct ID", arguments: ["", " "]) func blankDistinctIdFallsBack(distinctId: String) async throws { let sut = makeSDK() From fe456c21fbabaf7026d21485f8edc84946113fbc Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Mon, 9 Nov 2026 16:03:49 -0500 Subject: [PATCH 2/2] fix: clear the person-properties hash when queueing a maybe-personful update An update whose setting isn't a clear Boolean, such as the string "true", skipped the hash but left the previous one in place. PostHog may still apply it, so a later update back to the previous properties was dropped as a duplicate. Clear the stored hash instead. Co-Authored-By: Claude Opus 5.5 --- PostHog/PostHogSDK.swift | 12 ++++++------ PostHog/PostHogStorageManager.swift | 10 +++++++--- PostHogTests/PostHogCaptureV1Test.swift | 14 ++++++++++++++ 3 files changed, 27 insertions(+), 9 deletions(-) diff --git a/PostHog/PostHogSDK.swift b/PostHog/PostHogSDK.swift index eff4194d2..0b65ccb03 100644 --- a/PostHog/PostHogSDK.swift +++ b/PostHog/PostHogSDK.swift @@ -2701,23 +2701,23 @@ let maxRetryDelay = 30.0 let userPropertiesSetOnce = event.properties["$set_once"] as? [String: Any] // Presence, not content: sanitizing can empty a non-empty input (a `UUID` or `Data` value // is dropped), and that empty `$set` is still queued, so it needs a marker too. - // A personless event doesn't update the person, so it neither marks nor matches a hash. + // An update that may be personless never matches a hash, and clears the stored one: PostHog + // might still apply it, so a later update back to the previous properties must be sent. if event.event == PostHogKnownUnsafeEditableEvent.set.rawValue || event.event == PostHogKnownUnsafeEditableEvent.identify.rawValue, userProperties != nil || userPropertiesSetOnce != nil, - Self.surelyProcessesPersonProfile(event), let storageManager = config.storageManager { - let hash = getPersonPropertiesHash( + let hash = Self.surelyProcessesPersonProfile(event) ? getPersonPropertiesHash( distinctId: event.distinctId, userPropertiesToSet: userProperties, userPropertiesToSetOnce: userPropertiesSetOnce - ) + ) : nil // Check and enqueue under the same lock so concurrent calls cannot enqueue duplicates. let (isDuplicate, stored) = cachedPersonPropertiesLock.withLock { () -> (Bool, Bool) in - if deduplicatePersonProperties, storageManager.getPersonPropertiesHash() == hash { + if deduplicatePersonProperties, let hash, storageManager.getPersonPropertiesHash() == hash { return (true, false) } - // Only a stored event marks the properties as sent, so a failed write is retried. + // Only a stored event updates the hash, so a failed write is retried. let stored = queue.add(event) if stored { storageManager.setPersonPropertiesHash(hash) diff --git a/PostHog/PostHogStorageManager.swift b/PostHog/PostHogStorageManager.swift index 25571844e..fd8606fce 100644 --- a/PostHog/PostHogStorageManager.swift +++ b/PostHog/PostHogStorageManager.swift @@ -231,11 +231,15 @@ import Foundation /// Persists the hash of the last queued person properties update. /// - /// - Parameter hash: New hash to store. - func setPersonPropertiesHash(_ hash: String) { + /// - Parameter hash: New hash to store, or `nil` to clear it. + func setPersonPropertiesHash(_ hash: String?) { personPropertiesHashLock.withLock { personPropertiesHash = hash - storage.setString(forKey: .personPropertiesHash, contents: hash) + if let hash { + storage.setString(forKey: .personPropertiesHash, contents: hash) + } else { + storage.remove(key: .personPropertiesHash) + } } } diff --git a/PostHogTests/PostHogCaptureV1Test.swift b/PostHogTests/PostHogCaptureV1Test.swift index f66510750..497b607c2 100644 --- a/PostHogTests/PostHogCaptureV1Test.swift +++ b/PostHogTests/PostHogCaptureV1Test.swift @@ -808,6 +808,20 @@ final class PostHogCaptureV1OptionsTest { #expect(events.last?.options["process_person_profile"] == nil) } + @Test("an update that may be personful clears the stored hash, so going back to the previous properties is sent") + func maybePersonfulSetClearsHash() async throws { + let sut = makeSDK(personProfiles: .always, flushAt: 3) + defer { sut.close() } + + server.reset(batchCount: 1) + sut.setPersonProperties(userPropertiesToSet: ["plan": "a"]) + sut.setPersonProperties(userPropertiesToSet: ["plan": "b"], options: ["process_person_profile": "true"]) + sut.setPersonProperties(userPropertiesToSet: ["plan": "a"]) + let events = try await getServerEvents(server) + + #expect(events.compactMap { ($0.properties["$set"] as? [String: Any])?["plan"] as? String } == ["a", "b", "a"]) + } + @Test("an explicit true option beats a legacy false, so the same properties set later are deduplicated") func explicitTrueOptionDeduplicates() async throws { let sut = makeSDK(personProfiles: .always, flushAt: 2, beforeSend: Self.editFirstSet {