Skip to content

Feature/topic writer metrics - #940

Draft
NastyaKa wants to merge 9 commits into
ydb-platform:mainfrom
NastyaKa:feature/topic-writer-metrics
Draft

NastyaKa wants to merge 9 commits into
ydb-platform:mainfrom
NastyaKa:feature/topic-writer-metrics

Conversation

@NastyaKa

@NastyaKa NastyaKa commented Nov 7, 2026

Copy link
Copy Markdown

Pull request type

  • Bugfix
  • Feature
  • Code style update (formatting, renaming)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • Documentation content changes
  • Other (please describe):

What is the current behavior?

Topic Writers do not expose client-side metrics.

What is the new behavior?

Adds metrics for explicitly named Topic Writers:

  • Counters: sending.messages, sending.bytes, written.messages, session.errors
  • Gauges: buffer.used.bytes, buffer.limit.bytes, sending.oldest_age
  • Histograms: buffer.wait.duration, message.processing.duration, compression.duration, message.ack.duration

Includes sync/async support, retry/reconnect handling, OpenTelemetry integration, documentation, and tests.

@NastyaKa
NastyaKa marked this pull request as draft November 7, 2026 10:40
@codecov

codecov Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.86352% with 62 lines in your changes missing coverage. Please review.
✅ Project coverage is 83.30%. Comparing base (e231157) to head (cf0a34d).

Files with missing lines Patch % Lines
ydb/observability/metrics.py 89.60% 21 Missing and 29 partials ⚠️
ydb/_topic_reader/topic_reader_asyncio.py 95.65% 6 Missing and 1 partial ⚠️
ydb/_topic_writer/topic_writer_asyncio.py 96.62% 2 Missing and 1 partial ⚠️
ydb/_topic_reader/topic_reader_sync.py 60.00% 2 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #940      +/-   ##
==========================================
+ Coverage   82.70%   83.30%   +0.60%     
==========================================
  Files          99       99              
  Lines       12960    13638     +678     
  Branches     1266     1366     +100     
==========================================
+ Hits        10718    11361     +643     
- Misses       1789     1802      +13     
- Partials      453      475      +22     
Flag Coverage Δ
integration 80.55% <83.98%> (+0.16%) ⬆️
unit 50.36% <55.24%> (+1.02%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
ydb/_grpc/grpcwrapper/ydb_topic.py 86.15% <100.00%> (+0.04%) ⬆️
ydb/_topic_reader/datatypes.py 96.89% <100.00%> (+1.35%) ⬆️
ydb/_topic_reader/topic_reader.py 91.46% <100.00%> (+0.43%) ⬆️
ydb/_topic_writer/topic_writer.py 86.38% <100.00%> (+0.51%) ⬆️
ydb/observability/__init__.py 100.00% <ø> (ø)
ydb/opentelemetry/metrics_plugin.py 96.15% <100.00%> (+0.15%) ⬆️
ydb/topic.py 86.01% <ø> (ø)
ydb/_topic_reader/topic_reader_sync.py 73.17% <60.00%> (+1.01%) ⬆️
ydb/_topic_writer/topic_writer_asyncio.py 90.93% <96.62%> (+2.02%) ⬆️
ydb/_topic_reader/topic_reader_asyncio.py 89.53% <95.65%> (+2.87%) ⬆️
... and 1 more

... and 1 file with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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

Замечания к накладным расходам при выключенных метриках и совместимости encoder_executor.

self._metrics.add_pending_messages(accepted_at, len(internal_messages))

self._metrics.record_sending_messages(len(internal_messages))
self._metrics.record_sending_bytes(sum(message.uncompressed_size for message in internal_messages))

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.

При выключенных метриках здесь всё равно выполняется дополнительная работа на каждом write: проход с присваиванием _accepted_at, sum(...) для record_sending_bytes() и ещё один проход в _record_message_processing(). Перед отправкой _capture_first_send() создаёт список и присваивает _first_sent_at, хотя no-op возвращает None; на каждом ACK остаются три дополнительных no-op вызова. Сжатие также всегда идёт через обёртку метрик.

В изолированном CPU-пути приёма, учёта отправки и ACK с RAW-сообщениями по 100 байт и полностью выключенными метриками время выросло примерно с 1,83 до 2,38 мкс на сообщение при записи по одному и с 1,14 до 1,32 мкс при батчах по 100. Это микробенч без gRPC и сервера, а не оценка общей пропускной способности.

Проверку наличия инструментации следует делать до вычислений и дополнительных проходов: пустые методы no-op уже не отменяют вычисление аргументов и создание списков. Проверка на уровне целого блока позволит сохранить простой код и дешёвый путь без метрик.

encoded_data_futures = eventloop.run_in_executor(
self._encode_executor, encoder_function, message.get_data_bytes()
self._encode_executor,
self._encode_with_metrics,

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.

Передача bound method self._encode_with_metrics в executor ломает encoder_executor=ProcessPoolExecutor(...): для отправки задания в другой процесс теперь требуется сериализовать весь writer вместе с event loop и остальным состоянием. Раньше передавался непосредственно encoder, например gzip.compress, который можно сериализовать.

Воспроизводится с явно выбранным GZIP и выключенными метриками: на базе PR _encode_data_inplace() успешно сжимает сообщение через ProcessPoolExecutor, на head падает с ошибкой pickle (Can't get local object 'WeakSet.__init__.<locals>._remove').

Для выключенных метрик следует сохранить прямую передачу encoder. Измерение при включённых метриках можно вынести в отдельную сериализуемую функцию, принимающую encoder и данные и возвращающую результат с длительностью, а запись метрики выполнять в основном процессе.

This branch has not been deployed

No deployments
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