Skip to content

feat: Kafka message data components - #298

Draft
chrisk314 wants to merge 15 commits into
mainfrom
feat/kafka-message-data
Draft

chrisk314 wants to merge 15 commits into
mainfrom
feat/kafka-message-data

Conversation

@chrisk314

Copy link
Copy Markdown
Contributor

Draft while the testing story is unresolved. There is no Kafka broker available to integration-test against, and standing one up is an open decision (managed MSK/Confluent versus a container such as Redpanda in compose.yaml). It is also not yet clear that Kafka support is wanted enough to warrant the time needed to test it properly. This stays a draft until a testing setup is determined and there is appetite to invest in it.

What it adds

KafkaDataReader and KafkaDataWriter on the MessageDataReader/MessageDataWriter bases from #284 - the Apache Kafka equivalent of the PubSub and SQS/SNS components.

  • Consumer: consumer group with enable_auto_commit=False; acknowledging a batch commits TopicPartition -> OffsetAndMetadata(offset + 1) for the records actually processed, taking the highest offset per partition, so records still waiting in the buffer remain eligible for redelivery. An empty getmany poll returns no messages rather than ending the stream, matching the base class's "idle is not exhaustion" rule.
  • Producer: a batch is submitted with send() for every record and flushed once, so aiokafka's internal batching is used instead of one request/ack round trip per record.
  • Configuration: bootstrap_servers accepts a string or list and falls back to KAFKA_BOOTSTRAP_SERVERS; KAFKA_BOOTSTRAP_SERVERS also lands in Settings.kafka.
  • Errors: authorization and record-too-large failures map to MessageBrokerPermanentError (no retries burnt on them); connection, coordinator and rebalance errors map to MessageBrokerTransientError and are retried with backoff.
  • Packaging: the kafka extra (aiokafka>=0.11,<1) plus aiokafka in the test dependency group so the unit tests import the real error and offset types.
  • Docs: Kafka rows, install extra, settings and example in the Message Data usage page.

Split out of #284 as requested so that PR stays scoped to what can be tested: the base classes, PubSub and SQS/SNS.

Testing

24 unit tests (128 across the message data suite with this branch), all mock-based against unittest.mock doubles patched into plugboard.library.kafka_io - no broker required. They cover offset commit contents (including out-of-order records spanning partitions), empty polls, multi-partition flattening, batched sends with exactly one flush, error mapping, settings resolution and JSON vs raw encoding.

ruff, ty and tests/unit pass. No integration test against a real Kafka broker exists, which is the gap the draft status above is about; the behaviour most likely to bite is exactly the part mocks cannot show - group rebalances, session timeouts, and commit semantics under real partition assignment.

Notes for whoever picks this up

  • This PR targets feat/message-data-classes, not main. Retarget it to main once feat: Message data classes #284 merges (GitHub retargets automatically if the base branch is deleted after a squash-merge, but double-check).
  • uv.lock conflicts with feat: Message data classes #284 are likely: this branch re-adds aiokafka (and its async-timeout dependency) to the lockfile that feat: Message data classes #284 removes them from. Resolving by re-running uv lock on top of the merged base is the safest route.
  • If only a container-based setup is on the table, compose.yaml already provides the pattern used for RabbitMQ/Redis, and the CI job that starts it exports the broker URLs - Kafka would follow the same shape (KAFKA_BOOTSTRAP_SERVERS plus a test_kafka_io.py integration test that round-trips a record and asserts the commit).

fsspec license metadata is not detectable by licensecheck, causing
CI failures. Add to ignore list since it's BSD-3-Clause licensed.
Implements issue #102: Base component for external communication via
pub/sub message broker infrastructure.

New base classes:
- MessageDataReader: Abstract base for reading data from message brokers
  with connection management, reconnection with exponential backoff,
  retry logic, message acknowledgment, and chunked/buffered reading.
- MessageDataWriter: Abstract base for writing data to message brokers
  with connection management, reconnection, retry logic, and
  chunked/buffered writing.

Concrete implementations:
- GCPPubSubDataReader/Writer: Google Cloud PubSub
- AWSSQSDataReader/AWSSNSDataWriter: AWS SQS/SNS
- KafkaDataReader/Writer: Apache Kafka

