Skip to content

Share a linear repeated.unique check between the native and CEL paths - #208

Merged
jonbodner-buf merged 7 commits into
mainfrom
jbodner/unique-linear
Oct 22, 2026
Merged

jonbodner-buf merged 7 commits into
mainfrom
jbodner/unique-linear

Conversation

@jonbodner-buf

Copy link
Copy Markdown
Contributor

The native repeated.unique function already had an efficient Set-based approach for arrays longer than 16 elements long. However, it fell through to the CEL repeated.unique function if any of the elements were not primitive types. The CEL function remained inefficient.

The native unique function has been extracted into its own file and extended to support compound types. The native and CEL functions now call this independent implementation.

The CEL unique() function rescanned the whole list for every element -- an
indexOf (or full inner loop for uint and bytes) per element -- so validating a
repeated field against `unique` took O(n^2) on a list of distinct values and
blocked the thread. That path is taken when native rules are disabled and for
message- or wrapper-typed elements, so a comparatively small message could
occupy the validating thread for disproportionate time.

Extract the O(n) check the native evaluator already used into a shared
isUnique, and route both the native repeated.unique evaluator and the CEL
unique() function through it, so the two paths decide uniqueness identically.
It reads the list by index, which both a ReflectList and a CelList support, and
handles every value space either produces: numbers (every NaN distinct, signed
zeros collide), bigint, string, boolean, CEL uint wrappers (by value), and byte
arrays (by contents). A short list keeps the allocation-free scan; a long one
uses a Set.

CEL unique() on 64k distinct values drops from ~9.3s to ~11ms. The native path
is unchanged in behavior and within benchmark noise.
return true;
}
if (n <= uniqueLinearThreshold) {
// A proto repeated field is homogeneous, so the first element decides the

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A protobuf repeated field is homogeneous, but CEL lists don't have to be. I don't think it's clear what unique() should do for a mixed list.

Maybe document that it must only be called on a homogeneous list? WDYT?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

By a CEL list, do you mean a list defined in the CEL expression itself? Or is there some other way to construct one?

I think it's fine to say that unique is only meant for homogeneous lists.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A list defined in the CEL expression itself, or a repeated google.protobuf.Value x = 1 [(buf.validate.field).repeated.unique = true].

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suggest the following comment in lib.ts:

/**
 * 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.
 *
 * 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 {

Sounds reasonable?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is special case handling for Uint8Array in unique.ts. Should I remove it?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Special case handling is needed: === on Uint8Array compares identity, but CEL expects content comparison, see this conformance test.

The dedicated if (first instanceof Uint8Array) loop in isUnique looks unnecessary to me, because uniqueEquals already compares Uint8Array by content. I'd remove it unless it measured faster for you, or there is an edge case I'm missing.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

removed

Signed-off-by: Jon Bodner <jbodner@buf.build>
Signed-off-by: Jon Bodner <jbodner@buf.build>
Signed-off-by: Jon Bodner <jbodner@buf.build>
Signed-off-by: Jon Bodner <jbodner@buf.build>
Signed-off-by: Jon Bodner <jbodner@buf.build>
Signed-off-by: Jon Bodner <jbodner@buf.build>
@jonbodner-buf
jonbodner-buf merged commit ec08976 into main Oct 22, 2026
12 checks passed
@jonbodner-buf
jonbodner-buf deleted the jbodner/unique-linear branch October 22, 2026 15:23
thezachdrake added a commit that referenced this pull request Nov 4, 2026
Rewrite the root AGENTS.md from a short pointer file into a practical
guide for coding agents and automated reviewers (Claude Code, Codex CLI,
CodeRabbit). The content is distilled from all 196 pull requests in this
repository (#3 to #217, April 2025 to November 2026), their reviews,
inline review comments, and discussion threads, plus linked issues #151
and #188. Feedback from Timo Stamm, who authored most of the runtime and
95 of the reviews, is treated as the primary source of review standards;
53 of the 61 review comments cited are his.

What was added

- Non-negotiable rules, a repository map, and an architecture primer
  covering the planner, the Eval tree and pruning, plan caching for
  recursive types, native versus CEL rule paths, rule ordering, bounded
  violation collection, the lazy "now" binding, regex handling, and the
  Standard Schema adapter.
- Code standards split into package constraints, TypeScript idioms the
  maintainers ask for, and comment/TSDoc expectations.
- Validation correctness, public API and compatibility, performance,
  tests, and pull request sections, each with links to the PRs that
  established the rule.
- An "Intentional deviations from conventional practice" section
  organized around the guarantee each deviation protects.
- A "Recurring expectations from the primary maintainer" section.
- An automated-review heuristics table mapping diff patterns to the
  objection they draw and the comment that established it.
- Guidance on when to inspect existing patterns versus ask.
- A pre-submission checklist and an evidence/limitations note.

Review-history patterns behind each major section

- TypeScript idioms: repeated requests to remove unnecessary casts and
  narrow on $typeName unions (#162 r3373946287, r3396858192,
  r3396751979), use import type (#162 r3374240321), rely on Protobuf-ES
  narrowing helpers (#162 r3917039841, #50 r2144533918), pass only what
  a function needs (#50 r2144501029, #162 r3374231996), prefer getters
  over Object.defineProperty (#187 r3932808390), lean on JSON.stringify
  for Date (#161 r3350697426), keep hot paths monomorphic (#211
  r4341261343), and interpolate Desc* values directly (#48
  r2141964881).
- Comments and TSDoc: "What's this comment?" on process residue (#162
  r3373926019), phase references (#162 r3374030709), stale cross-repo
  notes (#162 r3374080325, r3979938965), intent over measurement (#211
  r4341261343), JSDoc tag consistency (#162 r3373957769, r3989404047),
  no comment blocks above imports (#149 r3311275758), detached doc
  comments (#205 r4261778895), documenting unspecified behavior (#208
  r4323363466).
- Tests: concise schemas (#100 r2510643490), compare every Violation
  field (#162 r3917154010), create() ignores unknown init keys (#100
  r2510611774), conformance is the home for general behavior (#104
  r2534943638), keep helpers simple (#104 r2535346919), type-level
  tests for Valid types (#54 r2167577444).
- Pull requests: separate dependency updates (#69, #70), update the
  description when code changes (#212), commit-by-commit review (#161,
  #6), benchmark results in the description (#186, #187).
- Bundle size and dependencies: structural typing over const tables
  (#162 r3374199478), thin wrappers over parallel paths (#169
  issuecomment-5527428731), new dependency called out (#162
  r3880966679), no unneeded deps (#149 r3342748444), lib.ts/native
  duplication tracked in #188 and reduced in #207 and #208.
- Cross-repository consistency: tsconfig and build flags match
  protobuf-es and connect-es (#191 r4063943402, r4063223514), env var
  naming and turbo globalPassThroughEnv (#162 r3917303400), release
  scripts (#3).

Repository-specific departures from conventional practice and the
guarantees they preserve

- Exact pins on @bufbuild/cel and @bufbuild/re2 instead of caret ranges,
  so breaking changes never reach users transitively (#39
  r2125787252).
- RE2 for every schema-supplied pattern instead of RegExp, accepting
  about 16 KB of bundle, to guarantee linear-time matching on untrusted
  input (#162 r3881326955, #43). Fixed internal formats still use
  RegExp by design; RE2 rejects \u escapes (#162 r3916989368).
- Dual ESM/CJS with no import.meta anywhere including tests (#104
  r2535337784), node10 resolution kept for the CJS build with the TS 6
  deprecation ignored (#191), TypeScript 7 excluded in dependabot
  (#199), exports entries with .js extension and typesVersions so attw
  passes (#152 issuecomment-5428247548, #151
  issuecomment-5397402620), and Biome held at 1.9.x (#193
  issuecomment-6085428731, #167) with the reason noted as undocumented.
- ES2020 target with { cause?: unknown } instead of ErrorOptions so
  ES2020 consumers compile (#12, #30 r2099944076).
- Standard Schema types copied rather than depended on, and the
  interface type not exported (#54 r2167551109).
- Native and CEL paths must be behaviorally identical, with the native
  path following cel-es where cel-es and cel-go differ (#162
  r3374957884); conformance runs on both paths in CI.
- Validation bypasses are never silent: unknown predefined rules raise
  CompilationError (#106), failed compilation evicts partial plans and
  re-raises for dependent roots (#137, #212), pruning never drops a
  plan that is still building (#211, replacing #206).
- EvalMany carries plan state as a field rather than a subclass to keep
  the hot eval() path monomorphic (#211 r4341261343, #186).
- Internal packages are TypeScript, not vanilla JS (#149 r3311772322);
  tinybench is kept after mitata proved order-dependent and noisy (#149
  r3318703717).

How this supports Codex CLI, Claude Code, and CodeRabbit

- Rules are stated as observable constraints with file paths, option
  names, and commands so an agent can check them without judgment
  calls, and each carries the PR or comment to read for nuance.
- The heuristics table is written as diff pattern, objection, source,
  so CodeRabbit can apply it directly alongside REVIEW.md and the
  path_filters in .coderabbit.yaml. Style is left to Biome.
- The "when to inspect or ask" section tells agents which files and
  sibling repositories to read before writing, and which decisions
  (violation changes, exports, dependencies, major tooling bumps)
  require a maintainer.
- The checklist mirrors what npm run all and CI enforce, plus the
  review-only expectations CI cannot catch.

Evidence and limitations

- Every one of the 108 GitHub links in the file was verified against
  the fetched PR data: each comment id exists and belongs to the cited
  thread.
- Commits before April 2025 were imported from bufbuild/cel-es; their
  PR numbers refer to that repository and were not reviewed.
- Rules resting on a single comment (parseArgs, record-vs-array,
  assertion wording) are labeled as such in the text.

Primary references
#39 (comment)
#54 (comment)
#104 (comment)
#149 (comment)
#152 (comment)
#162 (comment)
#162 (comment)
#162 (comment)
#187 (comment)
#191 (comment)
#205 (comment)
#208 (comment)
#211 (comment)
#212
#151 (comment)
#188
@timostamm timostamm mentioned this pull request Nov 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants