Skip to content

Fix SaveAwareArgResolver ignored in nested mutations - #2784

Merged
spawnia merged 10 commits into
masterfrom
fix-nested-pre-save-arg-resolver
Jul 29, 2026
Merged

Fix SaveAwareArgResolver ignored in nested mutations#2784
spawnia merged 10 commits into
masterfrom
fix-nested-pre-save-arg-resolver

Conversation

@spawnia

@spawnia spawnia commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator

Fixes a regression from #2777 (v6.68.0) where SaveAwareArgResolver::runBeforeSave() was only honoured at the top level of a mutation. One level down inside nested HasMany/HasOne/ManyToMany/BelongsTo mutations, the pre-save resolver ran AFTER the child model was already persisted — silently discarding its attribute changes.

The root cause: ResolveNested defaulted to a partitioner that unconditionally routed all resolver-bearing args into the post-save set. Only ModelMutationDirective::executeMutation() overrode this with the pre-save-aware variant; all 12 nested resolver call sites used the broken default.

The fix collapses nestedArgResolversWithoutPreSave into nestedArgResolvers so the correct behavior is the default everywhere. When root is not a Model, behavior is unchanged. When root is a Model, SaveAwareArgResolver instances with runBeforeSave=true stay in the regular set so SaveModel executes them before persisting. The now-redundant explicit partitioner in ModelMutationDirective is removed.

Coverage spans the create, update and upsert branches of nested relation mutations, since all three build ResolveNested with the same default partitioner. Each new test fails without the fix, leaving the attributes null.

Second fix: silent data loss when a @nest child collides with a sibling

