Backtestshugorun-20261009-153657#15323

Issue #15323 Merged fix PR # Run 9 Oct 2026 · run-20261009-153657 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's core complaint is that `union` silently returns an empty slice when the two argument types differ. Patch A removes that early return. When l1's element type is concrete, Patch A converts each l2 value to it through `convertUnionValue`. That function does a lossless numeric conversion, a direct assign, or a plain-string conversion. If none applies, it returns an explicit error. When l1's element type is an interface, Patch A keeps the prototype-based conversion and errors if the value is not assignable. Every path now either produces a correct union or returns an error. Removing the early return also lets the uncomparable-types check run, so `union (slice (slice 1)) (slice 2)` now errors as the issue says it should.

Patch B only lets numeric-to-numeric pairs through. `union (slice 1) (slice "a")`, which the issue explicitly lists, still silently returns `[]`. The uncomparable case `(slice (slice 1)) (slice 2)` is still short-circuited to an empty list. B's new `AssignableTo` guard also drops values silently: `[]int{} ∪ []float64{1.0}` yields `[]int{}`, and B's own test locks that in. So B fixes part of the symptom and keeps the silent-empty behaviour the issue objects to.

On tests, Patch A has broad unit coverage: numeric unification, lossy-conversion errors (`1.5` into int), string/int errors, the uncomparable error, a `template.HTML` safety case, and interface mixes. It also adds an integration test that reproduces the issue's template, including `intersect` parity and the error messages. A changes two existing expectations from empty-slice to error, which is the intended behaviour change. Patch B's tests cover only the numeric cases and encode a remaining silent-drop case as correct.

On craft, A refuses to convert into named string types like `template.HTML`, a thoughtful safety edge. A's refactor is larger but coherent. B is smaller but incomplete. A is the better fix.

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

20m

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

