Repository navigation
Fix Signature.clone() sharing kwargs with the original signature - #10571
Conversation
clone() with no `kwargs` override handed the new signature the *same* `kwargs` dict object as the source: the no-override branch assigns `kwargs = self.kwargs`, and `_merge()` returns `self.kwargs` unchanged both when no kwargs override is given (`... if kwargs else self.kwargs`) and via its immutable short-circuit. Only `options` was defensively `deepcopy`-d. So `sig.clone()`, `sig.clone(priority=5)`, `sig.clone(args=(1,))` and `sig.si(...).clone()` all produced a clone whose `kwargs` was aliased with the original's; mutating one mutated the source and every sibling clone. This also reaches `group.clone()` and `_chain.unchain_tasks()`, which rely on `clone()` for independence when fanning a signature into siblings. Give the clone its own mapping when `kwargs` is still `self.kwargs`, mirroring the copy already made for `options`. A shallow `dict` copy, not `deepcopy`: canvas primitives keep live objects in `kwargs` -- `chunks` / `xmap` / `xstarmap` hold a task `Signature` and a lazy iterator, `_chord` holds its `body` -- that must not be duplicated or consumed. `test_freeze_tasks_body_is_group` asserted that `top_group.freeze()` replaced the *original* chord's `body.tasks` with cloned, group-indexed signatures. That only happened because `_chord.clone()` wrote `signature.kwargs['body']` into the dict it shared with the source, i.e. via this bug -- freezing a container should not mutate a signature the caller still holds. Rewritten to assert on the frozen clone in `top_group.tasks`, plus a subtest that the caller's original is left untouched. Fixes celery#10560. Co-Authored-By: Claude Sonnet 5 <[email protected]>
There was a problem hiding this comment.
🟢 Approval recommended
The change is minimal and well-targeted, and the added/updated unit tests directly cover the previously broken aliasing behavior and its key call paths.
Pull request overview
This PR fixes a correctness bug in Celery canvas signatures where Signature.clone() could return a “clone” that shared the same kwargs dict object as the original signature (and as sibling clones), allowing mutations on one clone to corrupt others. The fix ensures kwargs is shallow-copied only when it would otherwise alias self.kwargs, avoiding deepcopy to preserve live objects (e.g., lazy iterators) stored in canvas kwargs.
Changes:
- Ensure
Signature.clone()gives the clone an independentkwargsmapping whenkwargswould otherwise beself.kwargsby reference. - Add regression tests covering no-override clone, non-
kwargsoverrides, immutable signatures, and the shallow-copy contract. - Adjust
test_freeze_tasks_body_is_groupto assert on the frozen cloned chord inside the group (and assert the original chord/body are not mutated byfreeze()).
File summaries
| File | Description |
|---|---|
celery/canvas.py |
Prevents Signature.clone() from aliasing kwargs with the original signature by shallow-copying the mapping when needed. |
t/unit/tasks/test_canvas.py |
Adds targeted tests for kwargs non-aliasing and updates a freeze-related test to avoid relying on mutation via the previous aliasing bug. |
Review details
- Files reviewed: 2/2 changed files
- Comments generated: 0
- Review effort level: Lite
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #10571 +/- ##
=======================================
Coverage 88.89% 88.89%
=======================================
Files 153 153
Lines 20058 20060 +2
Branches 2353 2354 +1
=======================================
+ Hits 17830 17832 +2
Misses 1929 1929
Partials 299 299
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. |
|
I would prefer this one. |
…ry#6734 is fixed by the clone de-aliasing The Signature.clone() kwargs de-aliasing in this PR resolves celery#6734 ("Result object for groups containing chords which have a chain as their body time out"): freezing the outer group cloned the chord through _chord.clone(), which reassigns signature.kwargs['body'] into a dict that was shared with the original signature, so the GroupResult's promise wiring tracked a stale body signature and never resolved. CI (integration test_canvas.py, all 8 broker/py matrix cells) went red on this branch because the test still asserted the timeout via pytest.raises(TimeoutError); with the fix res.get() returns [[42]] and "DID NOT RAISE" is a hard failure that xfail(raises=TimeoutError) does not absorb. Drop the xfail marker and the re-raise, and assert the correct result directly. Co-Authored-By: Claude Sonnet 5 <[email protected]>
|
Heads-up on the last push ( That test is an On this branch it no longer times out — The mechanism lines up with #6734's root cause:
I can't run the integration suite locally (needs a broker), so the "this fixes #6734" read rests on the failure being deterministic across all 8 broker/Python matrix cells plus the mechanism above — happy to be corrected if a maintainer sees it differently. |
There was a problem hiding this comment.
🟢 Approval recommended
The fix is focused and well tested; the remaining test-coverage comment is only a minor nit.
Review details
Suppressed comments (1)
t/unit/tasks/test_canvas.py:294
- Could this call include a non-
kwargsoverride so it actually exercises the immutable_merge()short-circuit? As written,clone()takes its no-override branch and never calls_merge(), so this test does not cover the path described by the preceding comment; the ordinary no-override path is already covered above.
clone = original.clone()
- Files reviewed: 3/3 changed files
- Comments generated: 0 new
- Review effort level: Balanced
|
lets see if the integrations tests pass now. we have docker setup for running integrations tests more easily locally, if in case that is needed |
Description
Fixes #10560.
Signature.clone()with nokwargsoverride hands the new signature the samekwargsdict object as the source.optionsis defensivelydeepcopy-d onclone;
kwargswas passed straight through by reference:_merge()also returnsself.kwargsunchanged when nokwargsoverride isgiven (
dict(self.kwargs, **kwargs) if kwargs else self.kwargs) and via itsimmutable short-circuit, so
sig.clone(priority=5),sig.clone(args=(1,))andsig.si(...).clone()alias too — onlysig.clone(kwargs={...})copies today.Mutating a clone mutates the source and every sibling clone. This reaches
group.clone()and_chain.unchain_tasks()([t.clone() for t in self.tasks]),which rely on
clone()for independence when fanning a signature into siblings.Minimal repro
Fix
Give the clone its own mapping when
kwargsis stillself.kwargs, mirroring thecopy already made for
options:Placed right before
from_dictso it covers every path (no-override, option-only/ args-only via
_merge, immutable) without touching_merge's other callers.A shallow
dictcopy, notdeepcopy— deliberate. Canvas primitives keeplive objects in
kwargs:chunks/xmap/xstarmaphold a taskSignatureand a lazy iterator,
_chordholds itsbody. Deep-copying those would consumegenerators and turn nested signatures into plain dicts. Shallow-copying the
mapping is enough to stop
clone.kwargs[...] = ...from reaching the original,and matches what
_mergealready does for thekwargs-override path(
dict(self.kwargs, **kwargs)).Tests
t/unit/tasks/test_canvas.py:test_clone_does_not_alias_kwargs— 3-way independence + mutation isolationtest_clone_does_not_alias_kwargs_with_non_kwargs_overrides—clone(priority=),clone(countdown=),clone(args=)test_clone_does_not_alias_kwargs_when_immutable—.si().clone()test_clone_kwargs_copy_is_shallow— pins the shallow contract (a nested value keeps its identity)Each fails on
mainwithout the one-line change and passes with it.test_freeze_tasks_body_is_groupis modified. It asserted thattop_group.freeze()replaced the original chord'sbody.taskswith cloned,group_index-stamped signatures. That only happened because_chord.clone()does
signature.kwargs['body'] = maybe_signature(..., clone=True)into the dictit shared with the source — i.e. via this bug. Freezing a container should not
mutate a signature the caller still holds a reference to. The test now asserts on
the frozen clone that lands in
top_group.tasks[0], with an added subtest thatthe caller's original chord and its body elements are untouched.
group_indexassignment on the frozen output is unchanged.
Verification
python -m pytest -q t/unit/tasks/test_canvas.py t/unit/tasks/test_stamping.py t/unit/tasks/test_chord.py t/unit/tasks/test_result.py t/unit/app/test_builtins.py t/unit/tasks/test_tasks.py→ 930 passed, 0 failed.flake8+isortclean.Note re #10560 / #10561
@auvipy — you invited a fix with test coverage on the issue. #10561 took the
deepcopy(kwargs)route the issue text suggested and hit the generator-exhaustion/ nested-signature / cycle regressions the Copilot reviewer flagged there; this PR
is the smaller shallow-copy alternative that sidesteps all of them. Happy to close
this if you'd rather land that one.