Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,4 @@ htmlcov/
coverage.xml
test.db
pip-wheel-metadata/
.vscode/
10 changes: 8 additions & 2 deletions celery/backends/database/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

from vine.utils import wraps

from kombu.utils.encoding import ensure_bytes

from celery import states
from celery.backends.base import BaseBackend
from celery.exceptions import ImproperlyConfigured
Expand Down Expand Up @@ -129,7 +131,7 @@ def _store_result(self, task_id, result, state, traceback=None,
def _update_result(self, task, result, state, traceback=None,
request=None):

meta = self._get_result_meta(result=result, state=state,
meta = self._get_result_meta(result=ensure_bytes(self.encode(result)), state=state,
traceback=traceback, request=request,
format_date=False, encode=True)

Expand All @@ -156,6 +158,9 @@ def _get_task_meta_for(self, task_id):
task = self.task_cls(task_id)
task.status = states.PENDING
task.result = None
else:
task.result = self.decode(task.result)

data = task.to_dict()
if 'args' in data:
data['args'] = self.decode(data['args'])
Expand All @@ -168,7 +173,7 @@ def _save_group(self, group_id, result):
"""Store the result of an executed group."""
session = self.ResultSession()
with session_cleanup(session):
group = self.taskset_cls(group_id, result)
group = self.taskset_cls(group_id, ensure_bytes(self.encode(result)))
session.add(group)
session.flush()
session.commit()
Expand All @@ -182,6 +187,7 @@ def _restore_group(self, group_id):
group = session.query(self.taskset_cls).filter(
self.taskset_cls.taskset_id == group_id).first()
if group:
group.result = self.decode(group.result)
return group.to_dict()

@retry
Expand Down
5 changes: 2 additions & 3 deletions celery/backends/database/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from datetime import datetime

import sqlalchemy as sa
from sqlalchemy.types import PickleType

from celery import states
from celery.five import python_2_unicode_compatible
Expand All @@ -26,7 +25,7 @@ class Task(ResultModelBase):
primary_key=True, autoincrement=True)
task_id = sa.Column(sa.String(155), unique=True)
status = sa.Column(sa.String(50), default=states.PENDING)
result = sa.Column(PickleType, nullable=True)
result = sa.Column(sa.LargeBinary(length=(2 ** 31) - 1), nullable=True)

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.

isn't this a breaking change?

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.

Not sure...I believe this could break celery apps using a serializer other than pickle when the results backend is sqlalchemy based.
According to the sqlalchemy docs:

PickleType builds upon the Binary type to apply Python’s pickle.dumps() to incoming objects, and pickle.loads() on the way out, allowing any pickleable Python object to be stored as a serialized binary field.

So, the database column should stay binary (I've been able to confirm this using postgres), the issue with PickleType is that Sqlalchemy pickles the objects automatically, despite having a json (or any but pickle) serializer configured for our app.

Hence, it seems that results from old task runs (tasks ran before this change) will have a pickled results instead of a json serialized one.

Can a celery client access to tasks results that were already ran in the past? I'm asking because am a celery noob.

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.

Can a celery client access to tasks results that were already ran in the past?

Yes, this is possible if someone has access to the result (task) ID.

This is indeed a breaking change, for configurations that used a different serializer than the pickle serializer. Perhaps this can be solved by allowing a transitional fallback to pickle.loads on a deserialization error, but only with a configuration option. So the new serializer support will be disabled by default, and we emit a warning for the deprecation in the next version.

How does that sound?

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.

Yes, this is possible if someone has access to the result (task) ID.

Alright then, let's suppose that this issue never existed and the serialization was working fine for any serializer. Also suppose someone started using celery configured with the json serializer, and after some time he changes his mind and decides to use pickle serializer. In this case, if someone has access to a result (task) ID corresponding to a task ran before the serializer change, would in this case the same deserialization error be expected?

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.

sqla should have support jsonfield as well, need to check that

date_done = sa.Column(sa.DateTime, default=datetime.utcnow,
onupdate=datetime.utcnow, nullable=True)
traceback = sa.Column(sa.Text, nullable=True)
Expand Down Expand Up @@ -83,7 +82,7 @@ class TaskSet(ResultModelBase):
id = sa.Column(sa.Integer, sa.Sequence('taskset_id_sequence'),
autoincrement=True, primary_key=True)
taskset_id = sa.Column(sa.String(155), unique=True)
result = sa.Column(PickleType, nullable=True)
result = sa.Column(sa.LargeBinary(length=(2 ** 31) - 1), nullable=True)

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.

a breaking change?

date_done = sa.Column(sa.DateTime, default=datetime.utcnow,
nullable=True)

Expand Down
64 changes: 52 additions & 12 deletions t/unit/backends/test_database.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ def __init__(self, data):
def __eq__(self, cmp):
return self.data == cmp.data

def __json__(self):
return {'data': self.data}


@skip.unless_module('sqlalchemy')
class test_session_cleanup:
Expand All @@ -51,14 +54,20 @@ def test_context_raises(self):
session.close.assert_called_with()


@pytest.fixture(params=['pickle', 'json'])
def result_serializer(request):
if request.instance:
request.instance.app.conf.result_serializer = request.param


@skip.unless_module('sqlalchemy')
@skip.if_pypy()
@skip.if_jython()
@pytest.mark.usefixtures('result_serializer')
class test_DatabaseBackend:

def setup(self):
self.uri = 'sqlite:///test.db'
self.app.conf.result_serializer = 'pickle'

def test_retry_helper(self):
from celery.backends.database import DatabaseError
Expand Down Expand Up @@ -103,17 +112,6 @@ def test_mark_as_done(self):
assert tb.get_state(tid) == states.SUCCESS
assert tb.get_result(tid) == 42

def test_is_pickled(self):
tb = DatabaseBackend(self.uri, app=self.app)

tid2 = uuid()
result = {'foo': 'baz', 'bar': SomeClass(12345)}
tb.mark_as_done(tid2, result)
# is serialized properly.
rindb = tb.get_result(tid2)
assert rindb.get('foo') == 'baz'
assert rindb.get('bar').data == 12345

def test_mark_as_started(self):
tb = DatabaseBackend(self.uri, app=self.app)
tid = uuid()
Expand Down Expand Up @@ -208,6 +206,48 @@ def test_TaskSet__repr__(self):
assert 'foo', repr(TaskSet('foo' in None))


@skip.unless_module('sqlalchemy')
@skip.if_pypy()
@skip.if_jython()
class test_DatabaseBackend_pickle_serializer:

def setup(self):
self.uri = 'sqlite:///test.db'
self.app.conf.result_serializer = 'pickle'

def test_is_pickled(self):
tb = DatabaseBackend(self.uri, app=self.app)

tid2 = uuid()
result = {'foo': 'baz', 'bar': SomeClass(12345)}
tb.mark_as_done(tid2, result)
# is serialized properly.
rindb = tb.get_result(tid2)
assert rindb.get('foo') == 'baz'
assert rindb.get('bar').data == 12345


@skip.unless_module('sqlalchemy')
@skip.if_pypy()
@skip.if_jython()
class test_DatabaseBackend_json_serializer:

def setup(self):
self.uri = 'sqlite:///test.db'
self.app.conf.result_serializer = 'json'

def test_is_serialized(self):
tb = DatabaseBackend(self.uri, app=self.app)

tid2 = uuid()
result = {'foo': 'baz', 'bar': SomeClass(12345)}
tb.mark_as_done(tid2, result)
# is serialized properly.
rindb = tb.get_result(tid2)
assert rindb.get('foo') == 'baz'
assert rindb.get('bar').get('data') == 12345


@skip.unless_module('sqlalchemy')
@skip.if_pypy()
@skip.if_jython()
Expand Down