Skip to content

Requests that arrive together in one read are dropped when they exceed max_buffer_size #3083

Closed

Description

@sankalpsthakur

Versions

  • Python: 3.14.7
  • OS: macOS 26.6.2
  • Pymodbus: dev at 0ccfdb4
  • Modbus Hardware (if used): none, ModbusTcpServer on 127.0.0.1

Pymodbus Specific

  • Server: tcp - async
  • Client: none, the repro writes raw requests to a plain socket

Description

Since #3026 (v3.16), ModbusProtocol.datagram_received empties recv_buffer as soon as it grows past max_buffer_size (264 bytes, 516 for ASCII), before any frame is decoded (pymodbus/transport/transport.py, around line 310).

TCP doesn't keep message boundaries and Modbus TCP allows several outstanding transactions, so two valid requests can arrive in one read. When they are larger than 264 bytes together, the server answers neither of them and nothing is logged, not even at DEBUG. The same two requests sent one after the other are both answered.

Two write multiple registers requests against a ModbusTcpServer on 127.0.0.1, dev at 0ccfdb4:

registers per request frame sent as two writes sent in one write
30 73 B 2 of 2 answered 2 of 2 (146 B)
59 131 B 2 of 2 2 of 2 (262 B)
60 133 B 2 of 2 0 of 2 (266 B)
100 213 B 2 of 2 0 of 2 (426 B)
123 259 B 2 of 2 0 of 2 (518 B)

Is the cap meant to bound a single read, or only the bytes that could not be decoded yet? If it's the second, decoding first and applying the cap to what is left fixes it in a few lines, since what remains after decoding can only be the start of one frame. I have that change with a test and can open a PR, or would you rather handle it in the framer as part of #3068?

Code and Logs

"""Frames that arrive together in one read are dropped when their total exceeds the buffer cap.

Run:  PYTHONPATH=<pymodbus checkout> python pymodbus_coalesced_frames.py
No network beyond 127.0.0.1. Each case starts a fresh pymodbus TCP server and sends FC16 (write multiple
registers) frames over a plain socket, once as two separate sends (each answered before the next goes out)
and once as ONE send holding both frames.

  frame size = 7 (MBAP) + 6 (fc, addr, count, byte count) + 2*N      two frames = 26 + 4*N bytes
  cap        = 264 (ModbusTransactionManager.max_buffer_size = framer.MAX_SIZE)
"""
import asyncio
import logging
import struct
import sys

import pymodbus
from pymodbus.server import ModbusTcpServer
from pymodbus.simulator import DataType, SimData, SimDevice

PORT = 15025
print("pymodbus from", pymodbus.__file__)


def fc16(tid: int, dev: int, addr: int, nregs: int) -> bytes:
    data = b"".join(struct.pack(">H", (addr + i) & 0xFFFF) for i in range(nregs))
    pdu = struct.pack(">BHHB", 16, addr, nregs, len(data)) + data
    return struct.pack(">HHHB", tid, 0, len(pdu) + 1, dev) + pdu


async def read_all(reader: asyncio.StreamReader, seconds: float) -> bytes:
    out = b""
    end = asyncio.get_running_loop().time() + seconds
    while (left := end - asyncio.get_running_loop().time()) > 0:
        try:
            chunk = await asyncio.wait_for(reader.read(4096), timeout=left)
        except asyncio.TimeoutError:
            break
        if not chunk:
            break
        out += chunk
    return out


async def case(nregs: int, coalesced: bool) -> str:
    server = ModbusTcpServer(
        SimDevice(1, SimData(0, datatype=DataType.REGISTERS, values=[0] * 400)),
        address=("127.0.0.1", PORT),
    )
    task = asyncio.create_task(server.serve_forever())
    await asyncio.sleep(0.3)
    try:
        reader, writer = await asyncio.open_connection("127.0.0.1", PORT)
        f1, f2 = fc16(1, 1, 0, nregs), fc16(2, 1, 100, nregs)
        if coalesced:
            writer.write(f1 + f2)
            await writer.drain()
            got = await read_all(reader, 1.5)
        else:
            writer.write(f1)
            await writer.drain()
            got = await read_all(reader, 0.6)
            writer.write(f2)
            await writer.drain()
            got += await read_all(reader, 0.6)
        writer.close()
        replies = len(got) // 12
        return (
            f"N={nregs:3d} frame={len(f1):3d}B  {'ONE send of ' + str(len(f1) + len(f2)) + 'B' if coalesced else 'two sends of ' + str(len(f1)) + 'B':>16}"
            f"  -> {replies} of 2 responses ({len(got)} bytes)"
        )
    finally:
        await server.shutdown()
        task.cancel()
        await asyncio.sleep(0.1)


async def main() -> None:
    logging.basicConfig(level=logging.WARNING)  # the drop itself logs nothing, even at DEBUG
    for nregs in (30, 59, 60, 100, 123):
        print(await case(nregs, coalesced=False))
        print(await case(nregs, coalesced=True))


asyncio.run(main())

Output on dev 0ccfdb4:

N= 30 frame= 73B  two sends of 73B  -> 2 of 2 responses (24 bytes)
N= 30 frame= 73B  ONE send of 146B  -> 2 of 2 responses (24 bytes)
N= 59 frame=131B  two sends of 131B  -> 2 of 2 responses (24 bytes)
N= 59 frame=131B  ONE send of 262B  -> 2 of 2 responses (24 bytes)
N= 60 frame=133B  two sends of 133B  -> 2 of 2 responses (24 bytes)
N= 60 frame=133B  ONE send of 266B  -> 0 of 2 responses (0 bytes)
N=100 frame=213B  two sends of 213B  -> 2 of 2 responses (24 bytes)
N=100 frame=213B  ONE send of 426B  -> 0 of 2 responses (0 bytes)
N=123 frame=259B  two sends of 259B  -> 2 of 2 responses (24 bytes)
N=123 frame=259B  ONE send of 518B  -> 0 of 2 responses (0 bytes)

Activity

  1. janiversen commented on Nov 8, 2026

    @janiversen
    Collaborator

    The server only handles request/response like most real life devices, so the pymodbus server can never received more than a single packet.

    The tcp protocol allows múltiple requests, but most devices do not...the exception is serial forwarder that allows a request to each connected line.

    The pymodbus client also are strictly request/response based.

    What is your practical application ?

  2. janiversen commented on Nov 8, 2026

    @janiversen
    Collaborator

    Feel free to submit your PR, #3068 have nothing to do with framing.

  3. sankalpsthakur commented on Nov 8, 2026

    @sankalpsthakur
    ContributorAuthor

    No device on my side. I found it while testing the transport with a plain socket. Modbus TCP allows a client several outstanding transactions, so a client that pipelines its requests can hit it, but the pymodbus client never does. The fix is in #3084.

  4. janiversen commented on Nov 8, 2026

    @janiversen
    Collaborator

    Be advised your fix does not work if a clientes sends a lot of requests, but it does help in simple situations.

    Once the PR is updated as requested it will be merged.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions