Fix the frame extractor for a TCP stream

Review the AI's codeEasy10 min

Your task

Your internal RPC protocol sends length-prefixed messages over TCP. The first reader assumed one read returns one whole message. TCP does not work that way: a read can return half a message, or several at once. The fix is a framing layer that pulls every complete frame out of whatever bytes have arrived.

An assistant wrote extract_frames(stream, max_frame_len). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • stream: the bytes received so far, as a list of integers from 0 to 255.
  • max_frame_len: the largest payload a frame may declare.
  • Return the payloads of the complete frames, in order, each as a list of integers.

Rules the tests check:

  • A frame is a 4-byte length, then that many payload bytes. The length is big-endian: the first byte is the most significant.
  • Read frames from the start of stream. Stop as soon as one of these holds:
    • fewer than 4 bytes remain for the next length,
    • the declared length is greater than max_frame_len,
    • fewer bytes remain than the declared length.
  • Return the payloads of the frames read before stopping. A length of 0 is a complete frame with an empty payload.
  • Bytes after the stopping point wait for the next read, so they are never returned.

Examples

extract_frames(stream: list[int], max_frame_len: int) -> list[list[int]]
Example 1
Inputextract_frames([0, 0, 0, 3, 104, 105, 33], 1024)
Output[[104, 105, 33]]
Example 2
Inputextract_frames([0, 0, 0, 2, 1, 2, 0, 0, 0, 1, 9], 1024)
Output[[1, 2], [9]]
Example 3
Inputextract_frames([0, 0, 0, 5, 1, 2], 1024)
Output[]