Skip to content

Add schema extension support for database result backend tables - #9908

Open
dxdc wants to merge 17 commits into
celery:mainfrom
dxdc:extend-backend
Open

dxdc wants to merge 17 commits into
celery:mainfrom
dxdc:extend-backend

Conversation

@dxdc

@dxdc dxdc commented Sep 24, 2025 •

Copy link
Copy Markdown

Motivation

Currently, customizing the schema of Celery’s SQLAlchemy result backend requires monkey-patching the models (Task, TaskSet, or TaskExtended) directly. This makes it hard to:

  • Change column types (e.g., use JSON instead of PickleType)
  • Add indexes or constraints
  • Apply dialect-specific adjustments

This PR introduces a clean, explicit extension mechanism that allows applications to declare schema modifications in a backwards-compatible way.

See:


Design

A new concept: Schema Extensions.

  • Schema extensions are classes implementing:

    class SchemaExtension(ABC):
        def extend(self, table: Table, metadata: MetaData) -> None:
            ...
  • Passed into DatabaseBackend via a new schema_extensions argument.

  • Keys in schema_extensions must be "task" or "group", mapping to a list of extensions for each table.

  • Extensions are applied once during model configuration, before tables are created.

This keeps the core code minimal while offering flexibility for production users who need advanced schema control.


Example Usage

from sqlalchemy import Index
from celery.backends.database.extensions import SchemaExtension, JsonResultExtension
from celery.backends.database import DatabaseBackend

class StatusIndexExtension(SchemaExtension):
    def extend(self, table: Table, metadata: MetaData) -> None:
        if table.name == "celery_taskmeta":
            Index("idx_taskmeta_status", table.c.status, unique=False)

backend = DatabaseBackend(
    url="postgresql://...",
    app=app,
    schema_extensions={
        "task": [JsonResultExtension(), StatusIndexExtension()],
        "group": [],
    }
)

This results in:

  • result column using JSON instead of PickleType.
  • A new index on status.
  • No changes to TaskSet schema.

Changes in This PR

  • DatabaseBackend.__init__:

    • Accepts new kwarg:
      schema_extensions: Optional[Dict[Literal["task", "group"], List[SchemaExtension]]]
    • Passes extensions to Task.configure and TaskSet.configure.
  • Task.configure / TaskSet.configure:

    • Accept new extensions argument.
    • Apply each extension’s extend() method to the underlying SQLAlchemy Table.
  • Added type hints for clarity.


Benefits

  • Backwards compatible: No changes for users who don’t pass extensions.
  • Explicit: Users can configure schema behavior per table, no monkey-patching required.
  • Composable: Multiple extensions can be stacked together.
  • Safe: Extensions run before any DDL is executed.

Future Idea: Validation

Extensions could optionally implement a validate() method to check the live database schema and warn about mismatches.
This could be extended later to add optional migrations (e.g., using checkfirst=True), but is out of scope for this PR.


Summary

This PR introduces schema_extensions, a lightweight, extensible way to customize Celery’s database backend schema.
It improves flexibility, reduces monkey-patching, and provides a more general solution than PR #9907.
It also helps address issue #9501.

@vladborovtsov vladborovtsov mentioned this pull request Sep 24, 2025
@dxdc

dxdc commented Sep 24, 2025

Copy link
Copy Markdown
Author

Example Usage

Schema extensions can be provided in two ways:

1. Pass directly when instantiating the backend:

from celery.backends.database import DatabaseBackend

backend = DatabaseBackend(
    url=backend_url,
    app=app,
    schema_extensions={
        "task": [
            WorkerHostnameExtension(),
            StatusIndexExtension(),
        ],
        "group": [],
    },
)
app.backend = backend

2. Configure via app.conf (auto-picked up by DatabaseBackend):

app.conf.update(
    database_url=backend_url,
    database_schema_extensions={   # note key name
        "task": [
            WorkerHostnameExtension(),
            StatusIndexExtension(),
        ],
        "group": [],
    },
    result_expires=36000,
)

@codecov

codecov Bot commented Sep 24, 2025 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.36842% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 88.11%. Comparing base (6b20dcd) to head (94d116e).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
celery/backends/database/extensions.py 95.23% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #9908      +/-   ##
==========================================
+ Coverage   88.09%   88.11%   +0.01%     
==========================================
  Files         153      154       +1     
  Lines       19469    19504      +35     
  Branches     2233     2240       +7     
==========================================
+ Hits        17151    17185      +34     
  Misses       2019     2019              
- Partials      299      300       +1     
Flag Coverage Δ
unittests 88.09% <97.36%> (+0.01%) ⬆️

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

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

@auvipy
auvipy self-requested a review September 25, 2025 04:41
Comment thread celery/backends/database/extensions.py Resolved
@dxdc

dxdc commented Sep 25, 2025

Copy link
Copy Markdown
Author

Some tests failed due to some internal codecov error, see codecov/codecov-action#1876

Seems like restarting those failed tests should solve the issue.

@Nusnus
Nusnus requested a review from Copilot September 27, 2025 14:09

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 introduces a schema extension mechanism for Celery's SQLAlchemy database result backend, enabling users to customize table schemas without monkey-patching. The design introduces a new SchemaExtension ABC and extends the DatabaseBackend constructor to accept schema extensions for task and group tables.

Key changes:

  • Adds SchemaExtension abstract base class and JsonResultExtension implementation
  • Extends DatabaseBackend.__init__ to accept and apply schema extensions
  • Updates model configure methods to support extension application

Reviewed Changes

Copilot reviewed 4 out of 5 changed files in this pull request and generated 2 comments.

File Description
celery/backends/database/extensions.py New module defining the SchemaExtension ABC and JsonResultExtension implementation
celery/backends/database/__init__.py Updates DatabaseBackend constructor to accept and apply schema extensions
celery/backends/database/models.py Extends Task.configure and TaskSet.configure methods to apply schema extensions
t/unit/backends/test_database_extensions.py Comprehensive test suite covering extension functionality and edge cases

Comment thread celery/backends/database/__init__.py Resolved

schemas = conf.database_table_schemas or {}
tablenames = conf.database_table_names or {}
schema_extensions = schema_extensions or conf.get('database_schema_extensions', {})

Copilot AI Sep 27, 2025

Copy link

Choose a reason for hiding this comment

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

The fallback to conf.get('database_schema_extensions', {}) introduces a new configuration option that isn't documented in the PR. Should we document this configuration option, or is the parameter-only approach preferred for this feature?

Suggested change
schema_extensions = schema_extensions or conf.get('database_schema_extensions', {})
schema_extensions = schema_extensions or {}

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I think it's worth keeping as a configuration option for ease for implementation. Where should we document it? Happy to add that.

dxdc added 3 commits October 4, 2025 20:38
Introduce schema_extensions argument to DatabaseBackend, allowing users
to modify Task/TaskSet table definitions in a clean, composable way.

Extensions implement SchemaExtension and can adjust column types,
add indexes, or other schema-level changes.

This is a backwards-compatible alternative to monkey-patching,
and a more flexible approach than PR celery#9907. Related to issue celery#9501.
@auvipy auvipy added this to the 5.7.0 milestone Oct 5, 2025
@auvipy

auvipy commented Mar 3, 2026

Copy link
Copy Markdown
Member

@ChickenBenny would you mind checking this?

@ChickenBenny

Copy link
Copy Markdown
Contributor

Great job making the model more flexible! This is a fantastic approach. However, I have two operational concerns regarding this, as follows:

  1. Schema Migrations (e.g., Alembic): Since users will now maintain custom extended models, relying on Celery's default metadata.create_all() might become risky, especially if future Celery updates introduce new core columns to the base Task table. Should we explicitly mention in the documentation that users adopting this feature should manage their own schema migrations (like using Alembic) to avoid conflicts?

  2. Core Field Override Safety: Is there any built-in safeguard (or planned validation) to prevent users from accidentally overriding core required fields (e.g., task_id, status, date_done) when subclassing?

Thanks for the awesome contribution!

@auvipy

auvipy commented Mar 5, 2026

Copy link
Copy Markdown
Member

good points @ChickenBenny . I already had one open long ago but faced some negetive feedback #8532

@ChickenBenny

Copy link
Copy Markdown
Contributor

I completely agree. Alembic is a much more robust and controlled tool for managing database schemas

@dxdc

dxdc commented Mar 5, 2026

Copy link
Copy Markdown
Author

Thanks for the thoughtful review @ChickenBenny!

Both excellent points:

  1. Schema Migrations: You're right - I've added a prominent note in the extensions.py module docstring making it clear that users who adopt schema extensions should manage their own migrations (e.g., via Alembic). Celery's metadata.create_all() is additive and won't drop/alter existing columns, but it also won't handle migration conflicts if future Celery releases add new core columns. I think documentation is the right approach here rather than baking Alembic into Celery itself (as explored in intial schema migrations setup for sqlalchemy models  #8532).

However, we could bake this into the SchemaExtension itself, then celery -A myapp db upgrade just calls ext.migrate(table_name) for each extension inside an Alembic migration context. Similar approach for validate.

class SchemaExtension(ABC):

    @abstractmethod
    def extend(self, table, metadata):
        ...

    def validate(self, table, inspector):
        return []

    def migrate(self, table_name):
        """Optional: run Alembic operations to align DB with extend()."""
        pass


class JsonResultExtension(SchemaExtension):

    def extend(self, table, metadata):
        table.c.result.type = JSON()

    def validate(self, table, inspector):
        cols = {c['name']: c for c in inspector.get_columns(table.name)}
        actual = type(cols.get('result', {}).get('type', PickleType())).__name__
        if actual.upper() not in ('JSON', 'JSONB'):
            return [f"result column is {actual}, expected JSON - run migrations"]
        return []

    def migrate(self, table_name):
        from alembic import op
        op.alter_column(table_name, 'result',
                        type_=JSON(), existing_type=PickleType())
  1. Core Field Override Safety: I've added a lightweight safeguard - a _warn_if_protected check that runs after extensions are applied. It logs a warning if an extension modifies the type of a core column (task_id, status, date_done, id, taskset_id). It doesn't block the change (there can be legitimate reasons to modify types), but it makes it very visible. Added tests for both the warning and no-false-positive cases.

Comment thread celery/backends/database/__init__.py Resolved

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

Copilot reviewed 4 out of 4 changed files in this pull request and generated 6 comments.

Comment thread celery/backends/database/__init__.py Resolved
Comment thread celery/backends/database/__init__.py Resolved
Comment on lines +109 to +113
schema_extensions = schema_extensions or conf.get('database_schema_extensions', {})
self.task_cls.configure(
schema=schemas.get('task'),
name=tablenames.get('task'))
name=tablenames.get('task'),
extensions=schema_extensions.get('task', ()))

Copilot AI Mar 30, 2026

Copy link

Choose a reason for hiding this comment

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

schema_extensions = schema_extensions or conf.get('database_schema_extensions', {}) will unexpectedly ignore an explicitly passed empty mapping ({}) and fall back to config. If you want config to be the default only when the argument is omitted, please check schema_extensions is None explicitly. Also, database_schema_extensions is a new config key; it should be documented alongside other database backend settings (e.g., in docs/userguide/configuration.rst).

Copilot uses AI. Check for mistakes.
Comment on lines 60 to +64
cls.__table__.schema = schema
cls.id.default.schema = schema
cls.__table__.name = name or cls.__tablename__

if extensions:

Copilot AI Mar 30, 2026

Copy link

Choose a reason for hiding this comment

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

_warn_if_protected appears to key off table.name, but configure() sets cls.__table__.name = name or cls.__tablename__ first. If an app customizes database_table_names, the table name will no longer be celery_taskmeta, and the “protected column” warning may never trigger. Consider basing the protected-column lookup on the model’s canonical __tablename__ (or otherwise passing the logical table kind) so the warning still works when tables are renamed.

Copilot uses AI. Check for mistakes.
Comment on lines 128 to +132
cls.__table__.schema = schema
cls.id.default.schema = schema
cls.__table__.name = name or cls.__tablename__

if extensions:

Copilot AI Mar 30, 2026

Copy link

Choose a reason for hiding this comment

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

Same issue for TaskSet.configure(): since cls.__table__.name may be overridden via database_table_names, any protected-column warning logic that depends on table.name can be bypassed. Using cls.__tablename__ (or an explicit logical identifier) for protected-column checks would keep warnings working even when tables are renamed.

Copilot uses AI. Check for mistakes.
@auvipy auvipy modified the milestones: 5.7.0, 5.8.0 Aug 29, 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.

5 participants