diff --git a/packages/protovalidate/src/lib.ts b/packages/protovalidate/src/lib.ts index 9756634..85c70e7 100644 --- a/packages/protovalidate/src/lib.ts +++ b/packages/protovalidate/src/lib.ts @@ -12,10 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { type CelList, isCelUint } from "@bufbuild/cel"; -import { scalarEquals } from "@bufbuild/protobuf/reflect"; -import { ScalarType } from "@bufbuild/protobuf"; +import type { CelList } from "@bufbuild/cel"; import { containsBytes } from "./native/bytes.js"; +import { isUnique } from "./unique.js"; /** * Returns true if the value is infinite, optionally limit to positive or @@ -1297,50 +1296,16 @@ class Uri { } /** - * Returns true if the array only contains values that are distinct from each - * other by strict comparison. + * Backs the CEL `unique()` method, which returns true if the items in the list + * are all distinct from each other. Every NaN counts as distinct, but `-0` and + * `0` are equal. * - * NaN is exempt: every NaN counts as distinct, because `NaN == NaN` is false - * under CEL equality. protovalidate-go gets this from Go's `==` (in both its - * native and CEL paths) and protovalidate-java skips NaN explicitly, so this - * is the cross-language behavior. - * - * `-0` and `0` do collide, which `indexOf` already gets right — it compares - * with strict equality, where `-0 === 0`. + * Only lists whose elements all have the same type are supported, where the + * type is one of bool, bytes, double, int, string, or uint. The result for a + * list with mixed element types is unspecified. */ export function unique(this: CelList): boolean { - return Array.from(this.values()).every((a, index, arr) => { - if (typeof a === "number" && Number.isNaN(a)) { - // `indexOf` can never find a NaN, so without this every list holding - // one would be reported as non-unique. - return true; - } - if (isCelUint(a)) { - for (let i = 0; i < arr.length; i++) { - if (i == index) { - continue; - } - const b = arr[i]; - if (isCelUint(b) && b.value === a.value) { - return false; - } - } - return true; - } - if (a instanceof Uint8Array) { - for (let i = 0; i < arr.length; i++) { - if (i == index) { - continue; - } - const b = arr[i]; - if (b instanceof Uint8Array && scalarEquals(ScalarType.BYTES, b, a)) { - return false; - } - } - return true; - } - return arr.indexOf(a) === index; - }); + return isUnique(this); } /** diff --git a/packages/protovalidate/src/native/repeated.ts b/packages/protovalidate/src/native/repeated.ts index 8d73c41..f855384 100644 --- a/packages/protovalidate/src/native/repeated.ts +++ b/packages/protovalidate/src/native/repeated.ts @@ -24,7 +24,7 @@ import { type RepeatedRules, RepeatedRulesSchema, } from "../gen/buf/validate/validate_pb.js"; -import { bytesEqual } from "./bytes.js"; +import { isUnique } from "../unique.js"; const F = RepeatedRulesSchema.field; @@ -41,7 +41,7 @@ export type ListNativeResult = { type UniqueKind = "scalar" | "float" | "bytes" | "enum"; type SizeRule = { readonly val: bigint; readonly path: Path }; -type UniqueRule = { readonly kind: UniqueKind; readonly path: Path }; +type UniqueRule = { readonly path: Path }; class EvalNativeRepeatedRules implements Eval { constructor( @@ -69,7 +69,7 @@ class EvalNativeRepeatedRules implements Eval { ); } - if (this.uniqueRule !== undefined && !isUnique(val, this.uniqueRule.kind)) { + if (this.uniqueRule !== undefined && !isUnique(val)) { cursor.violate( "repeated value must contain unique items", "repeated.unique", @@ -83,92 +83,6 @@ class EvalNativeRepeatedRules implements Eval { } } -// At and below this length, uniqueness is checked with an O(n^2) scan over a -// plain array rather than a Set. For short lists the scan wins: it skips -// allocating the Set and hashing every element, and for bytes it skips -// building a string key per element. Mirrors protovalidate-go's -// uniqueLinearThreshold. -const uniqueLinearThreshold = 16; - -function isUnique(list: ReflectList, kind: UniqueKind): boolean { - const n = list.size; - if (n <= 1) { - return true; - } - if (kind === "bytes") { - if (n <= uniqueLinearThreshold) { - const seen: Uint8Array[] = []; - for (let i = 0; i < n; i++) { - const v = list.get(i) as Uint8Array; - for (let j = 0; j < i; j++) { - if (bytesEqual(seen[j] as Uint8Array, v)) { - return false; - } - } - seen[i] = v; - } - return true; - } - const seen = new Set(); - for (let i = 0; i < n; i++) { - seen.add(bytesKey(list.get(i) as Uint8Array)); - if (seen.size !== i + 1) { - return false; - } - } - return true; - } - if (n <= uniqueLinearThreshold) { - // `===` needs no float special-casing: NaN never equals itself, so every - // NaN counts as distinct, and `-0 === 0`, so signed zeros collide. That - // is exactly what protovalidate-go and protovalidate-java produce. - const seen: unknown[] = []; - for (let i = 0; i < n; i++) { - const v = list.get(i); - for (let j = 0; j < i; j++) { - if (seen[j] === v) { - return false; - } - } - seen[i] = v; - } - return true; - } - if (kind === "float") { - const seen = new Set(); - let added = 0; - for (let i = 0; i < n; i++) { - const v = list.get(i) as number; - // A Set compares with SameValueZero, under which NaN equals itself. - // Skip NaN so this path agrees with the linear scan above. - if (Number.isNaN(v)) continue; - seen.add(v); - if (seen.size !== ++added) return false; - } - return true; - } - // scalar (number/bigint/string/boolean) and enum (number) — a strict-equal - // Set works; none of these kinds can hold NaN. - const seen = new Set(); - for (let i = 0; i < n; i++) { - seen.add(list.get(i)); - if (seen.size !== i + 1) return false; - } - return true; -} - -/** - * Build a deterministic string key for a Uint8Array. Each byte becomes one - * UTF-16 code unit so equal byte sequences hash to equal keys. - */ -function bytesKey(bytes: Uint8Array): string { - let out = ""; - for (let i = 0; i < bytes.length; i++) { - out += String.fromCharCode(bytes[i]); - } - return out; -} - /** * Decide whether the list element type supports native unique handling. * @@ -243,10 +157,8 @@ export function tryBuildNativeRepeatedRules( // `finite: false`. handled.add(F.unique); } else if (listField !== undefined) { - const kind = uniqueKindForListField(listField); - if (kind !== undefined) { + if (uniqueKindForListField(listField) !== undefined) { uniqueRule = { - kind, path: rulePath.clone().field(F.unique).toPath(), }; handled.add(F.unique); diff --git a/packages/protovalidate/src/unique.test.ts b/packages/protovalidate/src/unique.test.ts new file mode 100644 index 0000000..0e59762 --- /dev/null +++ b/packages/protovalidate/src/unique.test.ts @@ -0,0 +1,151 @@ +// Copyright 2024-2026 Buf Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import * as assert from "node:assert"; +import { readFileSync } from "node:fs"; +import { suite, test } from "node:test"; +import { celUint } from "@bufbuild/cel"; +import { create, type DescMessage } from "@bufbuild/protobuf"; +import { compileMessage } from "@bufbuild/protocompile"; +import { isUnique, type IndexedList } from "./unique.js"; +import { createValidator } from "./validator.js"; + +function list(values: readonly unknown[]): IndexedList { + return { size: values.length, get: (index) => values[index] }; +} + +// Runs a case through both the small-list scan and the large-list Set path by +// padding past the linear threshold with distinct fillers that never collide +// with the test values, and asserts the two paths agree. +function bothPaths(values: readonly unknown[]): boolean { + const small = isUnique(list(values)); + const filler = Array.from({ length: 40 }, (_, i) => `__pad_${i}__`); + const large = isUnique(list([...values, ...filler])); + assert.strictEqual(small, large, "scan and Set paths disagree"); + return small; +} + +void suite("isUnique (shared by native and CEL)", () => { + void test("distinguishes unique from duplicate scalars", () => { + assert.strictEqual(isUnique(list([1, 2, 3])), true); + assert.strictEqual(isUnique(list([1, 2, 1])), false); + assert.strictEqual(isUnique(list(["a", "b", "c"])), true); + assert.strictEqual(isUnique(list(["a", "a"])), false); + assert.strictEqual(isUnique(list([1n, 2n, 3n])), true); + assert.strictEqual(isUnique(list([2n, 2n])), false); + }); + + void test("every NaN counts as distinct", () => { + assert.strictEqual(isUnique(list([Number.NaN, Number.NaN, 1])), true); + assert.strictEqual(bothPaths([Number.NaN, Number.NaN]), true); + }); + + void test("signed zeros collide", () => { + assert.strictEqual(isUnique(list([-0, 0])), false); + assert.strictEqual(bothPaths([-0, 0]), false); + }); + + void test("byte arrays compare by contents, not identity", () => { + assert.strictEqual( + isUnique(list([new Uint8Array([1, 2]), new Uint8Array([1, 2])])), + false, + ); + assert.strictEqual( + isUnique(list([new Uint8Array([1]), new Uint8Array([2])])), + true, + ); + assert.strictEqual( + bothPaths([new Uint8Array([9, 9]), new Uint8Array([9, 9])]), + false, + ); + }); + + void test("CEL uint wrappers compare by value", () => { + assert.strictEqual(isUnique(list([celUint(1n), celUint(1n)])), false); + assert.strictEqual(isUnique(list([celUint(1n), celUint(2n)])), true); + }); + + void test("handles large lists", () => { + const distinct = Array.from({ length: 50_000 }, (_, i) => i); + assert.strictEqual(isUnique(list(distinct)), true); + assert.strictEqual(isUnique(list([...distinct.slice(0, -1), 0])), false); + }); +}); + +const bufCompileOptions = { + imports: { + "buf/validate/validate.proto": readFileSync( + "proto/buf/validate/validate.proto", + "utf-8", + ), + }, +}; + +function uniqueSchema(type: string): DescMessage { + return compileMessage( + `syntax = "proto3"; + import "buf/validate/validate.proto"; + message M { repeated ${type} x = 1 [(buf.validate.field).repeated.unique = true]; }`, + bufCompileOptions, + ); +} + +void suite("repeated.unique native and CEL agree", () => { + const native = createValidator(); + const cel = createValidator({ disableNativeRules: true }); + for (const type of [ + "int32", + "uint32", + "int64", + "string", + "bytes", + "double", + ]) { + void test(type, () => { + const schema = uniqueSchema(type); + const value = (v: number) => { + switch (type) { + case "int64": + return BigInt(v); + case "bytes": + return new Uint8Array([v]); + case "string": + return String(v); + default: + return v; + } + }; + const dup = create(schema, { x: [value(1), value(1)] } as never); + const uniq = create(schema, { x: [value(1), value(2)] } as never); + assert.strictEqual(native.validate(schema, dup).kind, "invalid"); + assert.strictEqual(cel.validate(schema, dup).kind, "invalid"); + assert.strictEqual(native.validate(schema, uniq).kind, "valid"); + assert.strictEqual(cel.validate(schema, uniq).kind, "valid"); + }); + } + + // Regression guard: the CEL path used to be O(n^2). At this size an O(n^2) + // scan would not finish within the test timeout. + void test( + "CEL path stays linear on a large distinct list", + { timeout: 10_000 }, + () => { + const schema = uniqueSchema("int32"); + const message = create(schema, { + x: Array.from({ length: 200_000 }, (_, i) => i), + }); + assert.strictEqual(cel.validate(schema, message).kind, "valid"); + }, + ); +}); diff --git a/packages/protovalidate/src/unique.ts b/packages/protovalidate/src/unique.ts new file mode 100644 index 0000000..68aae81 --- /dev/null +++ b/packages/protovalidate/src/unique.ts @@ -0,0 +1,127 @@ +// Copyright 2024-2026 Buf Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { isCelUint } from "@bufbuild/cel"; +import { bytesEqual } from "./native/bytes.js"; + +// At and below this length, uniqueness is checked with an O(n^2) scan over a +// cached copy of the list rather than a Set. For short lists the scan wins: it +// skips allocating the Set and hashing every element, and for bytes it skips +// building a string key per element. Mirrors protovalidate-go's +// uniqueLinearThreshold. +const uniqueLinearThreshold = 16; + +// Sentinel key for NaN. It is skipped rather than inserted, so every NaN counts +// as distinct even though a Set's SameValueZero would treat NaN as equal. +const nan = Symbol("nan"); + +/** + * A list that can be read by index. Both `@bufbuild/protobuf/reflect`'s + * `ReflectList` and `@bufbuild/cel`'s `CelList` satisfy this shape. + */ +export interface IndexedList { + readonly size: number; + get(index: number): unknown; +} + +/** + * Returns true if every element of the list is distinct, in O(n) for large + * lists. Shared by the native `repeated.unique` evaluator and the CEL + * `unique()` function so both decide uniqueness identically. + * + * Every value space either path produces is handled: numbers (every NaN is + * distinct, and `-0`/`0` collide), bigint, string, boolean, CEL uint wrappers + * (compared by value), and byte arrays (compared by contents). Object elements + * fall back to identity. This matches protovalidate-go and protovalidate-java. + */ +export function isUnique(list: IndexedList): boolean { + const n = list.size; + if (n <= 1) { + return true; + } + if (n <= uniqueLinearThreshold) { + // A proto repeated field is homogeneous, so the first element decides the + // comparison for the whole list. Byte lists compare by contents and get a + // dedicated loop; everything else compares with uniqueEquals. + const first = list.get(0); + const seen: unknown[] = [first]; + for (let i = 1; i < n; i++) { + const a = list.get(i); + for (let j = 0; j < i; j++) { + if (uniqueEquals(a, seen[j])) { + return false; + } + } + seen[i] = a; + } + return true; + } + const seen = new Set(); + let added = 0; + for (let i = 0; i < n; i++) { + const key = uniqueKey(list.get(i)); + if (key === nan) { + continue; + } + seen.add(key); + // If the Set did not grow, this key was already present. + if (seen.size !== ++added) { + return false; + } + } + return true; +} + +function uniqueKey(value: unknown): unknown { + switch (typeof value) { + case "number": + return Number.isNaN(value) ? nan : value; + case "object": + if (value instanceof Uint8Array) { + return bytesKey(value); + } + if (isCelUint(value)) { + return value.value; + } + return value; + default: + // bigint, string, boolean + return value; + } +} + +function uniqueEquals(a: unknown, b: unknown): boolean { + // Only object values need the structural comparisons; numbers (NaN never + // equals itself, so every NaN is distinct; `-0 === 0`, so signed zeros + // collide), bigint, string, and boolean compare strictly. + if (typeof a === "object" && a !== null) { + if (a instanceof Uint8Array) { + return b instanceof Uint8Array && bytesEqual(a, b); + } + if (isCelUint(a)) { + return isCelUint(b) && a.value === b.value; + } + } + return a === b; +} + +// A deterministic string key for a Uint8Array: each byte becomes one UTF-16 +// code unit, so equal byte sequences produce equal keys. +function bytesKey(bytes: Uint8Array): string { + let out = ""; + for (let i = 0; i < bytes.length; i++) { + out += String.fromCharCode(bytes[i]); + } + return out; +}