Skip to content

fix: drop alias() calls with a missing identity (sdk-specs alias) - #831

Draft
posthog[bot] wants to merge 1 commit into
mainfrom
posthog-code/alias-validate-identities
Draft

fix: drop alias() calls with a missing identity (sdk-specs alias)#831
posthog[bot] wants to merge 1 commit into
mainfrom
posthog-code/alias-validate-identities

Conversation

@posthog

@posthog posthog Bot commented Aug 5, 2026

Copy link
Copy Markdown

💡 Motivation and Context

The sdk-specs alias contract requires both identities to be present before an alias event is emitted:

  • openspec/specs/alias/spec.mdBehavior → Server-side flow, step 1: "Validate inputs. Both the existing id and the alias target id must be present."
  • Same file, scenario "Alias is dropped when required identities are missing (@both)""WHEN alias is called without a previous distinct id / THEN no event should be enqueued / AND the SDK should record a validation warning" (mirrored in acceptance/public/alias.feature)

Client.alias() did neither for previous_id — it was passed straight through with no check:

posthog.alias(None, "user-123")
# -> enqueued: {"event": "$create_alias", "distinct_id": null,
#               "properties": {"distinct_id": null, "alias": "user-123"}}
# -> returned a uuid, logged nothing

An alias event with a null source id cannot link anything, so this is a silently unusable event rather than a caught mistake. The same happened for previous_id="".

The other half of the validation — a missing alias target — was already dropped (get_identity_state reports personless when neither an explicit nor a context distinct id is available), but it returned None with no diagnostic at all, so the caller had no way to tell a dropped alias from a delivered one.

Change

  • previous_id is stringified and checked; empty/missing drops the call, logs a warning, and returns None.
  • The pre-existing missing-target drop now logs a warning too, so both spec-required "identity missing" paths record one.
  • previous_id is stringified once and reused, so distinct_id and properties.distinct_id agree for non-string ids (alias(0, ...) previously produced "0" at the top level and 0 in properties — _enqueue only stringifies the top-level field).

Signatures and the public API snapshot are unchanged; previous_id stays annotated str since passing None was never a supported call shape.

⚠️ Behavior change

Callers who pass a missing or empty previous_id stop getting a $create_alias event, and alias() returns None instead of a UUID for those calls. The events this removes were already inert — a $create_alias with a null distinct_id links no identities — so no working alias is affected. Callers checking the return value for success will now correctly see the failure, and will see a warning in the logs explaining it. Valid calls, including non-string ids such as alias(0, "user-123"), are unchanged.

💚 How did you test it?

Added four tests in posthog/test/test_client.py: previous_id=None and previous_id="" are dropped with a warning and nothing posted, previous_id=0 still sends and is stringified consistently, and a missing distinct_id is dropped with a warning. Confirmed the pre-change behavior first by running the SDK locally against a mocked batch_post.

Ran pytest posthog/test/test_client.py posthog/test/test_module.py posthog/test/test_contexts.py (190 passed), ruff format --check ., ruff check ., mypy ... | mypy-baseline filter (clean), check_public_api.py (snapshot up to date), and python -W error -c "import posthog". No manual or integration testing beyond that.

📝 Checklist

  • I reviewed the submitted code.
  • I added tests to verify the changes.
  • I updated the docs if needed. — alias() docstring documents the drop behavior.
  • No breaking change or entry added to the changelog. — behavior change, see above; changeset added.

