Skip to content

Truncate bodyResponse to the actual number of bytes read #85

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

ryan-gang
Copy link
Contributor

@ryan-gang ryan-gang commented Jul 26, 2025

Previously: #50

  • Validate response length and handle partial reads by truncating bodyResponse to the actual number of bytes read.
  • Improve connection retry logic and read handling.
  • Add support for ApiVersions length field edge cases on servers with debug enabled.
  • Add test scenarios and cases for ApiVersions length field validation errors.

Summary by CodeRabbit

  • New Features

    • Added validation to detect mismatches between the message size field and actual payload length in Kafka API responses.
  • Bug Fixes

    • Improved robustness when reading response data from the server, ensuring full length fields are read and handling partial reads more gracefully.
  • Tests

    • Introduced new test cases and scenarios to verify handling of API responses with incorrect length fields (too large or too small).

Copy link

coderabbitai bot commented Jul 26, 2025

Walkthrough

This change adds two new test cases to the TestStages function for the "pv1" stage, targeting scenarios where the Kafka "ApiVersions" response message length field is either too large or too small. Corresponding scenario fixtures, server implementations, and scripts are introduced to simulate these edge cases. The Kafka client is updated to robustly validate response length fields and handle partial reads.

Changes

Files/Paths Change Summary
internal/stages_test.go Added two test cases for "pv1" stage covering "apiversions" length field too large/small scenarios.
internal/test_helpers/fixtures/scenarios/apiversions_length_field_too_large Added new scenario fixture for length field too large test.
internal/test_helpers/fixtures/scenarios/apiversions_length_field_too_small Added new scenario fixture for length field too small test.
internal/test_helpers/scenarios/apiversions_length_field_too_large/{main.py,your_program.sh,codecrafters.yml} Added Python TCP server, shell runner, and config for "length field too large" scenario.
internal/test_helpers/scenarios/apiversions_length_field_too_small/{main.py,your_program.sh,codecrafters.yml} Added Python TCP server, shell runner, and config for "length field too small" scenario.
protocol/kafka_client/client.go Enhanced response length validation, improved read robustness, and minor retry logic update.

Sequence Diagram(s)

sequenceDiagram
    participant TestRunner
    participant KafkaServer (Python)
    participant KafkaClient (Go)

    TestRunner->>KafkaServer (Python): Start scenario server (main.py)
    TestRunner->>KafkaClient (Go): Run client test (TestStages)
    KafkaClient (Go)->>KafkaServer (Python): Connect and send ApiVersions request
    KafkaServer (Python)->>KafkaClient (Go): Send crafted ApiVersions response (length field too large/small)
    KafkaClient (Go)->>KafkaClient (Go): Validate response length field (checkLength)
    KafkaClient (Go)->>TestRunner: Report test result (pass/fail)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • rohitpaulk

Poem

A rabbit hops with code so neat,
Testing Kafka’s bytes and heat.
Too big, too small, the length it checks,
Ensuring bugs bounce off, not vex.
With fixtures, scripts, and tests anew,
This patch brings validation true!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch check-length

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@ryan-gang ryan-gang self-assigned this Jul 26, 2025
@ryan-gang ryan-gang requested a review from andy1li July 26, 2025 06:42
@ryan-gang
Copy link
Contributor Author

ryan-gang commented Jul 26, 2025

@andy1li can you please own this PR ?

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

♻️ Duplicate comments (1)
internal/test_helpers/scenarios/apiversions_length_field_too_small/main.py (1)

30-54: Apply the same error handling improvements as the companion scenario.

This implementation has the same robustness concerns as the "too large" scenario regarding malformed request handling and graceful shutdown. Consider applying similar improvements for consistency.

🧹 Nitpick comments (1)
internal/test_helpers/scenarios/apiversions_length_field_too_large/main.py (1)

20-27: Consider adding graceful shutdown mechanism.

The server runs indefinitely without a clean shutdown mechanism. For production-like test scenarios, consider adding signal handling or a shutdown flag.

import signal
import sys

def signal_handler(sig, frame):
    print('Shutting down gracefully...')
    sys.exit(0)

def main(port=9092):
    signal.signal(signal.SIGINT, signal_handler)
    # ... rest of the implementation
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b2b6f66 and 9dc05d3.

📒 Files selected for processing (10)
  • internal/stages_test.go (1 hunks)
  • internal/test_helpers/fixtures/scenarios/apiversions_length_field_too_large (1 hunks)
  • internal/test_helpers/fixtures/scenarios/apiversions_length_field_too_small (1 hunks)
  • internal/test_helpers/scenarios/apiversions_length_field_too_large/codecrafters.yml (1 hunks)
  • internal/test_helpers/scenarios/apiversions_length_field_too_large/main.py (1 hunks)
  • internal/test_helpers/scenarios/apiversions_length_field_too_large/your_program.sh (1 hunks)
  • internal/test_helpers/scenarios/apiversions_length_field_too_small/codecrafters.yml (1 hunks)
  • internal/test_helpers/scenarios/apiversions_length_field_too_small/main.py (1 hunks)
  • internal/test_helpers/scenarios/apiversions_length_field_too_small/your_program.sh (1 hunks)
  • protocol/kafka_client/client.go (7 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
internal/test_helpers/fixtures/scenarios/apiversions_length_field_too_small (1)
internal/stage_4.go (1)
  • testAPIVersionErrorCase (20-116)
internal/test_helpers/scenarios/apiversions_length_field_too_small/main.py (1)
internal/test_helpers/scenarios/apiversions_length_field_too_large/main.py (4)
  • Request (8-17)
  • from_bytes (15-17)
  • main (20-27)
  • handle_connection (30-53)
internal/test_helpers/scenarios/apiversions_length_field_too_large/main.py (1)
internal/test_helpers/scenarios/apiversions_length_field_too_small/main.py (4)
  • Request (8-17)
  • from_bytes (15-17)
  • main (20-27)
  • handle_connection (30-53)
🪛 Shellcheck (0.10.0)
internal/test_helpers/scenarios/apiversions_length_field_too_small/your_program.sh

[warning] 2-2: Quote this to prevent word splitting.

(SC2046)

internal/test_helpers/scenarios/apiversions_length_field_too_large/your_program.sh

[warning] 2-2: Quote this to prevent word splitting.

(SC2046)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Cursor Bugbot
🔇 Additional comments (20)
internal/test_helpers/scenarios/apiversions_length_field_too_large/your_program.sh (1)

1-2: Script logic is correct for test scenario execution.

The shell script properly forwards arguments and locates the Python server in the same directory.

internal/test_helpers/scenarios/apiversions_length_field_too_small/codecrafters.yml (1)

1-1: Configuration is appropriate for test scenario.

Enabling debug mode for this edge case scenario is a good practice for troubleshooting and development.

internal/test_helpers/scenarios/apiversions_length_field_too_large/codecrafters.yml (1)

1-1: Consistent configuration across test scenarios.

The debug mode setting is appropriate and maintains consistency with the companion "too_small" scenario.

internal/test_helpers/scenarios/apiversions_length_field_too_small/your_program.sh (1)

1-2: Script structure is consistent and functional.

The script maintains the same pattern as its companion, which is good for maintainability.

internal/stages_test.go (3)

43-49: Well-structured test case for "too_large" scenario.

The test case follows the established pattern and correctly expects failure (exit code 1) for this edge case scenario.


50-56: Consistent test case for "too_small" scenario.

The test case maintains consistency with its companion and the existing test structure, appropriately expecting failure for malformed responses.


43-56: Comprehensive edge case coverage added.

These test cases provide valuable coverage for Kafka protocol edge cases involving malformed length fields, which aligns well with the PR objective of improving response validation.

internal/test_helpers/fixtures/scenarios/apiversions_length_field_too_small (1)

1-46: Comprehensive test fixture for length validation edge case.

This fixture effectively captures the expected behavior when detecting malformed int32 fields in Kafka responses. The detailed error context (lines 37-42) clearly identifies the problematic field (throttle_time_ms) and provides precise byte-level information about the length mismatch.

internal/test_helpers/fixtures/scenarios/apiversions_length_field_too_large (1)

1-33: Well-designed complementary test fixture for length validation.

This fixture effectively tests the opposite edge case from the "too small" scenario. The error message format (lines 21-29) is particularly well-crafted with visual indicators and a helpful hint about the common mistake of including the message size field in its own length calculation.

internal/test_helpers/scenarios/apiversions_length_field_too_large/main.py (2)

8-17: Request parsing implementation is clean and correct.

The Request class with its from_bytes method effectively parses the Kafka request header using proper network byte order unpacking.


40-40: Verify the intentional length field error.

The 19 + 4 calculation deliberately creates a message length field that's too large, which is the intended behavior for this test scenario. This correctly simulates the edge case being tested.

protocol/kafka_client/client.go (7)

30-52: Excellent length validation implementation with comprehensive error reporting.

The checkLength() method provides robust validation with detailed error messages including hex byte representation and contextual hints. The special case handling for the common mistake (line 42-47) is particularly helpful for debugging.


68-68: Good improvement: More descriptive constant name.

Renaming RETRIES to maxRetries improves code readability and follows Go naming conventions.


76-76: Fix: Correct retry logic boundary condition.

The change from retries > maxRetries to retries >= maxRetries ensures that exactly maxRetries attempts are made, which is the expected behavior.


136-139: Proper integration of length validation.

The length check is appropriately placed after receiving the response but before returning it, ensuring validation occurs for all responses.


169-169: Enhanced robustness: Use io.ReadFull for length prefix.

Using io.ReadFull instead of conn.Read ensures the complete 4-byte length prefix is read, preventing partial reads that could cause protocol errors.


183-184: Proper handling of partial reads.

Capturing numBytesRead and truncating the slice accordingly handles cases where io.ReadFull reads fewer bytes than requested, improving robustness against network issues.


195-198: Good error handling for unexpected EOF.

Handling io.ErrUnexpectedEOF by returning partial responses allows for better error reporting and debugging, consistent with the timeout handling pattern.

internal/test_helpers/scenarios/apiversions_length_field_too_small/main.py (2)

8-17: Consistent request parsing implementation.

The Request class implementation is identical to the "too large" scenario, maintaining consistency across test helpers.


40-40: Verify the intentional length field error for "too small" case.

The 19 - 4 calculation correctly creates a message length field that's too small, properly simulating the opposite edge case from the "too large" scenario.

@andy1li andy1li requested review from rohitpaulk and removed request for andy1li July 27, 2025 16:01
@@ -108,6 +133,10 @@ func (c *Client) SendAndReceive(request kafka_interface.RequestI, stageLogger *l

stageLogger.Debugf("Hexdump of received \"%s\" response: \n%v\n", apiName, utils.GetFormattedHexdump(response.RawBytes))

if err := response.checkLength(); err != nil {
Copy link
Member

@rohitpaulk rohitpaulk Jul 28, 2025

Choose a reason for hiding this comment

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

The usage of partial responses seems like a mistake to me, I think this should be an error returned from Receive(). There's no reason to only raise an error when calling SendAndReceive and not when calling just Receive().

I also think the whole refactor thing here was done pretty poorly (cc: @ryan-gang) - earlier this method (SendAndReceive) was just calling Send() followed by Receive(). Now it's got things like logging mixed in but the logs aren't placed in Send() and Receive() respectively, giving rise to patterns like this where we need to return partial responses to ensure logging happens. I think this should've followed the pattern we did in Redis where we separated out "instrumentable" connections that had hooks when things were being sent/received.

Might be a larger change so @andy1li you can ignore this one for now - we'll handle.

@rohitpaulk rohitpaulk assigned rohitpaulk and unassigned andy1li and ryan-gang Jul 28, 2025
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.

3 participants