Repository navigation
fix(ai): use context distinct_id in LangChain callback handler - #1292
pcbeingused333 wants to merge 2 commits into
Conversation
The handler only looked at its own distinct_id argument, so an id set with identify_context() was ignored and $ai_span, $ai_generation, $ai_trace and exception events were captured personless under the run id. Resolve the id from the handler first, then the active context, matching the OpenAI/Anthropic wrappers. Signed-off-by: Alex <alex.castillog33@gmail.com>
dustinbyrne
left a comment
There was a problem hiding this comment.
AI-assisted review.
The core change cleanly resolves active PostHog context distinct_id values across LangChain $ai_span, $ai_trace, $ai_generation, and $exception events (verified with unit tests and end-to-end HTTP delivery against sdk-mock-server).
Two concerns to address before approval are noted inline:
_resolve_distinct_idand its three call sites useortruthiness, which drops integerdistinct_id=0(regressing_capture_exception_and_update_propertiesand misattributing events to an active context user).- The modified
_capture_exception_and_update_propertiespath has no test coverage for active context resolution, and the explicit-override block intest_context_distinct_id_is_usedomits acall_countguard andoptionscheck.
There is also one optional docstring suggestion inline. (Standard GitHub Actions CI workflows will still need to run on this fork PR before merge.)
|
|
||
| def _resolve_distinct_id(distinct_id: Any) -> Any: | ||
| """The caller's distinct id, else the one from the active PostHog context, else None.""" | ||
| return _user_distinct_id(distinct_id) or _user_distinct_id( |
There was a problem hiding this comment.
Concern: _resolve_distinct_id and its three call sites in posthog/ai/langchain/callbacks.py (lines 601, 627, and 783) use Python or truthiness, which silently drops integer distinct_id=0 and causes cross-user misattribution when a PostHog context is active.
Expected contract & evidence: CallbackHandler.__init__ (posthog/ai/langchain/callbacks.py:144) and PostHogMiddleware.__init__ (posthog/ai/langchain/middleware.py:57) accept distinct_id: Optional[Union[str, int, UUID]] = None. _explicit_distinct_id(0) (posthog/client.py:304-309) and _user_distinct_id(0) (posthog/ai/utils.py:70-72) both treat 0 as a present ID (0, not None), and call_llm_and_track_usage (posthog/ai/utils.py:628-629) uses explicit is not None checks.
Minimal caller & base vs. head result:
with new_context():
identify_context("context-user")
chain.invoke({}, config={"callbacks": [CallbackHandler(client, distinct_id=0)]})- Base (
84fc9e06): On a failed run withenable_exception_autocapture=True,_capture_exception_and_update_propertiessent$exceptionwithdistinct_id="0"andoptions={}(and without a context did not injectprocess_person_profile: False).$ai_*fell back to a run/trace UUID (pre-existingor). - Head (
c4d3d8ca):_user_distinct_id(0)returns0(falsy), so_resolve_distinct_id(0)evaluates the right-hand side and returns"context-user". Both$ai_*and$exceptionevents are sent withdistinct_id="context-user"andoptions={}(verified via base/head unit tests andsdk-mock-serverHTTP wire capture). Without a context,_resolve_distinct_id(0)returnsNone, regressing_capture_exception_and_update_propertiesto injectprocess_person_profile: False.
Impact: Although "0" is uncommon in production (and PostHog capture v1 disables person processing for "0" via ILLEGAL_DISTINCT_IDS), inside an active context this change turns an explicit distinct_id=0 into "context-user" (a valid person-processed ID), silently attributing those AI and exception events to another user's person profile, and bakes the truthiness bug into the new shared _resolve_distinct_id helper.
Recommendation: Consider replacing or with explicit is not None checks in _resolve_distinct_id (preserving non-string values like UUID expected by test_personless_mode) and at posthog/ai/langchain/callbacks.py:601,627,783:
def _resolve_distinct_id(distinct_id: Any) -> Any:
"""The caller's distinct id, else the one from the active PostHog context, else None."""
explicit = _user_distinct_id(distinct_id)
if explicit is not None:
return explicit
return _user_distinct_id(contexts.get_context_distinct_id())and in posthog/ai/langchain/callbacks.py:
distinct_id=resolved_distinct_id if resolved_distinct_id is not None else run_id, # line 601
distinct_id=resolved_distinct_id if resolved_distinct_id is not None else self._distinct_id, # line 627
distinct_id=resolved_distinct_id if resolved_distinct_id is not None else trace_id, # line 783Regression test (executed on base 84fc9e06 vs. head c4d3d8ca; exception assertions pass on base and fail on head):
def test_zero_distinct_id_preserved_over_context(mock_client):
from langchain_core.runnables import RunnableLambda
from posthog import identify_context, new_context
mock_client.enable_exception_autocapture = True
mock_client.capture_exception.return_value = "exc-id"
def fail(_):
raise ValueError("boom")
with new_context():
identify_context("context-user")
with pytest.raises(ValueError):
RunnableLambda(fail).invoke(
{}, config={"callbacks": [CallbackHandler(mock_client, distinct_id=0)]}
)
assert mock_client.capture_ai.call_count == 1
assert mock_client.capture_ai.call_args[1]["distinct_id"] == 0
assert "options" not in mock_client.capture_ai.call_args[1]
assert mock_client.capture_exception.call_count == 1
assert mock_client.capture_exception.call_args[1]["distinct_id"] == 0
assert mock_client.capture_exception.call_args[1]["options"] is None| handler = CallbackHandler(mock_client, distinct_id="explicit") | ||
| chain.invoke({}, config={"callbacks": [handler]}) | ||
| for call in mock_client.capture_ai.call_args_list: | ||
| assert call[1]["distinct_id"] == "explicit" |
There was a problem hiding this comment.
Concern: The modified _capture_exception_and_update_properties path (posthog/ai/langchain/callbacks.py:621-631) has no test coverage for active PostHog context resolution, and the explicit-override block here omits call_count and options assertions.
Evidence & impact: Before this PR, a failed LangChain run inside identify_context(...) with enable_exception_autocapture=True emitted $exception with the context user's distinct_id and options={"process_person_profile": False}. This PR fixes both the distinct_id forwarding and exception_options, but test_context_distinct_id_is_used is the only test in posthog/test/ai/langchain/ using identify_context and only covers a successful chain run. In addition, lines 558–559 loop over mock_client.capture_ai.call_args_list without asserting call_count == 3 (so zero calls would pass vacuously) or "options" not in call[1].
Recommendation: Consider:
- Adding
assert mock_client.capture_ai.call_count == 3andassert "options" not in call[1]to the explicit-override block. - Adding a test exercising
_capture_exception_and_update_propertiesinsideidentify_context(...)(and optionally blank explicitdistinct_id=" "falling back to context / reusing oneCallbackHandleracross contexts):
def test_context_distinct_id_exception_autocapture(mock_client):
from langchain_core.runnables import RunnableLambda
from posthog import identify_context, new_context
mock_client.enable_exception_autocapture = True
mock_client.capture_exception.return_value = "exception-uuid-ctx"
def failing_span(_):
raise ValueError("boom")
with new_context():
identify_context("context-user")
with pytest.raises(ValueError):
RunnableLambda(failing_span).invoke(
{}, config={"callbacks": [CallbackHandler(mock_client)]}
)
assert mock_client.capture_exception.call_count == 1
exc_kwargs = mock_client.capture_exception.call_args[1]
assert exc_kwargs["distinct_id"] == "context-user"
assert exc_kwargs["options"] is None
assert mock_client.capture_ai.call_count == 1
assert mock_client.capture_ai.call_args[1]["distinct_id"] == "context-user"
assert "options" not in mock_client.capture_ai.call_args[1](Verified against base 84fc9e06 vs. head c4d3d8ca: fails on base and passes on head.)
| finalize_ai_content(outputs, self._ph_client), | ||
| ) | ||
|
|
||
| resolved_distinct_id = _resolve_distinct_id(self._distinct_id) |
There was a problem hiding this comment.
Suggestion: Since CallbackHandler (and PostHogMiddleware, whose docstring defers to CallbackHandler) now resolves distinct_id from the active PostHog context before falling back to personless mode, consider noting that fallback in CallbackHandler.__init__'s docstring (posthog/ai/langchain/callbacks.py:154 and 162-163, outside this diff). For example:
distinct_id: Optional distinct ID of the user to associate the trace with. When omitted or blank, falls back to the active PostHog context distinct ID (set viaidentify_context), or sends personless events if neither is set.
This keeps IDE tooltips and generated SDK reference docs clear about when process_person_profile: False applies (per SDK guidelines: Treat docs and examples as part of the SDK).
…in context id Use explicit is-not-None checks in _resolve_distinct_id and its call sites so distinct_id=0 is not replaced by the context user; add tests for exception autocapture and the 0 id; document the context fallback.
|
Thanks for the detailed review, both concerns are addressed in the new commit:
Disclosure: this follow-up was prepared with AI assistance (Claude Code) and submitted by the account owner. |
SDK performance: posthog-pythonBenchmarks completed. No changes flagged for review. Flags require at least a 5% change in the median and all six pairs agreeing on direction. This is a noise filter, not proof of a performance change or a CI gate. View all results
Values are medians of paired measurements. Not flagged does not mean unchanged. Unavailable means a measurement could not be provided, not zero. Estimated allocation measurements retain their instrumentation uncertainty. RSS measures the whole process, not just SDK allocations; observed peaks are sampled checkpoints. Paired ranges in the diagnostics describe variability, not confidence intervals. Each shard uses its own runner; compare Before PR against With PR within a row, not across shards. Compared 102 metric rows; 102 rows shown in all results. Omitted or shortened data remain in |
dustinbyrne
left a comment
There was a problem hiding this comment.
AI-assisted review.
Thanks for the quick follow-up — all earlier items are cleanly addressed (is not None checks preserve explicit distinct_id=0, exception-autocapture and explicit-override tests are in place, and the CallbackHandler docstring documents the context fallback). Verified locally with pytest, ruff, mypy, check_public_api.py, and end-to-end sdk-mock-server HTTP delivery across traces, spans, generations, and autocaptured exceptions.
Note: Python 3.11/3.12/3.13 tests, ruff, mypy, and the public API snapshot check all passed on CI; the Python 3.10 failure (test_metrics_autocapture.py::test_keeps_aiohttp_exclusions_for_sessions_created_after_start, which cancelled Python 3.14) is unrelated to this PR and will need a CI rerun before merge.
Related to #1284 (same bug in the LangChain callback handler)
💡 Motivation and Context
CallbackHandlerbuilt$ai_span,$ai_trace,$ai_generationand the$exceptionevents from its owndistinct_idargument only. A distinct ID set withidentify_context()was ignored, so the events were captured personless under the run ID. The OpenAI and Anthropic wrappers already readget_context_distinct_id().The handler now resolves the ID through a small
_resolve_distinct_idhelper inposthog/ai/utils.py: the handler's owndistinct_idfirst, then the active context's ID, then the existing run/trace-ID fallback (still personless). An explicit handlerdistinct_idstill wins.💚 How did you test it?
test_context_distinct_id_is_used: runs a chain insidenew_context()afteridentify_context("context-user")and asserts every captured event uses that ID withoutprocess_person_profile: False; also checks an explicit handler ID wins. It fails on main and passes with the fix.posthog/test/ai/langchain: 132 passed, 8 skipped. Tests use a mocked client; nothing ran against a live API.📝 Checklist
If releasing new changes
sampo addto generate a changeset file (added.sampo/changesets/langchain-context-distinct-id.md)🤖 Agent context
Autonomy: Fully autonomous