On Sun, 22 Nov 2026 at 07:46, Tender Wang <[email protected]> wrote:
>
> I found a follow-up case for #19912.
> When a concurrent update causes MERGE to switch from MATCHED to NOT
> MATCHED BY SOURCE, ExecMergeMatched() builds an all-NULL plan slot for
> the action.
> If that action moves the target row to another partition, ExecInsert()
> evaluates RETURNING using context->planSlot, which still contains the
> source values from the original match.

Ugh yes, that's annoying. Well spotted.

> The attached patch adds an optional returningSlot to ModifyTableContext.
> ExecMergeMatched() sets it to the current action’s plan slot before
> calling ExecUpdateAct() and clears it when the call returns.
> This lets both update paths use the same slot for RETURNING and
> preserves the original plan slot for any subsequent WHEN NOT MATCHED
> BY TARGET action.
> ExecModifyTable() initializes the override to NULL, so ExecInsert()
> uses context->planSlot whenever no override is set.

Hmm, I don't like that solution because it's somewhat delocalised,
which I think makes it fragile if new code is added using
context->planSlot, instead of your new returningSlot.

I think a better (more localised) solution is to have
ExecMergeMatched() swap out context->planSlot while it executes the
NOT MATCHED BY SOURCE action. That feels more robust, because it
removes any chance of any code called while executing the action
seeing the old stale source values. Something like v2, attached.

Also, I don't think merge-match-recheck is the right place to test
this, since it's not about rechecking AND conditions. I've added new
tests to merge-not-matched, based on the ones added before for bug
#19912, testing both left and full joins.

(I didn't remove your tests from v2 yet, because I wanted to confirm
that they also passed with the new code.)

Regards,
Dean
diff --git a/src/backend/executor/nodeModifyTable.c b/src/backend/executor/nodeModifyTable.c
new file mode 100644
index b000650..98f7385
--- a/src/backend/executor/nodeModifyTable.c
+++ b/src/backend/executor/nodeModifyTable.c
@@ -3309,7 +3309,7 @@ ExecMergeMatched(ModifyTableContext *con
 	List	   *actionStates;
 	TupleTableSlot *newslot = NULL;
 	TupleTableSlot *rslot = NULL;
-	TupleTableSlot *planSlot = context->planSlot;
+	TupleTableSlot *origPlanSlot = context->planSlot;
 	EState	   *estate = context->estate;
 	ExprContext *econtext = mtstate->ps.ps_ExprContext;
 	bool		isNull;
@@ -3334,7 +3334,7 @@ ExecMergeMatched(ModifyTableContext *con
 	 * or NOT MATCHED BY SOURCE tuple and UPDATE/DELETE actions.
 	 */
 	econtext->ecxt_scantuple = resultRelInfo->ri_oldTupleSlot;
-	econtext->ecxt_innertuple = planSlot;
+	econtext->ecxt_innertuple = origPlanSlot;
 	econtext->ecxt_outertuple = NULL;
 
 	/*
@@ -3727,18 +3727,16 @@ lmerge_matched:
 									 * contain the NOT MATCHED BY TARGET
 									 * tuple, with non-NULL source values.
 									 * Instead, build a new all-NULL plan slot
-									 * for use locally, leaving
-									 * context->planSlot unchanged for any
-									 * subsequent NOT MATCHED BY TARGET
-									 * actions.  We don't bother setting
-									 * "junk" attributes, since they are no
-									 * longer needed.
+									 * to replace context->planSlot while we
+									 * execute the NOT MATCHED BY SOURCE
+									 * action.  We don't bother setting "junk"
+									 * attributes, since they aren't needed.
 									 */
-									planSlot =
+									context->planSlot =
 										MakeSingleTupleTableSlot(context->planSlot->tts_tupleDescriptor,
 																 &TTSOpsVirtual);
-									ExecStoreAllNullTuple(planSlot);
-									econtext->ecxt_innertuple = planSlot;
+									ExecStoreAllNullTuple(context->planSlot);
+									econtext->ecxt_innertuple = context->planSlot;
 
 									/*
 									 * If we have both NOT MATCHED BY SOURCE
@@ -3839,7 +3837,7 @@ lmerge_matched:
 												 false,
 												 resultRelInfo->ri_oldTupleSlot,
 												 newslot,
-												 planSlot);
+												 context->planSlot);
 					break;
 
 				case CMD_DELETE:
@@ -3848,7 +3846,7 @@ lmerge_matched:
 												 true,
 												 resultRelInfo->ri_oldTupleSlot,
 												 NULL,
-												 planSlot);
+												 context->planSlot);
 					break;
 
 				case CMD_NOTHING:
@@ -3871,12 +3869,13 @@ lmerge_matched:
 	 * Successfully executed an action or no qualifying action was found.
 	 */
 out:
-	if (planSlot != context->planSlot)
+	if (context->planSlot != origPlanSlot)
 	{
 		econtext->ecxt_innertuple = NULL;
 		if (resultRelInfo->ri_projectReturning != NULL)
 			resultRelInfo->ri_projectReturning->pi_exprContext->ecxt_outertuple = NULL;
-		ExecDropSingleTupleTableSlot(planSlot);
+		ExecDropSingleTupleTableSlot(context->planSlot);
+		context->planSlot = origPlanSlot;
 	}
 
 	if (ItemPointerIsValid(&lockedtid))
diff --git a/src/test/isolation/expected/merge-match-recheck.out b/src/test/isolation/expected/merge-match-recheck.out
new file mode 100644
index 10ef2ad..4d25cb8
--- a/src/test/isolation/expected/merge-match-recheck.out
+++ b/src/test/isolation/expected/merge-match-recheck.out
@@ -650,3 +650,30 @@ key|balance|status|val
 (1 row)
 
 step c1: COMMIT;
+
+starting permutation: break_match_pa merge_nmbs_move_pa c2 select_pa2 c1
+step break_match_pa: UPDATE target_pa SET key = 2 WHERE key = 1;
+step merge_nmbs_move_pa: 
+  MERGE INTO target_pa t
+  USING target s
+  ON s.key = t.key
+  WHEN MATCHED THEN
+    UPDATE SET val = s.val
+  WHEN NOT MATCHED BY SOURCE THEN
+    UPDATE SET balance = 210
+  RETURNING s.key AS source_key, t.balance;
+ <waiting ...>
+step c2: COMMIT;
+step merge_nmbs_move_pa: <... completed>
+source_key|balance
+----------+-------
+          |    210
+(1 row)
+
+step select_pa2: SELECT balance FROM ONLY target_pa2;
+balance
+-------
+    210
+(1 row)
+
+step c1: COMMIT;
diff --git a/src/test/isolation/expected/merge-not-matched.out b/src/test/isolation/expected/merge-not-matched.out
new file mode 100644
index acfe5dc..6ed324a
--- a/src/test/isolation/expected/merge-not-matched.out
+++ b/src/test/isolation/expected/merge-not-matched.out
@@ -53,6 +53,59 @@ id|val
 (2 rows)
 
 
+starting permutation: p_u1 p_m2a p_s2
+step p_u1: UPDATE p_tgt SET id = 22, val = val||' updated' WHERE id = 2;
+step p_m2a: 
+  WITH m AS (
+    MERGE INTO p_tgt t USING src s ON t.id = s.id
+      WHEN MATCHED THEN UPDATE SET id = t.id+100, val = t.val||' matched '||s.val
+      WHEN NOT MATCHED BY SOURCE THEN UPDATE SET id = t.id+100, val = t.val||' not matched'
+      RETURNING merge_action(), s.*, t.tableoid::regclass, t.*
+  )
+  SELECT * FROM m ORDER BY 5;
+
+merge_action|id|val|tableoid| id|val                   
+------------+--+---+--------+---+----------------------
+UPDATE      |  |   |p_tgt_p2|101|t1 not matched        
+UPDATE      |  |   |p_tgt_p2|122|t2 updated not matched
+(2 rows)
+
+step p_s2: SELECT tableoid::regclass, * FROM p_tgt ORDER BY id;
+tableoid| id|val                   
+--------+---+----------------------
+p_tgt_p2|101|t1 not matched        
+p_tgt_p2|122|t2 updated not matched
+(2 rows)
+
+
+starting permutation: b1 p_u1 p_m2a c1 p_s2
+step b1: BEGIN ISOLATION LEVEL READ COMMITTED;
+step p_u1: UPDATE p_tgt SET id = 22, val = val||' updated' WHERE id = 2;
+step p_m2a: 
+  WITH m AS (
+    MERGE INTO p_tgt t USING src s ON t.id = s.id
+      WHEN MATCHED THEN UPDATE SET id = t.id+100, val = t.val||' matched '||s.val
+      WHEN NOT MATCHED BY SOURCE THEN UPDATE SET id = t.id+100, val = t.val||' not matched'
+      RETURNING merge_action(), s.*, t.tableoid::regclass, t.*
+  )
+  SELECT * FROM m ORDER BY 5;
+ <waiting ...>
+step c1: COMMIT;
+step p_m2a: <... completed>
+merge_action|id|val|tableoid| id|val                   
+------------+--+---+--------+---+----------------------
+UPDATE      |  |   |p_tgt_p2|101|t1 not matched        
+UPDATE      |  |   |p_tgt_p2|122|t2 updated not matched
+(2 rows)
+
+step p_s2: SELECT tableoid::regclass, * FROM p_tgt ORDER BY id;
+tableoid| id|val                   
+--------+---+----------------------
+p_tgt_p2|101|t1 not matched        
+p_tgt_p2|122|t2 updated not matched
+(2 rows)
+
+
 starting permutation: u1 m2b s2
 step u1: UPDATE tgt SET id = 22, val = val||' updated' WHERE id = 2;
 step m2b: 
@@ -111,3 +164,62 @@ id|val
 22|t2 updated not matched
 (3 rows)
 
+
+starting permutation: p_u1 p_m2b p_s2
+step p_u1: UPDATE p_tgt SET id = 22, val = val||' updated' WHERE id = 2;
+step p_m2b: 
+  WITH m AS (
+    MERGE INTO p_tgt t USING src s ON t.id = s.id
+      WHEN MATCHED THEN UPDATE SET id = t.id+100, val = t.val||' matched '||s.val
+      WHEN NOT MATCHED BY SOURCE THEN UPDATE SET id = t.id+100, val = t.val||' not matched'
+      WHEN NOT MATCHED BY TARGET THEN INSERT VALUES (s.id, s.val)
+      RETURNING merge_action(), s.*, t.tableoid::regclass, t.*
+  )
+  SELECT * FROM m ORDER BY 5;
+
+merge_action|id|val|tableoid| id|val                   
+------------+--+---+--------+---+----------------------
+INSERT      | 2|s2 |p_tgt_p1|  2|s2                    
+UPDATE      |  |   |p_tgt_p2|101|t1 not matched        
+UPDATE      |  |   |p_tgt_p2|122|t2 updated not matched
+(3 rows)
+
+step p_s2: SELECT tableoid::regclass, * FROM p_tgt ORDER BY id;
+tableoid| id|val                   
+--------+---+----------------------
+p_tgt_p1|  2|s2                    
+p_tgt_p2|101|t1 not matched        
+p_tgt_p2|122|t2 updated not matched
+(3 rows)
+
+
+starting permutation: b1 p_u1 p_m2b c1 p_s2
+step b1: BEGIN ISOLATION LEVEL READ COMMITTED;
+step p_u1: UPDATE p_tgt SET id = 22, val = val||' updated' WHERE id = 2;
+step p_m2b: 
+  WITH m AS (
+    MERGE INTO p_tgt t USING src s ON t.id = s.id
+      WHEN MATCHED THEN UPDATE SET id = t.id+100, val = t.val||' matched '||s.val
+      WHEN NOT MATCHED BY SOURCE THEN UPDATE SET id = t.id+100, val = t.val||' not matched'
+      WHEN NOT MATCHED BY TARGET THEN INSERT VALUES (s.id, s.val)
+      RETURNING merge_action(), s.*, t.tableoid::regclass, t.*
+  )
+  SELECT * FROM m ORDER BY 5;
+ <waiting ...>
+step c1: COMMIT;
+step p_m2b: <... completed>
+merge_action|id|val|tableoid| id|val                   
+------------+--+---+--------+---+----------------------
+INSERT      | 2|s2 |p_tgt_p1|  2|s2                    
+UPDATE      |  |   |p_tgt_p2|101|t1 not matched        
+UPDATE      |  |   |p_tgt_p2|122|t2 updated not matched
+(3 rows)
+
+step p_s2: SELECT tableoid::regclass, * FROM p_tgt ORDER BY id;
+tableoid| id|val                   
+--------+---+----------------------
+p_tgt_p1|  2|s2                    
+p_tgt_p2|101|t1 not matched        
+p_tgt_p2|122|t2 updated not matched
+(3 rows)
+
diff --git a/src/test/isolation/specs/merge-match-recheck.spec b/src/test/isolation/specs/merge-match-recheck.spec
new file mode 100644
index 6054fca..62a8ec0
--- a/src/test/isolation/specs/merge-match-recheck.spec
+++ b/src/test/isolation/specs/merge-match-recheck.spec
@@ -103,6 +103,17 @@ step "merge_bal_pa"
 	UPDATE SET balance = balance * 8, val = t.val || ' when3'
   RETURNING t.key, old.balance AS old_balance, new.balance AS new_balance, t.status, t.val;
 }
+step "merge_nmbs_move_pa"
+{
+  MERGE INTO target_pa t
+  USING target s
+  ON s.key = t.key
+  WHEN MATCHED THEN
+    UPDATE SET val = s.val
+  WHEN NOT MATCHED BY SOURCE THEN
+    UPDATE SET balance = 210
+  RETURNING s.key AS source_key, t.balance;
+}
 step "merge_bal_tg"
 {
   WITH t AS (
@@ -145,6 +156,7 @@ step "merge_delete_tg"
 
 step "select1" { SELECT * FROM target; }
 step "select1_pa" { SELECT * FROM target_pa; }
+step "select_pa2" { SELECT balance FROM ONLY target_pa2; }
 step "select1_tg" { SELECT * FROM target_tg; }
 step "c1" { COMMIT; }
 
@@ -170,6 +182,7 @@ step "update7" { UPDATE target t SET bal
 step "update_bal1" { UPDATE target t SET balance = 50, val = t.val || ' updated by update_bal1' WHERE t.key = 1; }
 step "update_bal1_pa" { UPDATE target_pa t SET balance = 50, val = t.val || ' updated by update_bal1_pa' WHERE t.key = 1; }
 step "update_bal1_tg" { UPDATE target_tg t SET balance = 50, val = t.val || ' updated by update_bal1_tg' WHERE t.key = 1; }
+step "break_match_pa" { UPDATE target_pa SET key = 2 WHERE key = 1; }
 step "c2" { COMMIT; }
 
 # merge_status sees concurrently updated row and rechecks WHEN conditions, but recheck passes and final status = 's2'
@@ -217,3 +230,6 @@ permutation "update1_tg" "merge_delete_t
 # merge_delete sees concurrently updated row and rechecks WHEN conditions, recheck fails, so final balance is 100
 permutation "update_bal1" "merge_delete" "c2" "select1" "c1"
 permutation "update_bal1_tg" "merge_delete_tg" "c2" "select1_tg" "c1"
+
+# A concurrent update breaks the match, then the NMBS action moves the row.
+permutation "break_match_pa" "merge_nmbs_move_pa" "c2" "select_pa2" "c1"
diff --git a/src/test/isolation/specs/merge-not-matched.spec b/src/test/isolation/specs/merge-not-matched.spec
new file mode 100644
index ba658c4..6c671e6
--- a/src/test/isolation/specs/merge-not-matched.spec
+++ b/src/test/isolation/specs/merge-not-matched.spec
@@ -8,16 +8,22 @@ setup
   CREATE TABLE tgt (id int, val text);
   INSERT INTO src VALUES (2, 's2');
   INSERT INTO tgt VALUES (1, 't1'), (2, 't2');
+
+  CREATE TABLE p_tgt (id int, val text) PARTITION BY RANGE (id);
+  CREATE TABLE p_tgt_p1 PARTITION OF p_tgt FOR VALUES FROM (1) TO (100);
+  CREATE TABLE p_tgt_p2 PARTITION OF p_tgt DEFAULT;
+  INSERT INTO p_tgt VALUES (1, 't1'), (2, 't2');
 }
 
 teardown
 {
-  DROP TABLE src, tgt;
+  DROP TABLE src, tgt, p_tgt;
 }
 
 session s1
 step b1 { BEGIN ISOLATION LEVEL READ COMMITTED; }
 step u1 { UPDATE tgt SET id = 22, val = val||' updated' WHERE id = 2; }
+step p_u1 { UPDATE p_tgt SET id = 22, val = val||' updated' WHERE id = 2; }
 step c1 { COMMIT; }
 
 session s2
@@ -30,6 +36,15 @@ step m2a {
   )
   SELECT * FROM m ORDER BY 4;
 }
+step p_m2a {
+  WITH m AS (
+    MERGE INTO p_tgt t USING src s ON t.id = s.id
+      WHEN MATCHED THEN UPDATE SET id = t.id+100, val = t.val||' matched '||s.val
+      WHEN NOT MATCHED BY SOURCE THEN UPDATE SET id = t.id+100, val = t.val||' not matched'
+      RETURNING merge_action(), s.*, t.tableoid::regclass, t.*
+  )
+  SELECT * FROM m ORDER BY 5;
+}
 step m2b {
   WITH m AS (
     MERGE INTO tgt t USING src s ON t.id = s.id
@@ -40,10 +55,31 @@ step m2b {
   )
   SELECT * FROM m ORDER BY 4;
 }
+step p_m2b {
+  WITH m AS (
+    MERGE INTO p_tgt t USING src s ON t.id = s.id
+      WHEN MATCHED THEN UPDATE SET id = t.id+100, val = t.val||' matched '||s.val
+      WHEN NOT MATCHED BY SOURCE THEN UPDATE SET id = t.id+100, val = t.val||' not matched'
+      WHEN NOT MATCHED BY TARGET THEN INSERT VALUES (s.id, s.val)
+      RETURNING merge_action(), s.*, t.tableoid::regclass, t.*
+  )
+  SELECT * FROM m ORDER BY 5;
+}
 step s2 { SELECT * FROM tgt ORDER BY id; }
+step p_s2 { SELECT tableoid::regclass, * FROM p_tgt ORDER BY id; }
 
+# Test returning source values under left join
 permutation u1 m2a s2
 permutation b1 u1 m2a c1 s2
 
+# As above, but merge moves rows to new partition
+permutation p_u1 p_m2a p_s2
+permutation b1 p_u1 p_m2a c1 p_s2
+
+# Test returning source values under full join
 permutation u1 m2b s2
 permutation b1 u1 m2b c1 s2
+
+# As above, but merge moves rows to new partition
+permutation p_u1 p_m2b p_s2
+permutation b1 p_u1 p_m2b c1 p_s2

Reply via email to