Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .changeset/v4-major-release.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions MIGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,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.
Expand Down
44 changes: 33 additions & 11 deletions PostHog/PostHogSDK.swift
Original file line number Diff line number Diff line change
Expand Up @@ -687,6 +687,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("$")
Expand Down Expand Up @@ -796,11 +818,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
Expand Down Expand Up @@ -899,6 +916,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
}

Expand Down Expand Up @@ -2732,23 +2754,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,
event.options["process_person_profile"] as? Bool != false,
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)
Expand Down
10 changes: 7 additions & 3 deletions PostHog/PostHogStorageManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}

Expand Down
90 changes: 90 additions & 0 deletions PostHogTests/PostHogCaptureV1Test.swift
Original file line number Diff line number Diff line change
Expand Up @@ -769,6 +769,96 @@ 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 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 {
$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()
Expand Down
Loading