Skip to content

perf: avoid copying large bytearrays when binary output is summarized #602

Open

Description

@yeongseon

Source-observed avoidable allocation

server._coerce(value, max_inline_binary_bytes) currently does:

if isinstance(value, (bytes, bytearray)):
    data = bytes(value)
    if len(data) <= max_inline_binary_bytes:
        return base64.b64encode(data).decode("ascii")
    return f"<binary {len(data)} bytes>"

For an already-large bytearray, bytes(value) allocates a second full buffer before the code discovers that the value is too big to inline. The configured limit defaults to only 256 bytes, so this copy is unnecessary on the summarized branch.

This is a source observation, not a live CUBRID memory benchmark.

Bounded optimization

  • Check len(value) before converting/copying. For above-limit binary, return the same <binary N bytes> summary without a bytes() conversion. Preserve base64 output for small binary and the max_inline_binary_bytes=0 case.
  • Add offline tests for bytes and bytearray at lengths 0, the configured boundary, and one larger; confirm correct output and no eager copy on large bytearray via a suitable spy/instrumented test object.
  • Keep type, message text, execute_query budgeting and MCP response schema unchanged.

Acceptance

  • Oversized bytearray is not copied into a new large immutable bytes buffer before summarization.
  • Inline small binary values remain byte-for-byte base64 equivalent; boundary tests pass.
  • Existing tests, formatting and CI pass, without adding dependencies or requiring live database work.

Only this conversion path is in scope; do not widen output size limits or alter the database driver.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions