Skip to content
Latchkey

OpenTelemetry Python: reading resource attributes before async detection completes in CI

Resource detectors run when the provider is built. A test that reads resource.attributes immediately after start, before the detector has populated service.name/host fields, sees an empty or partial resource and fails an assertion.

What this error means

A test asserts resource.attributes["service.name"] equals a value, but gets unknown_service or a KeyError because the resource was inspected before detection merged its attributes.

python
KeyError: 'service.name'
# or:
assert resource.attributes.get('service.name') == 'my-service'
AssertionError: assert 'unknown_service' == 'my-service'

Common causes

Resource is inspected before detectors merge attributes

Detection populates the resource as the provider initializes. Reading attributes too early, or from a resource built without the detector, yields defaults.

No explicit service.name to fall back on

When detection provides nothing and OTEL_SERVICE_NAME is unset, the SDK uses unknown_service, which the test does not expect.

How to fix it

Build the resource explicitly and pass it in

  1. Create a Resource with the attributes you assert on.
  2. Pass it to the TracerProvider so it is available immediately.
  3. Read attributes from that resource, not a lazily detected one.
conftest.py
from opentelemetry.sdk.resources import Resource, SERVICE_NAME
resource = Resource.create({SERVICE_NAME: "my-service"})
provider = TracerProvider(resource=resource)
assert provider.resource.attributes[SERVICE_NAME] == "my-service"

Set OTEL_SERVICE_NAME in the environment

Provide the service name via env so it is present regardless of detector timing.

.github/workflows/ci.yml
env:
  OTEL_SERVICE_NAME: my-service

How to prevent it

  • Construct the Resource explicitly for tests instead of relying on detection.
  • Set OTEL_SERVICE_NAME so identity is deterministic.
  • Read attributes from the provider you configured, not the global default.

Frequently asked questions

What causes "Resource attributes empty at read time"?
Detection populates the resource as the provider initializes. Reading attributes too early, or from a resource built without the detector, yields defaults.
How do I fix Resource attributes empty at read time?
Build the resource explicitly and pass it in

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card