Backtestshugorun-20261024-162305#15323

Issue #15323 Merged fix PR # Run 24 Oct 2026 · run-20261024-162305 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 A = our agent, Patch B = the merged fix.

The issue asks that `union` return either the union or an error whenever the slice types differ, and it calls out three concrete cases: int/float, int/string, and the uncomparable `(slice (slice 1)) (slice 2)` case that the early return currently shadows. Patch A removes the early return at its root, converts l2 elements to l1's element type (numbers via convertNumber, strings via ToStringE, otherwise ConvertIfPossible), returns an explicit `union: unable to convert value of type X to Y` error when conversion is impossible, and moves the uncomparable-types check so it runs per element before any silent return. It also handles interface element types and nil values carefully. The independent tests confirm all four issue scenarios pass on A. Patch B only special-cases the numeric/numeric pair inside the existing early return; `union (slice 1) (slice "a")` still silently returns `[]`, and `union (slice (slice 1)) (slice 2)` still returns `[]` instead of the uncomparable error, both of which the independent tests show failing on B exactly as on base. B's own tests even enshrine the silent-empty behaviour (`[]string{"1","2"} ∪ []int{3} -> []string{}` and `[]int{} ∪ []float64{1.0} -> []int{}`), which is the behaviour the issue reports as the bug. On tests, A adds unit cases that flip the old silent-empty expectations to errors plus a template-level integration test covering the exact snippets from the issue, including error-message matches; B's tests only cover the numeric subset. A's scope is larger than a minimal error-return, but the issue explicitly offered the 'accept mixed types like intersect' direction, and the extra code is coherent and tested rather than risky churn. A also updates the doc comment, which previously stated an incorrect contract. A is clearly the better fix.

Four judges ruled on this ticket in parallel, and the verdict comes from counting their votes. Each saw the issue and the two patches, labelled A and B in random order (two of them saw ours as A), with issue links and version numbers removed. Where tests could check the fix, they also saw the results of tests a separate agent wrote for the issue, run on both patches. None was told which patch was ours. The reasoning above is one judge's, shown verbatim.

Solve

24m 27s

Wall-clock time in the container

Full test suite

No new failures

244 passed · 0 skipped · 244 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

142vs 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+118 −24
tpl/collections/collections.goindex a44603b53..b59963acf 100644@@ -630,9 +630,10 @@ func (i *intersector) handleValuePair(l1vv, l2vv reflect.Value) { 	} } -// Union returns the union of the given sets, l1 and l2. l1 and-// l2 must be of the same type and may be either arrays or slices.-// If l1 and l2 aren't of the same type then l1 will be returned.+// Union returns the union of the given sets, l1 and l2, which may be+// either arrays or slices. The result has the same type as l1; elements of+// l2 are converted to l1's element type, and an error is returned if that+// is not possible. // If either l1 or l2 is nil then the non-nil list will be returned. func (ns *Namespace) Union(l1, l2 any) (any, error) { 	if l1 == nil && l2 == nil {@@ -653,12 +654,7 @@ func (ns *Namespace) Union(l1, l2 any) (any, error) { 		switch l2v.Kind() { 		case reflect.Array, reflect.Slice: 			ins = &intersector{r: reflect.MakeSlice(l1v.Type(), 0, 0), seen: make(map[any]bool)}--			if l1v.Type() != l2v.Type() &&-				l1v.Type().Elem().Kind() != reflect.Interface &&-				l2v.Type().Elem().Kind() != reflect.Interface {-				return ins.r.Interface(), nil-			}+			elemType := l1v.Type().Elem()  			var ( 				l1vv  reflect.Value@@ -687,24 +683,46 @@ func (ns *Namespace) Union(l1, l2 any) (any, error) {  			for j := range l2v.Len() { 				l2vv := l2v.Index(j)-				typ := l1vv.Type()+				v, isNil := hreflect.Indirect(l2vv)+				if !isNil && !v.Type().Comparable() {+					return []any{}, errors.New("union does not support slices or arrays of uncomparable types")+				} -				switch kind := l1vv.Kind(); {-				case kind == reflect.String:-					l2t, err := hreflect.ToStringE(l2vv)-					if err == nil {-						ins.appendIfNotSeen(reflect.ValueOf(l2t))-					}-				case hreflect.IsNumber(kind):-					var err error-					l2vv, err = convertNumber(l2vv, typ)-					if err == nil {-						ins.appendIfNotSeen(l2vv)+				if elemType.Kind() != reflect.Interface {+					// The result can only hold l1's element type.+					cv, ok := unionConvert(l2vv, elemType)+					if !ok {+						l2t := l2vv.Type()+						if l2vv.Kind() == reflect.Interface && !l2vv.IsNil() {+							l2t = l2vv.Elem().Type()+						}+						return nil, fmt.Errorf("union: unable to convert value of type %s to %s", l2t, elemType) 					}-				case kind == reflect.Interface, kind == reflect.Struct, kind == reflect.Pointer:+					ins.appendIfNotSeen(cv)+					continue+				}++				if isNil {+					// Don't turn nil into a typed nil of l1's element type. 					ins.appendIfNotSeen(l2vv)+					continue+				} +				// Prefer the type of l1's elements, but keep the value as is+				// if it can't be converted.+				if l1vv.IsValid() {+					if cv, ok := unionConvert(l2vv, l1vv.Type()); ok {+						ins.appendIfNotSeen(cv)+						continue+					}+				}+				if l2vv.Kind() == reflect.Interface {+					l2vv = l2vv.Elem() 				}+				if !l2vv.Type().AssignableTo(elemType) {+					return nil, fmt.Errorf("union: unable to convert value of type %s to %s", l2vv.Type(), elemType)+				}+				ins.appendIfNotSeen(l2vv) 			}  			return ins.r.Interface(), nil@@ -716,6 +734,25 @@ func (ns *Namespace) Union(l1, l2 any) (any, error) { 	} } +// unionConvert converts v to typ, reporting whether it succeeded.+func unionConvert(v reflect.Value, typ reflect.Type) (reflect.Value, bool) {+	switch kind := typ.Kind(); {+	case kind == reflect.String:+		s, err := hreflect.ToStringE(v)+		if err != nil {+			return reflect.Value{}, false+		}+		return reflect.ValueOf(s).Convert(typ), true+	case hreflect.IsNumber(kind):+		cv, err := convertNumber(v, typ)+		return cv, err == nil+	case kind == reflect.Interface:+		return v, true+	default:+		return hreflect.ConvertIfPossible(v, typ)+	}+}+ // Uniq returns a new list with duplicate elements in the list l removed. func (ns *Namespace) Uniq(l any) (any, error) { 	if l == nil {tpl/collections/collections_integration_test.goindex 52939f3c3..0607783e6 100644@@ -19,6 +19,7 @@ import ( 	"strings" 	"testing" +	qt "github.com/frankban/quicktest" 	"github.com/gohugoio/hugo/hugolib" 	"github.com/gohugoio/hugo/resources/page" 	"github.com/gohugoio/hugo/tpl/collections"@@ -289,6 +290,46 @@ disableKinds = ['rss','sitemap', 'taxonomy', 'term', 'page'] 	b.AssertFileContentExact("public/index.html", "0: /a3_b1.html\n\n1: /b2.html\n\n2: /a1.html\n\n3: /a2.html\n$") } +func TestUnionDifferentSliceTypes(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+disableKinds = ['rss','sitemap', 'taxonomy', 'term', 'page']+-- layouts/home.html --+union int,int: {{ union (slice 1) (slice 2) }}|+union int,float: {{ union (slice 1) (slice 1.0) }}|+union lists: {{ union (slice 1 2) (slice 2.0 3.0) }}|+intersect lists: {{ intersect (slice 1 2) (slice 2.0 3.0) }}|+`++	b := hugolib.Test(t, files)++	b.AssertFileContent("public/index.html",+		"union int,int: [1 2]|",+		"union int,float: [1]|",+		"union lists: [1 2 3]|",+		"intersect lists: [2]|",+	)++	for _, tc := range []struct {+		tpl   string+		match string+	}{+		{`{{ union (slice 1) (slice "a") }}`, `.*union: unable to convert value of type string to int.*`},+		{`{{ union (slice (slice 1)) (slice 2) }}`, `.*union does not support slices or arrays of uncomparable types.*`},+	} {+		files := `+-- hugo.toml --+disableKinds = ['rss','sitemap', 'taxonomy', 'term', 'page']+-- layouts/home.html --+` + tc.tpl + `+`+		_, err := hugolib.TestE(t, files)+		b.Assert(err, qt.ErrorMatches, tc.match)+	}+}+ // Issue 14777. func TestWhereWithPageEqualityIssue14777(t *testing.T) { 	t.Parallel()tpl/collections/collections_test.goindex 5562a80d6..4af4387a8 100644@@ -664,8 +664,22 @@ func TestUnion(t *testing.T) { 		{[]string{"a", "b"}, nil, []string{"a", "b"}, false},  		// []A ∪ []B-		{[]string{"1", "2"}, []int{3}, []string{}, false},-		{[]int{1, 2}, []string{"1", "2"}, []int{}, false},+		{[]string{"1", "2"}, []int{3}, false, true},+		{[]int{1, 2}, []string{"1", "2"}, false, true},+		{[]int{1}, []float64{1.0}, []int{1}, false},+		{[]int{1, 2}, []float64{2.0, 3.0}, []int{1, 2, 3}, false},+		{[]float64{1.5, 2}, []int{2, 3}, []float64{1.5, 2, 3}, false},+		{[]int{}, []float64{2.0, 3.0}, []int{2, 3}, false},+		{[]int{1}, []float64{1.5}, false, true},+		{[]int{}, []float64{1.5}, false, true},+		{[]int{1}, []string{"a"}, false, true},+		{[]int{1}, []any{"a"}, false, true},+		{[]bool{true}, []bool{false, true}, []bool{true, false}, false},+		{pagesPtr{p1}, []any{"a"}, false, true},+		{[]any{1, "x"}, []any{true}, []any{1, "x", true}, false},+		{[]any{"a"}, []any{1, 1.0}, []any{"a", 1}, false},+		{[]fmt.Stringer{p1}, []any{"a"}, false, true},+		{[]fmt.Stringer{p1}, []fmt.Stringer{nil}, []fmt.Stringer{p1, nil}, false},  		// []T ∪ []T 		{[]string{"a", "b", "c", "c"}, []string{"a", "b", "b"}, []string{"a", "b", "c"}, false},@@ -720,6 +734,8 @@ func TestUnion(t *testing.T) { 		// uncomparable types - #3820 		{[]map[string]int{{"K1": 1}}, []map[string]int{{"K2": 2}, {"K2": 2}}, false, true}, 		{[][]int{{1, 1}, {1, 2}}, [][]int{{2, 1}, {2, 2}}, false, true},+		{[][]int{{1}}, []int{2}, false, true},+		{[]any{1}, []any{[]int{2}}, false, true}, 	} {  		errMsg := qt.Commentf("[%d] %v", i, test) 
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},