Making nestedArgResolvers the default widened the reach of a separate, pre-existing bug (from #2764, v6.68.0): lifting pre-save resolvers out of @nest wrote them into the flat regular set keyed by the child's bare field name. Field names are unique per input type, not across an input tree, so a name coincidence silently discarded an argument. Three ways to lose data:

  1. A plain sibling difficulty: Int next to a @nest child difficulty: LocationInput @geocode — different columns, no semantic conflict, yet difficulty persisted as null.
  2. Same-named children of two sibling @nest blocks — one resolver silently never ran.
  3. A @nest child named id clobbering the primary key that UpdateModel and UpsertModel consume to identify the row.

Widening the default also turned case 3 into a hard error where the colliding name matched a relation operation namespace (create/update/…), since NestedOneToMany and friends then iterate an ArgumentSet where they expect a list.

Resolvers are not name-addressed — SaveModel iterates them by value and discards the keys — so lifted resolvers now travel as an ordered list rather than a name-keyed map, handed to the saver through the new PreSaveArgumentsAware interface. Lifting also no longer mutates the nest it reads from, which matters because FieldValue caches transformed argument sets per path and @spread shares Argument objects across rebuilt sets.

The capability check is what keeps this non-regressive: UpdateModel and UpsertModel forward it to their own previous (via the shared DelegatesPreSaveArguments trait), and a saver that can not consume the list gets nothing lifted, so its children run post-save exactly as on master. Both declining paths are covered by unit tests: a previous that does not implement the interface, and one that implements it but returns null. Third-party savers built as new ResolveNested($closure) — the pattern documented in docs/master/concepts/arg-resolvers.md — fall into the first case.

All colliding resolvers now run in schema order, so the last write wins where two of them target the same column. The interface is deliberately not marked @api.

Still open, and out of scope here: @nest inside a relation operation namespace has its lifted pre-save resolvers ignored entirely, because NestedOneToMany and friends never consume them. The hard error is gone; whether @nest should be legal there at all is a separate design question.

One unrelated commit names the strict flag on the existing in_array() calls in src/, which is purely cosmetic and easy to drop if you would rather keep it out.

🤖 Generated with Claude Code

The default arg partitioner in ResolveNested unconditionally routed all
arguments with resolvers into the post-save set. This meant
SaveAwareArgResolver::runBeforeSave() was only honoured at the top level
(where ModelMutationDirective explicitly passed the pre-save-aware
partitioner) but silently ignored one level down inside nested
HasMany/HasOne/ManyToMany/BelongsTo mutations.

Collapse the two partitioner methods into one that always respects
pre-save semantics. When root is not a Model, behavior is unchanged
(all resolvers go to nested). When root is a Model,
SaveAwareArgResolvers with runBeforeSave=true stay in the regular set
so SaveModel can execute them before persisting.
@spawnia
spawnia requested a review from Copilot July 28, 2026 14:50
@spawnia
spawnia marked this pull request as ready for review July 28, 2026 14:50

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Fixes a regression where SaveAwareArgResolver::runBeforeSave() was not honored inside nested model mutations, causing pre-save arg resolvers to run after child models were already persisted.

Changes:

  • Make ArgPartitioner::nestedArgResolvers() pre-save aware by default (and remove the redundant nestedArgResolversWithoutPreSave() variant).
  • Remove the explicit partitioner override from ModelMutationDirective, relying on the corrected default behavior.
  • Add/extend integration test coverage for pre-save custom directives inside nested relations and add latitude/longitude test fields/columns.

Reviewed changes

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

Show a summary per file
File Description
src/Execution/Arguments/ArgPartitioner.php Makes the default nested/regular argument partitioning honor SaveAwareArgResolver::runBeforeSave() for model roots and lifts pre-save resolvers out of @nest recursively.
src/Schema/Directives/ModelMutationDirective.php Removes the now-unnecessary custom arg partitioner override when constructing ResolveNested.
tests/Unit/Execution/Arguments/ArgPartitionerTest.php Updates unit tests to reflect the new default partitioning behavior and removes coverage for the deleted method.
tests/Integration/Schema/Directives/CreateDirectiveTest.php Adds integration coverage demonstrating pre-save custom directive behavior in nested HasMany and deeper nested relations.
tests/database/migrations/2018_02_28_000003_create_testbench_tasks_table.php Adds latitude/longitude columns to support new integration assertions.
tests/database/migrations/2018_02_28_000004_create_testbench_posts_table.php Adds latitude/longitude columns to support deep relation integration assertions.
tests/Utils/Models/Task.php Documents latitude/longitude properties for test model.
tests/Utils/Models/Post.php Documents latitude/longitude properties for test model.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

spawnia added 3 commits July 29, 2026 09:12
Lifting pre-save resolvers out of @nest keys them by bare field name, so a
@nest child replaces a sibling of the same name in the regular arg set
without raising an error. Making nestedArgResolvers() the default
partitioner widens where this can happen, so pin down the current
behavior.
The update and upsert branches of NestedOneToMany build ResolveNested with
the same default partitioner as create, so they are fixed by the same
change. Both tests fail without it, the attributes end up null.
@spawnia

spawnia commented Jul 29, 2026

Copy link
Copy Markdown
Collaborator Author

Self-reviewed at 18882fb (thorough, full)

🤖 Posted by Claude Code

Lifting keyed resolvers by bare field name, so a child of a @nest whose
name collided with a sibling silently replaced it. Field names are unique
per input type, not across an input tree.

Lifted resolvers now travel as an ordered list handed to the saver through
the PreSaveArgumentsAware capability interface. Savers that can not consume
them get nothing lifted, so their children run post-save as before.

🤖 Generated with Claude Code

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

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

Comments suppressed due to low confidence (1)

src/Execution/Arguments/ArgPartitioner.php:194

  • The docblock says this method "Leaves the given arguments untouched", but it does mutate Argument objects by attaching resolver metadata via attachNestedArgResolver(). Consider rephrasing to avoid implying the input is completely immutable (only that arguments are not removed/re-keyed).
     * Leaves the given arguments untouched, as they may be shared with cached
     * or spread ArgumentSets that the caller still owns.

spawnia added 5 commits July 29, 2026 12:05
Pins that children still resolve after save when a PreSaveArgumentsAware
saver returns null, matching the behavior of a saver that does not
implement the interface at all.

🤖 Generated with Claude Code
🤖 Generated with Claude Code
🤖 Generated with Claude Code
Recursing on a single Argument removes the throw-away one-element
ArgumentSet the recursive call immediately unwrapped again.

🤖 Generated with Claude Code
UpdateModel and UpsertModel had byte-identical implementations.

🤖 Generated with Claude Code
@spawnia

spawnia commented Jul 29, 2026

Copy link
Copy Markdown
Collaborator Author

Self-reviewed at 89a56a2 (standard, full)

🤖 Posted by Claude Code

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

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

Comments suppressed due to low confidence (1)

src/Execution/Arguments/SaveModel.php:84

  • Lifted pre-save arguments from @nest are appended after all other pre-save arguments (array_values($preSave->arguments)), so their execution order is no longer tied to the schema/argument order relative to non-nested pre-save resolvers. If an input type places a @nest field before a sibling pre-save resolver that writes the same attribute(s), the "last write wins" outcome will be inverted (the nested one always runs last). Consider interleaving lifted arguments into the pre-save execution sequence based on the position of the @nest field in the original ArgumentSet, or otherwise preserving a single stable order across both lifted and non-lifted pre-save resolvers.
        foreach ([
            ...array_values($preSave->arguments),
            ...$this->preSaveArguments,
        ] as $preSaveArgument) {
            $resolver = $preSaveArgument->resolver;
            assert($resolver instanceof SaveAwareArgResolver, 'Resolver must be a SaveAwareArgResolver because we partitioned for it.');
            $resolver($model, $preSaveArgument->value);
        }

@spawnia
spawnia merged commit 584959c into master Jul 29, 2026
94 checks passed
@spawnia
spawnia deleted the fix-nested-pre-save-arg-resolver branch July 29, 2026 12:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants