Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 9 additions & 44 deletions packages/protovalidate/src/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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);
}

/**
Expand Down
96 changes: 4 additions & 92 deletions packages/protovalidate/src/native/repeated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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<ReflectList> {
constructor(
Expand Down Expand Up @@ -69,7 +69,7 @@ class EvalNativeRepeatedRules implements Eval<ReflectList> {
);
}

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",
Expand All @@ -83,92 +83,6 @@ class EvalNativeRepeatedRules implements Eval<ReflectList> {
}
}

// 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<string>();
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<number>();
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<unknown>();
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.
*
Expand Down Expand Up @@ -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);
Expand Down
151 changes: 151 additions & 0 deletions packages/protovalidate/src/unique.test.ts
Original file line number Diff line number Diff line change
@@ -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");
},
);
});
Loading
Loading