Skip to content

Fix Signature.clone() sharing kwargs with the original signature - #10571

Merged
auvipy merged 2 commits into
celery:mainfrom
tritsystem:fix/signature-clone-kwargs-alias
Sep 7, 2026
Merged

auvipy merged 2 commits into
celery:mainfrom
tritsystem:fix/signature-clone-kwargs-alias

Conversation

@tritsystem

Copy link
Copy Markdown
Contributor

Description

Fixes #10560.

Signature.clone() with no kwargs override hands the new signature the same
kwargs dict object
as the source. options is defensively deepcopy-d on
clone; kwargs was passed straight through by reference:

if args or kwargs or opts:
    args, kwargs, opts = self._merge(args, kwargs, opts)
else:
    args, kwargs, opts = self.args, self.kwargs, self.options   # <- by reference
... Signature.from_dict({..., 'kwargs': kwargs, 'options': deepcopy(opts), ...})

_merge() also returns self.kwargs unchanged when no kwargs override is
given (dict(self.kwargs, **kwargs) if kwargs else self.kwargs) and via its
immutable short-circuit, so sig.clone(priority=5), sig.clone(args=(1,)) and
sig.si(...).clone() alias too — only sig.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

from celery import Celery

app = Celery(set_as_current=False)

@app.task
def add(x, y):
    return x + y

original = add.s(1, 2)
clone_a = original.clone()
clone_b = original.clone()

assert clone_a.kwargs is original.kwargs   # True  -- should be False
clone_a.kwargs['x'] = 999
print(original.kwargs)   # {'x': 999}      -- corrupted by mutating a "clone"
print(clone_b.kwargs)    # {'x': 999}      -- 3-way aliasing

Fix

Give the clone its own mapping when kwargs is still self.kwargs, mirroring the
copy already made for options:

if kwargs is self.kwargs:
    kwargs = dict(kwargs)

Placed right before from_dict so it covers every path (no-override, option-only
/ args-only via _merge, immutable) without touching _merge's other callers.

A shallow dict copy, not deepcopy — deliberate. Canvas primitives keep
live objects in kwargs: chunks / xmap / xstarmap hold a task Signature
and a lazy iterator, _chord holds its body. Deep-copying those would consume
generators and turn nested signatures into plain dicts. Shallow-copying the
mapping is enough to stop clone.kwargs[...] = ... from reaching the original,
and matches what _merge already does for the kwargs-override path
(dict(self.kwargs, **kwargs)).

Tests

t/unit/tasks/test_canvas.py:

  • test_clone_does_not_alias_kwargs — 3-way independence + mutation isolation
  • test_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 main without the one-line change and passes with it.

test_freeze_tasks_body_is_group is modified. It asserted that
top_group.freeze() replaced the original chord's body.tasks with cloned,
group_index-stamped signatures. That only happened because _chord.clone()
does signature.kwargs['body'] = maybe_signature(..., clone=True) 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 a reference to. The test now asserts on
the frozen clone that lands in top_group.tasks[0], with an added subtest that
the caller's original chord and its body elements are untouched. group_index
assignment 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 + isort clean.

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.

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]>

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.

🟢 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 independent kwargs mapping when kwargs would otherwise be self.kwargs by reference.
  • Add regression tests covering no-override clone, non-kwargs overrides, immutable signatures, and the shallow-copy contract.
  • Adjust test_freeze_tasks_body_is_group to assert on the frozen cloned chord inside the group (and assert the original chord/body are not mutated by freeze()).
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.

@auvipy
auvipy requested review from auvipy and a balanced review from Copilot September 7, 2026 10:16
@codecov

codecov Bot commented Sep 7, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 88.89%. Comparing base (4c6619c) to head (70864e7).
⚠️ Report is 1 commits behind head on main.

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           
Flag Coverage Δ
unittests 88.87% <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 Sep 7, 2026

Copy link
Copy Markdown
Member

I would prefer this one.

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.

🟢 Approval recommended

The focused fix is well tested, with no unresolved issues.

Review details
  • Files reviewed: 2/2 changed files
  • Comments generated: 0 new
  • Review effort level: Balanced

@auvipy auvipy added this to the 5.7.0 milestone Sep 7, 2026
…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]>
@tritsystem

Copy link
Copy Markdown
Contributor Author

Heads-up on the last push (70864e7): the first CI run went red on one integration test, t/integration/test_canvas.py::test_group::test_nested_group_chord_body_chain, and it's an informative failure rather than a regression.

That test is an xfail pinning #6734 ("Result object for groups containing chords which have a chain as their body time out"). It builds group((chord(identity.si(42), chain((identity.s(),))),)), expects res.get(timeout=short) to raise TimeoutError, and re-raises it to force XFAIL.

On this branch it no longer times out — res.get() returns [[42]], so pytest.raises(TimeoutError) fails with "DID NOT RAISE", which xfail(raises=TimeoutError) doesn't absorb.

The mechanism lines up with #6734's root cause: group(...).delay() freezes the group and clones the chord via _chord.clone(), which does signature.kwargs['body'] = maybe_signature(body, clone=True). Before this PR, super().clone() returned a chord whose .kwargs was aliased with the original, so that body reassignment landed in a shared dict and the GroupResult's promise wiring tracked a stale body signature — which never resolved. With the de-aliasing, each clone gets its own kwargs, the body links correctly, and the group result resolves.

70864e7 drops the xfail marker and the timeout scaffolding from that test and asserts res.get() == [[42]] directly, with a comment explaining the link. If CI comes back green on the integration matrix, this PR also closes #6734.

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.

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.

🟢 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-kwargs override 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

@auvipy

auvipy commented Sep 7, 2026

Copy link
Copy Markdown
Member

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

@auvipy
auvipy merged commit a8e89e5 into celery:main Sep 7, 2026
285 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.

Signature.clone() aliases .kwargs with the original when called without override arguments

3 participants