Skip to content

fix(instrumentation): serialize non-string mapping keys instead of raising TypeError - #4168

Closed
simpleqt wants to merge 1 commit into
Arize-ai:mainfrom
simpleqt:fix/json-serialize-non-string-keys
Closed

simpleqt wants to merge 1 commit into
Arize-ai:mainfrom
simpleqt:fix/json-serialize-non-string-keys

Conversation

@simpleqt

Copy link
Copy Markdown
Contributor

resolves #4167

A small, focused bug fix: _json_serialize() claims to be a safe dump but calls json.dumps directly, and mapping keys never reach JSONEncoder.default. A mapping with tuple, bytes or enum keys therefore raises:

>>> _json_serialize({("a", "b"): 1})
TypeError: keys must be str, int, float, bool or None, not tuple

The paths that reach it are get_input_attributes, get_output_attributes, get_tool_attributes, get_llm_invocation_parameter_attributes and _document_attributes. The worst case is the tool decorator, because _tool_context() calls get_tool_attributes() while entering the span context manager, so the traced function never runs:

@tracer.tool(parameters={("a", "b"): 1})
def lookup(city: str) -> str:
    return city

lookup("Vienna")   # raises TypeError; lookup's body is never entered

That also breaks the invariant that instrumentation must never raise into user code.

The change adds a _stringify_mapping_keys() helper (plus _JSON_KEY_TYPES) and uses it both in _json_serialize() and in the asdict() branch of IOValueJSONEncoder.default(). Keys that JSON accepts are left alone, other objects are untouched, and non-encodable keys become str(key) recursively through nested mappings and sequences — the same convention langchain uses for this class of value, rather than skipkeys=True, which would drop the entries silently.

python/openinference-instrumentation/tests/test_attributes.py covers the direct call, each get_*_attributes helper, nested mappings and sequences, and the decorated-function case that never ran before. It fails on the current tree (4 failed, 1 passed, TypeError from json/encoder.py) and passes with the change (5 passed); the package suite goes from 8549 passed to 8554 passed with no failures. ruff check and ruff format --check are clean at the pinned version (python/dev-requirements.txt).

No version bump or changelog entry, since release-please owns those.

Note on process: this is a small focused fix, which CONTRIBUTING lists as most likely to be accepted, and I opened the issue above at the same time. If you would rather have this handled internally, say so and I will close the pull request.

Prepared with AI assistance (DeepSeek Harness, dsv41 agent); every line was verified by running the cases above.

…ising TypeError

`_json_serialize()` promises a safe dump but delegates straight to `json.dumps`,
which accepts only str/int/float/bool/None as object keys. Mapping keys never
reach `JSONEncoder.default`, so a dict keyed by a tuple, bytes or an Enum member
raises "TypeError: keys must be str, int, float, bool or None, not tuple" from
get_input_attributes(), get_output_attributes(), get_tool_attributes(),
get_llm_invocation_parameter_attributes() and _document_attributes().

The worst case is user-visible: `_tool_context()` calls get_tool_attributes()
while entering the span context manager, so a @tracer.tool(...) decorated
function with a tuple-keyed `parameters` mapping never runs and raises TypeError
from instrumentation alone.

Normalize mapping keys up front: keys JSON cannot encode become str(key),
recursively through mappings and sequences. Keys JSON already accepts keep their
type, so existing output is unchanged, and dataclasses/pydantic models/opaque
objects are still handed to IOValueJSONEncoder as before. This matches the
top-level treatment the langchain encoder already applies and, unlike
skipkeys=True, does not drop data.
@simpleqt
simpleqt requested a review from a team as a code owner October 27, 2026 13:58
Copilot AI balanced review requested due to automatic review settings October 27, 2026 13:58

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

@mikeldking mikeldking added the factory-review to be reviewed by the software factory label Oct 31, 2026 — with Claude
@openinference-factory

Copy link
Copy Markdown
Contributor

The factory started a review of f882ea2 (session sesn_01TouNvXpX5uXYF7rviAGYpE). It reports back here when the session ends.

@openinference-factory openinference-factory Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Factory review of f882ea2: Request changes

The fix works for tuple keys, but mypy fails on the new tests (Checks Fail), there are three blocking findings, and the eager rewrite changes output the PR doesn't mention (Fit Partial).

Criterion Result Notes
Fit Partial also changes output for non-dict Mappings; tests cover 2 of the 5 helpers the PR names
Checks Fail ci-instrumentation mypy: 2 dict-item errors in the new tests
Tests Pass 4 of 5 new tests fail on the base commit with the reported TypeError; dataclass branch untested
Blocking findings 3 eager rewrite raises/changes output _attributes.py:551; mypy failure tests/test_attributes.py:35; add/add conflict with main tests/test_attributes.py:1
Non-blocking findings 1 dataclass branch and output path untested _attributes.py:535
Risk Medium performance and backwards compatibility: every payload is copied (1.5× to 2.3×), and deep payloads now raise RecursionError
Review depth Deep changes the openinference-instrumentation core, and Risk is Medium
Details

Intent: Stop _json_serialize() from raising TypeError on mappings with non-JSON key types (tuple, bytes, Enum) by turning those keys into strings, so attribute helpers and @tracer.tool(parameters=...) no longer raise into user code (#4167).
Fit: The diff fixes the reported case.
It also rebuilds every payload before json.dumps, which changes non-dict Mapping output from str(obj) to a JSON object, and makes payloads nested about 500 levels deep raise RecursionError. The PR mentions neither.
The PR body says the tests cover each get_*_attributes helper, but only get_input_attributes and get_tool_attributes are tested.
Context, not a finding: helpers.safe_json_dumps, which many instrumentors use, has the same tuple-key TypeError and is not touched.
Verified: tox run -e ci-instrumentation (py3.11): ruff format and ruff check pass; mypy fails with 2 dict-item errors at tests/test_attributes.py:35 and :47, so tox stopped before pytest.
I ran pytest directly in the same environment: 8554 passed.
The new tests run against the base commit's source: 4 failed, 1 passed, each failure being TypeError: keys must be str, int, float, bool or None, not tuple. The passing one is the int-keys case.
Against both versions: a dict nested 500 levels deep serializes on the base and raises RecursionError with the PR; MappingProxyType({"a": 1}) gives "{'a': 1}" on the base and {"a": 1} with the PR.
git merge-tree origin/main HEAD reports an add/add conflict in tests/test_attributes.py.
The Python reviewer measured the timings (1.5× to 2.3× per call).
Not verified: Only py3.11 was run; CI also runs the py3.10 and py3.14 ci-instrumentation envs. CI also runs every instrumentor's suite after a core change, and none of those were run here, though _json_serialize is used only inside _attributes.py.
Findings without a diff line: none
Risk: side effects low, performance medium, backwards compatibility medium, from the Python reviewer

Graded against the review criteria.

"""
return json.dumps(
obj,
_stringify_mapping_keys(obj),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking. _stringify_mapping_keys now copies every payload recursively, even when all its keys are already valid JSON. That changes or breaks payloads that serialize fine today:

  • New raise into user code. The helper recurses in Python, two frames per level. A dict nested 500 levels deep serializes on the base commit, but with this change it raises RecursionError from get_input_attributes/get_output_attributes and the @tracer.* decorators. I checked this by running the same snippet against both versions. A self-referential container now runs to the recursion limit instead of failing fast with json's ValueError.
  • Output change the PR doesn't mention. Non-dict Mappings used to go to default() and become str(obj). For example, MappingProxyType({"a": 1}) gave "{'a': 1}". They now become JSON objects ({"a": 1}), so input.value/output.value changes for existing users.
  • Cost on every call. The reviewer measured this with timeit: 1.5× to 2.3× per call (a 50-message chat payload went from 218 µs to 498 µs), plus a full second copy of large payloads.

Fix: keep the existing path for payloads that already work, and stringify only when it fails:

def _json_serialize(obj: Any, **kwargs: Any) -> str:
    try:
        return json.dumps(obj, cls=IOValueJSONEncoder, ensure_ascii=False)
    except TypeError:
        return json.dumps(_stringify_mapping_keys(obj), cls=IOValueJSONEncoder, ensure_ascii=False)

Keep the stringify in the asdict branch of default(). In the fallback, consider restricting the helper to dict, or say in the PR that you mean to change the output for Mapping objects.



def test_tool_parameters_with_non_string_keys_is_json() -> None:
attributes = get_tool_attributes(name="f", parameters={("a", "b"): 1})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking. tox run -e ci-instrumentation fails at the mypy step, so CI fails too:

tests/test_attributes.py:35: error: Dict entry 0 has incompatible type "tuple[str, str]": "int"; expected "str": "Any"  [dict-item]
tests/test_attributes.py:47: error: Dict entry 0 has incompatible type "tuple[str, str]": "int"; expected "str": "Any"  [dict-item]

get_tool_attributes and OITracer.tool declare parameters: Union[str, Dict[str, Any]]. A tuple-keyed dict is outside the typed contract, so the tests have to say they pass one on purpose. Fix: add # type: ignore[dict-item] on lines 35 and 47, or build the dict as cast(Dict[str, Any], {("a", "b"): 1}). Then rerun tox run -e ci-instrumentation.

@@ -0,0 +1,56 @@
import json

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking. This file conflicts with main. #4194 (98aa84b) has since added its own python/openinference-instrumentation/tests/test_attributes.py, which holds the TestMessageAttributeTypeGuards tests. git merge-tree origin/main HEAD reports CONFLICT (add/add) here, and GitHub shows the PR as not mergeable. Fix: rebase on main and keep both sets of tests in the one module. The merged imports need get_llm_input_message_attributes and get_llm_output_message_attributes alongside yours.

try:
if _is_dataclass_instance(obj):
return asdict(obj)
return _stringify_mapping_keys(asdict(obj))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking. No test covers this branch. If default() is patched back to plain asdict(obj), all 5 new tests still pass. Yet a dataclass with a tuple-keyed dict field raises TypeError on the base commit and serializes with this change. Two related gaps:

  • The int-keys case (tests/test_attributes.py:22) passes without the change, because json already accepts int keys. It guards nothing.
  • The PR body says each get_*_attributes helper is covered, but only get_input_attributes and get_tool_attributes are tested.

Fix: add a dataclass-with-tuple-key case through get_input_attributes, and a get_output_attributes case. Add a case where a @tracer.chain-decorated function is called with a tuple-keyed dict argument. That goes through get_input_attributes(arguments) in _tracers.py and is the user-visible path that raises on the base commit. Assert the decoded content, not just isinstance(..., dict).

@openinference-factory

Copy link
Copy Markdown
Contributor

The factory recommends Request changes for f882ea2. Read the review.

@openinference-factory openinference-factory Bot removed the factory-review to be reviewed by the software factory label Oct 31, 2026
@mikeldking mikeldking added the factory-request-changes The factory review recommends requesting changes label Oct 31, 2026
@simpleqt

simpleqt commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

Closing this to get my open pull requests in this repository down to a sane number: I had 4 open here at once, which is more than anyone should be asked to review. The branch stays in my fork if it is ever useful - happy to reopen on request.

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

Labels

factory-request-changes The factory review recommends requesting changes

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

_json_serialize raises TypeError for a mapping with non-string keys, so a @tracer.tool(parameters={("a", "b"): 1}) function never runs

3 participants