Skip to content

feat(kafka): publish mixed tombstone batches to an explicit partition - #3388

Open
Lancetnik wants to merge 3 commits into
stack/tombstone-fastapi-singlefrom
stack/tombstone-publish-batch
Open

Lancetnik wants to merge 3 commits into
stack/tombstone-fastapi-singlefrom
stack/tombstone-publish-batch

Conversation

@Lancetnik

Copy link
Copy Markdown
Member

Summary

Publish ordinary records and explicit tombstones to a specified partition. Check the batch before sending, including whether the codec can encode individual records.

Layer 5 of 7. The diff contains 300 added and removed lines, including tests and docs. Derived from #3379.

Evidence

The regressions cover both orders of a keyed None and a tombstone and a middleware reorder with empty bytes. Connected tests check the native null on both backends.

AI assistance

Codex prepared and tested this layer from the earlier tombstone work.

@github-actions github-actions Bot added documentation Improvements or additions to documentation Confluent Issues related to `faststream.confluent` module AioKafka Issues related to `faststream.kafka` module labels Nov 22, 2026
@Lancetnik
Lancetnik added this pull request to stack #3391 November 22, 2026 20:22
@Lancetnik
Lancetnik marked this pull request as ready for review November 23, 2026 05:10
Send explicit tombstones through the driver’s single-record wire path. Encode the entire batch first and keep every value paired with its original key.
@Lancetnik
Lancetnik force-pushed the stack/tombstone-publish-batch branch from 52432d6 to 7b800a6 Compare November 23, 2026 19:10
for item in batch_bodies:
body, key = _extract_body_and_key(item)
bodies.append(body)
bodies.append(Tombstone() if isinstance(body, Tombstone) else body)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

What's the difference? In special effects?

Comment on lines +624 to +655
@pytest.mark.parametrize(
"from_handler",
(
pytest.param(False, id="direct"),
pytest.param(True, id="response"),
),
)
async def test_batch_publisher_preserves_empty_key(
self, queue: str, mock: Mock, from_handler: bool
) -> None:
broker = self.get_broker(apply_types=True)
publisher = broker.publisher(queue, batch=True, key=b"default", partition=0)

args, kwargs = self.get_subscriber_params(queue)
source_args, source_kwargs = self.get_subscriber_params(f"{queue}-source")

@broker.subscriber(*args, **kwargs)
async def destination(msg: Any = Context("message")) -> None:
mock(_raw_key_value(msg.raw_message))

@broker.subscriber(*source_args, **source_kwargs)
@publisher
async def source() -> Any:
return self.kafka_response(self.tombstone, key=b"")

async with self.patch_broker(broker) as test:
if from_handler:
await test.publish(b"start", queue + "-source")
else:
await publisher.publish(self.tombstone, key=b"")

mock.assert_called_once_with((b"", None))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Divide the test into two tests: 1 with broker.publish, 2 with publisher.publish

@@ -298,27 +298,53 @@ async def handler(msg: Any, raw_msg: Any = Context("message")) -> None:

@pytest.mark.asyncio()
@pytest.mark.parametrize(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Remove parameterization in favor of multiple tests.

@pytest.mark.asyncio()
@pytest.mark.parametrize(
"body", (pytest.param(None, id="legacy"), pytest.param(TOMBSTONE, id="explicit"))
("body", "batch"),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Remove parameterization in favor of multiple tests.

Comment on lines +105 to +116
if isinstance(body, Tombstone):
candidates = [
index
for index, candidate in enumerate(current_bodies)
if index not in used_indexes and isinstance(candidate, Tombstone)
]
index = next((i for i in candidates if current_bodies[i] is body), None)
if index is None:
if len(candidates) != 1:
msg = "Cannot identify the Kafka tombstone in the rewritten batch"
raise ValueError(msg)
index = candidates[0]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Batch rewriting can send tombstone under the key of the discarded record. If middleware replaces (first, second) with (first, first), the second null wire still goes under the second key. I reproduced it on real Kafka with aiokafka and Confluent. Such a replay must be rejected before sending. This is the same class of error that caused #2933 to be rolled back.

Comment on lines +171 to 181
final_headers = (
{"content-type": content_type, **headers_to_send}
if content_type
else headers_to_send
)
else:
encoded_batch = [
await self.codec.encode(body, self.serializer)
for body in cmd.batch_bodies
]

for message_position, (message, content_type) in enumerate(encoded_batch):
if content_type:
final_headers = {
"content-type": content_type,
**headers_to_send,
}
else:
final_headers = headers_to_send.copy()

metadata = batch.append(
key=cmd.key_for(message_position),
value=message,
key=cmd.key_for(index),
value=value if AIOKAFKA_V011 else tombstone_to_none(value),
timestamp=cmd.timestamp_ms,
headers=encode_headers(final_headers),
)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Batch with an explicit batch bypasses key_serializer on aiokafka 0.10.0. With key_serializer=lambda key: b"wire:" + key, publish() writes b"wire:target", and batch sends tombstone under b"target" to the same batch. On aiokafka 0.13.0, the keys match. Both key errors are saved at the top of the stack.

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

AioKafka Issues related to `faststream.kafka` module Confluent Issues related to `faststream.confluent` module documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants