Skip to content

fix(py/google-cloud): export metrics, honor credentials=, and add trace IDs to structlog logs - #62

Merged
huangjeff5 merged 10 commits into
mainfrom
fix/py-gcp-telemetry-exporter
Nov 11, 2026
Merged

huangjeff5 merged 10 commits into
mainfrom
fix/py-gcp-telemetry-exporter

Conversation

@huangjeff5

@huangjeff5 huangjeff5 commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

enable_google_cloud_telemetry() had three bugs. Each one was caught by a try/except during setup and logged as a warning, so the app kept running and the missing telemetry was easy to miss.

How broken, by scenario:

  • Metrics: broken for everyone. No metrics reached Cloud Monitoring in any setup, including default Application Default Credentials (ADC) on GCP.
  • Traces and logs: broken only with credentials={...}. With ADC (no credentials=), traces and logs already exported. With a service-account dict, trace export failed to start, and the OTel log exporter ignored the dict and used ADC.
  • structlog trace correlation: broken for any structlog config that ends in a renderer, which includes structlog's default config. Log lines never carried the Cloud Logging trace and span IDs, so Cloud Logging could not link them to traces.
# --- BEFORE ---
enable_google_cloud_telemetry()
# => logged: 'GenkitMetricExporter' object has no attribute '_preferred_aggregation'
#    (no metrics; traces still exported)

enable_google_cloud_telemetry(credentials=service_account_info)
# => logged: CloudTraceSpanExporter.__init__() got an unexpected keyword argument 'credentials'
#    (no traces, no metrics; logs exported under ADC, not this service account)

logger.info('checking inventory')
# => {"event": "checking inventory", "level": "info"}

# --- AFTER ---
# 1. Traces, metrics, and logs export, with ADC or with credentials=
enable_google_cloud_telemetry(credentials=service_account_info)

# 2. A dict that isn't a service-account key fails at the call
enable_google_cloud_telemetry(credentials={'type': 'service_account'})
# => GenkitError: INVALID_ARGUMENT: credentials= is not a service account key;
#    missing client_email, private_key, token_uri

# 3. structlog events carry Cloud Logging trace fields
logger.info('checking inventory')
# => {"event": "checking inventory", "level": "info",
#     "logging.googleapis.com/trace": "projects/my-proj/traces/3827...",
#     "logging.googleapis.com/spanId": "ffc8...",
#     "logging.googleapis.com/trace_sampled": "1"}

Changes

  • Metric export starts: GenkitMetricExporter never called super().__init__(), so OpenTelemetry's PeriodicExportingMetricReader raised AttributeError when it was built and metrics were never exported. It now initializes its base class. Up/down counters stay cumulative, since Cloud Monitoring writes them as current-value gauge points (as deltas, a queue going 5 -> 6 charted as 5 then 1). A flush shorter than 1ms no longer sends an end_time before start_time.
  • credentials={...} reaches all three exporters: The Cloud Trace, Monitoring, and Logging exporters take a pre-built GCP client=, not a credentials= dict. The dict is now loaded once into service-account credentials and passed as TraceServiceClient, MetricServiceClient, and LoggingServiceV2Client instances.
  • Bad credentials= raises instead of falling back to ADC: Before, a dict google-auth couldn't load logged a warning and telemetry went out under the machine's identity and project. Now enable_google_cloud_telemetry() raises GenkitError(INVALID_ARGUMENT) naming only the missing fields, never values, since the dict holds a private key. It raises before the once-per-process guard, so a corrected call can be retried. credentials={} also raises now; before, it silently meant ADC.
  • Trace fields land before the structlog renderer: The trace processor was appended after the renderer, which had already turned the event into a string, so the fields were dropped. It now goes right before the last processor.

Testing

Unit tests in tracing_test.py build a real OpenTelemetry PeriodicExportingMetricReader and CloudMonitoringMetricsExporter and mock only the GCP API client.

Verified live against a GCP test project, main vs this PR, with local wheels in fresh venvs:

  • Metrics: main logs 'GenkitMetricExporter' object has no attribute '_preferred_aggregation' and writes 0 series. This PR writes the probe counter with the expected values, and one generate produces gen_ai.client.operation.duration and gen_ai.client.token.usage, which had never appeared in the project before.
  • Up/down counters stay cumulative: a queue going 5 -> 6 charts as 5, 6, 6, not 5, 1.
  • Traces with ADC: unchanged and working on both; flow, step, generate, and model spans arrive.
  • credentials=: main raises TypeError in the trace and metric exporters and the log exporter silently uses ADC. This PR builds all three clients from the given service-account dict; with an unregistered key every API returns 401 and nothing falls back to ADC. Not yet run with a real service-account key.
  • structlog trace IDs: with structlog's default renderer and with JSONRenderer, log lines now carry logging.googleapis.com/trace and spanId, and they match the flow span in Cloud Trace.

Breaking changes

None.

@huangjeff5 huangjeff5 changed the title fix(py/google-cloud): fix metric exporter aggregation, credentials client forwarding, and structlog trace processor fix(py/google-cloud): fix metric exporter aggregation, credentials forwarding, and structlog trace processor Nov 10, 2026
@huangjeff5
huangjeff5 requested a review from hilariie November 10, 2026 05:12
…ient forwarding, and structlog trace processor
- structlog: insert the trace processor before the last processor, not
  before the first class named *Renderer. stdlib's
  ProcessorFormatter.wrap_for_formatter is a function, so the class-name
  scan appended after it and trace fields were still dropped.
- metrics: keep UpDownCounter and ObservableUpDownCounter CUMULATIVE.
  Cloud Monitoring writes non-monotonic sums as GAUGE points; as DELTA a
  queue going 5 -> 6 charted as 5 then 1.
- credentials: parse the dict once in initialize() and share one
  _build_exporter_kwargs(client_cls) across trace, metrics, and logs.
  Drop the Credentials-object branches in resolve_project and
  initialize(); credentials= is dict-only, so they were unreachable.
- tests: real PeriodicExportingMetricReader and CloudMonitoringMetricsExporter
  instead of hasattr checks; clear GOOGLE_CLOUD_PROJECT in the
  credentials test so it does not depend on the developer's shell.
A credentials= dict that google-auth can't load used to log a warning and
fall back to ADC, so telemetry exported under a different identity and
project than the one passed. enable() now raises
GenkitError(INVALID_ARGUMENT) naming the missing fields, before the
once-per-process latch, so a fixed call can be retried. The message never
echoes values, and the google-auth/cryptography error is dropped from the
chain since the dict holds a private key. {} now raises too instead of
meaning ADC.
@huangjeff5
huangjeff5 force-pushed the fix/py-gcp-telemetry-exporter branch from f50d21c to 2ab7f89 Compare November 10, 2026 22:14
@huangjeff5 huangjeff5 changed the title fix(py/google-cloud): fix metric exporter aggregation, credentials forwarding, and structlog trace processor fix(py/google-cloud): export metrics, honor credentials=, and add trace IDs to structlog logs Nov 11, 2026

@pavelgj pavelgj left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

@huangjeff5
huangjeff5 enabled auto-merge (squash) November 11, 2026 16:38
@huangjeff5
huangjeff5 merged commit 142d1dd into main Nov 11, 2026
20 checks passed
@huangjeff5
huangjeff5 deleted the fix/py-gcp-telemetry-exporter branch November 11, 2026 17:42
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