Skip to content

Add a backend for Valkey - #9300

Draft
amirreza-sf80 wants to merge 15 commits into
celery:mainfrom
amirreza-sf80:valkey
Draft

amirreza-sf80 wants to merge 15 commits into
celery:mainfrom
amirreza-sf80:valkey

Conversation

@amirreza-sf80

@amirreza-sf80 amirreza-sf80 commented Sep 19, 2024 •

Copy link
Copy Markdown

Description

add support for valkey as a backend.
it includes tests and documentation.
the coverage is 96%

Fixes #9092

@Nusnus
Nusnus requested review from Nusnus, auvipy and thedrow September 19, 2024 07:34
@codecov

codecov Bot commented Sep 19, 2024 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.72727% with 28 lines in your changes missing coverage. Please review.
✅ Project coverage is 78.52%. Comparing base (7cf9d89) to head (f5de6df).
⚠️ Report is 723 commits behind head on main.

Files with missing lines Patch % Lines
celery/backends/base_keyval.py 92.77% 15 Missing and 11 partials ⚠️
celery/backends/valkey.py 89.47% 0 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #9300      +/-   ##
==========================================
+ Coverage   78.50%   78.52%   +0.02%     
==========================================
  Files         153      155       +2     
  Lines       19127    19159      +32     
  Branches     2533     2535       +2     
==========================================
+ Hits        15015    15044      +29     
  Misses       3820     3820              
- Partials      292      295       +3     
Flag Coverage Δ
unittests 78.50% <92.72%> (+0.02%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

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

@Nusnus Nusnus 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.

If I understand correctly, Valkey is a Redis replacement that for the time being works the same, literally, using the same API in the new package.

Shouldn't we add integration tests as well then?

I'm also considering developing support for pytest-celery, but the integration tests will need to come first IMHO.

@Nusnus Nusnus 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.

I'd also recommend renaming the PR to something more meaningful for the sake of clear changelog.

@amirreza-sf80 amirreza-sf80 changed the title Valkey Add a backend for Valkey Sep 23, 2024
@amirreza-sf80

Copy link
Copy Markdown
Author

hi
i changed the name, see if it's ok

about the tests, if someone else want's to do it it's fine by me, but if not, i need a bit of time to see how integration tests are set up, either way i'm good

@Nusnus

Nusnus commented Sep 23, 2024

Copy link
Copy Markdown
Member

@amirreza8002

hi i changed the name, see if it's ok

about the tests, if someone else want's to do it it's fine by me, but if not, i need a bit of time to see how integration tests are set up, either way i'm good

I’ve added integration tests to the PR. When I run it locally, I get an error from one of the tests: valkey.exceptions.ResponseError: NOSUB 'unsubscribe' command executed not in subscribed mode

Steps to reproduce

  1. RabbitMQ broker: docker run -d -p 5672:5672 -p 15672:15672 --name rabbitmq rabbitmq:management
  2. Valkey backend: docker run -d -p 6379:6379 --name valkey valkey/valkey:latest
  3. Run Tests: docker start rabbitmq valkey && tox -e 3.12-integration-rabbitmq_valkey && docker stop rabbitmq valkey
docker start rabbitmq valkey && tox -e 3.12-integration-rabbitmq_valkey && docker stop rabbitmq valkey
rabbitmq
valkey
ROOT: will run in automatically provisioned tox, host /opt/homebrew/Cellar/tox/4.20.0/libexec/bin/python is missing [requires (has)]: tox-gh-actions
ROOT: provision> .tox/.tox/bin/python -m tox -e 3.12-integration-rabbitmq_valkey
ROOT: tox-gh-actions won't override envlist because tox is not running in GitHub Actions
3.12-integration-rabbitmq_valkey: install_deps> python -I -m pip install -r /Users/nusnus/dev/GitHub/celery/requirements/test.txt -r /Users/nusnus/dev/GitHub/celery/requirements/pkgutils.txt -r /Users/nusnus/dev/GitHub/celery/requirements/test-ci-default.txt -r /Users/nusnus/dev/GitHub/celery/requirements/docs.txt -r /Users/nusnus/dev/GitHub/celery/requirements/test-integration.txt
.pkg: _optional_hooks> python /Users/nusnus/dev/GitHub/celery/.tox/.tox/lib/python3.12/site-packages/pyproject_api/_backend.py True setuptools.build_meta __legacy__
.pkg: get_requires_for_build_editable> python /Users/nusnus/dev/GitHub/celery/.tox/.tox/lib/python3.12/site-packages/pyproject_api/_backend.py True setuptools.build_meta __legacy__
.pkg: build_editable> python /Users/nusnus/dev/GitHub/celery/.tox/.tox/lib/python3.12/site-packages/pyproject_api/_backend.py True setuptools.build_meta __legacy__
3.12-integration-rabbitmq_valkey: install_package> python -I -m pip install --force-reinstall --no-deps /Users/nusnus/dev/GitHub/celery/.tox/.tmp/package/9/celery-5.5.0b3-0.editable-py3-none-any.whl
3.12-integration-rabbitmq_valkey: commands[0]> pytest -xsvv t/integration
======================================================================================= test session starts =======================================================================================
platform darwin -- Python 3.12.6, pytest-8.3.3, pluggy-1.5.0 -- /Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/bin/python
cachedir: .tox/3.12-integration-rabbitmq_valkey/.pytest_cache
rootdir: /Users/nusnus/dev/GitHub/celery
configfile: pyproject.toml
plugins: docker-tools-3.1.3, cov-5.0.0, github-actions-annotate-failures-0.2.0, click-1.1.0, celery-1.1.3, anyio-4.6.0, rerunfailures-14.0, order-1.3.0, subtests-0.13.1, timeout-2.3.1
collected 227 items

t/integration/test_backend.py::test_AzureBlockBlobBackend::test_crud SKIPPED (Environment variable AZUREBLOCKBLOB_URL required)
t/integration/test_backend.py::test_AzureBlockBlobBackend::test_get_missing SKIPPED (Environment variable AZUREBLOCKBLOB_URL required)
t/integration/test_canvas.py::test_link_error::test_link_error_eager PASSED
t/integration/test_canvas.py::test_link_error::test_link_error PASSED
t/integration/test_canvas.py::test_link_error::test_link_error_callback_error_callback_retries_eager PASSED
t/integration/test_canvas.py::test_link_error::test_link_error_callback_retries PASSED
t/integration/test_canvas.py::test_link_error::test_link_error_using_signature_eager PASSED
t/integration/test_canvas.py::test_link_error::test_link_error_using_signature PASSED
t/integration/test_canvas.py::test_chain::test_simple_chain PASSED
t/integration/test_canvas.py::test_chain::test_single_chain PASSED
t/integration/test_canvas.py::test_chain::test_complex_chain PASSED
t/integration/test_canvas.py::test_chain::test_group_results_in_chain XFAIL (Task is timeout)
t/integration/test_canvas.py::test_chain::test_chain_of_chain_with_a_single_task PASSED
t/integration/test_canvas.py::test_chain::test_chain_on_error SKIPPED (Requires redis result backend.)
t/integration/test_canvas.py::test_chain::test_chain_inside_group_receives_arguments PASSED
t/integration/test_canvas.py::test_chain::test_eager_chain_inside_task PASSED
t/integration/test_canvas.py::test_chain::test_group_chord_group_chain SKIPPED (Requires redis result backend.)
t/integration/test_canvas.py::test_chain::test_group_result_not_has_cache PASSED
t/integration/test_canvas.py::test_chain::test_second_order_replace SKIPPED (Requires redis result backend.)
t/integration/test_canvas.py::test_chain::test_parent_ids PASSED
t/integration/test_canvas.py::test_chain::test_chord_soft_timeout_recuperation SKIPPED (Requires redis result backend.)
t/integration/test_canvas.py::test_chain::test_chain_error_handler_with_eta PASSED
t/integration/test_canvas.py::test_chain::test_groupresult_serialization PASSED
t/integration/test_canvas.py::test_chain::test_chain_of_task_a_group_and_a_chord PASSED
t/integration/test_canvas.py::test_chain::test_chain_of_chords_as_groups_chained_to_a_task_with_two_tasks PASSED
t/integration/test_canvas.py::test_chain::test_chain_of_chords_with_two_tasks PASSED
t/integration/test_canvas.py::test_chain::test_chain_of_a_chord_and_a_group_with_two_tasks PASSED
t/integration/test_canvas.py::test_chain::test_chain_of_a_chord_and_a_task_and_a_group PASSED
t/integration/test_canvas.py::test_chain::test_chain_of_a_chord_and_two_tasks_and_a_group PASSED
t/integration/test_canvas.py::test_chain::test_chain_of_a_chord_and_three_tasks_and_a_group PASSED
t/integration/test_canvas.py::test_chain::test_nested_chain_group_lone XFAIL (Task is timeout)
t/integration/test_canvas.py::test_chain::test_nested_chain_group_mid PASSED
t/integration/test_canvas.py::test_chain::test_nested_chain_group_last PASSED
t/integration/test_canvas.py::test_chain::test_chain_replaced_with_a_chain_and_a_callback SKIPPED (Requires redis result backend.)
t/integration/test_canvas.py::test_chain::test_chain_replaced_with_a_chain_and_an_error_callback SKIPPED (Requires redis result backend.)
t/integration/test_canvas.py::test_chain::test_chain_with_cb_replaced_with_chain_with_cb SKIPPED (Requires redis result backend.)
t/integration/test_canvas.py::test_chain::test_chain_flattening_keep_links_of_inner_chain SKIPPED (Requires redis result backend.)
t/integration/test_canvas.py::test_chain::test_chain_with_eb_replaced_with_chain_with_eb SKIPPED (Requires redis result backend.)
t/integration/test_canvas.py::test_chain::test_replace_chain_with_empty_chain FAILED

============================================================================================ FAILURES =============================================================================================
_________________________________________________________________________ test_chain.test_replace_chain_with_empty_chain __________________________________________________________________________

self = <t.integration.test_canvas.test_chain object at 0x1292cc3e0>, manager = <celery.contrib.testing.manager.Manager object at 0x12c17cfe0>

    def test_replace_chain_with_empty_chain(self, manager):
        r = chain(identity.s(1), replace_with_empty_chain.s()).delay()

        with pytest.raises(ImproperlyConfigured,
                           match="Cannot replace with an empty chain"):
>           r.get(timeout=TIMEOUT)

t/integration/test_canvas.py:659:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
celery/result.py:251: in get
    return self.backend.wait_for_pending(
celery/backends/asynchronous.py:221: in wait_for_pending
    for _ in self._wait_for_pending(result, **kwargs):
celery/backends/asynchronous.py:287: in _wait_for_pending
    for _ in self.drain_events_until(
celery/backends/asynchronous.py:54: in drain_events_until
    yield self.wait_for(p, wait, timeout=interval)
celery/backends/asynchronous.py:63: in wait_for
    wait(timeout=timeout)
celery/backends/redis.py:161: in drain_events
    message = self._pubsub.get_message(timeout=timeout)
.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/client.py:1072: in get_message
    response = self.parse_response(block=(timeout is None), timeout=timeout)
.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/client.py:883: in parse_response
    response = self._execute(conn, try_read)
.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/client.py:859: in _execute
    return conn.retry.call_with_retry(
.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/retry.py:62: in call_with_retry
    return do()
.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/client.py:860: in <lambda>
    lambda: command(*args, **kwargs),
.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/client.py:881: in try_read
    return conn.read_response(disconnect_on_error=False, push_request=True)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <valkey.connection.Connection(host=localhost,port=6379,db=0)>, disable_decoding = False

    def read_response(
        self,
        disable_decoding=False,
        *,
        disconnect_on_error=True,
        push_request=False,
    ):
        """Read the response from a previously sent command"""

        host_error = self._host_error()

        try:
            if self.protocol in ["3", 3] and not LIBVALKEY_AVAILABLE:
                response = self._parser.read_response(
                    disable_decoding=disable_decoding, push_request=push_request
                )
            else:
                response = self._parser.read_response(disable_decoding=disable_decoding)
        except socket.timeout:
            if disconnect_on_error:
                self.disconnect()
            raise TimeoutError(f"Timeout reading from {host_error}")
        except OSError as e:
            if disconnect_on_error:
                self.disconnect()
            raise ConnectionError(
                f"Error while reading from {host_error}" f" : {e.args}"
            )
        except BaseException:
            # Also by default close in case of BaseException.  A lot of code
            # relies on this behaviour when doing Command/Response pairs.
            # See #1128.
            if disconnect_on_error:
                self.disconnect()
            raise

        if self.health_check_interval:
            self.next_health_check = time() + self.health_check_interval

        if isinstance(response, ResponseError):
            try:
>               raise response
E               valkey.exceptions.ResponseError: NOSUB 'unsubscribe' command executed not in subscribed mode

.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/connection.py:570: ResponseError
---------------------------------------------------------------------------------------- Captured log call ----------------------------------------------------------------------------------------
INFO     celery.worker.strategy:strategy.py:161 Task t.integration.tasks.identity[fba9edad-7d68-4b3c-bf94-74e6a1d9b61f] received
INFO     celery.app.trace:trace.py:128 Task t.integration.tasks.identity[fba9edad-7d68-4b3c-bf94-74e6a1d9b61f] succeeded in 0.0011258750018896535s: 1
======================================================================================== warnings summary =========================================================================================
t/integration/test_canvas.py::test_chain::test_chain_error_handler_with_eta
  /Users/nusnus/dev/GitHub/celery/celery/canvas.py:2301: CPendingDeprecationWarning: task_allow_error_cb_on_chord_header=False is pending deprecation in a future release of Celery.
  Please test the new behavior by setting task_allow_error_cb_on_chord_header to True and report any concerns you might have in our issue tracker before we make a final decision regarding how errbacks should behave when used with chords.
    warnings.warn(

-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
===================================================================================== short test summary info =====================================================================================
FAILED t/integration/test_canvas.py::test_chain::test_replace_chain_with_empty_chain - valkey.exceptions.ResponseError: NOSUB 'unsubscribe' command executed not in subscribed mode
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! stopping after 1 failures !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
============================================================ 1 failed, 25 passed, 11 skipped, 2 xfailed, 1 warning in 72.59s (0:01:12) ============================================================
Exception ignored in: <function AsyncResult.__del__ at 0x1281a7f60>
Traceback (most recent call last):
  File "/Users/nusnus/dev/GitHub/celery/celery/result.py", line 417, in __del__
  File "/Users/nusnus/dev/GitHub/celery/celery/backends/asynchronous.py", line 208, in remove_pending_result
  File "/Users/nusnus/dev/GitHub/celery/celery/backends/asynchronous.py", line 216, in on_result_fulfilled
  File "/Users/nusnus/dev/GitHub/celery/celery/backends/redis.py", line 184, in cancel_for
  File "/Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/client.py", line 1000, in unsubscribe
  File "/Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/client.py", line 804, in execute_command
  File "/Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/connection.py", line 1107, in get_connection
  File "/Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/connection.py", line 314, in connect
  File "/Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/connection.py", line 345, in on_connect
  File "/Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/_parsers/libvalkey.py", line 51, in on_connect
ImportError: sys.meta_path is None, Python is likely shutting down
Exception ignored in: <function AsyncResult.__del__ at 0x1281a7f60>
Traceback (most recent call last):
  File "/Users/nusnus/dev/GitHub/celery/celery/result.py", line 417, in __del__
  File "/Users/nusnus/dev/GitHub/celery/celery/backends/asynchronous.py", line 208, in remove_pending_result
  File "/Users/nusnus/dev/GitHub/celery/celery/backends/asynchronous.py", line 216, in on_result_fulfilled
  File "/Users/nusnus/dev/GitHub/celery/celery/backends/redis.py", line 184, in cancel_for
  File "/Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/client.py", line 1000, in unsubscribe
  File "/Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/client.py", line 804, in execute_command
  File "/Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/connection.py", line 1120, in get_connection
  File "/Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/connection.py", line 314, in connect
  File "/Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/connection.py", line 345, in on_connect
  File "/Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/_parsers/libvalkey.py", line 51, in on_connect
ImportError: sys.meta_path is None, Python is likely shutting down
3.12-integration-rabbitmq_valkey: exit 1 (73.34 seconds) /Users/nusnus/dev/GitHub/celery> pytest -xsvv t/integration pid=62015
  3.12-integration-rabbitmq_valkey: FAIL code 1 (79.53=setup[6.19]+cmd[73.34] seconds)
  evaluation failed :( (79.89 seconds)

@Nusnus

Nusnus commented Sep 23, 2024

Copy link
Copy Markdown
Member

@amirreza8002

hi i changed the name, see if it's ok
about the tests, if someone else want's to do it it's fine by me, but if not, i need a bit of time to see how integration tests are set up, either way i'm good

I’ve added integration tests to the PR. When I run it locally, I get an error from one of the tests: valkey.exceptions.ResponseError: NOSUB 'unsubscribe' command executed not in subscribed mode

Steps to reproduce

  1. RabbitMQ broker: docker run -d -p 5672:5672 -p 15672:15672 --name rabbitmq rabbitmq:management
  2. Valkey backend: docker run -d -p 6379:6379 --name valkey valkey/valkey:latest

I’ve changed the port to avoid conflicts with Redis.
docker run -d -p 6379:6379 --name valkey valkey/valkey:latest
Use docker run -d -p 6380:6379 --name valkey valkey/valkey:latest

  1. Run Tests: docker start rabbitmq valkey && tox -e 3.12-integration-rabbitmq_valkey && docker stop rabbitmq valkey

Still gives the same error:

docker start rabbitmq valkey && tox -e 3.12-integration-rabbitmq_valkey && docker stop rabbitmq valkey
rabbitmq
valkey
ROOT: will run in automatically provisioned tox, host /opt/homebrew/Cellar/tox/4.20.0/libexec/bin/python is missing [requires (has)]: tox-gh-actions
ROOT: provision> .tox/.tox/bin/python -m tox -e 3.12-integration-rabbitmq_valkey
ROOT: tox-gh-actions won't override envlist because tox is not running in GitHub Actions
.pkg: _optional_hooks> python /Users/nusnus/dev/GitHub/celery/.tox/.tox/lib/python3.12/site-packages/pyproject_api/_backend.py True setuptools.build_meta __legacy__
.pkg: get_requires_for_build_editable> python /Users/nusnus/dev/GitHub/celery/.tox/.tox/lib/python3.12/site-packages/pyproject_api/_backend.py True setuptools.build_meta __legacy__
.pkg: build_editable> python /Users/nusnus/dev/GitHub/celery/.tox/.tox/lib/python3.12/site-packages/pyproject_api/_backend.py True setuptools.build_meta __legacy__
3.12-integration-rabbitmq_valkey: install_package> python -I -m pip install --force-reinstall --no-deps /Users/nusnus/dev/GitHub/celery/.tox/.tmp/package/10/celery-5.5.0b3-0.editable-py3-none-any.whl
3.12-integration-rabbitmq_valkey: commands[0]> pytest -xsvv t/integration
======================================================================================= test session starts =======================================================================================
platform darwin -- Python 3.12.6, pytest-8.3.3, pluggy-1.5.0 -- /Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/bin/python
cachedir: .tox/3.12-integration-rabbitmq_valkey/.pytest_cache
rootdir: /Users/nusnus/dev/GitHub/celery
configfile: pyproject.toml
plugins: docker-tools-3.1.3, cov-5.0.0, github-actions-annotate-failures-0.2.0, click-1.1.0, celery-1.1.3, anyio-4.6.0, rerunfailures-14.0, order-1.3.0, subtests-0.13.1, timeout-2.3.1
collected 227 items

t/integration/test_backend.py::test_AzureBlockBlobBackend::test_crud SKIPPED (Environment variable AZUREBLOCKBLOB_URL required)
t/integration/test_backend.py::test_AzureBlockBlobBackend::test_get_missing SKIPPED (Environment variable AZUREBLOCKBLOB_URL required)
t/integration/test_canvas.py::test_link_error::test_link_error_eager PASSED
t/integration/test_canvas.py::test_link_error::test_link_error PASSED
t/integration/test_canvas.py::test_link_error::test_link_error_callback_error_callback_retries_eager PASSED
t/integration/test_canvas.py::test_link_error::test_link_error_callback_retries PASSED
t/integration/test_canvas.py::test_link_error::test_link_error_using_signature_eager PASSED
t/integration/test_canvas.py::test_link_error::test_link_error_using_signature PASSED
t/integration/test_canvas.py::test_chain::test_simple_chain PASSED
t/integration/test_canvas.py::test_chain::test_single_chain PASSED
t/integration/test_canvas.py::test_chain::test_complex_chain PASSED
t/integration/test_canvas.py::test_chain::test_group_results_in_chain XFAIL (Task is timeout)
t/integration/test_canvas.py::test_chain::test_chain_of_chain_with_a_single_task PASSED
t/integration/test_canvas.py::test_chain::test_chain_on_error SKIPPED (Requires redis result backend.)
t/integration/test_canvas.py::test_chain::test_chain_inside_group_receives_arguments PASSED
t/integration/test_canvas.py::test_chain::test_eager_chain_inside_task PASSED
t/integration/test_canvas.py::test_chain::test_group_chord_group_chain SKIPPED (Requires redis result backend.)
t/integration/test_canvas.py::test_chain::test_group_result_not_has_cache PASSED
t/integration/test_canvas.py::test_chain::test_second_order_replace SKIPPED (Requires redis result backend.)
t/integration/test_canvas.py::test_chain::test_parent_ids PASSED
t/integration/test_canvas.py::test_chain::test_chord_soft_timeout_recuperation SKIPPED (Requires redis result backend.)
t/integration/test_canvas.py::test_chain::test_chain_error_handler_with_eta PASSED
t/integration/test_canvas.py::test_chain::test_groupresult_serialization PASSED
t/integration/test_canvas.py::test_chain::test_chain_of_task_a_group_and_a_chord PASSED
t/integration/test_canvas.py::test_chain::test_chain_of_chords_as_groups_chained_to_a_task_with_two_tasks PASSED
t/integration/test_canvas.py::test_chain::test_chain_of_chords_with_two_tasks PASSED
t/integration/test_canvas.py::test_chain::test_chain_of_a_chord_and_a_group_with_two_tasks PASSED
t/integration/test_canvas.py::test_chain::test_chain_of_a_chord_and_a_task_and_a_group PASSED
t/integration/test_canvas.py::test_chain::test_chain_of_a_chord_and_two_tasks_and_a_group PASSED
t/integration/test_canvas.py::test_chain::test_chain_of_a_chord_and_three_tasks_and_a_group PASSED
t/integration/test_canvas.py::test_chain::test_nested_chain_group_lone XFAIL (Task is timeout)
t/integration/test_canvas.py::test_chain::test_nested_chain_group_mid PASSED
t/integration/test_canvas.py::test_chain::test_nested_chain_group_last PASSED
t/integration/test_canvas.py::test_chain::test_chain_replaced_with_a_chain_and_a_callback SKIPPED (Requires redis result backend.)
t/integration/test_canvas.py::test_chain::test_chain_replaced_with_a_chain_and_an_error_callback SKIPPED (Requires redis result backend.)
t/integration/test_canvas.py::test_chain::test_chain_with_cb_replaced_with_chain_with_cb SKIPPED (Requires redis result backend.)
t/integration/test_canvas.py::test_chain::test_chain_flattening_keep_links_of_inner_chain SKIPPED (Requires redis result backend.)
t/integration/test_canvas.py::test_chain::test_chain_with_eb_replaced_with_chain_with_eb SKIPPED (Requires redis result backend.)
t/integration/test_canvas.py::test_chain::test_replace_chain_with_empty_chain PASSED
t/integration/test_canvas.py::test_chain::test_chain_children_with_callbacks SKIPPED (Requires redis result backend.)
t/integration/test_canvas.py::test_chain::test_chain_children_with_errbacks SKIPPED (Requires redis result backend.)
t/integration/test_canvas.py::test_chain::test_chain_with_callback_child_replaced SKIPPED (Requires redis result backend.)
t/integration/test_canvas.py::test_chain::test_chain_with_errback_child_replaced SKIPPED (Requires redis result backend.)
t/integration/test_canvas.py::test_chain::test_chain_child_with_callback_replaced SKIPPED (Requires redis result backend.)
t/integration/test_canvas.py::test_chain::test_chain_child_with_errback_replaced SKIPPED (Requires redis result backend.)
t/integration/test_canvas.py::test_chain::test_task_replaced_with_chain XPASS (Task is timeout instead of returning exception on rpc backend)
t/integration/test_canvas.py::test_chain::test_chain_child_replaced_with_chain_first PASSED
t/integration/test_canvas.py::test_chain::test_chain_child_replaced_with_chain_middle FAILED

============================================================================================ FAILURES =============================================================================================
_____________________________________________________________________ test_chain.test_chain_child_replaced_with_chain_middle ______________________________________________________________________

self = <t.integration.test_canvas.test_chain object at 0x105e79310>, manager = <celery.contrib.testing.manager.Manager object at 0x119174260>

    def test_chain_child_replaced_with_chain_middle(self, manager):
        orig_sig = chain(
            identity.s(42), replace_with_chain.s(), identity.s()
        )
        res_obj = orig_sig.delay()
>       assert res_obj.get(timeout=TIMEOUT) == 42

t/integration/test_canvas.py:803:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
celery/result.py:251: in get
    return self.backend.wait_for_pending(
celery/backends/asynchronous.py:221: in wait_for_pending
    for _ in self._wait_for_pending(result, **kwargs):
celery/backends/asynchronous.py:287: in _wait_for_pending
    for _ in self.drain_events_until(
celery/backends/asynchronous.py:54: in drain_events_until
    yield self.wait_for(p, wait, timeout=interval)
celery/backends/asynchronous.py:63: in wait_for
    wait(timeout=timeout)
celery/backends/redis.py:161: in drain_events
    message = self._pubsub.get_message(timeout=timeout)
.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/client.py:1072: in get_message
    response = self.parse_response(block=(timeout is None), timeout=timeout)
.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/client.py:883: in parse_response
    response = self._execute(conn, try_read)
.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/client.py:859: in _execute
    return conn.retry.call_with_retry(
.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/retry.py:62: in call_with_retry
    return do()
.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/client.py:860: in <lambda>
    lambda: command(*args, **kwargs),
.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/client.py:881: in try_read
    return conn.read_response(disconnect_on_error=False, push_request=True)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <valkey.connection.Connection(host=localhost,port=6380,db=0)>, disable_decoding = False

    def read_response(
        self,
        disable_decoding=False,
        *,
        disconnect_on_error=True,
        push_request=False,
    ):
        """Read the response from a previously sent command"""

        host_error = self._host_error()

        try:
            if self.protocol in ["3", 3] and not LIBVALKEY_AVAILABLE:
                response = self._parser.read_response(
                    disable_decoding=disable_decoding, push_request=push_request
                )
            else:
                response = self._parser.read_response(disable_decoding=disable_decoding)
        except socket.timeout:
            if disconnect_on_error:
                self.disconnect()
            raise TimeoutError(f"Timeout reading from {host_error}")
        except OSError as e:
            if disconnect_on_error:
                self.disconnect()
            raise ConnectionError(
                f"Error while reading from {host_error}" f" : {e.args}"
            )
        except BaseException:
            # Also by default close in case of BaseException.  A lot of code
            # relies on this behaviour when doing Command/Response pairs.
            # See #1128.
            if disconnect_on_error:
                self.disconnect()
            raise

        if self.health_check_interval:
            self.next_health_check = time() + self.health_check_interval

        if isinstance(response, ResponseError):
            try:
>               raise response
E               valkey.exceptions.ResponseError: NOSUB 'unsubscribe' command executed not in subscribed mode

.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/connection.py:570: ResponseError
---------------------------------------------------------------------------------------- Captured log call ----------------------------------------------------------------------------------------
INFO     celery.worker.strategy:strategy.py:161 Task t.integration.tasks.identity[90ef0c6e-095a-446b-92ae-d4b5c6007f66] received
INFO     celery.worker.strategy:strategy.py:161 Task t.integration.tasks.replace_with_chain[e7e908fe-71fa-45a0-9a1e-0d97334778bf] received
INFO     celery.app.trace:trace.py:128 Task t.integration.tasks.identity[90ef0c6e-095a-446b-92ae-d4b5c6007f66] succeeded in 0.001407832998665981s: 42
INFO     celery.worker.strategy:strategy.py:161 Task t.integration.tasks.identity[b727619c-72be-4079-b003-87b4d025d181] received
======================================================================================== warnings summary =========================================================================================
t/integration/test_canvas.py::test_chain::test_chain_error_handler_with_eta
  /Users/nusnus/dev/GitHub/celery/celery/canvas.py:2301: CPendingDeprecationWarning: task_allow_error_cb_on_chord_header=False is pending deprecation in a future release of Celery.
  Please test the new behavior by setting task_allow_error_cb_on_chord_header to True and report any concerns you might have in our issue tracker before we make a final decision regarding how errbacks should behave when used with chords.
    warnings.warn(

-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
===================================================================================== short test summary info =====================================================================================
FAILED t/integration/test_canvas.py::test_chain::test_chain_child_replaced_with_chain_middle - valkey.exceptions.ResponseError: NOSUB 'unsubscribe' command executed not in subscribed mode
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! stopping after 1 failures !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
====================================================== 1 failed, 27 passed, 17 skipped, 2 xfailed, 1 xpassed, 1 warning in 84.34s (0:01:24) =======================================================
Exception ignored in: <function AsyncResult.__del__ at 0x1051c3f60>
Traceback (most recent call last):
  File "/Users/nusnus/dev/GitHub/celery/celery/result.py", line 417, in __del__
  File "/Users/nusnus/dev/GitHub/celery/celery/backends/asynchronous.py", line 208, in remove_pending_result
  File "/Users/nusnus/dev/GitHub/celery/celery/backends/asynchronous.py", line 216, in on_result_fulfilled
  File "/Users/nusnus/dev/GitHub/celery/celery/backends/redis.py", line 184, in cancel_for
  File "/Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/client.py", line 1000, in unsubscribe
  File "/Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/client.py", line 804, in execute_command
  File "/Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/connection.py", line 1107, in get_connection
  File "/Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/connection.py", line 314, in connect
  File "/Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/connection.py", line 345, in on_connect
  File "/Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/_parsers/libvalkey.py", line 51, in on_connect
ImportError: sys.meta_path is None, Python is likely shutting down
Exception ignored in: <function AsyncResult.__del__ at 0x1051c3f60>
Traceback (most recent call last):
  File "/Users/nusnus/dev/GitHub/celery/celery/result.py", line 417, in __del__
  File "/Users/nusnus/dev/GitHub/celery/celery/backends/asynchronous.py", line 208, in remove_pending_result
  File "/Users/nusnus/dev/GitHub/celery/celery/backends/asynchronous.py", line 216, in on_result_fulfilled
  File "/Users/nusnus/dev/GitHub/celery/celery/backends/redis.py", line 184, in cancel_for
  File "/Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/client.py", line 1000, in unsubscribe
  File "/Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/client.py", line 804, in execute_command
  File "/Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/connection.py", line 1120, in get_connection
  File "/Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/connection.py", line 314, in connect
  File "/Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/connection.py", line 345, in on_connect
  File "/Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/_parsers/libvalkey.py", line 51, in on_connect
ImportError: sys.meta_path is None, Python is likely shutting down
Exception ignored in: <function AsyncResult.__del__ at 0x1051c3f60>
Traceback (most recent call last):
  File "/Users/nusnus/dev/GitHub/celery/celery/result.py", line 417, in __del__
  File "/Users/nusnus/dev/GitHub/celery/celery/backends/asynchronous.py", line 208, in remove_pending_result
  File "/Users/nusnus/dev/GitHub/celery/celery/backends/asynchronous.py", line 216, in on_result_fulfilled
  File "/Users/nusnus/dev/GitHub/celery/celery/backends/redis.py", line 184, in cancel_for
  File "/Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/client.py", line 1000, in unsubscribe
  File "/Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/client.py", line 804, in execute_command
  File "/Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/connection.py", line 1120, in get_connection
  File "/Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/connection.py", line 314, in connect
  File "/Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/connection.py", line 345, in on_connect
  File "/Users/nusnus/dev/GitHub/celery/.tox/3.12-integration-rabbitmq_valkey/lib/python3.12/site-packages/valkey/_parsers/libvalkey.py", line 51, in on_connect
ImportError: sys.meta_path is None, Python is likely shutting down
3.12-integration-rabbitmq_valkey: exit 1 (85.30 seconds) /Users/nusnus/dev/GitHub/celery> pytest -xsvv t/integration pid=74706
  3.12-integration-rabbitmq_valkey: FAIL code 1 (87.03=setup[1.73]+cmd[85.30] seconds)
  evaluation failed :( (87.41 seconds)

@Nusnus
Nusnus marked this pull request as draft September 23, 2024 13:21
@amirreza-sf80

Copy link
Copy Markdown
Author

hi @Nusnus
sorry i'm late
had a problem with pip and couldn't run the tests

so weird thing happened, i got the same error, then added a assert False to see what's breaking, and suddenly the test passed
now i removed the assert and the test passes again
so is tox caching the result or something?
i'm confused with both situations

@Nusnus

Nusnus commented Sep 24, 2024

Copy link
Copy Markdown
Member

hi @Nusnus
sorry i'm late
had a problem with pip and couldn't run the tests

so weird thing happened, i got the same error, then added a assert False to see what's breaking, and suddenly the test passed
now i removed the assert and the test passes again
so is tox caching the result or something?
i'm confused with both situations

Tbh I'm not sure, but it does reproduce in the CI so that's a blocker my friend.

I suggest good old debugging to find why it happens 🙏

@amirreza-sf80

Copy link
Copy Markdown
Author

i might have miscommunicated
i fully understand that when tests are failing, the code shouldn't be merged.

to inform you on the issue tho:
my problem is that i'm not able to reproduce the bug properly for a debug
sometimes the test failes, soemtimes it doesn't.

and i'm not sure the traceback is accurate, since putting assert False in one of the methods mentioned in the traceback should break the code, but it doesn't.

and the error message seems weird as well, i do not see anywhere in the traceback PubSub.unsubscribe() being called.
i do see PubSub.subscribe() but the error says it is not subscribed.
i will try again but i don't see myself finding the issue any time soon.

@zukka77

zukka77 commented Oct 14, 2024

Copy link
Copy Markdown

Hi, I don't know if this is the right place to write this, but I had the same problem with valkey 8.0.1:
random redis.exceptions.ResponseError: NOSUB 'unsubscribe' command executed not in subscribed mode when trying to "get" on tasks with no result.
It works using valkey version 7.x docker.io/valkey/valkey:7

@amirreza-sf80

Copy link
Copy Markdown
Author

Hi, I don't know if this is the right place to write this, but I had the same problem with valkey 8.0.1: random redis.exceptions.ResponseError: NOSUB 'unsubscribe' command executed not in subscribed mode when trying to "get" on tasks with no result. It works using valkey version 7.x docker.io/valkey/valkey:7

hi
thanks for the feedback
i'll test with 7.x valkey and see, if it is a problem with valkey i'll open an issue there

@amirreza-sf80

Copy link
Copy Markdown
Author

hi @Nusnus
testing with valkey 7.2.7
all tests passed

i'll make an issue in valkey's github inforimng the problem with 8.0.X
but meanwhile it's available for 7.2.7

@Nusnus Nusnus 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.

Can you please rebase on main / merge main and fix the conflicts so we can see how does the CI reacts?

@amirreza-sf80

Copy link
Copy Markdown
Author

i started an issue in valkey's github

the current guess is that there's some race condition happening in celery tests with valkey8
see if you have a comment

@Nusnus

Nusnus commented Oct 25, 2024

Copy link
Copy Markdown
Member

i started an issue in valkey's github

the current guess is that there's some race condition happening in celery tests with valkey8
see if you have a comment

Awesome, thank you!
Ping me when you have new updates 🚀

@amirreza-sf80

Copy link
Copy Markdown
Author

docker start rabbitmq valkey redis && pytest -svv t/integration && docker stop rabbitmq valkey redis

when not using tox, the above error doesn't happen anymore
so my current guess is that a race condition is happening when using tox

note that the above command will raise some errors due to lack of configuration, but the error in discussion doesn't happen

let me know what you think

@zukka77

zukka77 commented Oct 26, 2024

Copy link
Copy Markdown

@amirreza8002 I got the error in my code, maybe a test that raises an error which can happen in actual code is better than a test which passes 😅

@amirreza-sf80

amirreza-sf80 commented Oct 26, 2024 •

Copy link
Copy Markdown
Author

hi @zukka77
as i mentioned running the command i wrote will raise errors, five errors actually

that's because it's misconfigured

I'm not trying to hide any bugs here 🙃
the reason behind the last comment is that, the current guess on why the problem happened in the first place, is a race condition in the integration test.

and now I'm trying to find what is causing the race condition.

my current guess is that tox is causing it, because the previous problem doesn't happen when running tests without tox.

if you have a reason to disagree please do share your thoughts

@amirreza-sf80

amirreza-sf80 commented Oct 26, 2024 •

Copy link
Copy Markdown
Author

ok i feel like tihs is losing clarity
so let me rewind so we're all on the same page

  1. the integration tests fail, the error says that "an un-subscribe command has been called, while there is no subscription to unsubscribe from."
    this raises a question: what is calling unsubscribe (i can't find any trace of it in the traceback)?

  2. when running the tests multiple times, i noticed that the errors, while always happening, they happen at different cases, meaning a test case could fail one time and pass the other time, and a test that passed the last time would fail now.
    this caused me to think there is a race condition, initially i thought there is a thread happening (it could still be this)

  3. zukka77 mentioned that the tests pass when using valkey7.2.7, which is true, tests only fail when using valkey8.0.x
    this caused this issue which concluded this is not a problem in valkey, just valkey throwing an error when it should throw an error (this was added at 8.0.0)

this means two things:

  1. the test was always causing a race condition, but since redis doesn't throw an error, it was hidden away

  2. there is something causing an unsubscribe() to be called, and it to be called when there is no subscription
    the main guess is a race condition, now what is causing this?

    i have two guess, either celery is using a thread or the like in it's test case (i'm still not sure what some of the code in tests do), or it's tox

    while testing without tox, the race condition didn't happen, so my main guess is tox, i could be wrong

sorry it got long

@zukka77

zukka77 commented Oct 26, 2024

Copy link
Copy Markdown

Hi @amirreza8002 to clarify I'm here because I had the same error on a little project I'm doing (where I use valkey as a drop-in replacement of redis, my celery instance is configured as if I'm using redis) , I've never run the tests by myself.
When I noted that downgrading valkey to 7.x my program worked right I thought it might be of interest 😅 .

As I am understanding :

  • valkey 8.x changed behaviour (doing probably the right thing) returning the new status NOSUB when trying to unsubscibe without a subscription (no error was returned before).
  • Now celery is facing a new error never seen before, maybe it should ignore the NOSUB error after an unsubscribe call, maybe unsubscribe is called in every situation without checking if a prior subscribtion is in place (because it didn't throw an error), or it should check better when to call the unsubscribe (I've never watched at the sources).

I'm sorry if I caused confusion :(

@amirreza-sf80

Copy link
Copy Markdown
Author

hi
please don't apologise for helping out

so if i'm to understand correctly, you are getting the error in your project, and not in celery tests?

if so, can you provide information so i can reproduce it and see?

@zukka77

zukka77 commented Oct 27, 2024

Copy link
Copy Markdown

@amirreza8002 i created this repo https://git.zukka.net/andrea/valkey-celery-test with a fake backend which reproduces the error.
Using valkey 7 everything work, using valkey 8 I consistently get redis.exceptions.ResponseError: NOSUB 'unsubscribe' command executed not in subscribed mode

This happens when i call a .get() on a "result" after a .wait() on another tasks which has no return value:

res=app.send_task("task1") //task with no return value
res.wait()
res=app.send_task("task2")
res.get() // <-- here I get the error with valkey 8

@amirreza-sf80

Copy link
Copy Markdown
Author

hi @Nusnus
i made some changes on the code structure
it's a rather big change, so pls do take a moment and ponder on the changes
if it's not desired, i'll reset the commits

@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.

I will come back to this after celery v5.5 stable is released

@amirreza-sf80

Copy link
Copy Markdown
Author

reminder that this exists :p

@amirreza-sf80

Copy link
Copy Markdown
Author

hi @auvipy @Nusnus
if you have time have a look here
time goes by and i start to forget what i have written here which makes work harder 🙃

@auvipy

auvipy commented May 19, 2025

Copy link
Copy Markdown
Member

I think we do not need it as it is just a drop in replacement for redis and redis is open source again. And we can already see a 3rd party library for this.

@DmytroLitvinov

Copy link
Copy Markdown
Contributor

Posted my argument why it can be interested to integrate into a celery - #9092 (comment)

@amirreza-sf80

amirreza-sf80 commented May 19, 2025 •

Copy link
Copy Markdown
Author

from what i can gather, the redis backend probably will work with valkey as well

but:
the code I've written only adds a few lines of code, but in that it provides better error messages and checks for valkey

it also makes it easier to use valkey specific packages, such as libvalkey, or to switch the clinet to valkey-glide (when they make their sync interface)

it also makes more sense to have a valkey version to people who are already using valkey-py in their projects and installing redis-py would be a waste

but you are the maintainers of celery and if you feel it's unnecessary, I'm fine to close the pr

@auvipy

auvipy commented May 19, 2025

Copy link
Copy Markdown
Member

I think this can easily live as an extension of celery for now

@dpdoughe

Copy link
Copy Markdown
Contributor

Important notes about the limitations (and risks) of Redis' adoption of AGPL from: https://www.thestack.technology/redis-reverts-to-open-source. I think Celery support for Valkey would be helpful.

The primary purpose of AGPL appears to be creating barriers for public cloud providers, which likely guarantees that major sponsors like Amazon and Google will continue to support Valkey. For Redis, this appears to be largely a marketing maneuver to appease their user base… As a Linux Foundation-backed initiative, Valkey is establishing its distinct identity guided by community priorities rather than single-company interests.

This community-first approach enables performance enhancements and feature development to be incorporated directly into the open source project. Importantly, Valkey maintains the highly permissive and community-friendly BSD license. The repeated back-and-forth license changes we've seen from Redis significantly erode enterprise trust and create substantial uncertainty for organizations attempting to build long-term technology strategies,” he added:

Each license shift forces enterprises to reevaluate their technology stack, assess compliance risks, and potentially rework their architecture—all costly and disruptive…”

@auvipy

auvipy commented May 20, 2025

Copy link
Copy Markdown
Member

I think we can use the same codebase for supporting redis, valkey and dragonflydb.... that would reduce code duplication

@amirreza-sf80

Copy link
Copy Markdown
Author

hi @auvipy
does the current implementation not satisfy the code reuse you have in mind?

@rfenner

rfenner commented May 31, 2025

Copy link
Copy Markdown

If your concerned about code resuse maybe just alias vallkey to the redis backend and add code into it ro look for native valkey libraries before falling back to redis at least for the time being since they are for Celery's use case the same.

@auvipy

auvipy commented Jun 1, 2025 •

Copy link
Copy Markdown
Member

hi @auvipy does the current implementation not satisfy the code reuse you have in mind?

no it is still a lot of code and 2 separate codebase for same back end with different name. we should go for alias approach now with minimal code changes here.

And here is a relevant PR that should do the trick! celery/kombu#2246

@dpdoughe

dpdoughe commented Jul 1, 2025

Copy link
Copy Markdown
Contributor

IMO, it seems like this PR #9300 is doing it in a reasonable OOP way. The situation seems to be there is a lot of commonality between 2 classes. Ok, so we move the common code into a parent class, BaseKeyValueBackend in this case, and then extend both ValkeyBackend and RedisBackend from that common base class. That seems quite standard especially if we know these classes will likely diverge going forward based on the licenses and the feature sets. If the Redis folks change their license again to something more restrictive in the future, it also provides clean off-ramp.

@dpdoughe

dpdoughe commented Jul 1, 2025

Copy link
Copy Markdown
Contributor

From what I can gather, the alias approach, e.g., for pyamqp vs amqp vs librabbitmq, seems to be more about providing fail-over type of functionality. I.e., celery/kombu#189 (comment)

@eilgin

eilgin commented Nov 3, 2025

Copy link
Copy Markdown

I saw that this PR is still in "draft". Does anyone still actively working on it?
From what I saw in the changes, it's mostly a drop-in replacement of Redis backend. Do you wait from something specific to merge it (apart from failed linting/tests 😄)?

@tuminoid

tuminoid commented Nov 3, 2025 •

Copy link
Copy Markdown

hi @auvipy does the current implementation not satisfy the code reuse you have in mind?

no it is still a lot of code and 2 separate codebase for same back end with different name. we should go for alias approach now with minimal code changes here.

And here is a relevant PR that should do the trick! celery/kombu#2246

Kombu PR does provide a working alias for the broker, and even recently released Valkey 9.0 should fully work with that (they should be fully compatible still, while they do provide unique features now that Redis does not). Kombu does not play a role for the results backend though, for that we need separate support in Celery, but only in case we can't use Redis.

edit: I've implemented a small POC that installs combination of this PR and Kombu PR (bit tricky, their deps conflict) and configures celery to use valkey:// instead of redis:// for both use cases and it works. Obviously this PR is WIP and the Kombu one is just an alias, but step at a time.

@danzycbertin

Copy link
Copy Markdown

Over time, the differences between Redis and Valkey are likely to become more significant. It is recommended to use valkey-py instead of redis-py for Valkey adaptation.

@auvipy
auvipy requested review from Copilot and removed request for thedrow April 23, 2026 12:45

Copilot AI 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.

Pull request overview

This PR adds a Valkey result backend to Celery and refactors the existing Redis backend to share implementation via a new BaseKeyValueBackend abstraction.

Changes:

  • Introduces celery.backends.valkey and registers new backend URL aliases (valkey://, valkeys://, valkeysentinel://).
  • Refactors Redis backend/sentinel backend to inherit from BaseKeyValueBackend / BaseSentinelBackend.
  • Adds CI/tox integration coverage for Valkey plus new unit tests and documentation updates.

Reviewed changes

Copilot reviewed 18 out of 18 changed files in this pull request and generated 12 comments.

Show a summary per file
File Description
celery/backends/base_keyval.py New shared Redis/Valkey key-value backend implementation (incl. chords, SSL params, sentinel helpers).
celery/backends/redis.py Refactored to thin wrapper around BaseKeyValueBackend / BaseSentinelBackend.
celery/backends/valkey.py New Valkey result backend + sentinel backend.
celery/app/backends.py Registers Valkey backend aliases.
celery/app/defaults.py Adds valkey_* configuration namespace.
t/unit/backends/test_valkey.py Adds unit test suite for Valkey backend and consumer.
t/unit/backends/test_redis.py Updates Redis unit tests to match refactor paths/attributes.
t/integration/test_canvas.py Marks known chord error propagation issue as xfail for Valkey backend too.
tox.ini Adds rabbitmq_valkey integration environment.
.github/workflows/python-package.yml Adds Valkey service and toxenv to integration matrix.
requirements/extras/valkey.txt New Valkey extra requirements file.
requirements/test-integration.txt / requirements/test-ci-base.txt Includes Valkey extra in test requirements.
setup.py Adds valkey to extras list.
docs/includes/installation.txt Documents celery[valkey] bundle.
docs/getting-started/backends-and-brokers/valkey.rst New Valkey documentation page (currently broker-focused).
docs/getting-started/backends-and-brokers/index.rst Adds Valkey to toctree and overview content.
README.rst Mentions Valkey in supported transports/backends and adds reference link.

return [
e[1] for e in self._get_sorted_set(key)
if (min_ == "-inf" or e[0] >= min_) and
(max_ == "+inf" or e[1] <= max_)

Copilot AI Apr 23, 2026

Copy link

Choose a reason for hiding this comment

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

The Valkey mock client’s zrangebyscore() compares max_ to e[1] (the value) instead of e[0] (the score). This makes the fake implementation incorrect and can cause future tests using numeric score bounds to fail or behave incorrectly.

Suggested change
(max_ == "+inf" or e[1] <= max_)
(max_ == "+inf" or e[0] <= max_)

Copilot uses AI. Check for mistakes.
Comment thread README.rst
- **Message Transports**

- RabbitMQ_, Redis_, Amazon SQS, Google Pub/Sub
- RabbitMQ_, Redis_, Amazon SQS, Google Pub/Sub, Valkey_

Copilot AI Apr 23, 2026

Copy link

Choose a reason for hiding this comment

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

This adds Valkey to the list of supported “Message Transports”, but this PR appears to only implement a result backend (no broker transport registration in this repo). Please avoid claiming broker support in the README until transport support is actually implemented (or clarify what works).

Suggested change
- RabbitMQ_, Redis_, Amazon SQS, Google Pub/Sub, Valkey_
- RabbitMQ_, Redis_, Amazon SQS, Google Pub/Sub

Copilot uses AI. Check for mistakes.
Comment thread tox.ini
rabbitmq_redis: TEST_BROKER=pyamqp://
rabbitmq_redis: TEST_BACKEND=redis://

rabbitmq_valkey: TEST_BROKER=amqp://

Copilot AI Apr 23, 2026

Copy link

Choose a reason for hiding this comment

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

rabbitmq_valkey uses TEST_BROKER=amqp:// while the other RabbitMQ integration environments use pyamqp://. Using amqp:// can change which transport gets selected (depending on installed extras) and make the integration matrix less consistent/reproducible; consider using pyamqp:// here as well.

Suggested change
rabbitmq_valkey: TEST_BROKER=amqp://
rabbitmq_valkey: TEST_BROKER=pyamqp://

Copilot uses AI. Check for mistakes.
# If connparams or query string contain ssl params, raise error
if (any(key in connparams for key in ssl_param_keys) or
any(key in query for key in ssl_param_keys)):
raise ValueError(self.SSL_PARAMS_AND_SCHEME_MISMATCH)

Copilot AI Apr 23, 2026

Copy link

Choose a reason for hiding this comment

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

_params_from_url() raises ValueError(self.SSL_PARAMS_AND_SCHEME_MISMATCH), but SSL_PARAMS_AND_SCHEME_MISMATCH is not defined on the class. This will raise AttributeError when a non-TLS URL includes SSL query parameters. Use the module constant (e.g. E_SSL_PARAMS_AND_SCHEME_MISMATCH.format(self.backend_name) or similar) or define a class attribute.

Suggested change
raise ValueError(self.SSL_PARAMS_AND_SCHEME_MISMATCH)
raise ValueError(getattr(
self, 'SSL_PARAMS_AND_SCHEME_MISMATCH',
'SSL connection parameters may only be used with the '
f'{self.backend_name}s:// scheme'
))

Copilot uses AI. Check for mistakes.
Comment on lines +29 to +54
E_MISSING = """
You need to install the {} library in order to use \
the Valkey result store backend.
"""

E_SENTINEL_MISSING = """
You need to install the {} library with support of \
sentinel in order to use the Valkey result store backend.
"""

W_SSL_CERT_OPTIONAL = """
Setting ssl_cert_reqs=CERT_OPTIONAL when connecting to {} means that \
celery might not validate the identity of the valkey broker when connecting. \
This leaves you vulnerable to man in the middle attacks.
"""

W_SSL_CERT_NONE = """
Setting ssl_cert_reqs=CERT_NONE when connecting to {0} means that celery \
will not validate the identity of the {0} broker when connecting. This \
leaves you vulnerable to man in the middle attacks.
"""

E_SSL_PARAMS_AND_SCHEME_MISMATCH = """
SSL connection parameters have been provided but the specified URL scheme \
is {0}://. A Valkey SSL connection URL should use the scheme {0}s://.
"""

Copilot AI Apr 23, 2026

Copy link

Choose a reason for hiding this comment

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

The shared error/warning message templates are hard-coded to “Valkey” / “valkey broker” even when used by RedisBackend, leading to misleading exceptions/logs (e.g., missing redis dependency would say “Valkey result store backend”). These strings should be backend-neutral and interpolate the backend name consistently.

Copilot uses AI. Check for mistakes.
Comment on lines +250 to +256
self.connparams['connection_class'] = self.connection_class_ssl

if url:
self.connparams = self._params_from_url(url, self.connparams)

if ('connection_class' in self.connparams and
issubclass(self.connparams['connection_class'], self.backend_module.SSLConnection)):

Copilot AI Apr 23, 2026

Copy link

Choose a reason for hiding this comment

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

connection_class_ssl is evaluated in the base class using backend_module/backend before subclasses override them, so it stays None for RedisBackend/ValkeyBackend. When *_backend_use_ssl is configured, connparams['connection_class'] becomes None and the subsequent issubclass(...) check can raise TypeError, and TLS connections via config dict won’t work. Define connection_class_ssl in each concrete backend (e.g., redis.SSLConnection / valkey.SSLConnection) and guard the issubclass check by ensuring connection_class is a class.

Suggested change
self.connparams['connection_class'] = self.connection_class_ssl
if url:
self.connparams = self._params_from_url(url, self.connparams)
if ('connection_class' in self.connparams and
issubclass(self.connparams['connection_class'], self.backend_module.SSLConnection)):
connection_class_ssl = getattr(
self.backend_module, 'SSLConnection', self.connection_class_ssl,
)
if isinstance(connection_class_ssl, type):
self.connparams['connection_class'] = connection_class_ssl
if url:
self.connparams = self._params_from_url(url, self.connparams)
connection_class = self.connparams.get('connection_class')
if (isinstance(connection_class, type) and
issubclass(connection_class, self.backend_module.SSLConnection)):

Copilot uses AI. Check for mistakes.
Comment thread celery/backends/redis.py
from celery.exceptions import BackendStoreError, ChordError, ImproperlyConfigured
from celery.result import GroupResult, allow_join_result
from celery.utils.functional import _regen, dictfilter
from celery.utils.log import get_logger

Copilot AI Apr 23, 2026

Copy link

Choose a reason for hiding this comment

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

get_logger is imported but never used in this module after the refactor, which will fail linting (unused import). Remove it or use it to define a logger.

Suggested change
from celery.utils.log import get_logger

Copilot uses AI. Check for mistakes.
@@ -45,8 +46,6 @@ individual transport (see :ref:`broker_toc`).
+---------------+--------------+----------------+--------------------+
| *Kafka* | Experimental | No | No |
+---------------+--------------+----------------+--------------------+

Copilot AI Apr 23, 2026

Copy link

Choose a reason for hiding this comment

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

The broker comparison table no longer includes the GC PubSub row even though gcpubsub is still listed in the toctree and has a summary section below. This makes the “Broker Overview” table inconsistent; either restore the row or remove the related content.

Suggested change
+---------------+--------------+----------------+--------------------+
+---------------+--------------+----------------+--------------------+
| *GC PubSub* | Experimental | No | No |
+---------------+--------------+----------------+--------------------+

Copilot uses AI. Check for mistakes.
Comment on lines +122 to +125
Valkey is a free licenced fork of Redis, with a similar API that almost works the same.
it does everything redis does

:red:`See documentation for details <broker-valkey>`

Copilot AI Apr 23, 2026

Copy link

Choose a reason for hiding this comment

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

The Valkey section has multiple documentation issues: spelling/grammar (“free licenced”, sentence casing), and :red: is not a valid Sphinx role here (likely meant :ref:). As-is this is likely to break the docs build and should be corrected.

Suggested change
Valkey is a free licenced fork of Redis, with a similar API that almost works the same.
it does everything redis does
:red:`See documentation for details <broker-valkey>`
Valkey is a freely licensed fork of Redis with a similar API.
It does everything Redis does.
:ref:`See documentation for details <broker-valkey>`

Copilot uses AI. Check for mistakes.
Comment on lines +25 to +32
Configuration is easy, just configure the location of
your Valkey database:

.. code-block:: python

app.conf.broker_url = 'valkey://localhost:6379/0'

Where the URL is in the format of:

Copilot AI Apr 23, 2026

Copy link

Choose a reason for hiding this comment

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

The documentation uses broker_url = 'valkey://…' / valkeysentinel://… examples, but this PR only adds a result backend implementation and does not add/register a Kombu transport for Valkey. As written, these broker examples are likely non-functional; either implement the broker transport support or scope this page to the result backend (and mention that Valkey can be used with the existing Redis transport by pointing redis:// at a Valkey server, if that’s the intended story).

Copilot uses AI. Check for mistakes.

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.

These issues Copilot found all seem fixable. Is the next step to have Copilot work through these issues it found?

@auvipy auvipy modified the milestones: 5.7.0, 5.8.0 Aug 26, 2026

This branch has not been deployed

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support for using Valkey as a message transport or as a result backend.