perf(sdk): cache Resource.__hash__; OTLP encoders re-serialize the Resource for every span and log record

Aberta Para iniciantes
#5,994 0 comentários 0 reações 0 responsáveis Ver no GitHub

Mantenedores costumam responder em até 2 dias

Ninguém assumiu esta issue ainda.

Avaliação

Dificuldade
2/5
Tempo estimado
1-3 horas
Facilidade para iniciantes
78/100
Tipo de issue
Funcionalidade
Clareza
Claramente especificada
Status de atividade
Ativa
Stack de tecnologia
python
Domínio
backend, performance

Direção de pesquisa

Leia a implementação de Resource.__hash__ e os testes de Resource; a issue não especifica um arquivo de teste, então localize os testes que cobrem a igualdade e o hashing de Resource. Adicione uma verificação de que chamadas repetidas de hashing retornam o mesmo valor, preservando o comportamento de igualdade, e execute os testes específicos de Resource. O trabalho estará concluído quando o hash for reutilizado após o primeiro cálculo e os testes do comportamento existente de Resource continuarem passando.

Escrita pelo modelo de indexação a partir do texto da issue.

Descrição

feature-request
Is your feature request related to a problem?

Resource.__hash__ recomputes its hash from a JSON dump of all attributes on every call:

def __hash__(self) -> int:
    return hash(
        f"{dumps(self._attributes.copy(), sort_keys=True, default=_json_default)}"
        f"|{self._schema_url}|{self._schema_url_conflict}"
    )

The OTLP encoders group records by resource, using the Resource as a dict key once per record:

  • _encode_resource_spans: sdk_resource_spans[sdk_span.resource][sdk_instrumentation].append(pb2_span)
  • _encode_resource_logs: sdk_resource_logs[readable_log.resource][sdk_instrumentation].append(pb2_log)

So every exported span and log record copies, sorts and JSON-encodes the entire resource, even though a process almost always has a single, unchanging Resource. With the usual resource attributes (service, host, process, k8s/cloud detectors), this is a noticeable share of export CPU in high-throughput services.

Observed on opentelemetry-sdk 1.41.0; main has the same uncached implementation. No existing issue found (related but distinct: #5576/#5577, #5591).

Describe the solution you'd like

I'd like Resource to compute its hash once and reuse it.

A Resource is effectively immutable after construction (its attributes are a BoundedAttributes, there is no public mutator, and merge returns a new Resource), so the hash can be computed eagerly in __init__ or lazily on the first __hash__ call. Lazy caching keeps construction cost unchanged:

def __hash__(self) -> int:
    cached = self.__dict__.get("_hash")
    if cached is None:
        cached = self._hash = hash(
            f"{dumps(self._attributes.copy(), sort_keys=True, default=_json_default)}"
            f"|{self._schema_url}|{self._schema_url_conflict}"
        )
    return cached
Describe alternatives you've considered
  • Cache in the OTLP encoders instead, e.g. group by id(resource) or keep a per-batch resource → key map. That fixes only the OTLP path; other exporters and processors that hash a Resource still pay the cost, so fixing it in Resource itself is simpler and benefits every consumer.
  • Eagerly compute the hash in Resource.__init__. It works too, but it charges every construction, including the temporary resources made during detector merging, which may never be hashed.
  • Leave it to users to monkeypatch Resource.__hash__. That's what we do today; it works but depends on private attributes and could break on upgrades.
Additional Context
  • Similar fix in the Collector: open-telemetry/opentelemetry-collector-contrib#50955 caches the resource attribute hash per resource in the signaltometrics connector instead of rehashing on every signal.
  • Related Resource hashing issues in this repo (correctness, not performance): #5576 / #5577 (bytes-valued attributes), #5591.
  • Versions: observed on opentelemetry-sdk 1.41.0; main has the same uncached __hash__.
Would you like to implement a fix?

None

Tip

React with 👍 to help prioritize this issue. Please use comments to provide useful context, avoiding +1 or me too, to help us triage it. Learn more here.

Linguagem predominante
Python
Estrelas
2.7k
Forks
1.1k
Merge médio
3d 23h
PRs com merge (30d)
20

Preparar o ambiente

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Mais de open-telemetry/opentelemetry-python

Todas as issues de open-telemetry/opentelemetry-python

Issues semelhantes

Mais issues de Python

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.