135vs 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+113 −22
tpl/collections/collections.goindex a44603b53..d863c2a78 100644@@ -631,8 +631,9 @@ 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.+// l2 may be either arrays or slices. The result has the type of l1;+// values in l2 are converted to l1's element type when possible, and+// an error is returned if a value in l2 cannot be represented in the result. // 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@@ -677,6 +673,25 @@ func (ns *Namespace) Union(l1, l2 any) (any, error) { 				} 			} +			if elemType.Kind() != reflect.Interface {+				// The result can only hold values of l1's element type.+				for j := range l2v.Len() {+					l2vv := l2v.Index(j)+					if l2vv.Kind() == reflect.Interface {+						if l2vv.IsNil() {+							continue+						}+						l2vv = l2vv.Elem()+					}+					v, err := convertUnionValue(l2vv, elemType)+					if err != nil {+						return nil, fmt.Errorf("union: %w", err)+					}+					ins.appendIfNotSeen(v)+				}+				break+			}+ 			if !l1vv.IsValid() { 				// The first slice may be empty. Pick the first value of the second 				// to use as a prototype.@@ -687,33 +702,52 @@ func (ns *Namespace) Union(l1, l2 any) (any, error) {  			for j := range l2v.Len() { 				l2vv := l2v.Index(j)-				typ := l1vv.Type()+				v := l2vv +				// Convert to the type of the l1 prototype when possible,+				// otherwise keep the value as is. 				switch kind := l1vv.Kind(); { 				case kind == reflect.String:-					l2t, err := hreflect.ToStringE(l2vv)-					if err == nil {-						ins.appendIfNotSeen(reflect.ValueOf(l2t))+					if l2t, err := hreflect.ToStringE(l2vv); err == nil {+						v = reflect.ValueOf(l2t) 					} 				case hreflect.IsNumber(kind):-					var err error-					l2vv, err = convertNumber(l2vv, typ)-					if err == nil {-						ins.appendIfNotSeen(l2vv)+					if cv, err := convertNumber(l2vv, l1vv.Type()); err == nil {+						v = cv 					}-				case kind == reflect.Interface, kind == reflect.Struct, kind == reflect.Pointer:-					ins.appendIfNotSeen(l2vv)+				} +				if v.Kind() == reflect.Interface && !v.IsNil() {+					v = v.Elem() 				}+				if !v.Type().AssignableTo(elemType) {+					return nil, fmt.Errorf("union: unable to add value of type %q to %q", v.Type().String(), l1v.Type().String())+				}+				ins.appendIfNotSeen(v) 			}--			return ins.r.Interface(), nil 		default: 			return nil, errors.New("can't iterate over " + reflect.ValueOf(l2).Type().String()) 		} 	default: 		return nil, errors.New("can't iterate over " + reflect.ValueOf(l1).Type().String()) 	}++	return ins.r.Interface(), nil+}++// convertUnionValue converts v to typ without loss, returning an error if that is not possible.+func convertUnionValue(v reflect.Value, typ reflect.Type) (reflect.Value, error) {+	switch {+	case hreflect.IsNumber(typ.Kind()):+		return convertNumber(v, typ)+	case v.Type().AssignableTo(typ):+		return v, nil+	case typ == reflect.TypeFor[string]() && v.Kind() == reflect.String:+		// Only convert to a plain string; converting to a named string type+		// (e.g. template.HTML) would mark untrusted content as safe.+		return v.Convert(typ), nil+	}+	return reflect.Value{}, fmt.Errorf("unable to convert value of type %q to %q", v.Type().String(), typ.String()) }  // Uniq returns a new list with duplicate elements in the list l removed.tpl/collections/collections_integration_test.goindex 52939f3c3..462ba558b 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"@@ -653,3 +654,41 @@ All. 		} 	}) }++func TestUnionDifferentSliceTypes(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+baseURL = 'http://example.com/'+-- layouts/home.html --+int,int: {{ union (slice 1) (slice 2) }}|+int,float: {{ union (slice 1) (slice 1.0) }}|+lists: {{ union (slice 1 2) (slice 2.0 3.0) }}|+intersect: {{ intersect (slice 1 2) (slice 2.0 3.0) }}|+mixed: {{ union (slice 1 "x") (slice 1.0) }}|+`+	b := hugolib.Test(t, files)++	b.AssertFileContent("public/index.html",+		"int,int: [1 2]|",+		"int,float: [1]|",+		"lists: [1 2 3]|",+		"intersect: [2]|",+		"mixed: [1 x]|",+	)++	for _, tc := range []struct {+		tpl    string+		errMsg string+	}{+		{`{{ union (slice 1) (slice "a") }}`, `union: unable to convert value of type "string" to "int"`},+		{`{{ union (slice 1) (slice 1.5) }}`, `union: unable to convert value of type "float64" to "int"`},+		{`{{ union (slice (slice 1)) (slice 2) }}`, "union does not support slices or arrays of uncomparable types"},+	} {+		files := strings.Replace(files, "int,int:", tc.tpl+"\nint,int:", 1)+		_, err := hugolib.TestE(t, files)+		qt.Assert(t, err, qt.IsNotNil)+		qt.Assert(t, err.Error(), qt.Contains, tc.errMsg)+	}+}tpl/collections/collections_test.goindex 5562a80d6..5e3ff10fc 100644@@ -664,8 +664,26 @@ 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, 2}, []float64{2.0, 3.0}, []int{1, 2, 3}, false},+		{[]float64{1.5}, []int{1, 2}, []float64{1.5, 1, 2}, false},+		{[]float64{}, []int{1}, []float64{1}, false},+		{[]int{1}, []float64{1.5}, false, true},+		{[]int{1}, []string{"a"}, false, true},+		{[]bool{true}, []bool{false, true}, []bool{true, false}, false},+		{[][]int{{1}}, []int{2}, false, true},+		{[]template.HTML{"<b>a</b>"}, []string{"<script>"}, false, true},+		{[]string{"a"}, []template.HTML{"<b>b</b>"}, []string{"a", "<b>b</b>"}, false},++		// []T ∪ []interface{} with values that can't be converted to T+		{[]int{2}, []any{"a"}, false, true},+		{[]string{"a"}, []any{1}, false, true},++		// []interface{} ∪ []T with values that can't be converted to the l1 prototype+		{[]any{1, 2}, []string{"x"}, []any{1, 2, "x"}, false},+		{[]any{1}, []any{"a", 1.0}, []any{1, "a"}, false},+		{[]any{"a"}, []bool{true}, []any{"a", true}, false},  		// []T ∪ []T 		{[]string{"a", "b", "c", "c"}, []string{"a", "b", "b"}, []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},