Skip to content

fix(sqs): keep message attributes when a publish is retried - #2863

Open
alirezaazadi wants to merge 2 commits into
celery:mainfrom
alirezaazadi:fix/sqs-keep-message-attributes
Open

alirezaazadi wants to merge 2 commits into
celery:mainfrom
alirezaazadi:fix/sqs-keep-message-attributes

Conversation

@alirezaazadi

@alirezaazadi alirezaazadi commented Nov 19, 2026 •

Copy link
Copy Markdown

Problem

Channel._put used message['properties'].pop('message_attributes') to keep the attributes out of the message body. That mutates the caller's properties dict, which is shared:

  • Producer.publish passes the same properties dict to every attempt that Connection.ensure makes. When SendMessage fails with a connection error (for example botocore's EndpointConnectionError) and the publish is retried, the retry is sent without MessageAttributes.
  • When one message is delivered to several bound queues (DirectExchange.deliver calls _put once per queue), only the first queue gets the attributes.

No error is raised, so the message is silently delivered without its attributes.

Reproduction on main (4cadf8b), with send_message failing once and kombu retrying the publish:

SendMessage attempt 1: MessageAttributes={'tenant': {'DataType': 'String', 'StringValue': '42'}}
SendMessage attempt 2: MessageAttributes=None
Reproduction script (no AWS account needed)

The SQS client is replaced by a fake whose first SendMessage raises EndpointConnectionError, so kombu's own Connection.ensure retries the publish.

from unittest.mock import patch

from botocore.exceptions import EndpointConnectionError
from kombu import Connection, Producer
from kombu.transport.SQS import Channel

url = "https://sqs.us-east-1.amazonaws.com/123456789012/tasks"
conn = Connection("sqs://", transport_options={
    "region": "us-east-1",
    "predefined_queues": {
        "tasks": {"url": url, "access_key_id": "x", "secret_access_key": "y"},
    },
})
sent = []


class FakeSQS:
    def send_message(self, **kwargs):
        sent.append(kwargs)
        if len(sent) == 1:
            raise EndpointConnectionError(endpoint_url=url)
        return {"MessageId": "1"}


with patch.object(Channel, "sqs", lambda self, queue=None: FakeSQS()):
    Producer(conn).publish(
        {"hello": "world"},
        routing_key="tasks",
        retry=True,
        retry_policy={"max_retries": 1, "interval_start": 0,
                      "interval_step": 0, "interval_max": 0},
        message_attributes={"tenant": {"DataType": "String", "StringValue": "42"}},
    )

for attempt, kwargs in enumerate(sent, 1):
    print(f"SendMessage attempt {attempt}: "
          f"MessageAttributes={kwargs.get('MessageAttributes')}")

With this PR applied, both attempts print the attributes.

Fix

Read message_attributes without mutating the message, and serialize the body from a shallow copy whose properties omit them.

The module docstring said to pass message_attributes to basic_publish, but _put ignores basic_publish keyword arguments: the value is read from the properties passed to Producer.publish (or to Celery's apply_async). The docstring now says so and shows an example.

Tests

  • test_put_keeps_message_attributes_when_the_message_is_sent_again: calling _put twice with the same message sends the attributes both times, leaves the message unchanged, and keeps the attributes out of the body.
  • test_put_keeps_message_attributes_on_a_retried_publish: Producer.publish(retry=True) with send_message raising EndpointConnectionError once; both attempts carry the attributes.

Both tests fail on main and pass with the fix. t/unit/transport/SQS and t/unit/asynchronous pass (547 tests), and flake8, isort and codespell are clean on the changed files.

I did not find an existing issue for this.

Channel._put popped message_attributes from the message's properties
dict. Producer.publish passes that same dict to every attempt that
Connection.ensure makes, so a SendMessage retried after a connection
error went out without its MessageAttributes, and so did a message
delivered to more than one bound queue. Read the attributes without
mutating the message and build the body from a copy that omits them.

Also fix the module docstring: message_attributes is read from the
properties passed to Producer.publish, not from basic_publish kwargs.
@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.47%. Comparing base (ffccd1c) to head (ae919dd).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2863      +/-   ##
==========================================
+ Coverage   86.46%   86.47%   +0.01%     
==========================================
  Files          80       80              
  Lines       11860    11862       +2     
  Branches     1444     1444              
==========================================
+ Hits        10255    10258       +3     
+ Misses       1390     1389       -1     
  Partials      215      215              

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

@auvipy

auvipy commented Dec 4, 2026

Copy link
Copy Markdown
Member

@MehrazRumman

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.

2 participants