Also includes:
- Message broker exceptions (ConnectionError, TransientError, PermanentError)
- Settings for GCP PubSub, AWS, and Kafka
- Optional dependencies in pyproject.toml
- Proposal document with design rationale
- Comprehensive unit tests (72 new tests)
- Fix ruff lint errors: import sorting, unused imports, S110 noqa comments
- Fix ruff format errors in gcp_pubsub_io.py
- Fix mypy overlap errors: remove duplicate fields from ArgsDict TypedDicts
- Fix mypy multiple values error: use kwargs.setdefault instead of pop
- Remove untracked test data files causing lint failures
Increase connection establishment sleep in _ZMQPipelineConnectorProxy
from 0.1s to 0.5s to allow the proxy subprocess's SUB socket
subscription to propagate to XPUB before the sender starts publishing
(ZMQ slow joiner problem). Also mark the test as flaky with 3 reruns
following the existing pattern used elsewhere in the repo.

Fixes: test_process_with_components_run[RayProcess-zmq_connector_cls-zmq_pubsub_proxy=True-10-2.0]
- Fix invalid-raise errors in message_reader.py and message_writer.py
  by initializing last_exception with a non-None default instead of
  Optional[Exception]
- Remove PublisherClient.close() call in gcp_pubsub_io.py (method does
  not exist on the client); just set reference to None for GC
- Update test to match new disconnect behavior
The design proposal is not tracked in the repo. Added to .gitignore
to prevent accidental re-commit.
Resolve conflict in tests/integration/test_process_with_components_run.py:
keep main's native pytest parametrization (ConnectorCase + indirect +
ids) replacing pytest-cases, retaining the flaky marker for the
Ray + ZMQ proxy case. Regenerate uv.lock for merged pyproject extras.

Verified: ruff check, ruff format, ty check all pass; new ZMQ backend/
channel/proxy unit tests (21) and message data tests (72) pass; merged
integration file collects cleanly (25 tests).
Blocking issues:
- An empty broker poll no longer ends the stream. `_receive` returning [] means
  "nothing yet", so `step()` waits and polls again like `WebsocketReader`; only a
  subclass raising `NoMoreDataException` closes the IO (B1).
- A batch is acknowledged only after its last record is consumed, instead of after
  the first one. Previously a crash mid-batch lost the unread messages (B2).
- `KafkaDataReader._ack` commits the offsets following the processed records, per
  partition, instead of the consumer position, which could mark unprocessed records
  as done (B3).
- GCP reader and writer dispatch every synchronous PubSub call (client construction,
  pull, acknowledge, publish, future.result, stop, close) to a worker thread, so they
  no longer block the shared event loop (B4, B5).

Design and consolidation:
- `MessageDataReader`/`MessageDataWriter` now extend `DataReader`/`DataWriter`,
  reusing the buffer, binding and batching logic instead of copying it (W14).
- Retry, backoff and reconnect live in one place: `plugboard.utils.retry` with a
  frozen `RetryPolicy` value object shared by both bases (W13, L1, L2).
- A failing reconnect no longer escapes the retry loop; it costs an attempt and the
  broker error is raised once attempts run out (W12).
- Row-to-message encoding is shared as `iter_records`/`encode_records`/
  `encode_records_bytes`; the old per-row deque indexing was quadratic in buffer size
  and duplicated across three writers (W16, W19).
- Connection access is serialised with an `asyncio.Lock` across ack and reconnect (W15).
- Kafka writer submits all records then flushes once, instead of one round trip per
  record (W18). SQS deletes ack batches of up to 10 with `delete_message_batch` and
  reports partial failures rather than pretending success (L3).
- The GCP publisher is stopped on disconnect, so a reconnect no longer leaks a channel
  and its threads (W17).
- `MessageBrokerPermanentError`/`TransientError` are now actually raised and honoured:
  each broker maps its SDK's failures onto the hierarchy, and permanent errors skip the
  retries that previously burnt against a guaranteed failure (W1).

Configuration and packaging:
- The GCP/AWS/Kafka settings are read as constructor fallbacks via
  `resolve_argument`, so `GCP_PUBSUB_PROJECT_ID`, `AWS_REGION` and
  `KAFKA_BOOTSTRAP_SERVERS` work (W2).
- `aws-messaging` now uses `aiobotocore` instead of `aioboto3`, which no longer forces
  the shared botocore/boto3 stack backwards (W5).
- Broker SDKs are declared in the `test` dependency group, which also resolves the three
  `ty` unresolved-import findings (W10 root cause).
- The six concrete broker classes are exported from `plugboard.library` (W3).
- Removed the misleading broker-specific ArgsDicts that documented attributes they did
  not declare (W20).

Tests: 126 tests, up from 72, all using teardown-aware monkeypatch fixtures instead of
global `sys.modules` mocks, asserting broker calls rather than private attribute
identity (W10, W11). New coverage for retry exhaustion and the delay cap, empty-batch
handling, error-branch mapping, offset commits, reconnect failure, and the
acknowledgment timing that previously lost records (W7, W8, W9). Record encoding is
parametrised once rather than copied across three modules (L4).

Docs: new Message Data usage page (extras, worked example, delivery semantics), broker
settings in the configuration page, and the new extras in the README (W4).

Test isolation: the S3 file tests pinned their bucket region so they no longer depend
on the developer's ambient AWS profile, which the newer botocore resolves over
`AWS_REGION`.
The connection delay and the flaky marker on the Ray + ZMQ integration test fix an
unrelated ZMQ connector issue; they now move with it to their own change.
…ure at teardown

Closes the two remaining uncovered branches from the error-handling paths the review
asked about: a reconnect whose disconnect raises must still connect and let the retry
proceed, and a send still in flight when destroy runs must be reported rather than
swallowed. plugboard/utils/retry.py is now at 100% branch coverage.
Kafka is not part of the current testing round: there is no broker available to
integration-test against, and whether to run one (managed MSK/Confluent versus a
container) is still an open decision. Everything Kafka-specific moves to
`feat/kafka-message-data`, which stacks on this branch:

- `plugboard/library/kafka_io.py` and `tests/unit/test_kafka_io.py`
- the `kafka` extra and `aiokafka` in the test dependency group (dropped from the
  lockfile, so `async-timeout` goes too)
- `_KafkaSettings` and the `Settings.kafka` field
- the Kafka exports, doc rows, install extra, settings table row and example

The message data base classes, the PubSub and SQS/SNS implementations, the shared
retry/backoff helper and the docs structure all stay: none of them depended on Kafka.
Adds `KafkaDataReader` and `KafkaDataWriter` on the `MessageDataReader` /
`MessageDataWriter` bases:

- Consumer uses a consumer group with auto-commit disabled; acknowledging a batch
  commits the offsets following the processed records, highest per partition, so
  records still buffered remain eligible for redelivery.
- Producer submits a batch's records together and flushes once, keeping the
  client's internal batching instead of one round trip per record.
- `bootstrap_servers` falls back to `KAFKA_BOOTSTRAP_SERVERS` and accepts a string
  or a list; aiokafka failures are mapped onto the broker exception hierarchy
  (authorization / record-too-large are permanent, connection and rebalance errors
  are retried).
- The `kafka` extra declares aiokafka, and aiokafka is in the test dependency group
  so the unit tests can import the real error and offset types.

372 lines of tests cover offset commits (including out-of-order records across
partitions), empty polls returning no messages, multi-partition flattening, batched
sends with a single flush, error mapping, settings resolution and JSON vs raw
encoding.

Split out of #284, where it landed with the PubSub and SQS/SNS implementations.
@github-actions

Copy link
Copy Markdown

Benchmark comparison for 1be92fad (base) vs 861fa1d6 (PR)


------------------------------------------------------------------------------------------------------------------ benchmark: 2 tests -----------------------------------------------------------------------------------------------------------------
Name (time in ms)                                                                         Min                 Max                Mean            StdDev              Median               IQR            Outliers     OPS            Rounds  Iterations
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
test_benchmark_process_run (pr/.benchmarks/Linux-CPython-3.14-64bit/0001_pr)         291.9942 (1.0)      297.7815 (1.00)     294.7383 (1.00)     2.2927 (1.09)     294.1210 (1.0)      3.5155 (1.0)           2;0  3.3928 (1.00)          5           1
test_benchmark_process_run (main/.benchmarks/Linux-CPython-3.14-64bit/0001_base)     292.0238 (1.00)     296.5186 (1.0)      294.3717 (1.0)      2.1120 (1.0)      295.3671 (1.00)     3.8098 (1.08)          3;0  3.3971 (1.0)           5           1
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Legend:
  Outliers: 1 Standard Deviation from Mean; 1.5 IQR (InterQuartile Range) from 1st Quartile and 3rd Quartile.
  OPS: Operations Per Second, computed as 1 / Mean

chrisk314 added a commit that referenced this pull request Dec 5, 2026
# Summary

