Skip to content

Celery + MSSQL + Windows - multiple issues #9637

Closed

Description

@Abhijit-Revamp

Checklist

  • I have verified that the issue exists against the main branch of Celery.
  • This has already been asked to the discussions forum first.
  • I have read the relevant section in the
    contribution guide
    on reporting bugs.
  • I have checked the issues list
    for similar or identical bug reports.
  • I have checked the pull requests list
    for existing proposed fixes.
  • I have checked the commit log
    to find out if the bug was already fixed in the main branch.
  • I have included all related issues and possible duplicate issues
    in this issue (If there are none, check this box anyway).
  • I have tried to reproduce the issue with pytest-celery and added the reproduction script below.

Mandatory Debugging Information

  • I have included the output of celery -A proj report in the issue.
    (if you are not able to do this, then at least specify the Celery
    version affected).
  • I have verified that the issue exists against the main branch of Celery.
  • I have included the contents of pip freeze in the issue.
  • I have included all the versions of all the external dependencies required
    to reproduce this bug.

Optional Debugging Information

  • I have tried reproducing the issue on more than one Python version
    and/or implementation.
  • I have tried reproducing the issue on more than one message broker and/or
    result backend.
  • I have tried reproducing the issue on more than one version of the message
    broker and/or result backend.
  • I have tried reproducing the issue on more than one operating system.
  • I have tried reproducing the issue on more than one workers pool.
  • I have tried reproducing the issue with autoscaling, retries,
    ETA/Countdown & rate limits disabled.
  • I have tried reproducing the issue after downgrading
    and/or upgrading Celery and its dependencies.

Related Issues and Possible Duplicates

Related Issues

  • None

Possible Duplicates

  • None

Environment & Settings

Celery version:

celery report Output:

software -> celery:5.4.0 (opalescent) kombu:5.5.0 py:3.13.2
            billiard:4.2.1 py-amqp:5.3.1
platform -> system:Windows arch:64bit, WindowsPE
            kernel version:11 imp:CPython
loader   -> celery.loaders.app.AppLoader
settings -> transport:pyamqp results:mssql+pymssql://dev-glenmarklg%5Csql_2019/vcgGlenmark

broker_url: 'amqp://agentLogin:********@127.0.0.1:5672/myHost'
result_backend: 'mssql+pymssql://server%5Cinstance/myTable'
deprecated_settings: None
broker_connection_retry_on_startup: True
result_persistent: True
task_serializer: 'json'
result_serializer: 'json'
accept_content: ['json']

Steps to Reproduce

Required Dependencies

  • Minimal Python Version: N/A or Unknown
  • Minimal Celery Version: N/A or Unknown
  • Minimal Kombu Version: N/A or Unknown
  • Minimal Broker Version: N/A or Unknown
  • Minimal Result Backend Version: N/A or Unknown
  • Minimal OS and/or Kernel Version: N/A or Unknown
  • Minimal Broker Client Version: N/A or Unknown
  • Minimal Result Backend Client Version: N/A or Unknown

Python Packages

pip freeze Output:

amqp==5.3.1
annotated-types==0.7.0
ansicon==1.89.0
anyio==4.9.0
billiard==4.2.1
blessed==1.20.0
celery==5.4.0
cffi==1.17.1
click==8.1.8
click-didyoumean==0.3.1
click-plugins==1.1.1
click-repl==0.3.0
colorama==0.4.6
cryptography==44.0.2
dnspython==2.7.0
eventlet==0.39.1
fastapi==0.115.11
gevent==24.11.1
greenlet==3.1.1
h11==0.14.0
idna==3.10
jinxed==1.3.0
kombu==5.5.0
prompt_toolkit==3.0.50
pycparser==2.22
pydantic==2.10.6
pydantic_core==2.27.2
pymssql==2.3.2
pyodbc==5.2.0
python-dateutil==2.9.0.post0
pywin32==310
readchar==4.2.1
revel==0.9.1
setuptools==77.0.3
six==1.17.0
sniffio==1.3.1
SQLAlchemy==2.0.39
starlette==0.46.1
typing_extensions==4.12.2
tzdata==2025.1
uvicorn==0.34.0
vine==5.1.0
wcwidth==0.2.13
zope.event==5.0
zope.interface==7.2

Other Dependencies

Details

N/A

Minimally Reproducible Test Case

Details

