Backtestshugorun-20260922-141813#15323

Issue #15323 Merged fix PR # Run 22 Sep 2026 · run-20260922-141813 gohugoio/hugo

tpl/collections: union silently returns an empty list when the two slice types differ

Better

Our patch was judged better than the merged fix.

In this judgment, Patch B = our agent, Patch A = the merged fix.

Both patches unblock mixed numeric unions by removing the early return only when both element kinds are numeric, and both keep the correct empty-return for genuinely incompatible types (e.g. []int ∪ []string). They diverge on the empty-first-slice case, which is the root cause. In Union the result slice is built from l1v.Type(), and when l1 is empty a prototype is chosen to drive number conversion. Patch B fixes this at the root: it sets the prototype to reflect.Zero(l1.Elem()), so the prototype carries l1's element type (== the result slice's type). convertNumber then targets l1's type, values are assignable, and []int{} ∪ []float64{2,3} correctly yields [2,3]. Because the prototype is only used for its type/kind (never appended), this is behavior-preserving for the same-type empty case and correct for the mixed case, with no panic. Patch A instead leaves the original prototype logic (l1vv = l2.Index(0)), so for an empty []int the prototype is float64; convertNumber leaves it float64, and A's new AssignableTo(l1.Elem()) guard then silently drops it (the guard exists precisely to avoid the panic of appending float64 into []int). The result is a lossy []int{}, and behavior becomes inconsistent: union (slice 1) (slice 2.0) = [1 2] but []int{} ∪ []float64{2.0} = [] — reintroducing a silent-empty inconsistency of the same family as the reported bug, now keyed on whether l1 happens to be empty. On correctness B is clearly better (consistent, non-lossy, root-cause). Tests: both fail-before/pass-after, but A's {[]int{}, []float64{1.0}, []int{}} encodes the lossy behavior, while B's cases (int8 mixing, empty-first with real elements) assert correct union semantics and cover more. Scope and size are comparable; B's prototype change with its explanatory comment is the more targeted, clearer fix, whereas A masks a symptom with a drop-guard. Winner: B.

The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.

Solve

13m 57s19 turns

Wall-clock time in the container

Full test suite

No new failures

3,764 passed · 101 skipped · 3,871 total

Contamination audit

Unknown

See the audit notes for this run

Patch size

20vs 17 merged

Changed lines, ours vs merged

What version of Hugo are you using (hugo version)?

<pre>
$ hugo version
hugo v0.166.0-DEV-ae07063fcc9a59c95838e83e7fdf12e326ebee7d darwin/arm64
</pre>

Does this issue reproduce with the latest release?

I built master at ae07063 and reproduced it there. I did not run a tagged release binary, so I have not confirmed it against one directly, though Union is unchanged in tpl/collections/collections.go.

What did you expect to see?

union either returning the union of its two arguments, or returning an error. It already errors for the other argument shapes it cannot handle, for example union does not support slices or arrays of uncomparable types and can't iterate over ....

What did you see instead?

union returns an empty slice, with no error, whenever the two arguments have different slice types and neither has an interface element type.

layouts/index.html:

{{ printf "%T" (slice 1) }}
{{ printf "%T" (slice 1.0) }}
union int,int    -> {{ union (slice 1) (slice 2) }}
union int,float  -> {{ union (slice 1) (slice 1.0) }}
union int,string -> {{ union (slice 1) (slice "a") }}
union lists      -> {{ union (slice 1 2) (slice 2.0 3.0) }}
intersect lists  -> {{ intersect (slice 1 2) (slice 2.0 3.0) }}

Output:

[]int
[]float64
union int,int    -> [1 2]
union int,float  -> []
union int,string -> []
union lists      -> []
intersect lists  -> [2]

intersect handles the same two mixed-type lists and returns [2], so the sibling functions disagree about whether these arguments are usable at all.

The cause is this early return in Union:

if l1v.Type() != l2v.Type() &&
	l1v.Type().Elem().Kind() != reflect.Interface &&
	l2v.Type().Elem().Kind() != reflect.Interface {
	return ins.r.Interface(), nil
}

ins.r is the empty slice made just above, so a caller gets an empty list rather than an error. It is reachable from ordinary templates because slice 1 is []int and slice 1.0 is []float64, and it also runs before the uncomparable-types check, so union (slice (slice 1)) (slice 2) returns [] instead of the error that check would raise.

Adding one element of another type to the first argument avoids it, since the slice then becomes []interface {}: union (slice 1 "x") (slice 1.0) returns [1 x].

Stack traceback or browser console output

None, no error is raised. That is the problem.


This is a different mechanism from #3411, which was closed in 2017 and is now locked with a note asking that related bugs be opened as new issues.

Happy to send a PR. Returning an error here would be a small change; making union accept mixed types the way intersect does is bigger, so I would rather you pick the direction first.

This issue was written primarily by Claude Code, including the reproduction above.

The two patches

Our patch+14 −6
tpl/collections/collections.goindex a44603b53..ba6e19827 100644@@ -656,7 +656,8 @@ func (ns *Namespace) Union(l1, l2 any) (any, error) {  			if l1v.Type() != l2v.Type() && 				l1v.Type().Elem().Kind() != reflect.Interface &&-				l2v.Type().Elem().Kind() != reflect.Interface {+				l2v.Type().Elem().Kind() != reflect.Interface &&+				!(hreflect.IsNumber(l1v.Type().Elem().Kind()) && hreflect.IsNumber(l2v.Type().Elem().Kind())) { 				return ins.r.Interface(), nil 			} @@ -678,11 +679,9 @@ func (ns *Namespace) Union(l1, l2 any) (any, error) { 			}  			if !l1vv.IsValid() {-				// The first slice may be empty. Pick the first value of the second-				// to use as a prototype.-				if l2v.Len() > 0 {-					l1vv = l2v.Index(0)-				}+				// The first slice may be empty. Use a zero value of its element+				// type as a prototype so results conform to the first slice's type.+				l1vv = reflect.Zero(l1v.Type().Elem()) 			}  			for j := range l2v.Len() {tpl/collections/collections_test.goindex 5562a80d6..01b6c17a8 100644@@ -667,6 +667,15 @@ func TestUnion(t *testing.T) { 		{[]string{"1", "2"}, []int{3}, []string{}, false}, 		{[]int{1, 2}, []string{"1", "2"}, []int{}, false}, +		// []A ∪ []B, mixed but compatible numeric types - #15323+		{[]int{1}, []float64{1.0}, []int{1}, false},+		{[]int{1, 2}, []float64{2.0, 3.0}, []int{1, 2, 3}, false},+		{[]float64{1.0}, []int{1}, []float64{1}, false},+		{[]int8{2, 4}, []int{1, 2, 4}, []int8{2, 4, 1}, false},+		// empty first slice, mixed numeric types - #15323+		{[]int8{}, []int{1, 2}, []int8{1, 2}, false},+		{[]int{}, []float64{2.0, 3.0}, []int{2, 3}, false},+ 		// []T ∪ []T 		{[]string{"a", "b", "c", "c"}, []string{"a", "b", "b"}, []string{"a", "b", "c"}, false}, 		{[]string{"a", "b"}, []string{"a", "b", "c"}, []string{"a", "b", "c"}, false}, 
Merged fix · PR #+15 −2
tpl/collections/collections.goindex a44603b53..fdb2501f6 100644@@ -657,7 +657,12 @@ func (ns *Namespace) Union(l1, l2 any) (any, error) { 			if l1v.Type() != l2v.Type() && 				l1v.Type().Elem().Kind() != reflect.Interface && 				l2v.Type().Elem().Kind() != reflect.Interface {-				return ins.r.Interface(), nil+				// Numeric element types unify through the conversion below,+				// mirroring how intersect matches numbers across types.+				if !hreflect.IsNumber(l1v.Type().Elem().Kind()) ||+					!hreflect.IsNumber(l2v.Type().Elem().Kind()) {+					return ins.r.Interface(), nil+				} 			}  			var (@@ -698,7 +703,8 @@ func (ns *Namespace) Union(l1, l2 any) (any, error) { 				case hreflect.IsNumber(kind): 					var err error 					l2vv, err = convertNumber(l2vv, typ)-					if err == nil {+					// The empty l1 prototype comes from l2 and may not match l1's element type.+					if err == nil && l2vv.Type().AssignableTo(l1v.Type().Elem()) { 						ins.appendIfNotSeen(l2vv) 					} 				case kind == reflect.Interface, kind == reflect.Struct, kind == reflect.Pointer:tpl/collections/collections_test.goindex 5562a80d6..47c51e01d 100644@@ -667,6 +667,13 @@ func TestUnion(t *testing.T) { 		{[]string{"1", "2"}, []int{3}, []string{}, false}, 		{[]int{1, 2}, []string{"1", "2"}, []int{}, false}, +		// numeric []A ∪ []B unify. See issue 15323.+		{[]int{1}, []float64{1.0}, []int{1}, false},+		{[]int{1, 2}, []float64{2.0, 3.0}, []int{1, 2, 3}, false},+		{[]float64{1.0}, []int{1, 2}, []float64{1.0, 2.0}, false},+		// the empty l1 prototype comes from l2, so appends must stay assignable to l1's element type.+		{[]int{}, []float64{1.0}, []int{}, false},+ 		// []T ∪ []T 		{[]string{"a", "b", "c", "c"}, []string{"a", "b", "b"}, []string{"a", "b", "c"}, false}, 		{[]string{"a", "b"}, []string{"a", "b", "c"}, []string{"a", "b", "c"}, false}, 

What the agent reported

The change is complete and clean. The AGENTS.md/CLAUDE.md deletions were pre-existing in the starting snapshot, not part of this work. No scratch files.

Summary

What was wrong. In tpl/collections/collections.go, Union had an early return that fired whenever the two arguments were different concrete slice types and neither had an interface{} element type — returning the freshly-made empty result slice with no error. This silently swallowed compatible numeric mixes: union (slice 1) (slice 1.0) returned [] instead of [1], even though the sibling intersect handles the same mixed numeric types correctly.

Direction chosen. The report offered two directions (return an error, or accept mixed types like intersect) and asked me to pick. "Return an error" and "accept all mixed types" both require changing the existing, currently-passing assertions at collections_test.go:667-668, which lock string↔int cross-type to an empty slice with no error — and I may not modify existing tests. So I took the scoped version of direction 2: make union accept numeric cross-type slices the way intersect does, leaving genuinely-incompatible pairs (string↔int) returning empty, consistent with both intersect and those existing tests.

What I changed (tpl/collections/collections.go, Union only):

  1. Added a fourth clause to the early-return guard so it is skipped when both element kinds are numeric (!(hreflect.IsNumber(...) && hreflect.IsNumber(...))). The existing second loop already converts numeric l2 elements to l1's element type via convertNumber, so they now flow through correctly.
  2. Fixed a panic this first change newly exposed: the empty-first-slice "prototype" branch borrowed l2's element (l2v.Index(0)), so []int8{} ∪ []int{1,2} tried to append int into an []int8 result — reflect.Set: value of type int is not assignable to type int8. Changed it to use reflect.Zero(l1v.Type().Elem()) so results conform to the first slice's own type. Verified this preserves all pre-existing empty-first-slice cases (interface/struct/pointer).

Test evidence (collections_test.go, TestUnion table — 6 new rows):

  • Before: the numeric rows made TestUnion fail ([5] Got [] expected [1]), and the empty-first-slice rows made it panic (reflect.Set: value of type int is not assignable to type int8 at collections.go:606).
  • After: ./bt-test ./tpl/collections/... → ok github.com/gohugoio/hugo/tpl/collections with TestUnion, TestIntersect, TestUnionResourcesMatch, and all package tests (including the template integration tests) passing. No existing test was modified, weakened, or reordered.

Requirements list:

  • Pick a direction (error vs. accept mixed types) — Done: chose the numeric-scoped "accept mixed types like intersect," with rationale above.
  • union should not silently return [] for compatible mixed types — Implemented + tested: numeric cross-type unions now combine (int∪float64, float64∪int, int8∪int, and empty-first-slice variants).
  • Sibling consistency with intersect — Implemented: union (slice 1 2) (slice 2.0 3.0) now returns [1 2 3] (was []) while intersect returns [2]; both now treat mixed numerics as usable.
  • union int,string case from the report — Skipped (intentional), with evidence: string↔int stays empty. Evidence: collections_test.go:667-668 assert this and may not be changed; intersect also returns empty for string↔int (collections_test.go:363-364) because hreflect does not convert string↔number (common/hreflect/convert.go:118). Erroring here was the reporter's alternative direction, not taken.
  • Uncomparable-types secondary symptom (union (slice (slice 1)) (slice 2) returns [] instead of erroring) — Skipped (out of chosen scope), with evidence: those args are non-numeric different types, so the early return still fires and returns empty. The existing uncomparable-types error tests (collections_test.go:720-722) are same-type pairs, so they still error correctly and are unaffected. Addressing this cross-type nested case would require the broader "error on all incompatible types" direction, which conflicts with the locked existing tests.