Implements #102: feat: Base component for external communication
(#102).

Adds `MessageDataReader` / `MessageDataWriter` for reading and writing
**records** through a pub/sub broker - the broker equivalent of
`FileReader`/`FileWriter`, where each message carries one record and
`field_names` become the component's outputs (reader) or inputs
(writer). Both extend the existing `DataReader`/`DataWriter` bases,
adding what a broker needs and a finite source does not: a long-lived
connection, reconnection with backoff, and acknowledgment.

Two implementations are included: **Google Cloud PubSub** and **AWS
SQS/SNS**. Apache Kafka is split out into draft PR #298 - see the note
at the bottom for why.

**Integration tests against real infrastructure are deliberately
deferred** - no AWS/GCP accounts or broker resources exist yet.
Terraform for the required PubSub topic/subscription and SNS topic/SQS
queue lives in `plugboard-infra` (`terraform/ci-data-message-testing`),
and `plugboard-infra/docs/running-message-data-tests.md` describes
wiring its outputs into this suite. All 104 tests here are mock-based,
so no credentials are needed.

# Changes

**Base classes**
- `MessageDataReader` / `MessageDataWriter` extend `DataReader` /
`DataWriter` (buffer, input binding and batching are inherited, not
copied), adding `_connect`, `_disconnect`, `_receive`/`_send`,
`_convert`, and `_ack` (reader).
- Retry, exponential backoff and reconnect live in one shared place:
`plugboard/utils/retry.py`, with a frozen `RetryPolicy` value object
used by both bases.
- Broker exceptions (`MessageBrokerConnectionError` / `TransientError` /
`PermanentError`) are raised and honoured: each implementation maps its
SDK's failures onto them, and permanent errors skip retries that cannot
help.
- Settings for GCP/AWS are read as constructor fallbacks
(`GCP_PUBSUB_PROJECT_ID`, `AWS_REGION`); explicit arguments win.
- All four concrete classes are exported from `plugboard.library`.

**Implementations**
- `GCPPubSubDataReader` / `GCPPubSubDataWriter` (`google-cloud-pubsub`)
- every synchronous PubSub call is dispatched to a worker thread, so a
pull or publish never stalls the shared event loop.
- `AWSSQSDataReader` / `AWSSNSDataWriter` (`aiobotocore`) - long
polling, `delete_message_batch` for acks, and the 10-message SQS cap is
logged rather than applied silently.

**Packaging**: optional extras `gcp-pubsub` and `aws-messaging`; the
broker SDKs are also declared in the `test` dependency group, which is
what lets the tests import the real client and error types.

**Docs**: new [Message
Data](https://docs.plugboard.dev/usage/message-data/) usage page
(extras, worked example, delivery semantics), broker settings in the
configuration page, new extras in the README.

# Behaviour worth knowing

- **An empty poll is not the end of the stream.** A reader started
before its producer keeps waiting and picks up messages as they arrive,
like `WebsocketReader`. A subclass signals a genuinely exhausted source
by raising `NoMoreDataException`, which closes the IO as other data
readers do.
- **Messages are acknowledged after they are processed.** A batch
fetched from the broker is acked only once all of its records have been
published downstream, so a crash mid-batch leaves the unread messages
for redelivery (at-least-once). Unconsumed pre-fetched messages are
deliberately left unacked.
- **Sends are not cancelled at teardown**: an in-flight batch is awaited
(and any failure logged) rather than dropped.

# Testing

- 104 unit tests, all against teardown-aware `monkeypatch` fixtures
rather than global `sys.modules` mocks, asserting broker calls and
arguments rather than private attribute identity.
- Coverage for the paths the review flagged as untested: retry
exhaustion and the delay cap, empty-batch handling, SDK error mapping,
reconnect/disconnect failures, pending-send failure at teardown, and ack
timing.
- Branch coverage of the new modules: `utils/retry.py` 100%,
`message_reader.py` 95%, `message_writer.py` 94%, `gcp_pubsub_io.py`
94%, `aws_messaging_io.py` 95% - the remaining misses are
abstract-method bodies.
- `ruff check`, `ruff format --check`, `ty` over `plugboard/`,
`plugboard-schemas/` and `tests/` pass; `mkdocs build` is clean.
- Full unit suite: 387 passed, 6 skipped. Integration suite against the
compose services: 141 passed, 1 pre-existing ZMQ flake
(`test_process_stop_event[LocalProcess-ZMQConnector-...]`), which passes
on repeat runs in isolation and is addressed in #297.

# Related

- #298 (draft) - the Apache Kafka implementation and its tests, split
out of this PR.
- #297 - the ZMQ slow-joiner delay and flaky marker found while
debugging this branch; split out as unrelated scope.
- `plugboard-infra/terraform/ci-data-message-testing` - infrastructure
for the deferred real-broker integration tests.
Base automatically changed from feat/message-data-classes to main December 5, 2026 10:36

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.

1 participant