Skip to content

Database Backend: Use configured serializer, instead of always pickling. - #5907

Closed
martincapello wants to merge 12 commits into
celery:mainfrom
martincapello:3025-db-result-serialization
Closed

martincapello wants to merge 12 commits into
celery:mainfrom
martincapello:3025-db-result-serialization

Conversation

@martincapello

@martincapello martincapello commented Jan 6, 2020 •

Copy link
Copy Markdown

Rebases the changes defined on #2881 (since they are almost 4 years old) and refactors them a bit.
Original PR's comment:

Use the BLOB as an sa.BLOB
Serialise the result an add to the db as bytes

Signed-off-by: martincapello <[email protected]>

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

Nice work! Some tests are breaking, strings seem to be converted to unicode now as far as I can tell. Could also please add a test for this backend, which uses the JSON serializer?

Comment thread celery/backends/database/models.py Outdated
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.BLOB, nullable=True)

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 we use LargeBinary with custom length instead so that the largest possible datatype is used (at least for MySQL):

I think PostgreSQL BYTEA columns have a limit of 1GB, so that RDBMS will be covered too.

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.

Sure, will update it

@martincapello

Copy link
Copy Markdown
Author

Will try to add a test as soon as I can.

@codecov

codecov Bot commented Jan 10, 2020 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 83.45%. Comparing base (77099b8) to head (4b0a1e4).
⚠️ Report is 2046 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #5907      +/-   ##
==========================================
+ Coverage   83.19%   83.45%   +0.26%     
==========================================
  Files         145      145              
  Lines       17126    16819     -307     
  Branches     2110     2100      -10     
==========================================
- Hits        14248    14037     -211     
+ Misses       2663     2566      -97     
- Partials      215      216       +1     

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

…sult serializer instead of pickle.

Signed-off-by: martincapello <[email protected]>
@martincapello

Copy link
Copy Markdown
Author

@georgepsarakis I ended up creating a clone of the database backend tests with a different setup (the result serializer is set to json in this case). Does this makes sense? Or do you prefer a fixtures based approach modifying the current class?

@martincapello

Copy link
Copy Markdown
Author

I have an improvement for this...will push a commit on monday

@georgepsarakis

Copy link
Copy Markdown
Contributor

@martincapello it would be best if all files for this backend are contained within a single file. It would make it easier for future contributions to write tests that will cover all serializers.

Perhaps parametrize helps here.

@martincapello

Copy link
Copy Markdown
Author

Oh yeah, I didn't mean to add a new file, just a new class into the same file. I tried to use parametrize, but ran into some issues that I will explain on monday.

@martincapello

martincapello commented Jan 13, 2020 •

Copy link
Copy Markdown
Author

This is the issue I ran into:
Let's say I choose to use this:

    @pytest.mark.parametrize(
        'result_serializer', ['pickle', 'json'],
        ids=['using pickle', 'using json']
    )

For instance, for the following test (which I believe it should be renamed as "test_is_serialized", but we can discuss this later, I'll keep the name as is for now):

    @pytest.mark.parametrize(
        'result_serializer', ['pickle', 'json'],
        ids=['using pickle', 'using json']
    )
    def test_is_pickled(self, result_serializer):
        self.app.conf.result_serializer = result_serializer
        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

When I run the above test, it fails for the json result serializer, because rindb.get('bar') doesn't have a member named "data", this is due to rindb.get('bar') returning a dict (which is what the json decoder returns as far as I understood).
So, a quick workaround makes the test look like this:

    @pytest.mark.parametrize(
        'result_serializer', ['pickle', 'json'],
        ids=['using pickle', 'using json']
    )
    def test_is_pickled(self, result_serializer):
        self.app.conf.result_serializer = result_serializer
        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'
        if result_serializer == 'json':      # <--- custom logic to workaround the issue
            assert rindb.get('bar').get('data') == 12345
        else:
            assert rindb.get('bar').data == 12345

As you can see, I needed to add some logic to determine the right assertion to do, which -IMO- goes against the spirit of using parametrize.
So, for this reason, as a first approach I decided to make a copy of the class that works for the json serializer. It worked, so I pushed a commit.
Then I realized that I could improve that.
So, what I propose now is to split the test_DatabaseBackend class in three classes:

  • test_DatabaseBackend: would contain the tests that must pass for all the serializers. It would contain almost all the tests it has right now, except the test_is_pickled.
  • test_DatabaseBackend_pickle_serializer: would contain only tests that pass when using the pickle serializer and we don't care what happens for other serializers. It would contain the test_is_pickled.
  • test_DatabaseBackend_json_serializer: would contain only tests that pass when using the json serializer and we don't care what happens for other serializers. It would contain a test which is almost the same as test_is_pickled but with the fixed assertion for the json serializer.

If I wasn't clear, it might be easier to take a look at PR's code 🙂

@martincapello

Copy link
Copy Markdown
Author

@georgepsarakis any thoughts on my latest updates?

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

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?

@georgepsarakis

Copy link
Copy Markdown
Contributor

When I run the above test, it fails for the json result serializer, because rindb.get('bar') doesn't have a member named "data", this is due to rindb.get('bar') returning a dict (which is what the json decoder returns as far as I understood).

I am not really sure how you end up getting this result when using the JSON serializer, since SomeClass instances cannot be encoded by the JSON encoder:

assert rindb.get('bar').get('data') == 12345

I think the most easy way to test, would be to make the expected result parametric too, as seen in other test cases.

@martincapello

Copy link
Copy Markdown
Author

@georgepsarakis

I am not really sure how you end up getting this result when using the JSON serializer, since SomeClass instances cannot be encoded by the JSON encoder:

SomeClass was not json serializable until I added this json method.

I think the most easy way to test, would be to make the expected result parametric too, as seen in other test cases.

Sorry, but I'm not following you here, because the expected result is the same (12345 in this case) for both serializers. Instead, the thing that changes is the structure of the rindb instance, which is the result object that have the actual values I want to test.

@auvipy auvipy modified the milestones: 4.4.x, 4.5 Feb 28, 2020
@auvipy auvipy modified the milestones: 4.5, 5.2 Jan 14, 2021
@auvipy auvipy modified the milestones: 5.2, 5.3 Oct 30, 2021
@auvipy auvipy self-assigned this Dec 10, 2021
@Nusnus Nusnus modified the milestones: 5.3, Future Feb 19, 2023
@k-sparrow

Copy link
Copy Markdown

Any news on this?

@auvipy auvipy modified the milestones: Future, 5.7.0 Jul 27, 2025
@auvipy auvipy closed this Aug 31, 2026
@auvipy auvipy modified the milestones: 5.7.0, 5.8.0 Aug 31, 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.

6 participants