-
Notifications
You must be signed in to change notification settings - Fork 0
feat: emit LaunchDarkly context identity on AI SDK feature_flag spans #60
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ccschmitz-launchdarkly
wants to merge
4
commits into
main
Choose a base branch
from
AIC-3230-context-identity
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
25253b8
feat: derive canonical and per-kind context keys
ccschmitz-launchdarkly ea69afd
feat: emit LaunchDarkly context identity on the feature_flag span
ccschmitz-launchdarkly ecc6b79
test: lock the context identity vocabulary across all six handlers
ccschmitz-launchdarkly a820aa8
docs: record context identity in the telemetry contract
ccschmitz-launchdarkly File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
102 changes: 102 additions & 0 deletions
102
packages/client/src/launchdarkly_ai_server/ld_context.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| """Derives span-safe identity from an ``LDContext`` dict. | ||
|
|
||
| Ported from the observability browser SDK's LaunchDarkly integration | ||
| (``sdk/highlight-run/src/integrations/launchdarkly/index.ts``), and mirrored by | ||
| ``js-ai-sdk``'s ``packages/client/src/context.ts``, so every LaunchDarkly | ||
| emitter produces byte-identical canonical keys. | ||
|
|
||
| Its own module because it is pure: no OTel, no LD client, no I/O. That is also | ||
| why it does not go through ``ldclient.Context`` — ``ldclient`` is an optional | ||
| import here (see ``utils.to_ld_context``), so relying on it would make the | ||
| attribute silently absent for anyone using a custom client. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from typing import Any | ||
|
|
||
|
|
||
| def _encode_key(key: str) -> str: | ||
| """Escapes the two characters ambiguous inside a canonical key: ``%`` and ``:``. | ||
|
|
||
| ``%`` is replaced first so an escape sequence is never double-escaped. | ||
| """ | ||
| if "%" in key or ":" in key: | ||
| return key.replace("%", "%25").replace(":", "%3A") | ||
| return key | ||
|
|
||
|
|
||
| def _multi_kind_pairs(context: dict[str, Any]) -> list[tuple[str, str]]: | ||
| """``(kind, key)`` pairs of a multi-kind context, sorted by kind. | ||
|
|
||
| Skips any kind whose sub-context has no usable string key. Both public | ||
| functions go through this, so the canonical key and the per-kind map can | ||
| never disagree about which kinds are present. | ||
| """ | ||
| pairs: list[tuple[str, str]] = [] | ||
| for kind in sorted(context): | ||
| if kind == "kind": | ||
| continue | ||
| sub = context.get(kind) | ||
| key = sub.get("key") if isinstance(sub, dict) else None | ||
| if isinstance(key, str) and key: | ||
| pairs.append((kind, key)) | ||
| return pairs | ||
|
|
||
|
|
||
| def get_context_keys(context: dict[str, Any]) -> dict[str, str]: | ||
| """The per-kind keys of *context*, as ``{<kind>: <key>}``. | ||
|
|
||
| Keys are raw — only the canonical key is escaped. A legacy user (no | ||
| ``kind``) reports as kind ``user``, matching every other LaunchDarkly | ||
| integration. | ||
| """ | ||
| if context.get("kind") == "multi": | ||
| return dict(_multi_kind_pairs(context)) | ||
| key = context.get("key") | ||
| if not isinstance(key, str) or not key: | ||
| return {} | ||
| kind = context.get("kind") | ||
| return {kind if isinstance(kind, str) and kind else "user": key} | ||
|
|
||
|
|
||
| def get_canonical_key(context: dict[str, Any]) -> str: | ||
| """The canonical key of *context*. | ||
|
|
||
| The same value the Go SDK's ``ldotel`` hook puts on | ||
| ``feature_flag.context.id`` via ``Context().FullyQualifiedKey()``. Stable | ||
| and consistent, not for presentation: it is what links a span to a context | ||
| instance. | ||
| """ | ||
| if context.get("kind") == "multi": | ||
| return ":".join( | ||
| f"{kind}:{_encode_key(key)}" for kind, key in _multi_kind_pairs(context) | ||
| ) | ||
| key = context.get("key") | ||
| if not isinstance(key, str) or not key: | ||
| return "" | ||
| kind = context.get("kind") | ||
| # A legacy user (no kind) and an explicit `user` kind both canonicalise to | ||
| # the bare key, with no `user:` prefix. | ||
| if not isinstance(kind, str) or not kind or kind == "user": | ||
| return key | ||
| return f"{kind}:{_encode_key(key)}" | ||
|
|
||
|
|
||
| def context_identity(context: Any) -> tuple[str, dict[str, str]] | None: | ||
| """The canonical key and per-kind keys of *context*, or ``None``. | ||
|
|
||
| ``None`` whenever there is no usable identity. Never raises: this runs on | ||
| the emit path of every run, and a malformed context must degrade to | ||
| emitting nothing rather than break the caller's AI call. | ||
| """ | ||
| if not isinstance(context, dict): | ||
| return None | ||
| try: | ||
| context_keys = get_context_keys(context) | ||
| canonical_key = get_canonical_key(context) | ||
| except Exception: | ||
| return None | ||
| if not canonical_key or not context_keys: | ||
| return None | ||
| return canonical_key, context_keys |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,124 @@ | ||
| """The Python port must agree with the TypeScript port, key for key. | ||
|
|
||
| The fixtures here are the same ones in js-ai-sdk's | ||
| `packages/client/src/__tests__/context.test.ts`, which are in turn the | ||
| observability browser SDK's. A canonical key that differs between emitters | ||
| breaks context-instance linking, and nothing else would catch it. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from typing import Any | ||
|
|
||
| import pytest | ||
|
|
||
| from launchdarkly_ai_server.ld_context import ( | ||
| context_identity, | ||
| get_canonical_key, | ||
| get_context_keys, | ||
| ) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| ("context", "expected"), | ||
| [ | ||
| ({"key": "bob"}, {"user": "bob"}), | ||
| ({"kind": "user", "key": "bob"}, {"user": "bob"}), | ||
| ({"kind": "org", "key": "org123"}, {"org": "org123"}), | ||
| ({"kind": "device", "key": "device456"}, {"device": "device456"}), | ||
| ( | ||
| { | ||
| "kind": "multi", | ||
| "user": {"kind": "user", "key": "user-key", "name": "Test User"}, | ||
| "org": {"kind": "org", "key": "org-key"}, | ||
| }, | ||
| {"org": "org-key", "user": "user-key"}, | ||
| ), | ||
| ( | ||
| { | ||
| "kind": "multi", | ||
| "device": {"kind": "device", "key": "device-key"}, | ||
| "user": {"kind": "user", "key": "user-key"}, | ||
| }, | ||
| {"device": "device-key", "user": "user-key"}, | ||
| ), | ||
| ], | ||
| ) | ||
| def test_get_context_keys(context: dict[str, Any], expected: dict[str, str]) -> None: | ||
| assert get_context_keys(context) == expected | ||
|
|
||
|
|
||
| def test_get_context_keys_does_not_escape_the_key() -> None: | ||
| # Only the canonical key is escaped. The map holds the key the customer | ||
| # actually sent, because that is what a filter compares against. | ||
| assert get_context_keys({"kind": "org", "key": "a:b%c"}) == {"org": "a:b%c"} | ||
|
|
||
|
|
||
| def test_get_context_keys_skips_a_multi_kind_entry_with_no_usable_key() -> None: | ||
| context = {"kind": "multi", "user": {"kind": "user", "key": "bob"}, "org": {}} | ||
| assert get_context_keys(context) == {"user": "bob"} | ||
|
|
||
|
|
||
| def test_get_context_keys_is_empty_without_a_key() -> None: | ||
| assert get_context_keys({}) == {} | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| ("context", "expected"), | ||
| [ | ||
| ({"key": "bob"}, "bob"), | ||
| ({"kind": "user", "key": "bob"}, "bob"), | ||
| ({"kind": "org", "key": "org123"}, "org:org123"), | ||
| ( | ||
| { | ||
| "kind": "multi", | ||
| "user": {"kind": "user", "key": "user-key"}, | ||
| "org": {"kind": "org", "key": "org-key"}, | ||
| }, | ||
| "org:org-key:user:user-key", | ||
| ), | ||
| ( | ||
| { | ||
| "kind": "multi", | ||
| "device": {"kind": "device", "key": "device-key"}, | ||
| "user": {"kind": "user", "key": "user-key"}, | ||
| }, | ||
| "device:device-key:user:user-key", | ||
| ), | ||
| ], | ||
| ) | ||
| def test_get_canonical_key(context: dict[str, Any], expected: str) -> None: | ||
| assert get_canonical_key(context) == expected | ||
|
|
||
|
|
||
| def test_get_canonical_key_escapes_percent_before_colon() -> None: | ||
| # `%` first, then `:`, so an escape sequence is never double-escaped. | ||
| assert get_canonical_key({"kind": "org", "key": "a:b%c"}) == "org:a%3Ab%25c" | ||
|
|
||
|
|
||
| def test_get_canonical_key_is_empty_without_a_key() -> None: | ||
| assert get_canonical_key({}) == "" | ||
|
|
||
|
|
||
| def test_context_identity_returns_the_canonical_key_and_the_per_kind_keys() -> None: | ||
| context = { | ||
| "kind": "multi", | ||
| "user": {"kind": "user", "key": "u1"}, | ||
| "org": {"kind": "org", "key": "o1"}, | ||
| } | ||
| assert context_identity(context) == ("org:o1:user:u1", {"org": "o1", "user": "u1"}) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "context", | ||
| [ | ||
| None, | ||
| "user-key", | ||
| 42, | ||
| {}, | ||
| {"kind": "user", "key": 42}, | ||
| {"kind": "multi", "user": {}}, | ||
| ], | ||
| ) | ||
| def test_context_identity_is_none_for_anything_unusable(context: Any) -> None: | ||
| assert context_identity(context) is None |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
JSON encoding mismatches TypeScript output
Low Severity
json.dumpsstill usesensure_ascii=True, so non-ASCII context keys are emitted as\uXXXXescapes.JSON.stringifywrites those characters as-is, sofeature_flag.contextKeyswill not be byte-identical to js-ai-sdk or the browser SDK for the same context. That string is stored verbatim in ClickHouse and may be matched as text.Reviewed by Cursor Bugbot for commit a820aa8. Configure here.