Skip to content

fix(py/otel): set span error status on failed turns and add flushable lifecycle helpers - #55

Merged
huangjeff5 merged 9 commits into
fix/py-otel-tool-call-arguments-jsonfrom
fix/py-otel-bugbash-followups
Nov 11, 2026
Merged

huangjeff5 merged 9 commits into
fix/py-otel-tool-call-arguments-jsonfrom
fix/py-otel-bugbash-followups

Conversation

@huangjeff5

@huangjeff5 huangjeff5 commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

OpenTelemetry chat spans now go ERROR when a model returns its failure instead of raising. EVENT_ONLY content capture no longer fails the model call on non-JSON values. genkit.telemetry exports flush_instrumentations() so a serverless handler can drain exports before the process freezes.

import asyncio

from genkit.telemetry import flush_instrumentations

# 1. A model returns its failure instead of raising
response = await ai.generate(prompt='Is the pad thai safe for a peanut allergy?')
response.finish_reason
# => FinishReason.FAILED
# before: chat span status UNSET, gen_ai.response.finish_reasons=['stop']
# after:  chat span status ERROR, error.type='UNAVAILABLE', finish_reasons=['error']

# 2. Drain buffered spans, metrics, and log events before the handler returns
await asyncio.to_thread(flush_instrumentations)

Changes

  • A returned failure is still an error on the span: Previously, _run_model_span ignored response.error and _resolve_finish_reasons hardcoded failed=False. So a model that returned ModelResponse(finish_reason=failed, error=...) left the chat span UNSET with finish_reasons=['stop']. The chat span now gets StatusCode.ERROR with the failure message, error.type set to the Genkit status (or _OTHER when there isn't one), and finish_reasons=['error']. gen_ai.client.operation.duration gains the same error.type series. A raised exception keeps the existing record_exception path. The generate span was already ERROR on any boxed failure.
  • Telemetry never fails the call it's describing: Previously, EVENT_ONLY and SPAN_AND_EVENT ran bare json.dumps on mapped messages. A datetime in a tool response raised TypeError after the model had already replied, and generate returned finish_reason=failed. Span, event, and custom metadata values now go through one non-raising encoder (to_jsonable_python with by_alias=True, exclude_none=True, bytes_mode='base64', fallback=str).
  • Two app-facing helpers move to genkit.telemetry: FlushableInstrumentation was public, but flush_instrumentations lived in genkit._core, so a serverless drain needed a private import. genkit.telemetry now exports flush_instrumentations and set_custom_metadata_attributes (stamp tenant_id on the active span). set_span_state and dispose_instrumentations stay internal: Genkit writes genkit:state itself, and dispose already runs at exit.
  • GenAiInstrumentation is flushable: flush() force-flushes the global OTel tracer, meter, and logger providers. It skips proxy providers and logs instead of raising if a flush fails. Providers behind an injected tracer, meter, or otel_logger aren't reachable from there; flush those on the provider you built.
  • Dev UI clicks flush only the local trace collector: Under genkit start, the reflection server flushes before every runAction response so the trace is ready when the UI asks for it. It used to call flush_instrumentations(), which also blocked each click on remote OTel / APM exports. It now flushes only the Dev UI collector (flush_developer_ui_collector).

Breaking changes

None.

@huangjeff5
huangjeff5 force-pushed the fix/py-otel-bugbash-followups branch from 65e7961 to 53a1342 Compare November 9, 2026 19:08
@huangjeff5
huangjeff5 added this pull request to stack #60 November 9, 2026 19:59
@huangjeff5 huangjeff5 changed the title fix(py): OpenTelemetry span error status and flushable lifecycle helpers fix(py/otel): set span error status on failed turns and add flushable lifecycle helpers Nov 10, 2026
@huangjeff5
huangjeff5 requested a review from hilariie November 10, 2026 04:10
@huangjeff5
huangjeff5 force-pushed the fix/py-otel-bugbash-followups branch from 53a1342 to 5c11ba6 Compare November 10, 2026 07:44

@cabljac cabljac 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.

LGTM with comments

Comment thread packages/genkit-otel/README.md Resolved
@huangjeff5
huangjeff5 force-pushed the fix/py-otel-bugbash-followups branch from 5c11ba6 to 5a57b6b Compare November 10, 2026 19:57
@huangjeff5
huangjeff5 force-pushed the fix/py-otel-bugbash-followups branch from ad659fc to 9d8fc7a Compare November 11, 2026 06:23

@cabljac cabljac 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.

LGTM

The operation.details event path called bare json.dumps on mapped
messages. part_json dumps in python mode, so a datetime in a tool
response raised TypeError after the model had already replied, and
generate returned finish_reason=failed. Route span and event content
through one non-raising encoder; datetime/UUID/Decimal now encode via
pydantic_core.to_jsonable_python (ISO 8601 for datetime). (BR-02)
…tion flushable

set_custom_metadata_attributes, set_span_state, SpanState,
flush_instrumentations, and dispose_instrumentations lived only in
genkit._core, so apps stamping tenant_id or draining spans on serverless
shutdown needed private imports. Export them from genkit.telemetry.

GenAiInstrumentation now implements FlushableInstrumentation: flush()
force-flushes the global OTel tracer, meter, and logger providers,
skipping proxies and logging (not raising) on flush failure. (BR-03)
A model can return ModelResponse(finish_reason=failed, error=...) instead
of raising. _run_model_span ignored response.error and
_resolve_finish_reasons hardcoded failed=False, so the chat span stayed
UNSET with finish_reasons=['stop']. Now the span gets StatusCode.ERROR,
error.type (the Genkit status, or _OTHER), finish_reasons=['error'], and
the duration metric carries error.type. (BR-04)
…ttributes

set_span_state and SpanState write Genkit's own genkit:state, and
dispose_instrumentations already runs at exit. Keep them internal so the
public surface is the two calls app code actually makes. Document the
flush in the genkit-otel README.
flush_instrumentations runs on every Dev UI runAction success. With
GenAiInstrumentation flushable, that forced a metric and log export and
waited on all three OTel providers per run, up to the force_flush timeout
each when the collector is down. The reflection server now calls an
internal flush_span_exports(), which uses a provider's private
_flush_spans hook when present (GenAiInstrumentation flushes its tracer
provider only) and falls back to flush(). Same scope as JS flushTracing.
The public flush_instrumentations() still drains all three for
serverless shutdown.
@huangjeff5
huangjeff5 force-pushed the fix/py-otel-bugbash-followups branch from 9d8fc7a to a9eee50 Compare November 11, 2026 14:37
@huangjeff5
huangjeff5 enabled stacked auto-merge (squash) November 11, 2026 14:38
@huangjeff5
huangjeff5 merged commit 3098746 into main Nov 11, 2026
26 of 44 checks passed
@huangjeff5
huangjeff5 deleted the fix/py-otel-bugbash-followups branch November 11, 2026 17:16
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.

2 participants