If releasing new changes

  • Ran sampo add to generate a changeset file — hand-written at .sampo/changesets/alias-validates-identities.md (the sampo CLI isn't available in this environment); please sanity-check the format.

🤖 Agent context

Autonomy: Fully autonomous

Opened by the SDK Spec Compliance Enforcer loop, which audits posthog-python against the contracts in PostHog/sdk-specs. This run re-checked the spec capabilities whose Applicability is both or server, using parallel read-only sub-agents (Claude Code general-purpose agents with Read/Grep/Bash) and confirming each candidate by exercising the SDK locally.

This finding was chosen because the spec scenario is explicit and tagged @both, the current behavior produces an event that provably cannot do its job, and the fix is contained to one method. Runners-up left for humans, all from the same audit: group_identify() has the identical missing-validation gap against its own @both "Group identify requires type and key" scenario (a natural follow-up, kept out of this PR to keep it focused); capture() does not reject an empty event name, which the capture spec's Behavior/Error-handling prose requires but no scenario covers; and the capture spec asks for UUIDv7 event ids where the SDK generates UUIDv4, which is a larger change needing a product call. Note the previously closed #794 (wontfix) is unrelated to this change.

Agent-authored — requires human review; not self-merged.


Created with PostHog Code

The sdk-specs `alias` contract requires both identities to be present, and
its @both scenario "Alias is dropped when required identities are missing"
says no event should be enqueued and a validation warning should be recorded.

posthog-python did neither for `previous_id`: `alias(None, "user-123")` (or an
empty string) enqueued a `$create_alias` event with a null/empty `distinct_id`,
which links nothing. The missing-alias-target case already dropped the call but
logged nothing.

Both cases now log a warning and return None. `previous_id` is also stringified
once so `distinct_id` and `properties.distinct_id` agree for non-string ids.

Generated-By: PostHog Code
Task-Id: 0f22ca69-60f9-4887-908d-efef6c63b603
@github-actions

github-actions Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-08-05 07:57:08 UTC
Duration: 338849ms

✅ All Tests Passed!

111/111 tests passed


Capture_V1 Tests

94/94 tests passed

View Details
Test Status Duration
Endpoint And Method.Targets V1 Endpoint 516ms
Endpoint And Method.Does Not Use Legacy Endpoints 1011ms
Required Headers.Has Authorization Bearer Header 1009ms
Required Headers.Has Content Type Json 1008ms
Required Headers.Has Posthog Sdk Info Format 1009ms
Required Headers.Has Posthog Attempt Header 1009ms
Required Headers.Has Posthog Request Id 1009ms
Required Headers.Has Posthog Request Timestamp 1009ms
Required Headers.Has User Agent 1010ms
Body Format.Body Has Created At And Batch 1009ms
Body Format.No Api Key In Body 1010ms
Body Format.No Sent At In Body 1009ms
Event Format.Event Has Required Root Fields 1008ms
Event Format.Event Uuid Is Valid 1009ms
Event Format.Event Timestamp Is Rfc3339 1010ms
Event Format.Distinct Id Is String 1011ms
Event Format.Distinct Id At Root Not Properties 1007ms
Event Format.Custom Properties Preserved 1011ms
Event Format.Set Properties Preserved 1009ms
Event Format.Set Once Properties Preserved 1010ms
Event Format.Groups Properties Preserved 1010ms
Event Format.Sdk Generates Uuid If Not Provided 1009ms
Event Format.Event Has Required Root Fields Batch 1013ms
Event Format.Event Uuid Is Valid Batch 1013ms
Event Format.Event Timestamp Is Rfc3339 Batch 1013ms
Event Format.Distinct Id Is String Batch 1013ms
Event Format.Distinct Id At Root Not Properties Batch 1012ms
Event Format.Custom Properties Preserved Batch 1012ms
Event Format.Set Properties Preserved Batch 1013ms
Event Format.Set Once Properties Preserved Batch 1014ms
Event Format.Groups Properties Preserved Batch 1012ms
Event Format.Sdk Generates Uuid If Not Provided Batch 1013ms
Batch Behavior.Multiple Events In Single Batch 1507ms
Batch Behavior.Batch Envelope Smoke 1015ms
Batch Behavior.Flush With No Events Sends Nothing 1005ms
Batch Behavior.Flush At Triggers Batch 1508ms
Batch Behavior.Created At Reflects Batch Creation Time 1012ms
Deduplication.Generates Unique Uuids 1508ms
Deduplication.Different Events Same Content Different Uuids 1507ms
Deduplication.Preserves Uuid On Retry 7511ms
Deduplication.Preserves Timestamp On Retry 7516ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry 7512ms
Deduplication.No Duplicate Events In Batch 1503ms
Header Behavior On Retry.Attempt Header Starts At One 1010ms
Header Behavior On Retry.Attempt Header Increments On Retry 14515ms
Header Behavior On Retry.Request Id Preserved On Retry 7514ms
Header Behavior On Retry.Different Requests Have Different Request Ids 3518ms
Header Behavior On Retry.Request Timestamp Changes On Retry 7513ms
Response Format Validation.Success Response Has Uuid Keyed Results 1007ms
Response Format Validation.Success Response Has Ok For Each Event 1507ms
Response Format Validation.Success No Retry After When All Ok 1507ms
Response Format Validation.Success Retry After Present When Retry Events 2512ms
Response Format Validation.Success No Retry After When Drop Only 1506ms
Response Format Validation.Response Echoes Request Id 1009ms
Retry Behavior.Retries On 408 7519ms
Retry Behavior.Retries On 500 7510ms
Retry Behavior.Retries On 503 9517ms
Retry Behavior.Retries On 504 7511ms
Retry Behavior.Retryable Errors Have Retry After 4507ms
Retry Behavior.Respects Retry After On Retryable Error 12519ms
Retry Behavior.Does Not Retry On 400 3503ms
Retry Behavior.Does Not Retry On 401 3508ms
Retry Behavior.Does Not Retry On 402 3508ms
Retry Behavior.Does Not Retry On 413 3507ms
Retry Behavior.Does Not Retry On 415 3508ms
Retry Behavior.Non Retryable Errors Have No Retry After 3506ms
Retry Behavior.Implements Backoff 23531ms
Retry Behavior.Max Retries Respected 23521ms
Partial Batch Handling.Handles 200 Full Success 3002ms
Partial Batch Handling.Handles 200 With All Ok 4508ms
Partial Batch Handling.Does Not Retry Dropped Events 4506ms
Partial Batch Handling.Does Not Retry Limited Events 4507ms
Partial Batch Handling.Prunes Ok Events On Partial Retry 7515ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry 7510ms
Partial Batch Handling.Retries Only Retry Events From Partial 7512ms
Partial Batch Handling.Partial Retry Preserves Uuids 7508ms
Partial Batch Handling.Partial Retry Attempt Header Increments 7512ms
Partial Batch Handling.Partial Retry Request Id Preserved 7515ms
Partial Batch Handling.Respects Retry After On Partial 9510ms
Partial Batch Handling.Unknown Result Treated As Terminal 4505ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry 4511ms
Compression.Sends Gzip Content Encoding 1008ms
Compression.No Content Encoding When Disabled 1009ms
Compression.Compressed Body Is Decompressible 1009ms
Error Handling.Does Not Retry On Unknown 4Xx 3508ms
Event Options.Cookieless Mode Override 1008ms
Event Options.Disable Skew Correction Override 1009ms
Event Options.Process Person Profile Override 1011ms
Event Options.Product Tour Id Override 1009ms
Event Options.Unset Options Omitted 1009ms
Event Options.Options Override In Batch 1014ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties 1009ms
Geoip And Historical Migration.Historical Migration Set In Body 1010ms
Geoip And Historical Migration.Historical Migration Absent By Default 1009ms

Feature_Flags Tests

17/17 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id 1006ms
Request Payload.Flags Request Uses V2 Query Param 1007ms
Request Payload.Flags Request Hits Flags Path Not Decide 1007ms
Request Payload.Flags Request Omits Authorization Header 1006ms
Request Payload.Token In Flags Body Matches Init 1006ms
Request Payload.Groups Round Trip 1007ms
Request Payload.Groups Default To Empty Object 1007ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False 1006ms
Request Payload.Disable Geoip Omitted Defaults To False 1006ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key 1006ms
Request Lifecycle.No Flags Request On Init Alone 503ms
Request Lifecycle.No Flags Request On Normal Capture 1507ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests 1010ms
Request Lifecycle.Mock Response Value Is Returned To Caller 1003ms
Retry Behavior.Retries Flags On 502 1006ms
Retry Behavior.Retries Flags On 504 1007ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event 1509ms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants