Repository navigation
Conversation
Example UsageSchema 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 = backend2. Configure via app.conf.update(
database_url=backend_url,
database_schema_extensions={ # note key name
"task": [
WorkerHostnameExtension(),
StatusIndexExtension(),
],
"group": [],
},
result_expires=36000,
) |
Codecov Report❌ Patch coverage is
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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. |
|
Some tests failed due to some internal codecov error, see codecov/codecov-action#1876 Seems like restarting those failed tests should solve the issue. |
There was a problem hiding this comment.
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
SchemaExtensionabstract base class andJsonResultExtensionimplementation - Extends
DatabaseBackend.__init__to accept and apply schema extensions - Updates model
configuremethods 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 |
|
|
||
| schemas = conf.database_table_schemas or {} | ||
| tablenames = conf.database_table_names or {} | ||
| schema_extensions = schema_extensions or conf.get('database_schema_extensions', {}) |
There was a problem hiding this comment.
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?
| schema_extensions = schema_extensions or conf.get('database_schema_extensions', {}) | |
| schema_extensions = schema_extensions or {} |
There was a problem hiding this comment.
I think it's worth keeping as a configuration option for ease for implementation. Where should we document it? Happy to add that.
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.
|
@ChickenBenny would you mind checking this? |
|
Great job making the model more flexible! This is a fantastic approach. However, I have two operational concerns regarding this, as follows:
Thanks for the awesome contribution! |
|
good points @ChickenBenny . I already had one open long ago but faced some negetive feedback #8532 |
|
I completely agree. Alembic is a much more robust and controlled tool for managing database schemas |
|
Thanks for the thoughtful review @ChickenBenny! Both excellent points:
However, we could bake this into the SchemaExtension itself, then 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())
|
| 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', ())) |
There was a problem hiding this comment.
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).
| cls.__table__.schema = schema | ||
| cls.id.default.schema = schema | ||
| cls.__table__.name = name or cls.__tablename__ | ||
|
|
||
| if extensions: |
There was a problem hiding this comment.
_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.
| cls.__table__.schema = schema | ||
| cls.id.default.schema = schema | ||
| cls.__table__.name = name or cls.__tablename__ | ||
|
|
||
| if extensions: |
There was a problem hiding this comment.
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.
Co-authored-by: Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>
Motivation
Currently, customizing the schema of Celery’s SQLAlchemy result backend requires monkey-patching the models (
Task,TaskSet, orTaskExtended) directly. This makes it hard to:JSONinstead ofPickleType)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:
Passed into
DatabaseBackendvia a newschema_extensionsargument.Keys in
schema_extensionsmust 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
This results in:
resultcolumn usingJSONinstead ofPickleType.status.TaskSetschema.Changes in This PR
DatabaseBackend.__init__:Task.configureandTaskSet.configure.Task.configure/TaskSet.configure:extensionsargument.extend()method to the underlying SQLAlchemyTable.Added type hints for clarity.
Benefits
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.