open-policy-agent / opa

Open Policy Agent (OPA) is an open source, general-purpose policy engine.
https://www.openpolicyagent.org
Apache License 2.0
9.52k stars 1.32k forks source link

Type checker failure on referencing generated map with numeric keys #6736

Open anderseknert opened 4 months ago

anderseknert commented 4 months ago

Trying to reference an item in a generated map by its numeric index in a some .. in iteration seems to have the type checker confused. I'd expect this to work:

package p

import rego.v1

ns := [1, 2, 3]

nums[x] contains ns if some x in ns

bug if {
    some n1 in ns
    some n2 in nums[n1]
}

But it doesn't:

❯ opa eval -f pretty -d p.rego data.p
1 error occurred: p.rego:11: rego_type_error: undefined ref: data.p.nums[n1][__local6__]
    data.p.nums[n1][__local6__]
                ^
                have (type): number
                want (one of): [__local2__]
anderseknert commented 4 months ago

Some further digging, and I've removed the "some .. in" constraint from the description as that wasn't required.

package p

import rego.v1

nums[x] contains x if some x in [1, 2, 3]

bug if {
    n1 := 1
    nums[n1]
}
❯ opa eval -f pretty -d p.rego data.p
1 error occurred: p.rego:9: rego_type_error: undefined ref: data.p.nums[n1]
    data.p.nums[n1]
                ^
                have (type): number
                want (one of): [__local2__]

Using a numeric literal instead of a variable works:

not_bug if {
    nums[1]
}

It seems to only happen for numeric keys, as the same policy works when using string keys:

package p

import rego.v1

nums[x] contains x if some x in ["1", "2", "3"]

bug if {
    n1 := "1"
    nums[n1]
}
stale[bot] commented 3 months ago

This issue has been automatically marked as inactive because it has not had any activity in the last 30 days. Although currently inactive, the issue could still be considered and actively worked on in the future. More details about the use-case this issue attempts to address, the value provided by completing it or possible solutions to resolve it would help to prioritize the issue.

anderseknert commented 2 months ago

Bumped into this again in Regal. This time, it's at least clear that the type checker mistakenly expects strings as keys, even though numbers are clearly used. Simplified example:

package p

import rego.v1

nums[x] contains x if some x in [1, 2, 3]

bug if {
    nums[x]
    x == 1
}
1 error occurred: policy.rego:9: rego_type_error: match error
    left  : string
    right : number

Quite annoying :/