← Back to Pull requests

feat: add hashed user tracking #1332

Closed
unknown closed this pull request without merging on Dec 03, 2026 07:58 UTC
View on GitHub
unknown unknown commented on Nov 30, 2026 18:38 UTC
Author

TL; DR:

Watch video https://app.revyl.ai/sessions/report?token=fab9bd09-6f8b-42bd-81c4-6831145c8f74

Summary

Adds user.hash to every span and log record, so telemetry can tell users apart without saying who they are. I chose user.hash over user.id for privacy. Until the app signs a user in, the hash is a random value per installation. setHashedUser(_:), the only setter, takes raw identifiers such as an account ID and an email, and hashes them with HMAC-SHA256 under a key of the installation or one the app gives. The identifiers are never stored, stamped or logged. reset() returns to a new random value.

Ref: https://github.com/open-telemetry/opentelemetry-swift/issues/990

Testing

Updated hacker news demo

Limitations

Again, not doing user.id because that complicates the privacy stuff.

Checklist

  • swift test --enable-all-traits passes locally

  • Unit tests added or updated for the change

  • Instrumentation and event changes only: the integration tests in

  • Tests/IntegrationTests are updated. Anything that adds, removes or
    renames a span, log record, event name, or attribute emitted by an
    instrumentation (Sources/Instrumentation/) must be exercised by
    IntegrationTestScenario in Examples/HackerNewsDemo and asserted on
    in Tests/IntegrationTests/Assertions. Run make integ-tests-ios to
    verify, and see Tests/IntegrationTests/README.md.
  • Documentation updated (README, doc comments) where behavior changed
  • ---

    See docs Sources/Instrumentation/Users/README.md.

    ---

    Users

    Status: experimental. Names may change in any release. user.hash is at development stability in the semantic conventions.

    The UserManager** class tells users apart without exporting who they are. It holds one hash, stores it across launches, and two processors stamp it as user.hash on spans and log records. Until the app sets a user, the hash is a random value, so telemetry from one installation correlates before anyone signs in.

    !A timeline of one installation. The first launch generates and stores random hash A, and a restart restores it. Calling setHashedUser with an id and an email stores their HMAC in its place, and reset stores a new random hash B. A span that starts before setHashedUser and ends after it keeps A. The id and email are never stored, stamped or logged.

    Register both processors, ahead of the exporter:

    import Users
    
    let tracerProvider = TracerProviderBuilder()
      .add(spanProcessor: UserSpanProcessor())
      .add(spanProcessor: BatchSpanProcessor(spanExporter: spanExporter))
      .build()
    let loggerProvider = LoggerProviderBuilder()
      .with(processors: [
        UserLogRecordProcessor(nextProcessor: BatchLogRecordProcessor(logRecordExporter: logExporter))
      ])
      .build()
    

    Set the user at sign-in and at each signed-in launch, and reset at sign-out:

    let user = UserManagerProvider.getInstance()
    
    user.setHashedUser([accountId, email])
    user.reset()
    

    [!WARNING]

    setHashedUser(_:) receives personal data. The hash it makes is a pseudonym, not anonymous data: it still links one user's telemetry, and whoever holds the key can test guesses at an identifier. Pass only what you may process for this purpose.

    Instance properties

    <dl>
    <dt><code>userHash</code> <em>Read only</em></dt>
    <dd>The current hash. Never empty.</dd>
    </dl>

    user.hash

    <dl>
    <dt>On a span</dt>
    <dd>The hash current when the span started. A span that outlives a sign-in keeps the user who started it.</dd>
    <dt>On a log record</dt>
    <dd>The hash current when the record was emitted.</dd>
    </dl>

    A span that already carries user.hash when it starts, or a record that already carries it, is left alone. Attribute limits apply: a span or record already at its attribute count limit gets no user.hash, and a length limit under 64 truncates it. The SDK applies a span's limits, but applies LogLimits only before processors run, so give UserLogRecordProcessor the limits you give the LoggerProviderBuilder:

    let logLimits = LogLimits(maxAttributeCount: 64)
    let loggerProvider = LoggerProviderBuilder()
      .with(logLimits: logLimits)
      .with(processors: [
        UserLogRecordProcessor(nextProcessor: BatchLogRecordProcessor(logRecordExporter: logExporter), logLimits: logLimits)
      ])
      .build()
    

    Hashing

    setHashedUser(_:) computes HMAC-SHA256 and writes it as 64 lowercase hexadecimal digits. A plain SHA-256 would not hide an email address: anyone with the telemetry could hash a list of addresses and compare. The key prevents that, so where the key lives decides what the hash protects.

    | hashKey | Same user on two devices | Who can test a guess at an identifier |
    | ----------------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
    | None, the default | Different hashes, unless one was restored from the other's backup | Whoever holds that installation's storage or a backup of it, where its random key is |
    | Given by the app | The same hash | Whoever holds the key, or extracts it from the app |

    Order matters. Each identifier is length-prefixed, so ["ab", "c"] and ["a", "bc"] differ, and composed to Unicode NFC, so equal strings hash alike. Normalize case and whitespace before the call.

    Lifecycle

    | Event | Hash | Source |
    | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
    | First launch | Random, stored | This module |
    | Relaunch | Restored | [UserDefaults][defaults]: "a persistent store for app-specific and system-wide settings" |
    | setHashedUser(_:) | HMAC, stored | [UserDefaults][defaults]: "updates its in-memory version", then "writes the value to disk asynchronously" |
    | reset() | New random, stored | This module. The installation's key stays, so a returning user gets the same hash |
    | Device backup | Included, with the key | [UserDefaults][defaults]: "includes any persistent defaults databases in the backup data" |
    | App deleted and reinstalled | New random, and new key | Not documented |
    | Launch before the first unlock | If storage is unreadable, a new random hash overwrites the stored one, and the next setHashedUser(_:) overwrites the key | Not documented; not verified |

    <dl>
    <dt>Gaps</dt>
    <dd>The installation's key is in <code>UserDefaults</code>, which Apple says <a href="https://developer.apple.com/documentation/foundation/userdefaults">"stores information on disk in an unencrypted format"</a>. A crash reported on the next launch carries the user current then, not the one who crashed. Each manager reads storage only when created, so use one per storage key, in one process: the last to write wins. A new <code>hashKey</code> takes effect at the next <code>setHashedUser(_:)</code>. Metrics carry no <code>user.hash</code>.</dd>
    <dt>Opting out</dt>
    <dd>Leave the processors out. Nothing is generated or stored until a manager is created; a processor creates one at its first span or record.</dd>
    <dt>Privacy manifest</dt>
    <dd>Apps must declare <code>UserDefaults</code> in <code>PrivacyInfo.xcprivacy</code>, <a href="https://developer.apple.com/documentation/bundleresources/describing-use-of-required-reason-api">as a required-reason API</a>. This package ships no manifest.</dd>
    </dl>

    [defaults]: https://developer.apple.com/documentation/foundation/userdefaults

    Instance methods

    UserManager

    <dl>
    <dt><code>init(hashKey:userDefaults:storageKey:)</code></dt>
    <dd>Restores the stored hash, or generates and stores a random one. <code>hashKey</code> keys <code>setHashedUser(_:)</code>; an empty one counts as none. Storage defaults to <code>.standard</code>, under <code>otel-user-hash</code>.</dd>
    <dt><code>setHashedUser(_:)</code></dt>
    <dd>Takes a list of raw identifiers, such as an account ID and an email address, hashes them and sets the result. The identifiers are never stored, stamped or logged. A list with nothing in it, or only empty strings, changes nothing. Needs CryptoKit.</dd>
    <dt><code>reset()</code></dt>
    <dd>Replaces the hash with a new random value.</dd>
    </dl>

    Each change posts UserManager.didChangeNotification, with the manager as its object.

    UserManagerProvider

    <dl>
    <dt><code>register(userManager:)</code> <em>Static</em></dt>
    <dd>Shares a manager, such as one with a <code>hashKey</code>. Processors read it at each span or record, so one registered later still reaches them.</dd>
    <dt><code>getInstance()</code> <em>Static</em></dt>
    <dd>Returns the shared manager, creating a default one on first use.</dd>
    </dl>

    Specifications

    | Name | Kind | Specification |
    | ----------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
    | user.hash | Attribute | OpenTelemetry semantic conventions, as SemanticConventions.User.hash |

    The convention describes user.hash as a "unique user hash to correlate information for a user in anonymized form". The random value that stands in before sign-in is this module's own use.

    Compatibility

    | Platform | Minimum | Stamps user.hash | setHashedUser(_:) | Tested on |
    | --------------------------------------------- | --------------- | :----------------: | :-----------------: | ------------------------------------------- |
    | iOS | 15 | ✓ | ✓ | Simulator: unit tests and integration tests |
    | macOS | 12 | ✓ | ✓ | Unit tests |
    | iPadOS, tvOS, watchOS, visionOS, Mac Catalyst | 15, 15, 8, 1, — | ✓ | ✓ | — |
    | Linux, Windows | — | ✓, random only | —, no CryptoKit | — |

    Untested rows describe the code, not observed telemetry. The integration tests cover the generated hash; unit tests cover setHashedUser(_:).

    See also

  • Sessions: session.id, which changes while user.hash persists

  • Resource extension: app.installation.id, which the app cannot set

  • Crash: crash logs reported on the next launch

  • HMAC and UserDefaults

  • AwsOtelSwift AwsUIDManager: the design this module started from, which stamps a raw user.id
  • Diff: 650 lines (+487 / -163) across 8 files Reviewer: nachoBonafonte Review duration: 3680m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #1332"
    general weight: 0.35
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%