Skip to content

Multi-tier framework for evaluating AI agent skills and plugins with quality gates, security scanning, harness compatibility checks, semantic overlap detection, synthetic evaluation dataset generation, and live agent evaluation that measures how skills affect agent behavior. Ships reusable CI templates that bring every check to any repository.

fix(tier2): support larger bounded collection scans (#166)

Narendran Raghavanbf87c3791d5d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e6b3c9c4..b632c4d5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,20 @@ All notable changes to SkillEvaluator are documented in this file.
### Fixed
+- Separate Tier 2 collection limits from the 256-file per-skill limit. Fresh
+ similarity scans now allow 1,024 selected manifests and 128 million scalar
+ comparisons by default, covering 343 skills with 2,048-dimensional embeddings.
+ Add `--max-entries` and `--max-scalar-comparisons` for explicit scan budgets;
+ exceeded limits fail with actionable errors and never truncate the collection.
+ Fresh pairwise scans reject excessive scalar work after the first validated
+ embedding response, before requesting more embeddings or saving a catalog.
+ Collection discovery has its own 20,000-path ceiling, allowing the supported
+ 5,000-entry maximum for minimal collections while retaining the 4,096-path
+ per-skill ceiling. Invalid Python command API budgets raise option-specific
+ errors before provider initialization. Similarity comparisons validate and
+ normalize each vector once instead of once per pair, making large pairwise
+ scans more than an order of magnitude faster. Equal nonzero embeddings score
+ exactly 1.0, so `--threshold 1` reports exact duplicates.
- Keep headings and comments inside fenced code examples in their enclosing Markdown
section during Tier 2 content chunking, preserving original source line numbers.
- Run the public Docker image as an unprivileged user, with writable default report and home directories.
diff --git a/docs/cli-reference.mdx b/docs/cli-reference.mdx
index 0f395f0f..3fc71521 100644
--- a/docs/cli-reference.mdx
+++ b/docs/cli-reference.mdx
@@ -362,6 +362,8 @@ skillevaluator similarity-check ./skills
| `--model TEXT` | provider default | Embedding model override. |
| `--catalog FILE` | none | Compare exactly one skill against a local catalog. |
| `--save-catalog FILE` | none | Build and save a versioned local catalog from this collection. |
+| `--max-entries INTEGER` | `1024` | Maximum selected manifests for a fresh collection; range `1`–`5000`. Does not restrict loaded catalog queries. |
+| `--max-scalar-comparisons INTEGER` | `128000000` | Maximum comparisons multiplied by embedding dimensions; must be positive. Applies to pairwise scans and catalog queries. |
Plus the standard report options. Classification tiers and catalog rules are in [Tier 2: Deduplication](tier2-deduplication.mdx).
diff --git a/docs/tier2-deduplication.mdx b/docs/tier2-deduplication.mdx
index f28943ea..13fadd8d 100644
--- a/docs/tier2-deduplication.mdx
+++ b/docs/tier2-deduplication.mdx
@@ -173,6 +173,41 @@ matches.
| `--full-body` | off | Embed each discovered `SKILL.md` in full, including frontmatter, chunked at 512 tokens with 64-token overlap and average pooling — instead of only the name and description. Supporting files are not included |
| `--model` | configured embedding model | Embedding model override for this run |
| `--type skill` | `auto` | Explicit skill discovery when automatic detection is not suitable |
+| `--max-entries` | `1024` | Maximum selected manifests in a fresh collection; accepts `1` through `5000` |
+| `--max-scalar-comparisons` | `128000000` | Maximum comparisons multiplied by embedding dimensions; accepts a positive integer |
+
+The entry budget is independent of the 256-file limit inside one skill. A
+343-skill collection fits the defaults, including with 2,048-dimensional
+embeddings. Entry and comparison budgets are separate: a pairwise scan needs
+`n * (n - 1) / 2 * dimensions` scalar comparisons, so increasing the entry
+budget may also require increasing the comparison budget. For example, 500
+skills with 2,048-dimensional embeddings need 255,488,000 scalar comparisons:
+
+```bash title="Allow a larger comparison workload"
+skillevaluator similarity-check ./skills --max-entries 500 --max-scalar-comparisons 256000000
+```
+
+The entry budget counts selected manifests even when their frontmatter is
+invalid. It applies before any embedding request and never truncates a scan.
+Fresh pairwise scans check the comparison budget after the first validated
+embedding batch (or first full-body vector), before requesting the remaining
+embeddings or saving a catalog. Python index-only builds remain available for
+single-target queries that fit the smaller query budget. A failure names the
+option to adjust. Increasing
+either budget can increase provider usage or processing time. Neither option
+changes the separate path, input-byte, catalog-file, vector, or result limits.
+
+Collection discovery allows up to 20,000 paths, independently of the
+4,096-path limit inside one skill. Each visited directory and file counts,
+including files that are not selected as manifests; excluded directories count
+once, but their contents are pruned. This accommodates all 5,000 supported
+entries when each skill has a directory and `SKILL.md`. Collections with more
+supporting files or deeper layouts may reach the path ceiling before the
+selected-entry budget.
+
+For a saved catalog query, `--max-entries` does not reduce the catalog's existing
+5,000-entry capacity. Its comparison work is `catalog entries * dimensions`,
+bounded by `--max-scalar-comparisons`.
## Use a local catalog
@@ -263,8 +298,10 @@ discovered paths, file counts, per-file and total input bytes, content chunks,
candidate clusters, catalog size and entry count, vector length, returned
matches, and pairwise scalar work. Catalog loading also rejects duplicate JSON
keys, unexpected fields, invalid identities, non-finite vectors, and
-incompatible provider metadata. If a collection exceeds a limit, split it into
-intentional batches rather than scanning an unbounded directory tree.
+incompatible provider metadata. Increase the documented collection budgets only
+for a workload you intend to process. Splitting a collection into independent
+batches omits comparisons between batches and is not a complete deduplication
+scan.
### What leaves your machine
diff --git a/src/skillevaluator/cli.py b/src/skillevaluator/cli.py
index f152184f..25567b21 100644
--- a/src/skillevaluator/cli.py
+++ b/src/skillevaluator/cli.py
@@ -19,6 +19,11 @@ import click
from skillevaluator import __version__
from skillevaluator.cli_help import GroupedOption, RichGroup
+from skillevaluator.constants import (
+ SIMILARITY_DEFAULT_MAX_ENTRIES,
+ SIMILARITY_DEFAULT_MAX_SCALAR_COMPARISONS,
+ SIMILARITY_MAX_ENTRIES,
+)
from skillevaluator.logging_config import setup_logging
from skillevaluator.models.result import ValidationResult
from skillevaluator.reporting.console_ui import (
@@ -2126,6 +2131,20 @@ def lint_scripts(target_path: Path, report_formats: tuple[str, ...], output_dir:
@click.option("--threshold", type=float, default=0.75, show_default=True, callback=_validate_similarity_threshold)
@click.option("--full-body", is_flag=True, help="Embed full file bodies instead of descriptions.")
@click.option("--model", default=None, help="Embedding model override.")
+ "--max-entries",
+ type=click.IntRange(1, SIMILARITY_MAX_ENTRIES),
+ default=SIMILARITY_DEFAULT_MAX_ENTRIES,
+ show_default=True,
+ help="Maximum selected manifests for a fresh collection scan.",
+)
+ "--max-scalar-comparisons",
+ type=click.IntRange(min=1),
+ default=SIMILARITY_DEFAULT_MAX_SCALAR_COMPARISONS,
+ show_default=True,
+ help="Maximum comparisons multiplied by embedding dimensions.",
+)
@click.option(
"--catalog",
type=click.Path(file_okay=True, dir_okay=False, path_type=Path),
@@ -2147,6 +2166,8 @@ def similarity_check(
threshold: float,
full_body: bool,
model: str | None,
+ max_entries: int,
+ max_scalar_comparisons: int,
catalog: Path | None,
save_catalog: Path | None,
cache: Path | None,
@@ -2187,6 +2208,8 @@ def similarity_check(
threshold=threshold,
full_body=full_body,
model=model,
+ max_entries=max_entries,
+ max_scalar_comparisons=max_scalar_comparisons,
catalog=resolved_catalog,
save_catalog=resolved_save_catalog,
)
diff --git a/src/skillevaluator/constants.py b/src/skillevaluator/constants.py
index 921fa74f..ade04e71 100644
--- a/src/skillevaluator/constants.py
+++ b/src/skillevaluator/constants.py
@@ -268,6 +268,14 @@ CONTENT_DEDUP_MAX_TOTAL_BYTES = 8 * 1024 * 1024
CONTENT_DEDUP_MAX_CHUNKS = 512
CONTENT_DEDUP_MAX_LLM_CLUSTERS = 50
+# Collection-wide similarity budgets are independent of a single skill's file limit.
+SIMILARITY_DEFAULT_MAX_ENTRIES = 1_024
+SIMILARITY_MAX_ENTRIES = 5_000
+# Allow directories, manifests, and supporting paths at the maximum entry count,
+# without raising the independent per-skill content-deduplication path ceiling.
+SIMILARITY_MAX_DISCOVERED_PATHS = 4 * SIMILARITY_MAX_ENTRIES
+SIMILARITY_DEFAULT_MAX_SCALAR_COMPARISONS = 128_000_000
+
CONTENT_DEDUP_LLM_DEFAULT_MODEL = "azure/anthropic/claude-opus-4-8"
CONTENT_DEDUP_LLM_TEMPERATURE = 0.1
diff --git a/src/skillevaluator/embedding/client.py b/src/skillevaluator/embedding/client.py
index 4aa96287..711527f1 100644
--- a/src/skillevaluator/embedding/client.py
+++ b/src/skillevaluator/embedding/client.py
@@ -55,6 +55,45 @@ def validate_embedding_vector(
return len(values)
+def normalize_embedding_vector(
+ vector: object,
+ expected_dimension: int | None = None,
+ *,
+ context: str = "Embedding provider",
+ allow_zero: bool = False,
+) -> list[float]:
+ """Validate a vector and return a unit-vector copy for repeated comparisons.
+
+ Zero vectors remain zero when ``allow_zero`` is enabled, matching
+ :meth:`EmbeddingClient.cosine_similarity`.
+ """
+ values, norm = _validated_vector_values(
+ vector,
+ expected_dimension,
+ context=context,
+ allow_zero=allow_zero,
+ )
+ if norm == 0.0:
+ return values
+ return [value / norm for value in values]
+
+
+def unit_vector_similarity(left: list[float], right: list[float]) -> float:
+ """Return the cosine similarity of two same-width normalized vectors.
+
+ Pairwise scans normalize each vector once with :func:`normalize_embedding_vector`
+ instead of revalidating and renormalizing both vectors for every pair.
+ Equal nonzero vectors score exactly 1.0 so rounding cannot hide exact
+ duplicates at ``--threshold 1``; zero vectors still score 0.0.
+ """
+ if left == right:
+ return 1.0 if any(left) else 0.0
+ score = math.sumprod(left, right)
+ if not math.isfinite(score):
+ raise SimilarityConfigError("Cosine similarity produced a non-finite result.")
+ return max(-1.0, min(1.0, score))
+
+
class EmbeddingClient:
"""Public OpenAI-compatible client for generating text embeddings.
@@ -246,24 +285,19 @@ class EmbeddingClient:
"This usually means the embeddings were produced by different models "
"or a stale cache is being used."
)
- values_a, norm_a = _validated_vector_values(
+ unit_a = normalize_embedding_vector(
vec_a,
len(vec_a),
context="First similarity",
allow_zero=True,
)
- values_b, norm_b = _validated_vector_values(
+ unit_b = normalize_embedding_vector(
vec_b,
len(vec_a),
context="Second similarity",
allow_zero=True,
)
- if norm_a == 0.0 or norm_b == 0.0:
- return 0.0
- score = math.fsum((a / norm_a) * (b / norm_b) for a, b in zip(values_a, values_b, strict=True))
- if not math.isfinite(score):
- raise SimilarityConfigError("Cosine similarity produced a non-finite result.")
- return max(-1.0, min(1.0, score))
+ return unit_vector_similarity(unit_a, unit_b)
# ---------------------------------------------------------------------------
diff --git a/src/skillevaluator/embedding/extractor.py b/src/skillevaluator/embedding/extractor.py
index 4712703d..7788d6a1 100644
--- a/src/skillevaluator/embedding/extractor.py
+++ b/src/skillevaluator/embedding/extractor.py
@@ -18,29 +18,29 @@ from pathlib import Path
import yaml
from skillevaluator.constants import (
- CONTENT_DEDUP_MAX_DISCOVERED_PATHS,
CONTENT_DEDUP_MAX_FILE_BYTES,
- CONTENT_DEDUP_MAX_FILES,
CONTENT_DEDUP_MAX_TOTAL_BYTES,
CONTENT_TYPE_RULES,
CONTENT_TYPE_SKILL,
CONTENT_TYPE_WORKFLOWS,
RULES_FILE_EXTENSION,
SCAN_EXCLUDED_DIRS,
+ SIMILARITY_DEFAULT_MAX_ENTRIES,
+ SIMILARITY_MAX_DISCOVERED_PATHS,
SKILL_MANIFEST_VARIANTS,
WORKFLOWS_MANIFEST_FILE,
)
from skillevaluator.deduplication.utils.skill_collector import _SecureReadError, _SecureRoot
+from skillevaluator.embedding.limits import validate_max_entries
from skillevaluator.logging_config import get_logger
from skillevaluator.utils.tier2_paths import is_contained_compatibility_alias, safe_path_label
from skillevaluator.validators.frontmatter_parser import FRONTMATTER_PATTERN
logger = get_logger(__name__)
-MAX_COLLECTION_ENTRIES = CONTENT_DEDUP_MAX_FILES
MAX_MANIFEST_BYTES = CONTENT_DEDUP_MAX_FILE_BYTES
MAX_COLLECTION_BYTES = CONTENT_DEDUP_MAX_TOTAL_BYTES
-MAX_DISCOVERED_PATHS = CONTENT_DEDUP_MAX_DISCOVERED_PATHS
+MAX_DISCOVERED_PATHS = SIMILARITY_MAX_DISCOVERED_PATHS
DISCOVERY_EXCLUDED_DIRS = SCAN_EXCLUDED_DIRS
@@ -72,13 +72,17 @@ class ContentEntry:
class _ExtractionBudget:
"""Tracks collection bounds before any embedding request is made."""
+ max_entries: int = SIMILARITY_DEFAULT_MAX_ENTRIES
entry_count: int = 0
total_bytes: int = 0
def reserve(self, file_path: Path, declared_bytes: int) -> None:
self.entry_count += 1
- if self.entry_count > MAX_COLLECTION_ENTRIES:
- raise ValueError(f"Collection entry limit exceeded ({MAX_COLLECTION_ENTRIES}) before embedding")
+ if self.entry_count > self.max_entries:
+ raise ValueError(
+ f"Collection entry limit exceeded ({self.max_entries}) before embedding; "
+ "increase --max-entries within its supported range to scan the complete collection"
+ )
if declared_bytes > MAX_MANIFEST_BYTES:
raise ValueError(
f"Manifest exceeds the Tier 2 per-file byte limit ({MAX_MANIFEST_BYTES}): {file_path.name}"
@@ -176,22 +180,26 @@ def extract_from_workflow(workflow_dir: Path, *, budget: _ExtractionBudget | Non
# ---------------------------------------------------------------------------
-def discover_and_extract(root: Path, content_type: str) -> list[ContentEntry]:
+def discover_and_extract(
+ root: Path, content_type: str, *, max_entries: int = SIMILARITY_DEFAULT_MAX_ENTRIES
+) -> list[ContentEntry]:
"""Auto-discover content items under a directory and extract entries.
Args:
root: Root directory to scan.
content_type: One of "skill", "rules", "workflows".
+ max_entries: Maximum selected manifests, including those with invalid frontmatter.
Returns:
List of successfully extracted ContentEntry objects.
"""
+ validate_max_entries(max_entries)
strategy = _DISCOVERY_STRATEGIES.get(content_type)
if strategy is None:
logger.warning("Unknown content type '%s' for discovery", content_type)
return []
- entries = strategy(root, _ExtractionBudget())
+ entries = strategy(root, _ExtractionBudget(max_entries=max_entries))
logger.debug("Discovered %d %s entries in %s", len(entries), content_type, safe_path_label(root))
return entries
diff --git a/src/skillevaluator/embedding/limits.py b/src/skillevaluator/embedding/limits.py
new file mode 100644
index 00000000..947e7e6a
--- /dev/null
+++ b/src/skillevaluator/embedding/limits.py
@@ -0,0 +1,16 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Validated resource limits for inter-skill similarity scans."""
+
+from skillevaluator.constants import SIMILARITY_MAX_ENTRIES
+
+
+def validate_max_entries(max_entries: int) -> None:
+ if type(max_entries) is not int or not 1 <= max_entries <= SIMILARITY_MAX_ENTRIES:
+ raise ValueError(f"max_entries (--max-entries) must be an integer from 1 to {SIMILARITY_MAX_ENTRIES}")
+
+
+def validate_max_scalar_comparisons(max_scalar_comparisons: int) -> None:
+ if type(max_scalar_comparisons) is not int or max_scalar_comparisons < 1:
+ raise ValueError("max_scalar_comparisons (--max-scalar-comparisons) must be a positive integer")
diff --git a/src/skillevaluator/embedding/registry.py b/src/skillevaluator/embedding/registry.py
index 334caa3c..59edf926 100644
--- a/src/skillevaluator/embedding/registry.py
+++ b/src/skillevaluator/embedding/registry.py
@@ -31,17 +31,26 @@ from skillevaluator.constants import (
CONTENT_TYPE_SKILL,
CONTENT_TYPE_WORKFLOWS,
SIMILARITY_CRITICAL_THRESHOLD,
+ SIMILARITY_DEFAULT_MAX_ENTRIES,
+ SIMILARITY_DEFAULT_MAX_SCALAR_COMPARISONS,
SIMILARITY_HIGH_THRESHOLD,
SIMILARITY_LOW_THRESHOLD,
+ SIMILARITY_MAX_ENTRIES,
SIMILARITY_MEDIUM_THRESHOLD,
)
-from skillevaluator.embedding.client import EmbeddingClient, SimilarityConfigError, validate_embedding_vector
+from skillevaluator.embedding.client import (
+ EmbeddingClient,
+ SimilarityConfigError,
+ normalize_embedding_vector,
+ unit_vector_similarity,
+ validate_embedding_vector,
+)
from skillevaluator.embedding.extractor import (
- MAX_COLLECTION_ENTRIES,
MAX_MANIFEST_BYTES,
ContentEntry,
discover_and_extract,
)
+from skillevaluator.embedding.limits import validate_max_entries, validate_max_scalar_comparisons
from skillevaluator.logging_config import get_logger
from skillevaluator.models.result import Severity
from skillevaluator.utils.path_security import canonicalize_trusted_root_alias
@@ -51,14 +60,12 @@ logger = get_logger(__name__)
CATALOG_SCHEMA_VERSION = 1
MAX_CATALOG_BYTES = 32 * 1024 * 1024
-MAX_CATALOG_ENTRIES = 5_000
+MAX_CATALOG_ENTRIES = SIMILARITY_MAX_ENTRIES
MAX_VECTOR_DIMENSION = 65_536
MAX_CATALOG_TEXT_LENGTH = 16_384
EMBEDDING_BATCH_SIZE = 64
MAX_DESCRIPTION_EMBEDDING_TEXT_CHARS = 16_384
MAX_FULL_BODY_EMBEDDING_TEXT_BYTES = MAX_MANIFEST_BYTES
-MAX_PAIRWISE_COMPARISONS = MAX_COLLECTION_ENTRIES * (MAX_COLLECTION_ENTRIES - 1) // 2
-MAX_SCALAR_COMPARISONS = 25_000_000
MAX_SIMILARITY_MATCHES = 1_000
_SHA256_PATTERN = re.compile(r"^[0-9a-f]{64}$")
_ENDPOINT_FINGERPRINT_PATTERN = re.compile(r"^sha256:[0-9a-f]{64}$")
@@ -169,9 +176,21 @@ class EmbeddingRegistry:
2. Cached: load_cache() / save_cache() for pre-computed indexes.
"""
- def __init__(self, client: EmbeddingClient, *, full_body: bool = False) -> None:
+ def __init__(
+ self,
+ client: EmbeddingClient,
+ *,
+ full_body: bool = False,
+ max_entries: int = SIMILARITY_DEFAULT_MAX_ENTRIES,
+ max_scalar_comparisons: int = SIMILARITY_DEFAULT_MAX_SCALAR_COMPARISONS,
+ ) -> None:
+ validate_max_entries(max_entries)
+ validate_max_scalar_comparisons(max_scalar_comparisons)
self._client = client
self._full_body = full_body
+ self._max_entries = max_entries
+ self._max_pairwise_comparisons = max_entries * (max_entries - 1) // 2
+ self._max_scalar_comparisons = max_scalar_comparisons
self._entries: dict[str, RegistryEntry] = {}
self._vector_dimension: int | None = None
@@ -185,13 +204,19 @@ class EmbeddingRegistry:
content_type: str,
*,
minimum_entries: int = 1,
+ for_pairwise_scan: bool = False,
) -> int:
"""Discover content items, embed them, and populate the index.
+ Set ``for_pairwise_scan`` when the caller will compare all entries.
+ The first validated response then checks the pairwise work budget
+ before requesting the remaining embeddings. Index-only builds retain
+ their independent capacity for single-target queries.
+
Returns:
Number of entries successfully indexed.
"""
- content_entries = discover_and_extract(root, content_type)
+ content_entries = discover_and_extract(root, content_type, max_entries=self._max_entries)
if not content_entries:
logger.debug("No content entries found in %s", safe_path_label(root))
return 0
@@ -205,36 +230,47 @@ class EmbeddingRegistry:
texts = [entry.full_text if self._full_body else entry.embedding_text for entry in content_entries]
for text in texts:
_validate_embedding_text(text, full_body=self._full_body)
- if self._full_body:
- vectors = [self._client.embed_chunked(text) for text in texts]
- else:
- vectors = []
- for start in range(0, len(texts), EMBEDDING_BATCH_SIZE):
- vectors.extend(self._client.embed(texts[start : start + EMBEDDING_BATCH_SIZE]))
- if len(vectors) != len(content_entries):
- raise ValueError(f"Embedding provider returned {len(vectors)} vectors for {len(content_entries)} entries")
-
resolved_root = root.resolve(strict=True)
- for entry, vector in zip(content_entries, vectors, strict=True):
- vector_dimension = _validate_vector(vector, self._vector_dimension)
- if self._vector_dimension is None:
- self._vector_dimension = vector_dimension
+ pending_entries: list[RegistryEntry] = []
+ for entry in content_entries:
resolved_entry = Path(entry.path).resolve(strict=True)
try:
relative_path = resolved_entry.relative_to(resolved_root).as_posix() or "."
except ValueError as exc:
raise ValueError(f"Discovered content path escapes scan root: {entry.path}") from exc
entry_id = f"{entry.content_type}:{relative_path}"
- self._entries[entry_id] = RegistryEntry(
- name=entry.name,
- description=entry.description,
- path=relative_path,
- content_type=entry.content_type,
- embedding=vector,
- entry_id=entry_id,
- content_fingerprint=_fingerprint(entry.full_text if self._full_body else entry.embedding_text),
+ pending_entries.append(
+ RegistryEntry(
+ name=entry.name,
+ description=entry.description,
+ path=relative_path,
+ content_type=entry.content_type,
+ entry_id=entry_id,
+ content_fingerprint=_fingerprint(entry.full_text if self._full_body else entry.embedding_text),
+ )
)
+ entry_count = len(self._entries.keys() | {entry.entry_id for entry in pending_entries})
+ comparison_count = entry_count * (entry_count - 1) // 2
+ vector_dimension = self._vector_dimension
+ validated_vectors: list[list[float]] = []
+ batch_size = 1 if self._full_body else EMBEDDING_BATCH_SIZE
+ for start in range(0, len(texts), batch_size):
+ batch = texts[start : start + batch_size]
+ vectors = [self._client.embed_chunked(batch[0])] if self._full_body else self._client.embed(batch)
+ if len(vectors) != len(batch):
+ raise ValueError(f"Embedding provider returned {len(vectors)} vectors for {len(batch)} entries in batch")
+ for vector in vectors:
+ vector_dimension = _validate_vector(vector, vector_dimension)
+ validated_vectors.append(vector)
+ if start == 0 and for_pairwise_scan:
+ _validate_scalar_work(comparison_count, vector_dimension or 0, self._max_scalar_comparisons)
+
+ for entry, vector in zip(pending_entries, validated_vectors, strict=True):
+ entry.embedding = vector
+ self._entries.update((entry.entry_id, entry) for entry in pending_entries)
+ self._vector_dimension = vector_dimension
+
logger.debug("Indexed %d entries from %s", len(self._entries), safe_path_label(root))
return len(self._entries)
@@ -247,14 +283,18 @@ class EmbeddingRegistry:
_validate_threshold(threshold)
entries = list(self._entries.values())
comparison_count = len(entries) * (len(entries) - 1) // 2
- if comparison_count > MAX_PAIRWISE_COMPARISONS:
- raise ValueError(f"Pairwise comparison limit exceeded ({MAX_PAIRWISE_COMPARISONS})")
- vector_dimension = _validate_registry_vectors(entries, self._vector_dimension)
- _validate_scalar_work(comparison_count, vector_dimension)
+ if comparison_count > self._max_pairwise_comparisons:
+ raise ValueError(
+ f"Pairwise comparison limit exceeded ({self._max_pairwise_comparisons}); "
+ "increase --max-entries within its supported range to compare the complete collection"
+ )
+ vector_dimension = _registry_vector_dimension(entries, self._vector_dimension)
+ _validate_scalar_work(comparison_count, vector_dimension, self._max_scalar_comparisons)
+ unit_vectors = _normalized_registry_vectors(entries, vector_dimension)
matches: list[SimilarityMatch] = []
- for a, b in combinations(entries, 2):
- score = EmbeddingClient.cosine_similarity(a.embedding, b.embedding)
+ for (a, unit_a), (b, unit_b) in combinations(zip(entries, unit_vectors, strict=True), 2):
+ score = unit_vector_similarity(unit_a, unit_b)
if score >= threshold:
if len(matches) >= MAX_SIMILARITY_MATCHES:
raise ValueError(f"Similarity match limit exceeded ({MAX_SIMILARITY_MATCHES})")
@@ -278,15 +318,16 @@ class EmbeddingRegistry:
"""
_validate_threshold(threshold)
entries = list(self._entries.values())
- vector_dimension = _validate_registry_vectors(entries, self._vector_dimension)
- _validate_scalar_work(len(entries), vector_dimension)
+ vector_dimension = _registry_vector_dimension(entries, self._vector_dimension)
+ _validate_scalar_work(len(entries), vector_dimension, self._max_scalar_comparisons)
+ unit_vectors = _normalized_registry_vectors(entries, vector_dimension)
_validate_embedding_text(text, full_body=self._full_body)
vector = self._client.embed_chunked(text) if self._full_body else self._client.embed_single(text)
- _validate_vector(vector, vector_dimension or self._vector_dimension)
+ query_vector = _normalized_vector(vector, vector_dimension or self._vector_dimension)
matches: list[SimilarityMatch] = []
- for entry in entries:
- score = EmbeddingClient.cosine_similarity(vector, entry.embedding)
+ for entry, unit_vector in zip(entries, unit_vectors, strict=True):
+ score = unit_vector_similarity(query_vector, unit_vector)
if score >= threshold:
if len(matches) >= MAX_SIMILARITY_MATCHES:
raise ValueError(f"Similarity match limit exceeded ({MAX_SIMILARITY_MATCHES})")
@@ -307,17 +348,18 @@ class EmbeddingRegistry:
"""Compare one extracted target entry against every catalog entry."""
_validate_threshold(threshold)
catalog_entries = list(self._entries.values())
- vector_dimension = _validate_registry_vectors(catalog_entries, self._vector_dimension)
- _validate_scalar_work(len(catalog_entries), vector_dimension)
+ vector_dimension = _registry_vector_dimension(catalog_entries, self._vector_dimension)
+ _validate_scalar_work(len(catalog_entries), vector_dimension, self._max_scalar_comparisons)
+ unit_vectors = _normalized_registry_vectors(catalog_entries, vector_dimension)
text = entry.full_text if self._full_body else entry.embedding_text
_validate_embedding_text(text, full_body=self._full_body)
vector = self._client.embed_chunked(text) if self._full_body else self._client.embed_single(text)
- _validate_vector(vector, vector_dimension or self._vector_dimension)
+ query_vector = _normalized_vector(vector, vector_dimension or self._vector_dimension)
target_path = Path(entry.path).name or "."
matches: list[SimilarityMatch] = []
- for catalog_entry in catalog_entries:
- score = EmbeddingClient.cosine_similarity(vector, catalog_entry.embedding)
+ for catalog_entry, unit_vector in zip(catalog_entries, unit_vectors, strict=True):
+ score = unit_vector_similarity(query_vector, unit_vector)
if score >= threshold:
if len(matches) >= MAX_SIMILARITY_MATCHES:
raise ValueError(f"Similarity match limit exceeded ({MAX_SIMILARITY_MATCHES})")
@@ -565,17 +607,38 @@ def _validate_vector(vector: object, expected_dimension: int | None) -> int:
raise ValueError(str(exc)) from exc
-def _validate_registry_vectors(entries: list[RegistryEntry], expected_dimension: int | None) -> int:
- dimension = expected_dimension
- for entry in entries:
- dimension = _validate_vector(entry.embedding, dimension)
- return dimension or 0
+def _normalized_vector(vector: object, expected_dimension: int | None) -> list[float]:
+ if isinstance(vector, list) and len(vector) > MAX_VECTOR_DIMENSION:
+ raise ValueError(f"Catalog vector dimension exceeds {MAX_VECTOR_DIMENSION}")
+ try:
+ return normalize_embedding_vector(
+ vector,
+ expected_dimension,
+ context="Catalog embedding",
+ )
+ except SimilarityConfigError as exc:
+ raise ValueError(str(exc)) from exc
+
+
+def _registry_vector_dimension(entries: list[RegistryEntry], expected_dimension: int | None) -> int:
+ """Return the width for work-budget checks without retaining normalized copies."""
+ if expected_dimension is not None or not entries:
+ return expected_dimension or 0
+ return _validate_vector(entries[0].embedding, None)
+
+def _normalized_registry_vectors(entries: list[RegistryEntry], dimension: int) -> list[list[float]]:
+ """Validate every vector against the registry width and normalize each once."""
+ return [_normalized_vector(entry.embedding, dimension or None) for entry in entries]
-def _validate_scalar_work(comparison_count: int, vector_dimension: int) -> None:
+
+def _validate_scalar_work(comparison_count: int, vector_dimension: int, max_scalar_comparisons: int) -> None:
scalar_work = comparison_count * vector_dimension
- if scalar_work > MAX_SCALAR_COMPARISONS:
- raise ValueError(f"Scalar comparison work limit exceeded ({MAX_SCALAR_COMPARISONS}); requested {scalar_work}")
+ if scalar_work > max_scalar_comparisons:
+ raise ValueError(
+ f"Scalar comparison work limit exceeded ({max_scalar_comparisons}); requested {scalar_work}. "
+ "Increase --max-scalar-comparisons to allow this comparison workload"
+ )
def _validate_catalog_identity(entry_id: object, path: object, content_type: object) -> None:
diff --git a/src/skillevaluator/tier2/commands.py b/src/skillevaluator/tier2/commands.py
index a72ccae9..323519b4 100644
--- a/src/skillevaluator/tier2/commands.py
+++ b/src/skillevaluator/tier2/commands.py
@@ -7,7 +7,9 @@ from __future__ import annotations
from pathlib import Path
+from skillevaluator.constants import SIMILARITY_DEFAULT_MAX_ENTRIES, SIMILARITY_DEFAULT_MAX_SCALAR_COMPARISONS
from skillevaluator.deduplication.intra_skill.intra_skill_validator import IntraSkillValidator
+from skillevaluator.embedding.limits import validate_max_entries, validate_max_scalar_comparisons
from skillevaluator.models.result import ValidationResult
from skillevaluator.tier1.commands import emit_reports
from skillevaluator.validators.similarity import SimilarityValidator
@@ -44,7 +46,13 @@ def run_similarity_check(
save_catalog: Path | None = None,
cache: Path | None = None,
save_cache: Path | None = None,
+ max_entries: int = SIMILARITY_DEFAULT_MAX_ENTRIES,
+ max_scalar_comparisons: int = SIMILARITY_DEFAULT_MAX_SCALAR_COMPARISONS,
) -> list[ValidationResult]:
+ # Caller option errors have safe diagnostics and should not become provider failures.
+ validate_max_entries(max_entries)
+ validate_max_scalar_comparisons(max_scalar_comparisons)
+
def _run() -> ValidationResult:
validator = SimilarityValidator(
threshold=threshold,
@@ -55,6 +63,8 @@ def run_similarity_check(
save_cache_path=save_cache,
content_type=None if content_type == "auto" else content_type,
full_body=full_body,
+ max_entries=max_entries,
+ max_scalar_comparisons=max_scalar_comparisons,
)
return validator.validate(content_path)
diff --git a/src/skillevaluator/validators/similarity.py b/src/skillevaluator/validators/similarity.py
index 7a8d558c..00e5aa43 100644
--- a/src/skillevaluator/validators/similarity.py
+++ b/src/skillevaluator/validators/similarity.py
@@ -14,10 +14,13 @@ from pathlib import Path
from skillevaluator.constants import (
CONTENT_TYPE_UNKNOWN,
+ SIMILARITY_DEFAULT_MAX_ENTRIES,
+ SIMILARITY_DEFAULT_MAX_SCALAR_COMPARISONS,
SIMILARITY_DEFAULT_THRESHOLD,
)
from skillevaluator.embedding.client import EmbeddingClient, SimilarityConfigError
from skillevaluator.embedding.extractor import extract_from_skill
+from skillevaluator.embedding.limits import validate_max_entries, validate_max_scalar_comparisons
from skillevaluator.embedding.registry import EmbeddingRegistry, SimilarityMatch
from skillevaluator.logging_config import get_logger
from skillevaluator.models.result import Finding
@@ -44,7 +47,11 @@ class SimilarityValidator(ValidatorBase):
save_cache_path: Path | None = None,
content_type: str | None = None,
full_body: bool = False,
+ max_entries: int = SIMILARITY_DEFAULT_MAX_ENTRIES,
+ max_scalar_comparisons: int = SIMILARITY_DEFAULT_MAX_SCALAR_COMPARISONS,
) -> None:
+ validate_max_entries(max_entries)
+ validate_max_scalar_comparisons(max_scalar_comparisons)
if not math.isfinite(threshold) or not 0.0 <= threshold <= 1.0:
raise ValueError("Similarity threshold must be finite and within [0, 1]")
if catalog_path and cache_path and catalog_path != cache_path:
@@ -63,6 +70,8 @@ class SimilarityValidator(ValidatorBase):
self._save_catalog_path = resolved_save_catalog
self._content_type = content_type
self._full_body = full_body
+ self._max_entries = max_entries
+ self._max_scalar_comparisons = max_scalar_comparisons
@property
def name(self) -> str:
@@ -101,7 +110,12 @@ class SimilarityValidator(ValidatorBase):
return result
client = EmbeddingClient(model=self._model)
- registry = EmbeddingRegistry(client, full_body=self._full_body)
+ registry = EmbeddingRegistry(
+ client,
+ full_body=self._full_body,
+ max_entries=self._max_entries,
+ max_scalar_comparisons=self._max_scalar_comparisons,
+ )
try:
if self._catalog_path:
@@ -130,6 +144,7 @@ class SimilarityValidator(ValidatorBase):
skill_path,
content_type,
minimum_entries=minimum_entries,
+ for_pairwise_scan=True,
)
if count == 0:
if self._save_catalog_path:
diff --git a/tests/deduplication/utils/test_skill_collector.py b/tests/deduplication/utils/test_skill_collector.py
index 2ad7a5a5..8e5a758d 100644
--- a/tests/deduplication/utils/test_skill_collector.py
+++ b/tests/deduplication/utils/test_skill_collector.py
@@ -365,6 +365,19 @@ class TestCollectFilesSafety:
assert exc_info.value.check_name == "path_count_limit"
assert exc_info.value.metadata == {"actual": 3, "limit": 2}
+ def test_per_skill_path_budget_remains_4096(self, skill_root: Path) -> None:
+ for index in range(4_096):
+ (skill_root / f"irrelevant-{index}.bin").write_bytes(b"x")
+
+ assert collect_files(skill_root) == []
+
+ (skill_root / "overflow.bin").write_bytes(b"x")
+ with pytest.raises(SkillCollectionError) as exc_info:
+ collect_files(skill_root)
+
+ assert exc_info.value.check_name == "path_count_limit"
+ assert exc_info.value.metadata == {"actual": 4_097, "limit": 4_096}
+
def test_directory_traversal_error_is_actionable(self, skill_root: Path, monkeypatch) -> None:
def deny_traversal(_root: Path, *, onerror=None, **_kwargs):
assert onerror is not None
diff --git a/tests/embedding/test_client.py b/tests/embedding/test_client.py
index fa9ee46a..9aa2b67f 100644
--- a/tests/embedding/test_client.py
+++ b/tests/embedding/test_client.py
@@ -18,6 +18,8 @@ from skillevaluator.embedding.client import (
_fixed_size_chunks,
_split_by_headings,
_split_into_chunks,
+ normalize_embedding_vector,
+ unit_vector_similarity,
)
@@ -47,6 +49,34 @@ class TestCosineSimilarity:
score = EmbeddingClient.cosine_similarity(a, b)
assert 0.99 < score < 1.0
+ def test_matches_exactly_summed_reference(self) -> None:
+ a = [math.sin(index * 0.37) * (index % 7 + 1) for index in range(2_048)]
+ b = [math.cos(index * 0.11) - 0.25 for index in range(2_048)]
+ norm_a = math.sqrt(math.fsum(value * value for value in a))
+ norm_b = math.sqrt(math.fsum(value * value for value in b))
+ expected = math.fsum((x / norm_a) * (y / norm_b) for x, y in zip(a, b, strict=True))
+
+ assert EmbeddingClient.cosine_similarity(a, b) == pytest.approx(expected, abs=1e-15)
+
+ def test_equal_nonzero_vectors_score_exactly_one(self) -> None:
+ vector = [-5.479683767155414, -6.166558151604646]
+ unit = normalize_embedding_vector(vector)
+
+ assert math.sumprod(unit, unit) < 1.0 # Rounding alone would hide the duplicate at --threshold 1.
+ assert unit_vector_similarity(unit, list(unit)) == 1.0
+ assert EmbeddingClient.cosine_similarity(vector, list(vector)) == 1.0
+ assert unit_vector_similarity([0.0, 0.0], [0.0, 0.0]) == 0.0
+
+ def test_normalized_vectors_reuse_the_same_score(self) -> None:
+ a, b = [3.0, 4.0, 0.0], [4.0, 3.0, 0.0]
+ unit_a, unit_b = normalize_embedding_vector(a), normalize_embedding_vector(b)
+
+ assert unit_a == [0.6, 0.8, 0.0]
+ assert unit_vector_similarity(unit_a, unit_b) == EmbeddingClient.cosine_similarity(a, b)
+ assert normalize_embedding_vector([0.0, 0.0], allow_zero=True) == [0.0, 0.0]
+ with pytest.raises(SimilarityConfigError, match="zero vector"):
+ normalize_embedding_vector([0.0, 0.0])
+
@dataclass
class _FakeEmbeddingItem:
diff --git a/tests/embedding/test_extractor.py b/tests/embedding/test_extractor.py
index 4fe560a9..b72b6ac6 100644
--- a/tests/embedding/test_extractor.py
+++ b/tests/embedding/test_extractor.py
@@ -373,6 +373,27 @@ class TestDiscoverAndExtract:
with pytest.raises(ValueError, match=r"path.*limit"):
discover_and_extract(tmp_path, "skill")
+ @pytest.mark.parametrize("content_type", ["skill", "rules", "workflows"])
+ def test_discovery_path_budget_counts_directories_and_unselected_files(
+ self, tmp_path: Path, monkeypatch, content_type: str
+ ) -> None:
+ monkeypatch.setattr(extractor_module, "MAX_DISCOVERED_PATHS", 4)
+ manifest_name, manifest_text = {
+ "skill": ("SKILL.md", VALID_SKILL_MD),
+ "rules": ("rule.mdc", VALID_RULE_MDC),
+ "workflows": ("workflow-rules.mdc", VALID_WORKFLOW_MDC),
+ }[content_type]
+ item_dir = tmp_path / "nested" / "item"
+ item_dir.mkdir(parents=True)
+ (item_dir / manifest_name).write_text(manifest_text)
+ (item_dir / "a.bin").write_bytes(b"x")
+
+ assert len(discover_and_extract(tmp_path, content_type, max_entries=5_000)) == 1
+
+ (item_dir / "b.bin").write_bytes(b"x")
+ with pytest.raises(ValueError, match=r"Collection path limit exceeded \(4\)"):
+ discover_and_extract(tmp_path, content_type, max_entries=5_000)
+
def test_discovery_prunes_standard_excluded_directories(self, tmp_path: Path, write_skill, monkeypatch) -> None:
hidden_skill = tmp_path / ".git" / "nested-skill"
hidden_skill.mkdir(parents=True)
diff --git a/tests/embedding/test_pairwise_preflight.py b/tests/embedding/test_pairwise_preflight.py
new file mode 100644
index 00000000..eb1662f4
--- /dev/null
+++ b/tests/embedding/test_pairwise_preflight.py
@@ -0,0 +1,161 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Fresh pairwise scans reject unaffordable work before embedding later batches."""
+
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from skillevaluator.embedding.client import EmbeddingClient
+from skillevaluator.embedding.registry import EmbeddingRegistry, RegistryEntry
+from skillevaluator.tier2.commands import run_similarity_check
+
+ENTRY_COUNT = 65
+DIMENSION = 65
+PAIRWISE_WORK = ENTRY_COUNT * (ENTRY_COUNT - 1) // 2 * DIMENSION
+
+
+def _collection(root: Path) -> Path:
+ root.mkdir()
+ for index in range(ENTRY_COUNT):
+ directory = root / f"skill-{index:04}"
+ directory.mkdir()
+ (directory / "SKILL.md").write_text(
+ f"---\nname: skill-{index:04}\ndescription: Description {index}\n---\nBody\n"
+ )
+ return root
+
+
+def _client() -> MagicMock:
+ client = MagicMock(spec=EmbeddingClient)
+ client.model = "test-model"
+ client._resolved_config.return_value = SimpleNamespace(provider="openai", base_url="https://api.openai.com/v1")
+
+ def vector(text: str) -> list[float]:
+ name = text.split("name: ", 1)[1].splitlines()[0] if text.startswith("---") else text.split(":", 1)[0]
+ index = int(name.removeprefix("skill-"))
+ embedding = [0.0] * DIMENSION
+ embedding[0 if index == ENTRY_COUNT - 1 else index] = 1.0
+ return embedding
+
+ client.embed.side_effect = lambda texts: [vector(text) for text in texts]
+ client.embed_chunked.side_effect = vector
+ client.embed_single.return_value = vector("skill-0000: query")
+ return client
+
+
+def _assert_requests(client: MagicMock, *, full_body: bool, completes: bool) -> None:
+ if full_body:
+ assert client.embed_chunked.call_count == (ENTRY_COUNT if completes else 1)
+ client.embed.assert_not_called()
+ else:
+ assert [len(call.args[0]) for call in client.embed.call_args_list] == ([64, 1] if completes else [64])
+ client.embed_chunked.assert_not_called()
+
+
[email protected]("full_body", [False, True])
[email protected]("preexisting", [False, True])
+def test_preflight_stops_after_first_response_without_mutating_registry(tmp_path: Path, full_body, preexisting) -> None:
+ collection = _collection(tmp_path / "skills")
+ client = _client()
+ registry = EmbeddingRegistry(client, full_body=full_body, max_scalar_comparisons=PAIRWISE_WORK - 1)
+ if preexisting:
+ registry._entries["prior"] = RegistryEntry("prior", "Prior", "prior", "skill", [1.0] + [0.0] * 64)
+ registry._vector_dimension = DIMENSION
+ before = dict(registry._entries)
+ before_dimension = registry._vector_dimension
+
+ with pytest.raises(ValueError, match="--max-scalar-comparisons"):
+ registry.build_from_directory(collection, "skill", for_pairwise_scan=True)
+
+ assert registry._entries == before
+ assert registry._vector_dimension == before_dimension
+ _assert_requests(client, full_body=full_body, completes=False)
+
+
[email protected]("full_body", [False, True])
[email protected]("existing_output", [False, True])
+def test_failed_scan_does_not_create_or_replace_saved_index(tmp_path: Path, full_body, existing_output) -> None:
+ collection = _collection(tmp_path / "skills")
+ client = _client()
+ output = tmp_path / "catalog.json"
+ if existing_output:
+ output.write_text("existing index")
+ with patch("skillevaluator.validators.similarity.EmbeddingClient", return_value=client):
+ (result,) = run_similarity_check(
+ collection,
+ content_type="skill",
+ full_body=full_body,
+ max_scalar_comparisons=PAIRWISE_WORK - 1,
+ save_catalog=output,
+ )
+
+ assert any("--max-scalar-comparisons" in error for error in result.errors)
+ assert not result.findings
+ assert not any(success.check_name == "index_built" for success in result.success_details)
+ assert output.read_text() == "existing index" if existing_output else not output.exists()
+ _assert_requests(client, full_body=full_body, completes=False)
+
+
[email protected]("full_body", [False, True])
[email protected]("budget,completes", [(PAIRWISE_WORK - 1, False), (PAIRWISE_WORK, True)])
+def test_exact_pairwise_budget_allows_cross_batch_duplicate(tmp_path: Path, full_body, budget, completes) -> None:
+ collection = _collection(tmp_path / "skills")
+ client = _client()
+ with patch("skillevaluator.validators.similarity.EmbeddingClient", return_value=client):
+ (result,) = run_similarity_check(
+ collection, content_type="skill", full_body=full_body, max_scalar_comparisons=budget
+ )
+ _assert_requests(client, full_body=full_body, completes=completes)
+ if completes:
+ assert len(result.findings) == 1
+ assert {result.findings[0].metadata[key] for key in ("entry_a", "entry_b")} == {"skill-0000", "skill-0064"}
+ else:
+ assert any("--max-scalar-comparisons" in error for error in result.errors)
+ assert not result.findings
+
+
+def test_index_only_build_and_saved_query_do_not_require_pairwise_budget(tmp_path: Path) -> None:
+ collection = _collection(tmp_path / "skills")
+ client = _client()
+ query_work = ENTRY_COUNT * DIMENSION
+ registry = EmbeddingRegistry(client, max_scalar_comparisons=query_work)
+ assert registry.build_from_directory(collection, "skill") == ENTRY_COUNT
+ _assert_requests(client, full_body=False, completes=True)
+ with pytest.raises(ValueError, match="--max-scalar-comparisons"):
+ registry.find_duplicates(0.75)
+ assert len(registry.query("skill-0000: query", 0.75)) == 2
+ output = tmp_path / "catalog.json"
+ registry.save_catalog(output)
+ loaded = EmbeddingRegistry(client, max_entries=1, max_scalar_comparisons=query_work)
+ loaded.load_catalog(output)
+ assert len(loaded.query("skill-0000: query", 0.75)) == 2
+
+
[email protected]("failure", ["dimension", "count", "exception"])
+def test_later_invalid_batch_leaves_existing_registry_unchanged(tmp_path: Path, failure) -> None:
+ collection = _collection(tmp_path / "skills")
+ client = _client()
+ embed = client.embed.side_effect
+
+ def faulty_embed(texts):
+ if len(texts) == 64:
+ return embed(texts)
+ if failure == "exception":
+ raise ValueError("Provider failure")
+ return [] if failure == "count" else [[1.0, 0.0]]
+
+ client.embed.side_effect = faulty_embed
+ registry = EmbeddingRegistry(client)
+ prior = RegistryEntry("prior", "Prior", "prior", "skill", [1.0] + [0.0] * 64)
+ registry._entries["prior"] = prior
+ registry._vector_dimension = DIMENSION
+ before_dimension = registry._vector_dimension
+ with pytest.raises(ValueError):
+ registry.build_from_directory(collection, "skill", for_pairwise_scan=True)
+ assert registry._entries == {"prior": prior}
+ assert registry._vector_dimension == before_dimension
+ _assert_requests(client, full_body=False, completes=True)
diff --git a/tests/embedding/test_registry.py b/tests/embedding/test_registry.py
index 132223be..8a2b62ae 100644
--- a/tests/embedding/test_registry.py
+++ b/tests/embedding/test_registry.py
@@ -88,7 +88,7 @@ class TestBuildFromDirectory:
collection = tmp_path / "nested" / "external-skills"
collection.mkdir(parents=True)
debug = MagicMock()
- monkeypatch.setattr(registry_module, "discover_and_extract", lambda *_args: [])
+ monkeypatch.setattr(registry_module, "discover_and_extract", lambda *_args, **_kwargs: [])
monkeypatch.setattr(registry_module.logger, "debug", debug)
count = EmbeddingRegistry(_make_mock_client([])).build_from_directory(collection, "skill")
@@ -155,14 +155,13 @@ class TestBuildFromDirectory:
assert {entry.name for entry in registry._entries.values()} == {"shared-name"}
assert {entry.path for entry in registry._entries.values()} == {"team-a", "team-b"}
- def test_entry_limit_is_enforced_before_embedding(self, tmp_path: Path, write_skill, monkeypatch) -> None:
+ def test_entry_limit_is_enforced_before_embedding(self, tmp_path: Path, write_skill) -> None:
write_skill(tmp_path, "skill-a", "First skill")
write_skill(tmp_path, "skill-b", "Second skill")
- monkeypatch.setattr(extractor_module, "MAX_COLLECTION_ENTRIES", 1, raising=False)
client = _make_mock_client([[1.0, 0.0], [0.0, 1.0]])
with pytest.raises(ValueError, match="entry limit"):
- EmbeddingRegistry(client).build_from_directory(tmp_path, "skill")
+ EmbeddingRegistry(client, max_entries=1).build_from_directory(tmp_path, "skill")
client.embed.assert_not_called()
@@ -223,9 +222,9 @@ class TestBuildFromDirectory:
class TestFindDuplicates:
def _build_registry_with_entries(
- self, client: EmbeddingClient, entries: dict[str, list[float]]
+ self, client: EmbeddingClient, entries: dict[str, list[float]], **limits: int
) -> EmbeddingRegistry:
- registry = EmbeddingRegistry(client)
+ registry = EmbeddingRegistry(client, **limits)
for name, embedding in entries.items():
registry._entries[name] = RegistryEntry(
name=name,
@@ -306,16 +305,33 @@ class TestFindDuplicates:
scores = [m.score for m in matches]
assert scores == sorted(scores, reverse=True)
+ def test_pairwise_scan_normalizes_each_vector_once(self, monkeypatch) -> None:
+ vectors = {"a": [1.0, 0.0, 2.0], "b": [3.0, 0.5, 1.0], "c": [2.0, 1.0, 4.0], "d": [0.2, 3.0, 1.0]}
+ registry = self._build_registry_with_entries(_make_mock_client([]), vectors)
+ normalize = MagicMock(wraps=registry_module.normalize_embedding_vector)
+ monkeypatch.setattr(registry_module, "normalize_embedding_vector", normalize)
+
+ matches = registry.find_duplicates(threshold=0.0)
+
+ assert normalize.call_count == len(vectors)
+ assert len(matches) == 6
+ for match in matches:
+ expected = EmbeddingClient.cosine_similarity(vectors[match.entry_a], vectors[match.entry_b])
+ assert match.score == pytest.approx(expected, abs=1e-15)
+
def test_pairwise_comparison_limit_fails_before_comparing(self, monkeypatch) -> None:
client = _make_mock_client([])
registry = self._build_registry_with_entries(
client,
{"a": [1.0, 0.0], "b": [1.0, 0.0], "c": [1.0, 0.0]},
+ max_entries=2,
)
- monkeypatch.setattr(registry_module, "MAX_PAIRWISE_COMPARISONS", 2, raising=False)
+ cosine = MagicMock(side_effect=AssertionError("limit must fail before cosine"))
+ monkeypatch.setattr(registry_module, "unit_vector_similarity", cosine)
with pytest.raises(ValueError, match="comparison limit"):
registry.find_duplicates(0.75)
+ cosine.assert_not_called()
def test_pairwise_match_limit_fails_closed(self, monkeypatch) -> None:
client = _make_mock_client([])
@@ -323,7 +339,6 @@ class TestFindDuplicates:
client,
{"a": [1.0, 0.0], "b": [1.0, 0.0], "c": [1.0, 0.0]},
)
- monkeypatch.setattr(registry_module, "MAX_PAIRWISE_COMPARISONS", 10, raising=False)
monkeypatch.setattr(registry_module, "MAX_SIMILARITY_MATCHES", 1, raising=False)
with pytest.raises(ValueError, match="match limit"):
@@ -334,11 +349,17 @@ class TestFindDuplicates:
registry = self._build_registry_with_entries(
client,
{"a": [1.0, 0.0], "b": [1.0, 0.0]},
+ max_scalar_comparisons=1,
)
- monkeypatch.setattr(registry_module, "MAX_SCALAR_COMPARISONS", 1, raising=False)
+ cosine = MagicMock(side_effect=AssertionError("limit must fail before cosine"))
+ monkeypatch.setattr(registry_module, "unit_vector_similarity", cosine)
+ normalize = MagicMock(side_effect=AssertionError("limit must fail before normalizing vectors"))
+ monkeypatch.setattr(registry_module, "normalize_embedding_vector", normalize)
with pytest.raises(ValueError, match=r"scalar.*limit|work limit"):
registry.find_duplicates(0.75)
+ cosine.assert_not_called()
+ normalize.assert_not_called()
class TestCachePersistence:
diff --git a/tests/embedding/test_similarity_limits.py b/tests/embedding/test_similarity_limits.py
new file mode 100644
index 00000000..0ce7a729
--- /dev/null
+++ b/tests/embedding/test_similarity_limits.py
@@ -0,0 +1,293 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Collection size and comparison work are independent, configurable limits."""
+
+import json
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+import pytest
+from click.testing import CliRunner
+
+import skillevaluator.embedding.registry as registry_module
+from skillevaluator.cli import cli
+from skillevaluator.embedding.client import EmbeddingClient
+from skillevaluator.embedding.extractor import ContentEntry, discover_and_extract
+from skillevaluator.embedding.registry import EmbeddingRegistry
+from skillevaluator.tier2.commands import run_similarity_check
+from skillevaluator.validators.similarity import SimilarityValidator
+
+
+def _collection(root: Path, count: int) -> None:
+ for index in range(count):
+ directory = root / f"skill-{index:04d}"
+ directory.mkdir(parents=True, exist_ok=True)
+ (directory / "SKILL.md").write_text(f"---\nname: skill-{index}\ndescription: Description {index}\n---\n")
+
+
+def _client(dimension: int = 3, duplicate_last: bool = False) -> MagicMock:
+ client = MagicMock(spec=EmbeddingClient)
+ client.model = "test-model"
+ client._resolved_config.return_value = SimpleNamespace(provider="openai", base_url="https://api.openai.com/v1")
+
+ def embed(texts: list[str]) -> list[list[float]]:
+ vectors = []
+ for text in texts:
+ index = int(text.split(":", 1)[0].removeprefix("skill-"))
+ vector = [0.0] * dimension
+ vector[0 if duplicate_last and index == 342 else index] = 1.0
+ vectors.append(vector)
+ return vectors
+
+ client.embed.side_effect = embed
+ client.embed_single.return_value = [1.0] + [0.0] * (dimension - 1)
+ return client
+
+
[email protected]("value", [0, -1, 5_001, True, False, 1.5, "343", None])
+def test_invalid_entry_limits_fail_at_python_boundaries(tmp_path: Path, value: object) -> None:
+ with pytest.raises(ValueError, match="--max-entries"):
+ discover_and_extract(tmp_path, "skill", max_entries=value)
+ with pytest.raises(ValueError, match="--max-entries"):
+ EmbeddingRegistry(_client(), max_entries=value)
+ with pytest.raises(ValueError, match="--max-entries"):
+ SimilarityValidator(max_entries=value)
+
+
[email protected]("value", [0, -1, True, False, 1.5, "128000000", None])
+def test_invalid_scalar_limits_fail_at_python_boundaries(value: object) -> None:
+ with pytest.raises(ValueError, match="--max-scalar-comparisons"):
+ EmbeddingRegistry(_client(), max_scalar_comparisons=value)
+ with pytest.raises(ValueError, match="--max-scalar-comparisons"):
+ SimilarityValidator(max_scalar_comparisons=value)
+
+
+def test_default_entry_boundary_and_explicit_increase(tmp_path: Path) -> None:
+ _collection(tmp_path, 1_024)
+ assert len(discover_and_extract(tmp_path, "skill")) == 1_024
+ _collection(tmp_path, 1_025)
+ with pytest.raises(ValueError, match=r"entry limit exceeded \(1024\).*--max-entries"):
+ discover_and_extract(tmp_path, "skill")
+ assert len(discover_and_extract(tmp_path, "skill", max_entries=1_025)) == 1_025
+ assert EmbeddingRegistry(_client(), max_entries=5_000).size == 0
+
+
+def test_maximum_entry_budget_extracts_all_5000_skills(tmp_path: Path) -> None:
+ _collection(tmp_path, 5_000)
+
+ entries = discover_and_extract(tmp_path, "skill", max_entries=5_000)
+
+ assert len(entries) == 5_000
+ assert {entry.name for entry in entries} == {f"skill-{index}" for index in range(5_000)}
+
+
[email protected]("content_type", ["skill", "rules", "workflows"])
+def test_entry_budget_counts_selected_invalid_manifests(tmp_path: Path, content_type: str) -> None:
+ for index in range(2):
+ directory = tmp_path / str(index)
+ directory.mkdir()
+ filename = {"skill": "SKILL.md", "rules": "rule.mdc", "workflows": "workflow-rules.mdc"}[content_type]
+ (directory / filename).write_text("No valid frontmatter")
+ with pytest.raises(ValueError, match="--max-entries"):
+ discover_and_extract(tmp_path, content_type, max_entries=1)
+
+
+def test_default_scan_compares_all_343_skills_at_2048_dimensions(tmp_path: Path, monkeypatch) -> None:
+ _collection(tmp_path, 343)
+ client = _client(2_048, duplicate_last=True)
+ monkeypatch.setattr("skillevaluator.validators.similarity.EmbeddingClient", lambda **_kwargs: client)
+
+ (result,) = run_similarity_check(tmp_path, content_type="skill")
+
+ assert not result.is_incomplete
+ assert len(result.errors) == 1
+ assert result.errors[0].startswith("[SIMILARITY-CRITICAL]")
+ indexed = next(detail for detail in result.success_details if detail.check_name == "index_built")
+ assert indexed.metadata["entry_count"] == 343
+ assert sum(len(call.args[0]) for call in client.embed.call_args_list) == 343
+ assert len(result.findings) == 1
+ match = result.findings[0]
+ assert {match.metadata["entry_a"], match.metadata["entry_b"]} == {"skill-0", "skill-342"}
+ assert match.metadata["score"] == 1.0
+
+
[email protected]("limit, succeeds", [(8, False), (9, True)])
+def test_cli_passes_comparison_budget_through_real_pipeline(tmp_path: Path, monkeypatch, limit: int, succeeds: bool):
+ _collection(tmp_path, 3)
+ client = _client()
+ monkeypatch.setattr("skillevaluator.validators.similarity.EmbeddingClient", lambda **_kwargs: client)
+ cosine = MagicMock(wraps=registry_module.unit_vector_similarity)
+ monkeypatch.setattr(registry_module, "unit_vector_similarity", cosine)
+
+ result = CliRunner().invoke(
+ cli,
+ [
+ "similarity-check",
+ str(tmp_path),
+ "--type",
+ "skill",
+ "--max-entries",
+ "3",
+ "--max-scalar-comparisons",
+ str(limit),
+ "-r",
+ "cli",
+ ],
+ )
+
+ assert result.exit_code == (0 if succeeds else 1), result.output
+ assert cosine.call_count == (3 if succeeds else 0)
+ if not succeeds:
+ assert "--max-scalar-comparisons" in result.output
+
+
+def test_cli_entry_limit_fails_without_embedding_or_partial_catalog(tmp_path: Path, monkeypatch) -> None:
+ _collection(tmp_path, 3)
+ client = _client()
+ monkeypatch.setattr("skillevaluator.validators.similarity.EmbeddingClient", lambda **_kwargs: client)
+ catalog = tmp_path / "catalog.json"
+
+ result = CliRunner().invoke(
+ cli,
+ [
+ "similarity-check",
+ str(tmp_path),
+ "--type",
+ "skill",
+ "--max-entries",
+ "2",
+ "--save-catalog",
+ str(catalog),
+ "-r",
+ "cli",
+ ],
+ )
+
+ assert result.exit_code == 1
+ assert "--max-entries" in result.output
+ client.embed.assert_not_called()
+ client.embed_chunked.assert_not_called()
+ assert not catalog.exists()
+
+
+ "flag,value",
+ [("--max-entries", "0"), ("--max-entries", "5001"), ("--max-scalar-comparisons", "0"), ("--max-entries", "1.5")],
+)
+def test_cli_rejects_invalid_limits(tmp_path: Path, monkeypatch, flag: str, value: str) -> None:
+ client = _client()
+ monkeypatch.setattr("skillevaluator.validators.similarity.EmbeddingClient", lambda **_kwargs: client)
+ result = CliRunner().invoke(cli, ["similarity-check", str(tmp_path), flag, value])
+ assert result.exit_code == 2
+ assert flag in result.output
+ client.embed.assert_not_called()
+
+
[email protected]("query_method", ["query", "query_entry"])
[email protected]("limit, succeeds", [(8, False), (9, True)])
+def test_catalog_queries_keep_catalog_capacity_and_apply_work_budget(
+ tmp_path: Path, monkeypatch, query_method: str, limit: int, succeeds: bool
+) -> None:
+ _collection(tmp_path, 3)
+ client = _client()
+ source = EmbeddingRegistry(client)
+ source.build_from_directory(tmp_path, "skill")
+ catalog = tmp_path / "catalog.json"
+ source.save_catalog(catalog)
+ registry = EmbeddingRegistry(client, max_entries=1, max_scalar_comparisons=limit)
+ registry.load_catalog(catalog)
+ assert registry.size == 3
+ cosine = MagicMock(wraps=registry_module.unit_vector_similarity)
+ monkeypatch.setattr(registry_module, "unit_vector_similarity", cosine)
+ target = ContentEntry("target", "Target skill", "target", "skill") if query_method == "query_entry" else "target"
+ if succeeds:
+ matches = getattr(registry, query_method)(target, 0.75)
+ assert len(matches) == 1
+ assert matches[0].entry_b == "skill-0"
+ assert cosine.call_count == 3
+ else:
+ with pytest.raises(ValueError, match="--max-scalar-comparisons"):
+ getattr(registry, query_method)(target, 0.75)
+ client.embed_single.assert_not_called()
+ cosine.assert_not_called()
+
+
+# Distinct skills with this embedding previously scored 0.9999999999999999 after normalization.
+_EXACT_DUPLICATE_VECTOR = [-5.479683767155414, -6.166558151604646]
+
+
+def _identical_client() -> MagicMock:
+ client = _client()
+ client.embed.side_effect = lambda texts: [list(_EXACT_DUPLICATE_VECTOR) for _ in texts]
+ client.embed_single.return_value = list(_EXACT_DUPLICATE_VECTOR)
+ return client
+
+
+def test_cli_reports_identical_embeddings_at_threshold_one(tmp_path: Path, monkeypatch) -> None:
+ _collection(tmp_path / "skills", 2)
+ client = _identical_client()
+ monkeypatch.setattr("skillevaluator.validators.similarity.EmbeddingClient", lambda **_kwargs: client)
+ reports = tmp_path / "reports"
+
+ result = CliRunner().invoke(
+ cli,
+ [
+ "similarity-check",
+ str(tmp_path / "skills"),
+ "--type",
+ "skill",
+ "--threshold",
+ "1",
+ "-r",
+ "json",
+ "sarif",
+ "-o",
+ str(reports),
+ ],
+ )
+
+ assert result.exit_code == 1, result.output
+ (finding,) = json.loads((reports / "skillevaluator-similarity.json").read_text())["results"][0]["findings"]
+ assert finding["check_name"] == "EXACT_DUPLICATE"
+ assert finding["metadata"]["score"] == 1.0
+ sarif = json.loads((reports / "skillevaluator-similarity.sarif.json").read_text())
+ assert [item["ruleId"] for item in sarif["runs"][0]["results"]] == ["Similarity-Check/EXACT_DUPLICATE"]
+
+
[email protected]("query_method", ["query", "query_entry"])
+def test_catalog_queries_report_identical_embeddings_at_threshold_one(tmp_path: Path, query_method: str) -> None:
+ _collection(tmp_path, 2)
+ registry = EmbeddingRegistry(_identical_client())
+ registry.build_from_directory(tmp_path, "skill")
+ target = ContentEntry("target", "Target skill", "target", "skill") if query_method == "query_entry" else "target"
+
+ assert [match.score for match in getattr(registry, query_method)(target, 1.0)] == [1.0, 1.0]
+ assert [match.score for match in registry.find_duplicates(1.0)] == [1.0]
+
+
[email protected]("operation", ["find_duplicates", "query", "query_entry"])
+def test_loaded_catalog_rejects_over_budget_work_before_normalizing(
+ tmp_path: Path, monkeypatch, operation: str
+) -> None:
+ _collection(tmp_path, 3)
+ client = _client()
+ source = EmbeddingRegistry(client)
+ source.build_from_directory(tmp_path, "skill")
+ catalog = tmp_path / "catalog.json"
+ source.save_catalog(catalog)
+ registry = EmbeddingRegistry(client, max_scalar_comparisons=8)
+ registry.load_catalog(catalog)
+ normalize = MagicMock(side_effect=AssertionError("the work budget must fail before normalizing the catalog"))
+ monkeypatch.setattr(registry_module, "normalize_embedding_vector", normalize)
+ target = ContentEntry("target", "Target skill", "target", "skill") if operation == "query_entry" else "target"
+
+ with pytest.raises(ValueError, match="--max-scalar-comparisons"):
+ if operation == "find_duplicates":
+ registry.find_duplicates(0.75)
+ else:
+ getattr(registry, operation)(target, 0.75)
+
+ normalize.assert_not_called()
+ client.embed_single.assert_not_called()
diff --git a/tests/golden/cli_surface.json b/tests/golden/cli_surface.json
index c1a2b70d..16f5c5a1 100644
--- a/tests/golden/cli_surface.json
+++ b/tests/golden/cli_surface.json
@@ -1080,6 +1080,24 @@
"param_type": "option",
"type": "text"
},
+ {
+ "default": "1024",
+ "name": "max_entries",
+ "opts": [
+ "--max-entries"
+ ],
+ "param_type": "option",
+ "type": "integer range"
+ },
+ {
+ "default": "128000000",
+ "name": "max_scalar_comparisons",
+ "opts": [
+ "--max-scalar-comparisons"
+ ],
+ "param_type": "option",
+ "type": "integer range"
+ },
{
"name": "catalog",
"opts": [
@@ -1751,6 +1769,24 @@
"param_type": "option",
"type": "text"
},
+ {
+ "default": "1024",
+ "name": "max_entries",
+ "opts": [
+ "--max-entries"
+ ],
+ "param_type": "option",
+ "type": "integer range"
+ },
+ {
+ "default": "128000000",
+ "name": "max_scalar_comparisons",
+ "opts": [
+ "--max-scalar-comparisons"
+ ],
+ "param_type": "option",
+ "type": "integer range"
+ },
{
"name": "catalog",
"opts": [
diff --git a/tests/test_tier2_command_failures.py b/tests/test_tier2_command_failures.py
index 72425cb4..bc33bad4 100644
--- a/tests/test_tier2_command_failures.py
+++ b/tests/test_tier2_command_failures.py
@@ -18,16 +18,44 @@ from skillevaluator.models.result import Finding, Severity, ValidationResult
from skillevaluator.tier2 import commands
[email protected]("option", ["max_entries", "max_scalar_comparisons"])
[email protected]("value", [0, -1, True, False, 1.5, "private-input", None])
+def test_similarity_check_rejects_invalid_limit_options_before_construction(
+ tmp_path: Path, monkeypatch, option: str, value: object
+) -> None:
+ def unexpected_construction(**_kwargs):
+ pytest.fail("Invalid limit options must be rejected before constructing the validator")
+
+ monkeypatch.setattr(commands, "SimilarityValidator", unexpected_construction)
+
+ with pytest.raises(ValueError, match=option) as failure:
+ commands.run_similarity_check(tmp_path, **{option: value})
+
+ assert f"--{option.replace('_', '-')}" in str(failure.value)
+ assert "private-input" not in str(failure.value)
+ assert "provider" not in str(failure.value)
+
+
+def test_similarity_check_rejects_entry_limit_above_hard_cap(tmp_path: Path) -> None:
+ with pytest.raises(ValueError, match=r"max_entries.*--max-entries"):
+ commands.run_similarity_check(tmp_path, max_entries=5_001)
+
+
[email protected]("during_construction", [False, True])
[email protected]("error_type", [RuntimeError, ValueError])
def test_similarity_check_wraps_unexpected_validator_exceptions(
tmp_path: Path,
monkeypatch,
+ during_construction: bool,
+ error_type: type[Exception],
) -> None:
class BrokenSimilarityValidator:
def __init__(self, **_kwargs):
- pass
+ if during_construction:
+ raise error_type("provider body contains private-token")
def validate(self, _content_path: Path):
- raise RuntimeError("provider body contains private-token")
+ raise error_type("provider body contains private-token")
monkeypatch.setattr(commands, "SimilarityValidator", BrokenSimilarityValidator)
diff --git a/tests/validators/test_similarity.py b/tests/validators/test_similarity.py
index d738f549..5d7617b6 100644
--- a/tests/validators/test_similarity.py
+++ b/tests/validators/test_similarity.py
@@ -97,6 +97,7 @@ class TestValidateNoContent:
tmp_path,
"rules",
minimum_entries=2,
+ for_pairwise_scan=True,
)