Backtestshugorun-20261007-020926#15323
tpl/collections: union silently returns an empty list when the two slice types differ
Our patch was judged better than the merged fix.
In this judgment, Patch B = our agent, Patch A = the merged fix.
The issue is that `union` silently returns an empty list when the two slice types differ. It asks for either a real union or an error, never a silent empty result.
**Patch A only partly fixes this.** It bypasses the early return when both element types are numeric, so `union (slice 1 2) (slice 2.0 3.0)` now yields `[1 2 3]`. Every other mismatched case still hits the unchanged `return ins.r.Interface(), nil` with no error:
- `union (slice 1) (slice "a")` still returns `[]`.
- `union (slice (slice 1)) (slice 2)` still returns `[]` instead of the uncomparable-types error the issue calls out.
A's own test suite keeps the existing `[]string ∪ []int → []string{}` expectations, preserving the silent behavior the issue reports as a bug. Its added guard (`AssignableTo(l1v.Type().Elem())`) patches a prototype mismatch that A's partial approach itself exposes. It also makes `[]int{} ∪ []float64{1.0}` return `[]int{}`, which is arguably wrong: the union should contain 1.
**Patch B fixes the root cause.** It removes the early return and converts each l2 element to l1's element type, returning an error when that is impossible:
- Numeric mixes unify, matching how `intersect` already behaves.
- Incompatible types (int vs string, a lossy 1.5 → int) raise `union: failed to convert value`.
- The uncomparable check is now reached and raises its error.
- Interface-element slices keep the previous normalize-or-keep behavior.
- An empty l1 with numeric l2 correctly yields `[1 2]`.
B updates the outdated unit expectations to errors and adds wide coverage: int/float in both directions, int64, empty l1, `template.HTML` from string, pages ptr/vals, nested slices, and `[]any` cases. It also adds an integration test reproducing the issue's template exactly, plus error-case assertions. These tests would fail before the change.
B is a larger rewrite, which carries some risk around how `convertValue` handles struct and pointer elements. The retained `[]T ∪ []T` tests and the explicit pages cases mitigate that, and the doc comment was updated accurately.
Overall, B resolves every scenario in the issue while A leaves most of them silently broken.
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
1h 3m
Wall-clock time in the container
Full test suite
No new failures
3,769 passed · 101 skipped · 3,872 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
136vs 17 merged
Changed lines, ours vs merged
The issue
View on GitHubWhat 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
tpl/collections/collections.goindex a44603b53..050e1d6d0 100644@@ -631,8 +631,11 @@ 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 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 l1's element type is an interface,+// strings and numbers in l2 are converted to the type of l1's last element+// when possible and kept as-is otherwise. // 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 +656,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 := ins.r.Type().Elem() var ( l1vv reflect.Value@@ -677,34 +675,17 @@ 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)- }- }- for j := range l2v.Len() { l2vv := l2v.Index(j)- typ := l1vv.Type()-- 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)- }- case kind == reflect.Interface, kind == reflect.Struct, kind == reflect.Pointer:- ins.appendIfNotSeen(l2vv)+ if l2vv.Kind() == reflect.Interface && !l2vv.IsNil() {+ l2vv = l2vv.Elem()+ } + v, err := unionConvert(l2vv, elemType, l1vv)+ if err != nil {+ return nil, fmt.Errorf("union: failed to convert value: %w", err) }+ ins.appendIfNotSeen(v) } return ins.r.Interface(), nil@@ -716,6 +697,37 @@ func (ns *Namespace) Union(l1, l2 any) (any, error) { } } +// unionConvert converts v so it can be appended to a slice with the element type elemType.+// If elemType is an interface, prototype (a value from the first slice) is used to+// normalize strings and numbers to the type already in use, when possible.+func unionConvert(v reflect.Value, elemType reflect.Type, prototype reflect.Value) (reflect.Value, error) {+ if elemType.Kind() == reflect.Interface {+ if prototype.IsValid() && prototype.Kind() != reflect.Interface {+ if k := prototype.Kind(); k == reflect.String || hreflect.IsNumber(k) {+ if cv, err := convertValue(v, prototype.Type()); err == nil {+ v = cv+ }+ }+ }+ if !v.Type().AssignableTo(elemType) {+ return reflect.Value{}, fmt.Errorf("%s is not assignable to %s", v.Type(), elemType)+ }+ return v, nil+ }++ cv, err := convertValue(v, elemType)+ if err != nil {+ return reflect.Value{}, err+ }+ if !cv.Type().AssignableTo(elemType) {+ if !cv.Type().ConvertibleTo(elemType) {+ return reflect.Value{}, fmt.Errorf("%s is not assignable to %s", v.Type(), elemType)+ }+ cv = cv.Convert(elemType)+ }+ return cv, nil+}+ // 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..38cfd9ccb 100644@@ -19,6 +19,8 @@ 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 +291,45 @@ 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 TestUnionMixedSliceTypes(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) }}|+union mixed: {{ union (slice 1 "x") (slice 1.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]|",+ "union mixed: [1 x]|",+ )++ for _, tc := range []struct {+ tpl string+ errMsg string+ }{+ {`{{ union (slice 1) (slice "a") }}`, "union: failed to convert value"},+ {`{{ union (slice 1) (slice 1.5) }}`, "union: failed to convert value"},+ {`{{ union (slice (slice 1)) (slice 2) }}`, "union does not support slices or arrays of uncomparable types"},+ } {+ files := strings.ReplaceAll(files, "-- layouts/home.html --\n", "-- layouts/home.html --\n"+tc.tpl+"\n")+ _, err := hugolib.TestE(t, files)+ b.Assert(err, qt.IsNotNil, qt.Commentf(tc.tpl))+ b.Assert(err.Error(), qt.Contains, tc.errMsg, qt.Commentf(tc.tpl))+ }+}+ // Issue 14777. func TestWhereWithPageEqualityIssue14777(t *testing.T) { t.Parallel()tpl/collections/collections_test.goindex 5562a80d6..b1fbcb1e9 100644@@ -664,8 +664,23 @@ 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}, []int{1, 2}, []float64{1.5, 1, 2}, false},+ {[]int64{1}, []int{1, 2}, []int64{1, 2}, false},+ {[]int{}, []float64{1.0, 2.0}, []int{1, 2}, false},+ {[]int{1}, []float64{1.5}, false, true},+ {[]int{1}, []string{"a"}, false, true},+ {[]template.HTML{"a"}, []string{"a", "b"}, []template.HTML{"a", "b"}, false},+ {pagesPtr{p1}, pagesVals{p2v}, false, true},+ {[][]int{{1}}, []int{2}, false, true},++ // []interface{} ∪ []T where T cannot be normalized to the type in []interface{}+ {[]any{1}, []string{"a"}, []any{1, "a"}, false},+ {[]any{1, "x"}, []float64{1.0, 2.0}, []any{1, "x", 2.0}, false},+ {[]any{true}, []bool{true, false}, []any{true, false}, false}, // []T ∪ []T {[]string{"a", "b", "c", "c"}, []string{"a", "b", "b"}, []string{"a", "b", "c"}, false},
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},