From 9592309e9c1a01b31d3ce980e8c5c1d7b9dfde9b Mon Sep 17 00:00:00 2001 From: kafkiansky Date: Thu, 26 Nov 2026 16:21:39 +0300 Subject: [PATCH 1/4] fix: generator client versions and null structs (012) Co-Authored-By: Claude Fable 5.2 --- generator/Generator.php | 77 +++++- generator/Schema/Message.php | 1 + src/Protocol/Generated/ApiKey.php | 8 +- .../ConsumerGroupHeartbeatResponse.php | 2 +- .../DescribeTopicPartitionsRequest.php | 2 +- .../DescribeTopicPartitionsResponse.php | 2 +- .../Generated/ShareGroupHeartbeatResponse.php | 2 +- .../DescribedGroup.php | 4 +- .../DescribedGroup/Member.php | 4 +- .../StreamsGroupHeartbeatRequest.php | 4 +- tests/ClientVersionsTest.php | 22 ++ tests/Generator/GeneratorTest.php | 239 +++++++++++++++++- tests/NullableStructTest.php | 128 ++++++++++ 13 files changed, 472 insertions(+), 23 deletions(-) create mode 100644 tests/ClientVersionsTest.php create mode 100644 tests/NullableStructTest.php diff --git a/generator/Generator.php b/generator/Generator.php index 858df0e..f572c5d 100644 --- a/generator/Generator.php +++ b/generator/Generator.php @@ -44,13 +44,28 @@ 'records' => 1, ]; + /** + * The last request version that a client may use, by API key name. + * Later versions are for brokers only. The schemas say it only in + * comments, so the numbers come from the Java client + * (LAST_CLIENT_VERSION in its request classes). + * Check this list after `make sync-schemas`. + */ + private const array LAST_CLIENT_VERSIONS = [ + 'AddPartitionsToTxn' => 3, + ]; + private TreeMapper $mapper; + /** + * @param array $lastClientVersions + */ public function __construct( private Writer $fs, private Generator\NamespaceGenerator $protocolNs, private Generator\NamespaceGenerator $generatedNs, ?TreeMapper $mapper = null, + private array $lastClientVersions = self::LAST_CLIENT_VERSIONS, ) { $this->mapper = $mapper ?? new MapperBuilder() ->allowSuperfluousKeys() @@ -99,7 +114,7 @@ public function generate(SchemaSource $input): void name: $name, value: $message->apiKey, min: $message->validVersions->min, - max: $message->validVersions->max, + max: $this->lastClientVersion($name, $message), flexibleVersions: $message->flexibleVersions, listeners: $listenersForKey, )); @@ -115,10 +130,50 @@ public function generate(SchemaSource $input): void } } + foreach (array_keys($this->lastClientVersions) as $name) { + if (!array_any($apiKeys->keys, static fn(Schema\ApiKey $key) => $key->name === $name)) { + throw new \LogicException("The last client version is set for API key '{$name}', but no request schema has this API key."); + } + } + $this->generateListener(array_keys($listeners)); $this->generateApiKey($apiKeys); } + /** + * @param non-empty-string $name + * @return non-negative-int + */ + private function lastClientVersion(string $name, Schema\Message $request): int + { + $min = $request->validVersions->min; + $max = $request->validVersions->max; + \assert($min !== null && $max !== null); + + $last = $max; + + // A broker does not offer an unstable version by default, and the Java client does not use it. + if ($request->latestVersionUnstable) { + if ($max <= $min) { + throw new \LogicException("API key '{$name}' has only one valid version, and it is unstable."); + } + + $last = $max - 1; + } + + if (isset($this->lastClientVersions[$name])) { + $lastClientVersion = $this->lastClientVersions[$name]; + + if ($lastClientVersion < $min || $lastClientVersion > $max) { + throw new \LogicException("The last client version {$lastClientVersion} of API key '{$name}' is outside of its valid versions {$min}-{$max}."); + } + + $last = min($last, $lastClientVersion); + } + + return $last; + } + private function generateRequestInterface(): void { $interface = new InterfaceType('Request') @@ -727,6 +782,13 @@ private static function taggedFields(array $fields): array static fn(Schema\Field $field): bool => !$field->taggedVersions->isNone(), ); + foreach ($tagged as $field) { + // Kafka uses another null marker for a struct in a tagged field. No schema needs it yet. + if (self::isStruct($field->type) && !$field->nullableVersions->intersect($field->taggedVersions)->isNone()) { + throw new \LogicException("Field '{$field->name}' is a nullable struct in a tagged field. The generator does not support it."); + } + } + usort( $tagged, static fn(Schema\Field $left, Schema\Field $right): int => ($left->tag ?? -1) <=> ($right->tag ?? -1), @@ -1275,8 +1337,9 @@ private static function emitStructWrite( ]; } + // Kafka writes -1 before a null struct and 1 before a present one. $nullable = static fn(Expr $v): array => [ - Ast::stmt(Ast::call($ctx->writer, 'writeBool', Ast::neq($v, Ast::null()))), + Ast::stmt(Ast::call($ctx->writer, 'writeInt8', Ast::ternary(Ast::eq($v, Ast::null()), Ast::int(-1), Ast::int(1)))), Ast::stmt(Ast::nullsafeCall($v, 'encode', $ctx->writer, Ast::var('version'))), ]; @@ -1465,10 +1528,11 @@ private static function emitStructRead( $nullable = static fn(string $targetVar): array => [ Ast::assign( Ast::var($targetVar), + // Kafka reads any negative marker as null. Ast::ternary( - Ast::call($ctx->reader, 'readBool'), - Ast::staticCall($structRef, 'decode', $ctx->reader, Ast::var('version')), + Ast::lt(Ast::call($ctx->reader, 'readInt8'), Ast::int(0)), Ast::null(), + Ast::staticCall($structRef, 'decode', $ctx->reader, Ast::var('version')), ), ), ]; @@ -1811,6 +1875,11 @@ private function usesUuidFactory(array $fields, Schema\VersionRange $containerVe return false; } + private static function isStruct(string $type): bool + { + return !str_starts_with($type, '[]') && !isset(self::SCALARS[$type]) && !isset(self::PREFIXED[$type]); + } + /** * @param non-empty-string $listener * @return non-empty-string diff --git a/generator/Schema/Message.php b/generator/Schema/Message.php index 4f53e3b..100c70a 100644 --- a/generator/Schema/Message.php +++ b/generator/Schema/Message.php @@ -20,6 +20,7 @@ public function __construct( public Type $type, public string $name, public VersionRange $validVersions = new VersionRange(), + public bool $latestVersionUnstable = false, public VersionRange $flexibleVersions = new VersionRange(), public ?int $apiKey = null, public array $listeners = [], diff --git a/src/Protocol/Generated/ApiKey.php b/src/Protocol/Generated/ApiKey.php index 3efc542..872214e 100644 --- a/src/Protocol/Generated/ApiKey.php +++ b/src/Protocol/Generated/ApiKey.php @@ -215,8 +215,7 @@ public function clientVersionRange(): VersionRange self::OffsetCommit => new VersionRange(2, 10), self::OffsetFetch => new VersionRange(1, 10), self::FindCoordinator, - self::DescribeGroups, - self::InitProducerId => new VersionRange(0, 6), + self::DescribeGroups => new VersionRange(0, 6), self::JoinGroup => new VersionRange(0, 9), self::Heartbeat, self::ApiVersions, @@ -225,7 +224,7 @@ public function clientVersionRange(): VersionRange self::LeaveGroup, self::SyncGroup, self::ListGroups, - self::AddPartitionsToTxn, + self::InitProducerId, self::EndTxn, self::TxnOffsetCommit => new VersionRange(0, 5), self::SaslHandshake, @@ -257,6 +256,8 @@ public function clientVersionRange(): VersionRange self::DescribeCluster, self::ListTransactions => new VersionRange(0, 2), self::OffsetForLeaderEpoch => new VersionRange(2, 4), + self::AddPartitionsToTxn, + self::CreatePartitions => new VersionRange(0, 3), self::WriteTxnMarkers, self::AlterReplicaLogDirs, self::RenewDelegationToken, @@ -270,7 +271,6 @@ public function clientVersionRange(): VersionRange self::DescribeDelegationToken => new VersionRange(1, 3), self::DescribeConfigs, self::DescribeLogDirs => new VersionRange(1, 4), - self::CreatePartitions => new VersionRange(0, 3), self::ListPartitionReassignments, self::OffsetDelete, self::DescribeUserScramCredentials, diff --git a/src/Protocol/Generated/ConsumerGroupHeartbeatResponse.php b/src/Protocol/Generated/ConsumerGroupHeartbeatResponse.php index 41d6199..b7991af 100644 --- a/src/Protocol/Generated/ConsumerGroupHeartbeatResponse.php +++ b/src/Protocol/Generated/ConsumerGroupHeartbeatResponse.php @@ -43,7 +43,7 @@ public static function decode(Reader $reader, int $version): static $memberId = $reader->readCompactNullableString(); $memberEpoch = $reader->readInt32(); $heartbeatIntervalMs = $reader->readInt32(); - $assignment = $reader->readBool() ? ConsumerGroupHeartbeatResponse\Assignment::decode($reader, $version) : null; + $assignment = $reader->readInt8() < 0 ? null : ConsumerGroupHeartbeatResponse\Assignment::decode($reader, $version); $unknownTags = $reader->readTaggedFields(); return new self($throttleTimeMs, $errorCode, $errorMessage, $memberId, $memberEpoch, $heartbeatIntervalMs, $assignment, $unknownTags); } diff --git a/src/Protocol/Generated/DescribeTopicPartitionsRequest.php b/src/Protocol/Generated/DescribeTopicPartitionsRequest.php index f876535..f26bf64 100644 --- a/src/Protocol/Generated/DescribeTopicPartitionsRequest.php +++ b/src/Protocol/Generated/DescribeTopicPartitionsRequest.php @@ -47,7 +47,7 @@ public function encode(Writer $writer, int $version): void $item->encode($writer, $version); } $writer->writeInt32($this->responsePartitionLimit); - $writer->writeBool($this->cursor !== null); + $writer->writeInt8($this->cursor === null ? -1 : 1); $this->cursor?->encode($writer, $version); $writer->writeTaggedFields($this->unknownTags); } diff --git a/src/Protocol/Generated/DescribeTopicPartitionsResponse.php b/src/Protocol/Generated/DescribeTopicPartitionsResponse.php index 79d8cad..366f14d 100644 --- a/src/Protocol/Generated/DescribeTopicPartitionsResponse.php +++ b/src/Protocol/Generated/DescribeTopicPartitionsResponse.php @@ -36,7 +36,7 @@ public static function decode(Reader $reader, int $version): static $item = DescribeTopicPartitionsResponse\DescribeTopicPartitionsResponseTopic::decode($reader, $version); $topics[] = $item; } - $nextCursor = $reader->readBool() ? DescribeTopicPartitionsResponse\Cursor::decode($reader, $version) : null; + $nextCursor = $reader->readInt8() < 0 ? null : DescribeTopicPartitionsResponse\Cursor::decode($reader, $version); $unknownTags = $reader->readTaggedFields(); return new self($throttleTimeMs, $topics, $nextCursor, $unknownTags); } diff --git a/src/Protocol/Generated/ShareGroupHeartbeatResponse.php b/src/Protocol/Generated/ShareGroupHeartbeatResponse.php index 92f8952..929b6d9 100644 --- a/src/Protocol/Generated/ShareGroupHeartbeatResponse.php +++ b/src/Protocol/Generated/ShareGroupHeartbeatResponse.php @@ -43,7 +43,7 @@ public static function decode(Reader $reader, int $version): static $memberId = $reader->readCompactNullableString(); $memberEpoch = $reader->readInt32(); $heartbeatIntervalMs = $reader->readInt32(); - $assignment = $reader->readBool() ? ShareGroupHeartbeatResponse\Assignment::decode($reader, $version) : null; + $assignment = $reader->readInt8() < 0 ? null : ShareGroupHeartbeatResponse\Assignment::decode($reader, $version); $unknownTags = $reader->readTaggedFields(); return new self($throttleTimeMs, $errorCode, $errorMessage, $memberId, $memberEpoch, $heartbeatIntervalMs, $assignment, $unknownTags); } diff --git a/src/Protocol/Generated/StreamsGroupDescribeResponse/DescribedGroup.php b/src/Protocol/Generated/StreamsGroupDescribeResponse/DescribedGroup.php index b4e1dfa..9cd49ce 100644 --- a/src/Protocol/Generated/StreamsGroupDescribeResponse/DescribedGroup.php +++ b/src/Protocol/Generated/StreamsGroupDescribeResponse/DescribedGroup.php @@ -50,7 +50,7 @@ public function encode(Writer $writer, int $version): void $writer->writeCompactString($this->groupState); $writer->writeInt32($this->groupEpoch); $writer->writeInt32($this->assignmentEpoch); - $writer->writeBool($this->topology !== null); + $writer->writeInt8($this->topology === null ? -1 : 1); $this->topology?->encode($writer, $version); $writer->writeCompactArrayLength(\count($this->members)); foreach ($this->members as $item) { @@ -69,7 +69,7 @@ public static function decode(Reader $reader, int $version): static $groupState = $reader->readCompactString(); $groupEpoch = $reader->readInt32(); $assignmentEpoch = $reader->readInt32(); - $topology = $reader->readBool() ? DescribedGroup\Topology::decode($reader, $version) : null; + $topology = $reader->readInt8() < 0 ? null : DescribedGroup\Topology::decode($reader, $version); $membersCount = $reader->readCompactArrayLength(); $members = []; for ($membersIndex = 0; $membersIndex < $membersCount; ++$membersIndex) { diff --git a/src/Protocol/Generated/StreamsGroupDescribeResponse/DescribedGroup/Member.php b/src/Protocol/Generated/StreamsGroupDescribeResponse/DescribedGroup/Member.php index 0d3d31e..603b27e 100644 --- a/src/Protocol/Generated/StreamsGroupDescribeResponse/DescribedGroup/Member.php +++ b/src/Protocol/Generated/StreamsGroupDescribeResponse/DescribedGroup/Member.php @@ -68,7 +68,7 @@ public function encode(Writer $writer, int $version): void $writer->writeCompactString($this->clientHost); $writer->writeInt32($this->topologyEpoch); $writer->writeCompactString($this->processId); - $writer->writeBool($this->userEndpoint !== null); + $writer->writeInt8($this->userEndpoint === null ? -1 : 1); $this->userEndpoint?->encode($writer, $version); $writer->writeCompactArrayLength(\count($this->clientTags)); foreach ($this->clientTags as $item) { @@ -99,7 +99,7 @@ public static function decode(Reader $reader, int $version): static $clientHost = $reader->readCompactString(); $topologyEpoch = $reader->readInt32(); $processId = $reader->readCompactString(); - $userEndpoint = $reader->readBool() ? Endpoint::decode($reader, $version) : null; + $userEndpoint = $reader->readInt8() < 0 ? null : Endpoint::decode($reader, $version); $clientTagsCount = $reader->readCompactArrayLength(); $clientTags = []; for ($clientTagsIndex = 0; $clientTagsIndex < $clientTagsCount; ++$clientTagsIndex) { diff --git a/src/Protocol/Generated/StreamsGroupHeartbeatRequest.php b/src/Protocol/Generated/StreamsGroupHeartbeatRequest.php index 09853da..c1a091c 100644 --- a/src/Protocol/Generated/StreamsGroupHeartbeatRequest.php +++ b/src/Protocol/Generated/StreamsGroupHeartbeatRequest.php @@ -77,7 +77,7 @@ public function encode(Writer $writer, int $version): void $writer->writeCompactNullableString($this->instanceId); $writer->writeCompactNullableString($this->rackId); $writer->writeInt32($this->rebalanceTimeoutMs); - $writer->writeBool($this->topology !== null); + $writer->writeInt8($this->topology === null ? -1 : 1); $this->topology?->encode($writer, $version); $writer->writeCompactNullableArrayLength($this->activeTasks === null ? null : \count($this->activeTasks)); if ($this->activeTasks !== null) { @@ -98,7 +98,7 @@ public function encode(Writer $writer, int $version): void } } $writer->writeCompactNullableString($this->processId); - $writer->writeBool($this->userEndpoint !== null); + $writer->writeInt8($this->userEndpoint === null ? -1 : 1); $this->userEndpoint?->encode($writer, $version); $writer->writeCompactNullableArrayLength($this->clientTags === null ? null : \count($this->clientTags)); if ($this->clientTags !== null) { diff --git a/tests/ClientVersionsTest.php b/tests/ClientVersionsTest.php new file mode 100644 index 0000000..7334098 --- /dev/null +++ b/tests/ClientVersionsTest.php @@ -0,0 +1,22 @@ +test(static function (Kafka $kafka): void { + Assert::same($kafka->negotiatedVersion(ApiKey::AddPartitionsToTxn), 3); + Assert::int($kafka->negotiatedVersion(ApiKey::InitProducerId) ?? -1)->between(0, 5); + }); + } +} diff --git a/tests/Generator/GeneratorTest.php b/tests/Generator/GeneratorTest.php index 9d1e14b..7c3da73 100644 --- a/tests/Generator/GeneratorTest.php +++ b/tests/Generator/GeneratorTest.php @@ -5,10 +5,12 @@ namespace Thesis\Kafka\Generator; use Testo\Assert; +use Testo\Expect; use Testo\Test; use Thesis\Kafka\Generator\Generator\NamespaceGenerator; use Thesis\Kafka\Generator\SchemaSource\StaticSource; use Thesis\Kafka\Generator\Writer\InMemoryWriter; +use Thesis\Kafka\Protocol\Generated\ApiKey; final class GeneratorTest { @@ -1003,24 +1005,251 @@ public static function decode(Reader $reader, int $version): static ); } + #[Test] + public function keepsBrokerOnlyVersionsOutOfClientRange(): void + { + $apiKey = self::generate(self::sampleRequest('0-5'), ['Sample' => 3])->get('ApiKey.php'); + + Assert::string($apiKey ?? '')->contains('self::Sample => new VersionRange(0, 3),'); + } + + #[Test] + public function failsOnLastClientVersionOfUnknownApiKey(): void + { + Expect::exception(\LogicException::class) + ->withMessage("The last client version is set for API key 'Missing', but no request schema has this API key."); + + self::generate(self::sampleRequest('0-5'), ['Sample' => 3, 'Missing' => 1]); + } + + #[Test] + public function failsOnLastClientVersionAboveValidVersions(): void + { + Expect::exception(\LogicException::class) + ->withMessage("The last client version 6 of API key 'Sample' is outside of its valid versions 0-5."); + + self::generate(self::sampleRequest('0-5'), ['Sample' => 6]); + } + + #[Test] + public function failsOnLastClientVersionBelowValidVersions(): void + { + Expect::exception(\LogicException::class) + ->withMessage("The last client version 0 of API key 'Sample' is outside of its valid versions 1-5."); + + self::generate(self::sampleRequest('1-5'), ['Sample' => 0]); + } + + #[Test] + public function keepsUnstableLatestVersionOutOfClientRange(): void + { + $unstable = self::generate(self::sampleRequest('0-6', latestVersionUnstable: true))->get('ApiKey.php'); + $stable = self::generate(self::sampleRequest('0-6', latestVersionUnstable: false))->get('ApiKey.php'); + + Assert::string($unstable ?? '')->contains('self::Sample => new VersionRange(0, 5),'); + Assert::string($stable ?? '')->contains('self::Sample => new VersionRange(0, 6),'); + } + + #[Test] + public function realSchemasHaveClientVersionRanges(): void + { + Assert::same( + [ApiKey::AddPartitionsToTxn->clientVersionRange()->min, ApiKey::AddPartitionsToTxn->clientVersionRange()->max], + [0, 3], + ); + Assert::same( + [ApiKey::InitProducerId->clientVersionRange()->min, ApiKey::InitProducerId->clientVersionRange()->max], + [0, 5], + ); + } + + #[Test] + public function writesAndReadsNullMarkerOfNullableStruct(): void + { + self::assertSameContent( + <<<'JSON' + { + "type": "response", + "name": "NullableStructResponse", + "validVersions": "0-1", + "fields": [ + { + "name": "Outer", + "type": "Outer", + "versions": "0+", + "about": "Outer struct.", + "fields": [ + { + "name": "Always", + "type": "Always", + "versions": "0+", + "nullableVersions": "0+", + "about": "Nullable in all versions.", + "fields": [ + { "name": "Value", "type": "int32", "versions": "0+", "about": "A value." } + ] + }, + { + "name": "Gated", + "type": "Gated", + "versions": "0+", + "nullableVersions": "1+", + "about": "Nullable in version 1 only.", + "fields": [ + { "name": "Value", "type": "int32", "versions": "0+", "about": "A value." } + ] + } + ] + } + ] + } + JSON, + [ + 'NullableStructResponse/Outer.php' => <<<'PHP' + writeInt8($this->always === null ? -1 : 1); + $this->always?->encode($writer, $version); + if ($version >= 1) { + $writer->writeInt8($this->gated === null ? -1 : 1); + $this->gated?->encode($writer, $version); + } else { + if ($this->gated === null) { + throw new \UnexpectedValueException("Field 'Gated' must not be null in version '{$version}'"); + } + $this->gated->encode($writer, $version); + } + } + + #[\Override] + public static function decode(Reader $reader, int $version): static + { + $always = $reader->readInt8() < 0 ? null : Outer\Always::decode($reader, $version); + if ($version >= 1) { + $gated = $reader->readInt8() < 0 ? null : Outer\Gated::decode($reader, $version); + } else { + $gated = Outer\Gated::decode($reader, $version); + } + return new self($always, $gated); + } + } + + PHP, + ], + ); + } + + #[Test] + public function failsOnNullableStructInTaggedField(): void + { + Expect::exception(\LogicException::class) + ->withMessage("Field 'Meta' is a nullable struct in a tagged field. The generator does not support it."); + + self::generate( + <<<'JSON' + { + "type": "response", + "name": "TaggedNullableResponse", + "validVersions": "0+", + "flexibleVersions": "0+", + "fields": [ + { + "name": "Meta", + "type": "Meta", + "versions": "0+", + "taggedVersions": "0+", + "nullableVersions": "0+", + "tag": 0, + "about": "Tagged nullable meta.", + "fields": [ + { "name": "LeaderId", "type": "int32", "versions": "0+", "about": "Leader id." } + ] + } + ] + } + JSON, + ); + } + + /** + * @param non-empty-string $validVersions + * @return non-empty-string + */ + private static function sampleRequest(string $validVersions, bool $latestVersionUnstable = false): string + { + $unstable = $latestVersionUnstable ? 'true' : 'false'; + + return << $classes + * @param array $lastClientVersions */ - private static function assertSameContent( - string $json, - array $classes, - ): void { + private static function generate(string $json, array $lastClientVersions = []): InMemoryWriter + { $writer = new InMemoryWriter(); $generator = new Generator( fs: $writer, protocolNs: new NamespaceGenerator('Thesis\Kafka\Protocol'), generatedNs: new NamespaceGenerator('Thesis\Kafka\Protocol\Generated'), + lastClientVersions: $lastClientVersions, ); $generator->generate(new StaticSource([$json])); + return $writer; + } + + /** + * @param non-empty-string $json + * @param array $classes + */ + private static function assertSameContent( + string $json, + array $classes, + ): void { + $writer = self::generate($json); + foreach ($classes as $path => $class) { Assert::same($class, $writer->get($path)); } diff --git a/tests/NullableStructTest.php b/tests/NullableStructTest.php new file mode 100644 index 0000000..37d2928 --- /dev/null +++ b/tests/NullableStructTest.php @@ -0,0 +1,128 @@ +test(static function (Kafka $kafka): void { + $topic = $kafka->topic(partitions: 3); + + $response = $kafka->client->request(new Generated\DescribeTopicPartitionsRequest( + topics: [new Generated\DescribeTopicPartitionsRequest\TopicRequest($topic)], + responsePartitionLimit: 2000, + cursor: null, + )); + + \assert(\count($response->topics) === 1); + Assert::same($response->topics[0]->errorCode, 0); + Assert::same($response->topics[0]->name, $topic); + Assert::same( + array_map( + static fn(Generated\DescribeTopicPartitionsResponse\DescribeTopicPartitionsResponseTopic\DescribeTopicPartitionsResponsePartition $partition) => [$partition->partitionIndex, $partition->errorCode], + $response->topics[0]->partitions, + ), + [[0, 0], [1, 0], [2, 0]], + ); + Assert::null($response->nextCursor); + }); + } + + #[Test] + public function clientReadsNullStructInResponse(): void + { + Kafka::connect(...Kafka::KAFKA_4_SEEDS)->test(static function (Kafka $kafka): void { + $topic = $kafka->topic(partitions: 2); + $groupId = $kafka->groupId(); + $memberId = Uuid::uuid4()->toString(); + + $metadata = $kafka->client->request(Kafka::metadataRequest([$topic])); + \assert(\count($metadata->topics) === 1); + $topicId = $metadata->topics[0]->topicId; + + // The first heartbeat joins the group with no partitions. A null field of a later heartbeat means "no change". + $heartbeat = static fn(int $memberEpoch, ?Generated\ConsumerGroupHeartbeatRequest\TopicPartitions $owned = null): Generated\ConsumerGroupHeartbeatResponse => $kafka->client->request( + new Generated\ConsumerGroupHeartbeatRequest( + groupId: $groupId, + memberId: $memberId, + memberEpoch: $memberEpoch, + instanceId: null, + rackId: null, + rebalanceTimeoutMs: $memberEpoch === 0 ? 30_000 : -1, + subscribedTopicNames: $memberEpoch === 0 ? [$topic] : null, + subscribedTopicRegex: null, + serverAssignor: null, + topicPartitions: match (true) { + $memberEpoch === 0 => [], + $owned === null => null, + default => [$owned], + }, + ), + ); + + // A new broker loads the offsets topic first. Until then the coordinator is not ready. + $joined = $kafka->poll(static fn() => $heartbeat(0)) + ->expecting('a joined member') + ->describedBy(static fn(Generated\ConsumerGroupHeartbeatResponse $response) => "error code {$response->errorCode}") + ->until(static fn(Generated\ConsumerGroupHeartbeatResponse $response) => $response->errorCode === 0); + + Assert::same($joined->memberId, $memberId); + Assert::int($joined->memberEpoch)->greaterThan(0); + + // The coordinator can assign the partitions with the join or with a later heartbeat. + // The first assignment can be empty when the coordinator does not see the new topic yet. + $hasPartitions = static fn(Generated\ConsumerGroupHeartbeatResponse $response): bool => $response->errorCode === 0 + && ($response->assignment->topicPartitions ?? []) !== []; + + $epoch = $joined->memberEpoch; + $assigned = $hasPartitions($joined) ? $joined : $kafka + ->poll(static function () use ($heartbeat, &$epoch): Generated\ConsumerGroupHeartbeatResponse { + $response = $heartbeat($epoch); + $epoch = $response->memberEpoch; + + return $response; + }) + ->expecting('a heartbeat response with an assignment') + ->describedBy(static fn(Generated\ConsumerGroupHeartbeatResponse $response) => "error code {$response->errorCode}") + ->until($hasPartitions); + + Assert::same($assigned->memberId, $memberId); + Assert::notNull($assigned->assignment); + Assert::same( + array_map( + static function (Generated\ConsumerGroupHeartbeatResponse\TopicPartitions $partitions): array { + $indexes = $partitions->partitions; + sort($indexes); + + return [$partitions->topicId->toString(), $indexes]; + }, + $assigned->assignment->topicPartitions, + ), + [[$topicId->toString(), [0, 1]]], + ); + + $next = $heartbeat( + $assigned->memberEpoch, + new Generated\ConsumerGroupHeartbeatRequest\TopicPartitions($topicId, [0, 1]), + ); + + Assert::null($next->assignment); + Assert::same($next->errorCode, 0); + Assert::same($next->memberId, $memberId); + Assert::same($next->memberEpoch, $assigned->memberEpoch); + }); + } +} From a5decd46a2817a1aedb3f32ca8d05c7af4cecdff Mon Sep 17 00:00:00 2001 From: kafkiansky Date: Thu, 26 Nov 2026 16:21:39 +0300 Subject: [PATCH 2/4] chore: journal 012 done Co-Authored-By: Claude Fable 5.2 --- docs/journal/0.1.x/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/journal/0.1.x/README.md b/docs/journal/0.1.x/README.md index e3b31e3..2aa7a2b 100644 --- a/docs/journal/0.1.x/README.md +++ b/docs/journal/0.1.x/README.md @@ -39,7 +39,7 @@ One line per task, in the order of work: - [x] [040 Metadata timer: interval and log](040-metadata-timer-details.md) — [6171caf](https://github.com/thesis-php/kafka/commit/6171caf) - [x] [010 Varint and int64 without copies](010-varint-decoding.md) — [e3a9669](https://github.com/thesis-php/kafka/commit/e3a9669) - [x] [011 Retriable errors and leader change](011-retriable-errors.md) — [01d14e0](https://github.com/thesis-php/kafka/commit/01d14e0) -- [ ] [012 Generator: client versions and null structs](012-generator-client-versions.md) +- [x] [012 Generator: client versions and null structs](012-generator-client-versions.md) — [9592309](https://github.com/thesis-php/kafka/commit/9592309) - [ ] 016 Producer shutdown - [ ] 017 Producer concurrency - [ ] 018 Idempotent producer after a failed batch From 5fcbd9b3fd55c621360067f996145284d3506316 Mon Sep 17 00:00:00 2001 From: kafkiansky Date: Thu, 26 Nov 2026 16:59:50 +0300 Subject: [PATCH 3/4] fix: assertion that the lowest Testo version has (012) Co-Authored-By: Claude Fable 5.2 --- tests/NullableStructTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/NullableStructTest.php b/tests/NullableStructTest.php index 37d2928..c50338f 100644 --- a/tests/NullableStructTest.php +++ b/tests/NullableStructTest.php @@ -100,7 +100,7 @@ public function clientReadsNullStructInResponse(): void ->until($hasPartitions); Assert::same($assigned->memberId, $memberId); - Assert::notNull($assigned->assignment); + Assert::instanceOf($assigned->assignment, Generated\ConsumerGroupHeartbeatResponse\Assignment::class); Assert::same( array_map( static function (Generated\ConsumerGroupHeartbeatResponse\TopicPartitions $partitions): array { From 423e58caf9215d8b694a97020fc02621c5c16d36 Mon Sep 17 00:00:00 2001 From: kafkiansky Date: Thu, 26 Nov 2026 17:04:53 +0300 Subject: [PATCH 4/4] fix: create the offsets topic before the heartbeat test (012) Co-Authored-By: Claude Fable 5.2 --- tests/NullableStructTest.php | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/tests/NullableStructTest.php b/tests/NullableStructTest.php index c50338f..421a2e2 100644 --- a/tests/NullableStructTest.php +++ b/tests/NullableStructTest.php @@ -73,7 +73,14 @@ public function clientReadsNullStructInResponse(): void ), ); - // A new broker loads the offsets topic first. Until then the coordinator is not ready. + // A new broker has no offsets topic. Only FindCoordinator creates it, a heartbeat does not. + // Until the topic is loaded, the heartbeat gets NOT_COORDINATOR. + $kafka->client->request(new Generated\FindCoordinatorRequest( + key: $groupId, + keyType: 0, + coordinatorKeys: [$groupId], + )); + $joined = $kafka->poll(static fn() => $heartbeat(0)) ->expecting('a joined member') ->describedBy(static fn(Generated\ConsumerGroupHeartbeatResponse $response) => "error code {$response->errorCode}")