Skip to content

Commit 851b241

Browse files
authored
fix(vm): handle non-comparable groupBy keys (#940)
Check that the groupBy predicate result is comparable before using it as a map key. Previously, a non-comparable type such as a slice would cause a raw Go runtime panic. Now it produces a clear error message instead. Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
1 parent 27acc2d commit 851b241

File tree

3 files changed

+9
-0
lines changed

3 files changed

+9
-0
lines changed

test/fuzz/fuzz_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ func FuzzExpr(f *testing.F) {
6565
regexp.MustCompile(`sortBy order argument must be a string`),
6666
regexp.MustCompile(`invalid order .*, expected asc or desc`),
6767
regexp.MustCompile(`unknown order, use asc or desc`),
68+
regexp.MustCompile(`cannot use .* as a key for groupBy: type is not comparable`),
6869
}
6970

7071
env := NewEnv()

vm/vm.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -578,6 +578,9 @@ func (vm *VM) Run(program *Program, env any) (_ any, err error) {
578578
case OpGroupBy:
579579
scope := vm.currScope
580580
key := vm.pop()
581+
if key != nil && !reflect.TypeOf(key).Comparable() {
582+
panic(fmt.Sprintf("cannot use %T as a key for groupBy: type is not comparable", key))
583+
}
581584
scope.Acc.(groupBy)[key] = append(scope.Acc.(groupBy)[key], scope.Item())
582585

583586
case OpSortBy:

vm/vm_test.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -487,6 +487,11 @@ func TestVM_GroupAndSortOperations(t *testing.T) {
487487
"odd": {1, 3, 5},
488488
},
489489
},
490+
{
491+
name: "group by with non-comparable key",
492+
expr: `groupBy([1, 2, 3], [#, # + 1])`, // predicate returns a slice, which is not comparable
493+
expectError: "not comparable",
494+
},
490495
{
491496
name: "invalid sort order",
492497
expr: `sortBy([1, 2, 3], #, "invalid")`,

0 commit comments

Comments
 (0)