# tasks.py
import os
from celery import Celery
import time
from fastapi import requests
from celery.backends.database import models
from sqlalchemy import BigInteger,JSON
import sqlalchemy as sa
import pymssql

_srv = 'server\\instance'
connection_url = f'mssql+pymssql://{_srv}/myTable?driver=SQL+Server'
os.environ.setdefault('FORKED_BY_MULTIPROCESSING', '1')

celery_app = Celery(
    'tasks',
    broker='pyamqp://agentLogin:*******@127.0.0.1/myHost',
    backend=connection_url,
)
celery_app.conf.broker_connection_retry_on_startup = True
celery_app.conf.update({
    'result_persistent': True,
    'task_serializer': 'json',
    'result_serializer': 'json',
    'accept_content': ['json']})

@celery_app.task(bind=True)
def process_data(self, data):
    """
    Simulate a long-running analysis.
    This task updates its state as it progresses.
    """
    total_steps = 5
    for step in range(total_steps):
        pass
    # Return final result.
    return {"result": f"Processed data: {data}"}

Expected Behavior

Celery app should start

Actual Behavior

Exception while starting

[2025-03-26 03:15:41,904: CRITICAL/MainProcess] Unrecoverable error: ModuleNotFoundError("No module named 'mssql'")
Traceback (most recent call last):
  File "D:\PROJ\.venv\Lib\site-packages\celery\worker\worker.py", line 202, in start
    self.blueprint.start(self)
    ~~~~~~~~~~~~~~~~~~~~^^^^^^
  File "D:\PROJ\.venv\Lib\site-packages\celery\bootsteps.py", line 112, in start
    self.on_start()
    ~~~~~~~~~~~~~^^
  File "D:\PROJ\.venv\Lib\site-packages\celery\apps\worker.py", line 135, in on_start
    self.emit_banner()
    ~~~~~~~~~~~~~~~~^^
  File "D:\PROJ\.venv\Lib\site-packages\celery\apps\worker.py", line 169, in emit_banner
    ' \n', self.startup_info(artlines=not use_image))),
           ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\PROJ\.venv\Lib\site-packages\celery\apps\worker.py", line 231, in startup_info
    results=self.app.backend.as_uri(),
            ^^^^^^^^^^^^^^^^
  File "D:\PROJ\.venv\Lib\site-packages\celery\app\base.py", line 1303, in backend
    self._backend = self._get_backend()
                    ~~~~~~~~~~~~~~~~~^^
  File "D:\PROJ\.venv\Lib\site-packages\celery\app\base.py", line 968, in _get_backend
    backend, url = backends.by_url(
                   ~~~~~~~~~~~~~~~^
        self.backend_cls or self.conf.result_backend,
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        self.loader)
        ^^^^^^^^^^^^
  File "D:\PROJ\.venv\Lib\site-packages\celery\app\backends.py", line 69, in by_url
    return by_name(backend, loader), url
           ~~~~~~~^^^^^^^^^^^^^^^^^
  File "D:\PROJ\.venv\Lib\site-packages\celery\app\backends.py", line 49, in by_name
    cls = symbol_by_name(backend, aliases)
  File "D:\PROJ\.venv\Lib\site-packages\kombu\utils\imports.py", line 59, in symbol_by_name
    module = imp(module_name, package=package, **kwargs)
  File "D:\Python\Lib\importlib\__init__.py", line 88, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
           ~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap>", line 1387, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1360, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1324, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'mssql'

Activity

  1. auvipy commented on Mar 26, 2025

    @auvipy
    Member

    this should be issue on your project level. make sure the mssql module is in the python path.

  2. Abhijit-Revamp commented on Mar 26, 2025

    @Abhijit-Revamp
    Author

    @auvipy Forgot to mention, "mssql" module is installed and in path.
    There is something between celery and sqlalchemy that is triggering this issue.

  3. changed the title [-]Unrecoverable error: ModuleNotFoundError("No module named 'mssql'")[/-] [+]Celery + MSSQL + Windows - multiple issues[/+] on Mar 26, 2025
  4. Abhijit-Revamp commented on Mar 26, 2025

    @Abhijit-Revamp
    Author

    After 24 hours of pain, I was able to solve everything and here are the learnings and what led me to introduce these issues
    (probably feedback for Documentation)

    1. At one point I even contemplated to move from Celery to Dramatiq
    2. Got sucked into connection strings for MSSQL (Integrated auth vs others)
    3. Not completely reading previous issues and resolution (incl StackOverflow)

    Here is the full working solution

    1. for "backend" parameter, ensure it starts with "db+" followed what SqlAlchemy recommends. This was my downfall to begin with.
    2. Apply monkey patch "Daniel Caspi" (Arithmetic Overflow Error with MSSQL Backend due to Integer 'id' Field Limitation #8634 (comment))
    • Include JSON result.type so that you can see stuff in SQL
    1. IMP: After monkey patch if you still encounter "Arithmetic overflow error", (backup and) drop the tables in SQL and restart celery again.

    Here is my fully working code (RabbitMQ and DB settings redacted) along with DB output

    # tasks.py
    import os
    from celery import Celery
    import time
    from fastapi import requests
    import vfSpimacoCeleryCfg
    from celery.backends.database import models
    from sqlalchemy import BigInteger,JSON
    import sqlalchemy as sa
    
    # Monkey Patch for MSSQL Compatibility in Celery's Result Backend
    # ---------------------------------------------------------------
    # This code addresses a compatibility issue when using Microsoft SQL Server (MSSQL)
    # as the backend for Celery's task results. In MSSQL, the 'id' field in the results
    # tables can exceed the maximum value for an Integer data type, leading to overflow errors.
    # To prevent this, the data type of the 'id' column in both the Task and TaskSet models
    # is changed from Integer to BigInteger. This alteration ensures that the 'id' field can
    # accommodate larger values, aligning with MSSQL's capacity for handling big integers.
    # This patch modifies the column type directly in the SQLAlchemy table definition
    # for Celery's backend models before any tables are created in the database.
    # It is a simple yet effective solution to avoid overflow issues in MSSQL
    # while using Celery's database backend for storing task results.
    
    models.Task.__table__.c.id.type = BigInteger()
    models.TaskSet.__table__.c.id.type = BigInteger()
    models.Task.__table__.c.result.type = JSON()
    
    con_url = sa.URL.create(
        "db+mssql+pyodbc",
        host="dbSrv\\Instance",
        database='myDatabase',
        query={"driver": "SQL Server Native Client 11.0"},
    )
    connection_url = con_url.render_as_string(hide_password=False)
    
    os.environ.setdefault('FORKED_BY_MULTIPROCESSING', '1')
    
    # Configure Celery: using RabbitMQ as broker and RPC as backend.
    celery_app = Celery(
        'tasks',
        broker='pyamqp://user:****@127.0.0.1/myHost',
        backend=connection_url,
    )
    celery_app.conf.broker_connection_retry_on_startup = True
    celery_app.conf.update({
        'result_persistent': True,
        'task_serializer': 'json',
        'result_serializer': 'json',
        'accept_content': ['json']})
    
    @celery_app.task(bind=True)
    def process_data(self, data):
        """
        Simulate a long-running analysis.
        This task updates its state as it progresses.
        """
        total_steps = 5
        for step in range(total_steps):
            # Simulate processing for this step.
            time.sleep(15)  # Replace with actual work.
    
            progress_msg = {
                "current": step + 1,
                "total": total_steps,
                "status": f"Completed step {step + 1} of {total_steps}"
            }
            # Update progress: step numbers are 1-indexed.
            self.update_state(state='PROGRESS', meta=progress_msg)
    
        # Return final result.
        return {"result": f"Processed data: {data}"}

    Here is the database output
    Image

    Now let me focus on building what I intended to.

  5. Abhijit-Revamp commented on Mar 27, 2025

    @Abhijit-Revamp
    Author

    Now, while using "update_state" to show progress, this is indeed saved to database with actual progress

  6. auvipy commented on Mar 27, 2025

    @auvipy
    Member

    we actually do not have any real mssql infra or official support to be honest.

  7. Abhijit-Revamp commented on Mar 28, 2025

    @Abhijit-Revamp
    Author

    @auvipy - I understand. That was my prime reason to get into the depth and make it fully workable project.
    This issue is now documentation / tutorial only.
    I will post a complete solution blog how I am able to use Celery to achieve things on Windows stack end to end.

  8. self-assigned this
    on May 19, 2025
  9. added this to the 5.7.0 milestone on May 19, 2025
  10. auvipy commented on Sep 21, 2025

    @auvipy
    Member

    can you please check if this PR is related to this issue? #9904

  11. modified the milestones: 5.7.0, 5.8.0, 5.6.x on Aug 31, 2026
  12. auvipy commented on Aug 31, 2026

    @auvipy
    Member

    most probably already fixed

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

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions