Skip to content

Chapter 21 - tcp_mojifinder.py crashes on empty search result #61

@timheiko

Description

@timheiko

Issue

If index.search(query) in tcp_mojifinder.py returns empty result, it crashes TCP because asyncio.StreamWriter.writelines(data) raises AssertionError: Data should not be empty error if data is an empty iterable.

How to reproduce

Start the TCP server

% ./tcp_mojifinder.py 
Building index.
Serving on ('127.0.0.1', 2323). Hit CTRL-C to stop.
...

Connect to the TCP server and send a search query which returns no results, e.g. missing

% nc localhost 2323
?> missing
% 

The TCP server terminal will spit out an error stack trace like

% ./tcp_mojifinder.py 
Building index.
Serving on ('127.0.0.1', 2323). Hit CTRL-C to stop.
 From ('127.0.0.1', 63253): 'missing'
Unhandled exception in client_connected_cb
transport: <_SelectorSocketTransport fd=7 read=polling write=<idle, bufsize=0>>
Traceback (most recent call last):
  File "/Users/tim/projects/python/example-code-2e/21-async/mojifinder/./tcp_mojifinder.py", line 33, in finder
    results = await search(query, index, writer)  # <13>
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/tim/projects/python/example-code-2e/21-async/mojifinder/./tcp_mojifinder.py", line 48, in search
    writer.writelines(lines)  # <4>
    ~~~~~~~~~~~~~~~~~^^^^^^^
  File "/opt/homebrew/Cellar/[email protected]/3.13.5/Frameworks/Python.framework/Versions/3.13/lib/python3.13/asyncio/streams.py", line 343, in writelines
    self._transport.writelines(data)
    ~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^
  File "/opt/homebrew/Cellar/[email protected]/3.13.5/Frameworks/Python.framework/Versions/3.13/lib/python3.13/asyncio/selector_events.py", line 1174, in writelines
    self._write_ready()
    ~~~~~~~~~~~~~~~~~^^
  File "/opt/homebrew/Cellar/[email protected]/3.13.5/Frameworks/Python.framework/Versions/3.13/lib/python3.13/asyncio/selector_events.py", line 1090, in _write_sendmsg
    assert self._buffer, 'Data should not be empty'
           ^^^^^^^^^^^^
AssertionError: Data should not be empty

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions