Skip to content

Fix shared retry_kwargs mutation in autoretry - #10461

Merged
auvipy merged 9 commits into
celery:mainfrom
Namraa310806:fix-shared-retry-kwargs
Aug 16, 2026
Merged

auvipy merged 9 commits into
celery:mainfrom
Namraa310806:fix-shared-retry-kwargs

Conversation

@Namraa310806

Copy link
Copy Markdown
Contributor

Description

Add a regression test covering the getattr(task, "retry_kwargs", {}) code path in add_autoretry_behaviour().

The existing regression test added in #10458 verifies that retry_kwargs passed explicitly via the task decorator is not mutated during autoretry. However, it does not cover the case where retry_kwargs is defined as a class attribute on a shared base Task class.

This test verifies that:

  • retry_kwargs inherited from a shared base Task class is not mutated during autoretry.
  • The shared base class dictionary remains unchanged after one task retries.
  • Separate tasks inheriting from the same base class do not leak retry state (such as countdown) between each other.

This adds regression coverage for the getattr(task, "retry_kwargs", {}) branch without modifying the implementation.

Fixes #10456

Test:
Screenshot 2026-08-06 085329

Copilot AI lite review requested due to automatic review settings August 6, 2026 03:30

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 a concurrency/state-leak bug in Celery’s autoretry wrapper by ensuring the retry_kwargs mapping captured at task-registration time is not mutated across retry attempts, including when retry_kwargs is inherited as a shared class attribute from a base Task.

Changes:

  • Copy retry_kwargs per retry attempt inside add_autoretry_behaviour() before injecting calculated values like countdown / max_retries.
  • Add a regression test that specifically exercises the getattr(task, "retry_kwargs", {}) branch when retry_kwargs is shared via a base Task class.
  • Verify the shared base dict remains unchanged after retries and that tasks inheriting from the same base don’t share mutated retry state.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
celery/app/autoretry.py Avoids mutating shared retry_kwargs by copying into a per-attempt dict before adding backoff/override values.
t/unit/tasks/test_tasks.py Adds regression coverage for inherited/shared base-class retry_kwargs to prevent cross-task leakage.

@auvipy
auvipy self-requested a review August 6, 2026 15:12
@codecov

codecov Bot commented Aug 6, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 88.68%. Comparing base (f52429c) to head (eddd107).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #10461   +/-   ##
=======================================
  Coverage   88.68%   88.68%           
=======================================
  Files         153      153           
  Lines       19852    19853    +1     
  Branches     2311     2311           
=======================================
+ Hits        17606    17607    +1     
  Misses       1948     1948           
  Partials      298      298           
Flag Coverage Δ
unittests 88.66% <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 commented Aug 6, 2026

Copy link
Copy Markdown
Member

can you cross check the changes or approach followed in this PR #10465 and see which might be better

@Namraa310806

Namraa310806 commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for pointing me to #10465. I cross-checked its approach locally against the relevant autoretry tests.

Both approaches are trying to solve the same underlying issue: avoiding mutation of the retry_kwargs captured when add_autoretry_behaviour() creates the run() wrapper.

The main difference I found is how the per-invocation copy is introduced.

Approach in #10465

#10465 currently does:

retry_kwargs = dict(retry_kwargs)

inside the nested run() wrapper.

The problem with this approach is Python's scoping behavior. Since retry_kwargs is assigned inside run(), Python treats retry_kwargs as a local variable throughout that function.

Therefore, when evaluating:

retry_kwargs = dict(retry_kwargs)

the retry_kwargs on the right-hand side refers to that local variable rather than the value from the enclosing add_autoretry_behaviour() scope. At that point, the local variable has not been initialized yet.

I applied the implementation from #10465 locally and ran the same autoretry-focused unit test selection. The result was:

32 failed, 3 passed, 99 deselected
Screenshot 2026-08-06 220336

The failures included existing autoretry behavior such as:

  • backoff and jitter
  • autoretry_for inherited from a base task
  • override_autoretry_for inherited from a base task
  • class-based autoretry configurations

There is also a related effect on the regression test in #10465.

The test attempts to retrieve the captured dictionary using:

free_vars = task.run.__code__.co_freevars
shared_retry_kwargs = task.run.__closure__[
    free_vars.index("retry_kwargs")
].cell_contents

However, once retry_kwargs is assigned inside run(), Python no longer treats it as a free variable captured from the enclosing scope. As a result, "retry_kwargs" is not present in co_freevars, and that regression test fails as well.

Approach in #10461

In #10461, I keep the captured configuration and the per-invocation retry state separate:

call_retry_kwargs = dict(retry_kwargs)

The original retry_kwargs therefore remains the value captured from add_autoretry_behaviour(), while call_retry_kwargs is local to the current invocation.

Only the per-invocation dictionary receives dynamically generated values:

call_retry_kwargs["countdown"] = ...
call_retry_kwargs["max_retries"] = ...

and that dictionary is then passed to:

task.retry(exc=exc, **call_retry_kwargs)

This keeps the two responsibilities separate:

  • retry_kwargs remains the captured/configured retry state and is not mutated.
  • call_retry_kwargs contains the runtime retry state for the current invocation.

I ran the same autoretry-focused test selection with this approach and got:

35 passed, 99 deselected
Screenshot 2026-08-06 220523

This includes the existing backoff/jitter, inherited configuration, and class-based autoretry tests, as well as the regression coverage for shared base-class retry_kwargs.

@Namraa310806

Copy link
Copy Markdown
Contributor Author

Based on the Python scoping behavior and the results from running the same
autoretry-focused tests against both implementations, I think keeping a
distinct per-invocation dictionary (call_retry_kwargs) is the more
appropriate approach here.

It avoids mutating the captured retry_kwargs without rebinding that closure
variable inside run(), and therefore preserves the existing autoretry
behavior while isolating invocation-specific values such as countdown and
max_retries.

That's my conclusion from comparing the two implementations locally.

@auvipy

auvipy commented Aug 6, 2026

Copy link
Copy Markdown
Member

great! would you mind checking the failing integration tests as well?

@Namraa310806

Copy link
Copy Markdown
Contributor Author

I looked into the failing/canceled checks — they're not related to this diff.

The root cause is that useblacksmith/setup-docker-builder@v2 requires a cache-key input as of v2, but docker.yml and smoke-tests.yml on main still call it without one. As a result, every Docker/Smoke-test job fails with:

Error during Blacksmith builder setup: The 'cache-key' input is required...

This then cascades into the larger set of canceled jobs through matrix fail-fast.

I confirmed that this is broken on main itself, independent of this branch.

If it's useful, I'm happy to open a separate PR adding the missing cache-key to each job. Let me know and I'll put that up — I didn't want to send an unrelated CI PR without checking first in case it's already being tracked or fixed elsewhere.

The unit test jobs that actually exercise this diff aren't among the failures, for what it's worth.

@auvipy

auvipy commented Aug 8, 2026

Copy link
Copy Markdown
Member

can you check the possibility of improving the test coverage?

@Namraa310806

Copy link
Copy Markdown
Contributor Author

Thanks for the suggestion! I took another look through the existing autoretry tests and the regression coverage added in this PR.

One area that looks like a genuine gap is the override_max_retries path. The current regression test verifies that invocation-specific countdown values don't leak into the shared retry_kwargs, but the same copied dictionary is also used when override_max_retries injects a temporary max_retries value. That path isn't currently covered by the shared-dictionary regression.

I'll work on extending the regression coverage to verify that both invocation-specific values (countdown and max_retries) remain isolated and don't mutate the shared retry_kwargs.

@auvipy auvipy added this to the 5.7.0 milestone Aug 16, 2026
@auvipy
auvipy merged commit 583fa06 into celery:main Aug 16, 2026
350 checks passed
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.

autoretry_for + retry_backoff mutate a single retry_kwargs dict shared across all executions of a task, corrupting backoff under concurrent execution

3 participants