Skip to content

Fix: DatabaseBackend now honors result_serializer (#3025) - #10536

Merged
auvipy merged 4 commits into
celery:mainfrom
ghirailghiro:issue-3025-database-result-serializer
Sep 1, 2026
Merged

auvipy merged 4 commits into
celery:mainfrom
ghirailghiro:issue-3025-database-result-serializer

Conversation

@ghirailghiro

Copy link
Copy Markdown
Contributor

Summary

Fixes #3025.

The database (SQLAlchemy) result backend always stored Task.result and
TaskSet.result as a Python pickle, regardless of the configured
result_serializer. This is because both columns were declared as
sa.PickleType, a SQLAlchemy TypeDecorator that pickles/unpickles values
automatically at the ORM level, before Celery's own encode()/decode()
(the methods that actually respect result_serializer) ever get a chance
to run. Every other backend (mongodb, redis/KeyValueStoreBackend) already
calls self.encode()/self.decode() explicitly — the database backend was
the one exception.

Two earlier attempts tried to fix this (#2881, #5907) and stalled — not on
the core design (column as raw bytes + explicit encode()/decode(),
which is what this PR does too, matching mongodb.py), but because neither
handled the backward-compatibility question raised in review on #5907:
rows written before the fix are always pickle, no matter what
result_serializer says, since that's exactly the bug. After fixing the
write path, those pre-existing rows would fail to decode under a
non-pickle serializer.

This PR closes that gap: _decode_stored_result() tries self.decode()
first, and falls back to pickle.loads() if that fails, so existing
databases keep working unmodified after the upgrade — only new writes use
the configured serializer.

  • celery/backends/database/models.py: Task.result / TaskSet.result
    changed from PickleType to LargeBinary. No schema/DDL change:
    PickleType's underlying storage is already LargeBinary, confirmed by
    comparing generated CREATE TABLE output across sqlite/postgres/mysql.
  • celery/backends/database/__init__.py: _update_result/_save_group
    now call self.encode() before storing; _get_task_meta_for/
    _restore_group decode through the new fallback-aware helper.
  • docs/userguide/configuration.rst: documents the behavior change and
    the backward-compatibility guarantee under the database backend section
    and the result_serializer setting.

Test plan

  • New regression tests in t/unit/backends/test_database.py assert
    the raw bytes in the DB are valid JSON when result_serializer
    is json (not a pickle blob), for both task and group results.
  • New test simulates a pre-fix row (raw pickle written directly via
    SQL) and confirms it's still readable — and logs a warning — with
    result_serializer='json' configured.
  • Existing suite passes unmodified: pytest t/unit/backends/test_database.py
    (80 passed).
  • Manual verification: exceptions (mark_as_failure/mark_as_retry)
    round-trip correctly under both pickle and json.
  • Manual verification script covering forward path, legacy pickle
    rows, and a mixed old/new table — confirmed it fails against the
    pre-fix code and passes against the fix.

The SQLAlchemy result backend stored Task.result and TaskSet.result as
sa.PickleType, which pickles/unpickles values at the ORM level regardless
of the configured result_serializer. This meant results were always
persisted as pickle even when result_serializer was set to json, msgpack,
etc., silently ignoring the setting.

Switch both columns to sa.LargeBinary and have the backend call
self.encode()/self.decode() explicitly, the same pattern already used by
the mongodb and redis backends. The column's DDL is unchanged (PickleType
already stores as a binary column under the hood), so no schema migration
is needed.

Rows written before this fix are always a raw pickle blob no matter what
result_serializer was configured, so decoding falls back to pickle.loads
when the configured serializer can't parse a row. This keeps existing
databases readable after upgrading; only newly written results use the
configured serializer.
@codecov

codecov Bot commented Aug 30, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 88.81%. Comparing base (e362d69) to head (56431fc).

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #10536      +/-   ##
==========================================
+ Coverage   88.80%   88.81%   +0.01%     
==========================================
  Files         153      153              
  Lines       19953    19971      +18     
  Branches     2331     2333       +2     
==========================================
+ Hits        17719    17737      +18     
  Misses       1938     1938              
  Partials      296      296              
Flag Coverage Δ
unittests 88.78% <100.00%> (+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 requested review from auvipy and a lite review from Copilot August 30, 2026 15:13

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 fixes the SQLAlchemy (database) result backend so that it stores task and group results using Celery’s configured result_serializer (via encode()/decode()), while preserving backward compatibility by reading legacy rows that were written as pickles.

Changes:

  • Change DB models to store result as raw bytes (LargeBinary) instead of ORM-level PickleType.
  • Encode results explicitly on write, and decode explicitly on read with a legacy pickle fallback.
  • Add regression tests and document the behavior change + compatibility guarantee.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.

File Description
celery/backends/database/models.py Switch result columns from PickleType to LargeBinary so Celery controls serialization.
celery/backends/database/__init__.py Encode results on write; decode on read via a helper that supports legacy pickle rows.
t/unit/backends/test_database.py Add tests asserting JSON bytes are stored when configured, plus legacy pickle fallback coverage.
docs/userguide/configuration.rst Document that the database backend now honors result_serializer and how legacy rows are handled.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread celery/backends/database/__init__.py Resolved
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
@auvipy auvipy added this to the 5.8.0 milestone Aug 31, 2026
@auvipy
auvipy requested a balanced review from Copilot August 31, 2026 15:29

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

we have to keep it backward compatible

Comment thread celery/backends/database/models.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 1 comment.

Suppressed comments (1)

Previously missed (1) — in code that hasn't changed since the last review.

celery/backends/database/init.py:210

  • This helper also handles TaskSet rows from _restore_group, so this warning incorrectly labels group payloads as task results. Could it use a backend-neutral label to keep the diagnostic accurate?
                'Task result payload could not be decoded using the '

Comment thread celery/backends/database/__init__.py Resolved
ghirailghiro and others added 2 commits August 31, 2026 23:39
_save_group/_restore_group now go through self.prepare_value()/
result_from_tuple(), the same pattern already used by
BaseKeyValueStoreBackend, so GroupResult.save()/.restore() keeps working
when result_serializer isn't pickle (a real GroupResult isn't directly
JSON-encodable, so it needs to be flattened to its tuple form on the way
in and reconstructed on the way out).

test_save__restore__delete_group now saves/restores an actual GroupResult
instead of a plain dict, since that's the shape every other backend
already assumes; a new test covers the same round-trip under json
specifically, both flagged in PR review.
@auvipy auvipy modified the milestones: 5.8.0, 5.7.0 Sep 1, 2026
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.

Celery results are NOT obeying results serializer config in databases

3 participants