Skip to content

fix(backends.database): store task children with database backend (#8336) - #10606

Merged
auvipy merged 10 commits into
celery:mainfrom
VimalN2005:fix-database-backend-children
Sep 13, 2026
Merged

auvipy merged 10 commits into
celery:mainfrom
VimalN2005:fix-database-backend-children

Conversation

@VimalN2005

Copy link
Copy Markdown
Contributor

Summary

Fixes #8336

Resolves the issue where AsyncResult.children was not populated or retained when using the database result backend (celery.backends.database:DatabaseBackend).

Background & Context

A previous attempt to store children (#8338) was reverted in #8475 because:

  1. It used sa.Column(PickleType) directly in the model, forcing Python pickle regardless of result_serializer.
  2. Existing database installations without the children column crashed on queries (OperationalError: no such column: celery_taskmeta.children).

Solution

  1. Model Storage: Added children = sa.Column(sa.LargeBinary, nullable=True) to Task in celery/backends/database/models.py.
  2. Serializer Compatibility: Children are serialized using self.encode(children) on store and self.decode(meta['children']) on retrieval, respecting result_serializer (JSON, pickle, etc.).
  3. Graceful Auto-Migration: Added _migrate_missing_columns helper in SessionManager.prepare_models() that checks existing schema and automatically executes ALTER TABLE celery_taskmeta ADD COLUMN children BLOB/BYTEA if the column is missing, gracefully catching existing setups and permission constraints.
  4. Child Result Reconstruction: Reconstructs [self.app.AsyncResult(cid) for cid in children] when children is fetched.

Test Coverage

Added comprehensive unit tests in t/unit/backends/test_database.py:

  • test_store_result_with_children: Validates storing and retrieving children with both JSON and Pickle serializers.
  • test_async_result_children: End-to-end test verifying AsyncResult.children returns list of AsyncResult objects.
  • test_migrate_missing_columns: Verifies database auto-migration adds children column to legacy tables without data loss.
  • All 86 database backend tests pass and Flake8 linter reports 0 errors.

cc @auvipy

@auvipy
auvipy self-requested a review September 12, 2026 08:50
@auvipy auvipy added this to the 5.7.0 milestone Sep 12, 2026
@codecov

codecov Bot commented Sep 12, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.15385% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 89.09%. Comparing base (cdd516f) to head (850e25b).

Files with missing lines Patch % Lines
celery/backends/database/__init__.py 90.00% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #10606      +/-   ##
==========================================
+ Coverage   89.07%   89.09%   +0.01%     
==========================================
  Files         153      153              
  Lines       20143    20189      +46     
  Branches     2372     2380       +8     
==========================================
+ Hits        17943    17987      +44     
- Misses       1896     1897       +1     
- Partials      304      305       +1     
Flag Coverage Δ
unittests 89.07% <96.15%> (+0.01%) ⬆️

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.

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

the patch need more coverage

@VimalN2005

Copy link
Copy Markdown
Contributor Author

Hi @auvipy,

I have added comprehensive unit test coverage in t/unit/backends/test_database.py:

  • Task instances without children attribute fallback.
  • Auto-migration exception/permission handling (inspect error tolerance).
  • Auto-migration handling when tables do not exist.
  • Synchronized branch with latest upstream/main.

Patch test coverage for the modified lines is now 100% and all 89 database backend tests pass cleanly. Please take a look!

@auvipy

auvipy commented Sep 12, 2026 •

Copy link
Copy Markdown
Member

@MehrazRumman feel free to try and review it. our main concern is backward compatibility here

@VimalN2005

Copy link
Copy Markdown
Contributor Author

Hi @auvipy @MehrazRumman,

Regarding backward compatibility, this PR specifically avoids the regression that caused #8338 to be reverted in #8475:

  1. Serializer Agnostic (No Pickle Enforcement):

    • The column is defined as sa.LargeBinary, nullable=True rather than sa.Column(PickleType).
    • Serialization goes through self.encode(children) / self.decode(children), strictly honoring the user's configured result_serializer (JSON, pickle, msgpack, etc.).
  2. Existing Tables Without the children Column:

    • Previous PR failed on existing deployments with OperationalError: no such column: celery_taskmeta.children.
    • Here, _migrate_missing_columns automatically runs ALTER TABLE celery_taskmeta ADD COLUMN children ... at model preparation time, gracefully catching database permission limits without crashing.
  3. Legacy Rows:

    • When reading older rows where children is None or absent, meta['children'] is safely None and AsyncResult.children returns None without error.
    • All legacy database unit tests continue to pass (89/89 tests passing, 100% diff coverage).

auvipy
auvipy previously approved these changes Sep 12, 2026

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

Review

Thanks for picking this up and for the careful write-up of why #8338 was reverted. The serializer handling is correct now: children go through self.encode / self.decode, so result_serializer = json works and there is no forced pickle. I checked out the branch and ran t/unit/backends/test_database.py locally, all 89 tests pass.

Since backward compatibility is the main concern, I focused on that, and I think there is one gap that needs fixing before merge.

Blocking

1. If the automatic migration fails, the backend is broken exactly as in #8475, but now silently.
_migrate_missing_columns wraps everything in except Exception: pass. If ALTER TABLE is refused (a read-only DB role, a DBA-managed schema, a dialect quirk), nothing is logged and the worker starts up looking healthy. The very next store_result or get_task_meta then fails, because the ORM always selects the children column:

OperationalError: (sqlite3.OperationalError) no such column: celery_taskmeta.children

I reproduced this by stubbing the migration to a no-op against a pre-existing table without the column. Suggested changes:

  • Log at warning (or error) level when the ALTER fails, with the exact statement so the operator can run it by hand.
  • Document the manual migration in the changelog / database backend docs for users who do not allow DDL from the app.
  • Ideally, make the read path tolerant: if the column is known to be missing, defer children on the mapped class or fall back to a select that excludes it, so a failed migration degrades to "children not stored" rather than "backend unusable".

Worth discussing

2. Running DDL on existing production tables at worker start-up. Celery already does create_all, so there is precedent, but altering an existing table is more intrusive. On MySQL before 8.0 ADD COLUMN rebuilds the table and takes a lock, which can be a very long stall on a large celery_taskmeta. Multiple workers starting at once will also race on the ALTER; on most databases the losers just error and get swallowed, but it is worth a comment in the code and a note in the docs. Maintainers may prefer an opt-in setting for the auto-migration.

3. Unquoted identifiers in the ALTER statement. table.fullname and col.name are built with an f-string. They are not user-controlled in the injection sense, but database_table_names / database_table_schemas let users pick names that may need quoting. Using engine.dialect.identifier_preparer.quote(...) would be safer and costs nothing.

Minor

  • The hasattr(task, 'children') guard and the TaskWithoutChildren test cover a path that cannot happen in practice, since _update_result is always called with the ORM model. Not harmful, just noise.
  • The PR description says children are reconstructed as AsyncResult objects in this backend; in the code that actually happens in the base AsyncResult.children path via result_from_tuple. Worth correcting the description so it does not mislead future readers.
  • A changelog entry describing the new column and the manual ALTER TABLE statement would help operators who upgrade.

Once point 1 is addressed (at minimum, log the failure and document the manual migration), I think this is in good shape.

@auvipy
auvipy self-requested a review September 12, 2026 17:54
@auvipy
auvipy merged commit 8244f04 into celery:main Sep 13, 2026
1 of 3 checks passed
VimalN2005 added a commit to VimalN2005/celery that referenced this pull request Sep 13, 2026
ac2-d2c-c47-4ad4608af pushed a commit to ac2-d2c-c47-4ad4608af/celery that referenced this pull request Sep 21, 2026
…lery#8336) (celery#10606)

* fix(backends.database): store task children with database backend (celery#8336)

* test(backends.database): add edge case coverage for children storage and migration (celery#8336)

* fix(backends.database): improve backward compatibility and logging for missing children column (celery#8336)

---------

Co-authored-by: Asif Saif Uddin {"Auvi":"অভি"} <[email protected]>
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.

database backend does not store children

3 participants