Skip to content

fix(pidbox): reject a non-string pattern or matcher on its own - #2898

Open
qianeric-backup wants to merge 2 commits into
celery:mainfrom
qianeric-backup:pidbox-pattern-matcher-type-guard
Open

qianeric-backup wants to merge 2 commits into
celery:mainfrom
qianeric-backup:pidbox-pattern-matcher-type-guard

Conversation

@qianeric-backup

Copy link
Copy Markdown

Mailbox._broadcast() guards its two optional arguments with and, so the ValueError it raises only fires when both are non-strings:

if (pattern is not None and not isinstance(pattern, str) and
        matcher is not None and not isinstance(matcher, str)):
    raise ValueError('pattern and matcher must be strings not {}, {}' ...)

Control.broadcast() only checks truthiness (if pattern and matcher:), so one bad argument gets straight through, and the failure surfaces later in the worker instead of at the call site:

call before after
broadcast('ping', pattern=42, matcher=42) ValueError ValueError
broadcast('ping', pattern=42, matcher='glob') no error at the caller; worker raises TypeError: expected str, bytes or os.PathLike object, not int ValueError
broadcast('ping', pattern='node*', matcher=42) no error at the caller; worker raises MatcherNotInstalled: No matcher installed for 42 ValueError

The destination check three lines above is the shape the rest of this function uses - one bad argument raises:

if destination is not None and not isinstance(destination, (list, tuple)):
    raise ValueError('destination must be a list/tuple not {}'.format(...))

The existing test only covered the one combination that and happens to catch (pattern=1, matcher=2), which is why this has been there since the guard was introduced.

Change

Group the two checks with or instead of and:

-        if (pattern is not None and not isinstance(pattern, str) and
-                matcher is not None and not isinstance(matcher, str)):
+        if ((pattern is not None and not isinstance(pattern, str)) or
+                (matcher is not None and not isinstance(matcher, str))):

Test

test_broadcast_matcher_pattern_string_type is parametrized over the three combinations ((1, 2), (1, 'glob'), ('test*', 2)); the last two fail with DID NOT RAISE ValueError without the change. Additional cases cover the valid combinations that must keep working (None/None, 'node*'/None, None/'glob', 'node*'/'glob').

_broadcast() joins the two type checks with 'and', so the ValueError fires only
when pattern and matcher are both non-strings. Control.broadcast() checks
truthiness only, so one bad argument reaches the worker and fails there - a
TypeError for a bad pattern and MatcherNotInstalled for a bad matcher.

The destination check above it already raises on a single bad argument; use the
same shape.
@qianeric-backup
qianeric-backup marked this pull request as ready for review November 30, 2026 09:40

@auvipy auvipy left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

is there any related issues or discussions you are trying to fix?

@auvipy

auvipy commented Dec 3, 2026

Copy link
Copy Markdown
Member

@ChristianMurphy

@auvipy auvipy added this to the 5.7.x milestone Dec 3, 2026
@codecov

codecov Bot commented Dec 3, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 86.46%. Comparing base (e42ae1b) to head (4560d21).

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #2898   +/-   ##
=======================================
  Coverage   86.46%   86.46%           
=======================================
  Files          80       80           
  Lines       11860    11860           
  Branches     1444     1444           
=======================================
  Hits        10255    10255           
  Misses       1390     1390           
  Partials      215      215           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

@ChristianMurphy ChristianMurphy left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The fix is right. Before merge I'd keep one input that works today, and add a test that goes through a broker.

I ran 4560d2174 against main (e42ae1bd8) with two Celery workers on a Redis broker, calling app.control.broadcast('ping', reply=True, ...):

Call main This PR
pattern=1, matcher=2 ValueError ValueError
pattern=1, matcher='glob' sent; both workers log a traceback, nobody replies ValueError
pattern='a*', matcher=2 the same ValueError
pattern=['a*'], matcher='glob' the same ValueError
pattern='a*', matcher='glob' the matching worker replies the same
pattern=b'a*', matcher='glob' the matching worker replies ValueError

The workers keep answering after each of these, on main and here.

1. A bytes pattern works on main and is rejected here. It is the last row. For a 5.7.x release I'd reject only what already fails on the worker, so pattern would accept str and bytes. With the change below the bytes pattern reaches the matching worker again and the other rows stay as they are.

2. A test through a broker. The unit tests are good: they catch the six bugs I planted in the condition. They stop at _broadcast(), though, so nothing shows what the check is for. An integration test for Redis is below. Its two bad-argument cases fail on main, where the node raises TypeError or MatcherNotInstalled, and pass here (3 of 3 runs each). kombu has no smoke suite, so I have nothing to offer there.

Change for point 1, with a test case
--- a/kombu/pidbox.py
+++ b/kombu/pidbox.py
@@ -338,3 +338,4 @@ class Mailbox:
                     type(destination)))
-        if ((pattern is not None and not isinstance(pattern, str)) or
+        if ((pattern is not None and
+             not isinstance(pattern, (str, bytes))) or
                 (matcher is not None and not isinstance(matcher, str))):

And (b'test*', 'glob') added to the parameters of test_broadcast_matcher_pattern_valid_types.

Integration test

In t/integration/test_redis.py:

def _pidbox_ping_ran(conn, mailbox, **broadcast):
    """Broadcast a ping to one node, ``a1``, and return whether it ran it."""
    ran = []
    node = mailbox.Node('a1', handlers={'ping': lambda state: ran.append(1)})
    consumer = node.listen(channel=conn.default_channel)
    try:
        # Redis subscribes to a fanout exchange on the first poll.
        try:
            conn.drain_events(timeout=0.1)
        except socket.timeout:
            pass
        mailbox._broadcast('ping', **broadcast)
    finally:
        try:
            while True:
                conn.drain_events(timeout=0.5)
        except socket.timeout:
            pass
        consumer.cancel()
    return bool(ran)


@pytest.mark.env('redis')
def test_pidbox_broadcast_pattern_selects_the_node(connection):
    with connection as conn:
        mailbox = pidbox.Mailbox(f'pattern-{uuid4().hex}', type='fanout')(conn)
        assert _pidbox_ping_ran(conn, mailbox, pattern='a*', matcher='glob')
        assert not _pidbox_ping_ran(conn, mailbox, pattern='b*', matcher='glob')


@pytest.mark.env('redis')
@pytest.mark.parametrize('pattern,matcher', [(1, 'glob'), ('a*', 2)])
def test_pidbox_broadcast_sends_nothing_for_a_bad_pattern_or_matcher(
        connection, pattern, matcher):
    # Sent, either one makes every node that receives it raise.
    with connection as conn:
        mailbox = pidbox.Mailbox(f'pattern-{uuid4().hex}', type='fanout')(conn)
        with pytest.raises(ValueError):
            _pidbox_ping_ran(conn, mailbox, pattern=pattern, matcher=matcher)
What I did not run
  • Brokers other than Redis 7.0.
  • Python versions other than 3.13.

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