Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
15 changes: 14 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,19 @@ All notable changes to SkillEvaluator are documented in this file.
dimensions, 362 at 4,096), which the incomplete-scan error and the JSON
`work_limit` record now report as `effective_chunk_limit`, next to the
skill's own `chunk_count`.
- Tier 2 context deduplication no longer stops skills with many repeated
sections at the `llm_cluster_member_limit` work limit. A candidate cluster
with more than 64 members was reported as incomplete even when its review
prompt fit the 64,000-character budget. The member limit now equals the
512-chunk ceiling, so the per-cluster prompt, total prompt, and cluster-count
limits decide. When a cluster's request (system prompt plus cluster text)
would exceed 64,000 characters, each exactly repeated chunk text is sent once
as `SHARED CONTENT n`, and every occurrence keeps its own entry with its file,
section, and line range. Distinct text is never dropped or sampled, so a
cluster still over the budget stays incomplete with `llm_prompt_size_limit`.
Duplicate and `llm_refused` finding messages name at most 64 member locations
and source files and count the rest; the JSON `source_files` list stays
complete.
- Local-mode verifier uploads now copy directly to the absent destination,
avoiding an unnecessary rollback snapshot of an empty tests directory.
Inputs and rewritten scripts are prepared privately before publication,
Expand Down Expand Up @@ -459,7 +472,7 @@ All notable changes to SkillEvaluator are documented in this file.

- A skill that exceeds a Tier 2 context-deduplication work limit (more than
512 content chunks, too much pairwise comparison work, or an LLM-review limit:
more than 50 candidate clusters, more than 64 members in one cluster, or an
more than 50 candidate clusters, more than 512 members in one cluster, or an
oversized per-cluster or total review prompt) is now reported as
**INCOMPLETE** instead of failing with a CRITICAL `chunk_count_limit`,
`scalar_comparison_limit`, `llm_cluster_count_limit`,
Expand Down
16 changes: 16 additions & 0 deletions docs/tier2-deduplication.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,18 @@ Duplicate findings map to severities by confidence:
| `DUPLICATE` with confidence < 0.70 | MEDIUM — advisory |
| Short, same-file duplicate dominated by comment or configuration-style text | Capped at LOW — advisory |

Each candidate cluster is reviewed in one chat-LLM request that carries every
member's file, section, line range, and text. When that request (the system
prompt plus the cluster text) would exceed 64,000 characters, text that repeats
exactly is listed once as `SHARED CONTENT n`. Each occurrence keeps its own
entry with its file, section, and line range, plus a reference to the shared
text. Distinct text is always sent in full; nothing is sampled or dropped to
fit. A cluster that is still over 64,000 characters stops the scan as
incomplete (`llm_prompt_size_limit`), as described below. A duplicate or
`llm_refused` finding names up to 64 member locations and source files and
counts the rest; its `source_files` metadata in the JSON report lists every
file.

If chat-LLM analysis fails for a candidate cluster, Tier 2 reports the
incomplete analysis as a blocking error rather than treating the content as
clean.
Expand Down Expand Up @@ -341,6 +353,10 @@ you intend to skip Tier 2 entirely.
| High-confidence duplicate boundary | `0.70` | Maps actionable duplicate verdicts to HIGH rather than MEDIUM |
| Intra-skill content chunks | 512 | Per-skill ceiling, checked before any embedding request |
| Intra-skill comparison work | 267,911,168 scalar comparisons | Bounds all-pairs clustering; allows all 512 chunks with embeddings of up to 2,048 dimensions, 418 chunks at 3,072, and 362 at 4,096 |
| Intra-skill LLM review clusters | 50 | Most candidate clusters sent for chat-LLM review in one skill |
| Intra-skill cluster members | 512 | Same as the chunk ceiling; every member must also fit the review prompt limits |
| Intra-skill review prompt | 64,000 characters | One cluster's request, system prompt included; exactly repeated text is listed once before this limit applies |
| Intra-skill review prompts in total | 1,000,000 characters | All cluster requests for one skill, checked before the first chat-LLM call |

Intra-skill clustering compares every pair of chunks, so its work is
`n * (n - 1) / 2 * dimensions`. A skill over the chunk ceiling stops before any
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
CONTENT_DEDUP_TRIVIAL_DUP_MAX_CHARS,
)
from skillevaluator.deduplication.intra_skill.llm_analyzer import (
MAX_PROMPT_CHARS,
SYSTEM_PROMPT,
analyze_cluster,
build_user_prompt,
Expand All @@ -48,9 +49,16 @@
# config assignment. Used to recognize repeated config/comment snippets.
_COMMENT_PREFIXES = ("#", ";", "//", "--", "!")
_CONFIG_KV_RE = re.compile(r"^[\w.\-/]+\s*[=:]\s*\S")
CONTENT_DEDUP_MAX_CLUSTER_MEMBERS = 64
CONTENT_DEDUP_MAX_LLM_PROMPT_CHARS = 64_000
# One cluster may hold every chunk of the scan. The per-call and aggregate
# prompt budgets bound paid review; a fixed member cap below the chunk ceiling
# would refuse large repeated-content clusters whose prompt fits.
CONTENT_DEDUP_MAX_CLUSTER_MEMBERS = CONTENT_DEDUP_MAX_CHUNKS
Comment thread
rng1995 marked this conversation as resolved.
Resolved
# build_user_prompt shares exactly repeated text against this same budget.
CONTENT_DEDUP_MAX_LLM_PROMPT_CHARS = MAX_PROMPT_CHARS
Comment thread
rng1995 marked this conversation as resolved.
Resolved
CONTENT_DEDUP_MAX_TOTAL_LLM_PROMPT_CHARS = 1_000_000
# Most member locations and source files named in one finding message. The
# rest are counted, so a finding for a 512-member cluster stays a few kilobytes.
_MAX_REPORTED_LOCATIONS = 64

# Scan label recorded when a work limit stops duplicate analysis early.
_WORK_LIMIT_SCAN = "context-deduplication"
Expand Down Expand Up @@ -112,6 +120,27 @@ def _is_trivial_intra_file_duplicate(cluster: ContentCluster) -> bool:
return all(_chunk_is_short_config(member) for member in cluster.members)


def _cluster_location_text(cluster: ContentCluster) -> tuple[str, str]:
"""Return the finding scope and member location list, bounded in length."""
distinct_files = sorted({c.source_file for c in cluster.members})
if len(distinct_files) == 1:
scope = f"within {distinct_files[0]}"
else:
scope = f"across {' and '.join(distinct_files[:_MAX_REPORTED_LOCATIONS])}"
if (omitted_files := len(distinct_files) - _MAX_REPORTED_LOCATIONS) > 0:
scope += f" and {omitted_files} more file{'s' if omitted_files != 1 else ''}"

locations = [
f'"{c.heading}" in {c.source_file} (lines {c.start_line}-{c.end_line})'
for c in cluster.members[:_MAX_REPORTED_LOCATIONS]
]
location_text = "\n vs ".join(locations)
if (omitted := len(cluster.members) - _MAX_REPORTED_LOCATIONS) > 0:
noun = "locations" if omitted != 1 else "location"
location_text += f"\n and {omitted} more {noun} ({len(cluster.members)} in total)"
return scope, location_text


def _mark_work_limit_incomplete(
result: ValidationResult,
check_name: str,
Expand Down Expand Up @@ -418,15 +447,7 @@ def analyze_one(cluster):
continue

distinct_files = sorted({c.source_file for c in cluster.members})

locations = []
for c in cluster.members:
locations.append(f'"{c.heading}" in {c.source_file} (lines {c.start_line}-{c.end_line})')
location_text = "\n vs ".join(locations)
if len(distinct_files) == 1:
scope = f"within {distinct_files[0]}"
else:
scope = f"across {' and '.join(distinct_files)}"
scope, location_text = _cluster_location_text(cluster)

if verdict is None:
# Report the refused overlap so the author can review it, but
Expand Down
42 changes: 40 additions & 2 deletions src/skillevaluator/deduplication/intra_skill/llm_analyzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

from __future__ import annotations

from collections import Counter
from typing import TYPE_CHECKING, Any

from skillevaluator.inference import LLMClient, LLMClientError, LLMVerdict
Expand All @@ -18,6 +19,10 @@

VALID_VERDICTS = {"DUPLICATE", "INTENTIONAL_DETAIL", "RELATED_BUT_DISTINCT"}

# Per-call budget for one review request: SYSTEM_PROMPT plus the user prompt.
# The validator refuses a cluster whose request is still over it.
MAX_PROMPT_CHARS = 64_000

VERDICT_JSON_SCHEMA: dict[str, Any] = {
"type": "object",
"properties": {
Expand Down Expand Up @@ -55,15 +60,48 @@


def build_user_prompt(cluster: ContentCluster) -> str:
"""Build the user prompt from cluster member chunks."""
"""Build the user prompt from cluster member chunks.

Every member is rendered with its full text. When the request
(``SYSTEM_PROMPT`` plus this prompt) would exceed ``MAX_PROMPT_CHARS``,
each exactly repeated chunk text is listed once as ``SHARED CONTENT n``.
Every occurrence keeps its own ``CHUNK`` entry with file, section and
lines, plus a reference to the shared text. Distinct text is never
dropped or shortened, so a request still over budget stays over budget.
"""
prompt = _render_user_prompt(cluster)
if len(SYSTEM_PROMPT) + len(prompt) <= MAX_PROMPT_CHARS:
return prompt
counts = Counter(chunk.text for chunk in cluster.members)
Comment thread
rng1995 marked this conversation as resolved.
Resolved
repeated = (text for text, count in counts.items() if count > 1)
shared = {text: index for index, text in enumerate(repeated, start=1)}
if not shared:
return prompt
compact = _render_user_prompt(cluster, shared)
return compact if len(compact) < len(prompt) else prompt


def _render_user_prompt(cluster: ContentCluster, shared: dict[str, int] | None = None) -> str:
"""Render every member; texts in ``shared`` are listed once and referenced."""
parts: list[str] = []
if shared:
parts.append(
"Identical content is listed once below. Each content reference stands for the exact "
"shared text. Review every occurrence in its own file, section and line context. "
"No chunks were omitted."
)
parts.extend(f"---SHARED CONTENT {index}---\n{text}" for text, index in shared.items())
for i, chunk in enumerate(cluster.members, start=1):
if shared and chunk.text in shared:
content = f"Content reference: SHARED CONTENT {shared[chunk.text]}"
else:
content = f"Content:\n{chunk.text}"
parts.append(
f"---CHUNK {i}---\n"
f"File: {chunk.source_file}\n"
f"Section: {chunk.heading}\n"
f"Lines: {chunk.start_line}-{chunk.end_line}\n"
f"Content:\n{chunk.text}"
f"{content}"
)

parts.append(f"\nEmbedding similarity: {cluster.max_similarity:.3f}")
Expand Down
118 changes: 118 additions & 0 deletions tests/deduplication/intra_skill/test_intra_llm_analyzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,116 @@

import pytest

from skillevaluator.deduplication.intra_skill import llm_analyzer
from skillevaluator.deduplication.intra_skill.llm_analyzer import (
SYSTEM_PROMPT,
VERDICT_JSON_SCHEMA,
analyze_cluster,
build_user_prompt,
verdict_to_severity,
)
from skillevaluator.deduplication.intra_skill.semantic_clustering import ContentCluster
from skillevaluator.inference import LLMClient, LLMClientError, LLMVerdict
from skillevaluator.models.result import Severity


def _request_chars(prompt: str) -> int:
"""Characters of one review request, measured as the validator measures it."""
return len(SYSTEM_PROMPT) + len(prompt)


class TestBuildUserPrompt:
def test_large_repeated_content_preserves_each_occurrence(self, make_chunk) -> None:
repeated = "Exact repeated instructions. " * 10
unique = "Unique instructions for the final section. " * 3
members = [
make_chunk(source_file=f"file-{index // 4}.md", heading=f"Section {index}", text=repeated)
for index in range(500)
]
members.append(make_chunk(source_file="unique.md", heading="Unique", text=unique))
cluster = ContentCluster(members, 0.95, 0.85, True, {"markdown"})

prompt = build_user_prompt(cluster)

assert _request_chars(prompt) <= llm_analyzer.MAX_PROMPT_CHARS
assert prompt.count(repeated) == 1
assert prompt.count(unique) == 1
assert prompt.count("---SHARED CONTENT ") == 1
assert prompt.count("---CHUNK ") == 501
assert prompt.count("Content reference: SHARED CONTENT 1") == 500
assert "No chunks were omitted." in prompt
for index, member in enumerate(members, start=1):
assert (
f"---CHUNK {index}---\nFile: {member.source_file}\nSection: {member.heading}\n"
f"Lines: {member.start_line}-{member.end_line}\n"
) in prompt
assert f"Section: Unique\nLines: 1-5\nContent:\n{unique}" in prompt
assert prompt.endswith("Classify this content overlap.")

def test_each_repeated_text_is_shared_once_in_first_seen_order(self, make_chunk) -> None:
first = "f" * 1_500
second = "s" * 1_500
members = [make_chunk(heading=f"Section {index}", text=first if index % 2 else second) for index in range(60)]
cluster = ContentCluster(members, 0.95, 0.85, False, {"markdown"})

prompt = build_user_prompt(cluster)

assert _request_chars(prompt) <= llm_analyzer.MAX_PROMPT_CHARS
assert prompt.count(first) == prompt.count(second) == 1
assert prompt.index(f"---SHARED CONTENT 1---\n{second}") < prompt.index(f"---SHARED CONTENT 2---\n{first}")
assert prompt.count("Content reference: SHARED CONTENT 1") == 30
assert prompt.count("Content reference: SHARED CONTENT 2") == 30
assert "Section: Section 1\nLines: 1-5\nContent reference: SHARED CONTENT 2" in prompt

def test_request_budget_includes_the_system_prompt(self, make_chunk, monkeypatch) -> None:
repeated = "r" * 2_000
filler = make_chunk(source_file="unique.md", heading="Unique", text="u" * 80)
members = [make_chunk(heading=f"Section {index}", text=repeated) for index in range(30)]
cluster = ContentCluster([*members, filler], 0.95, 0.85, True, {"markdown"})
budget = llm_analyzer.MAX_PROMPT_CHARS
with monkeypatch.context() as patched:
patched.setattr(llm_analyzer, "MAX_PROMPT_CHARS", 10**9)
filler.text += "u" * (budget - len(SYSTEM_PROMPT) // 2 - len(build_user_prompt(cluster)))
full_prompt = build_user_prompt(cluster)
# The user prompt alone fits; the request with the system prompt does not.
assert len(full_prompt) <= budget < _request_chars(full_prompt)

prompt = build_user_prompt(cluster)

assert _request_chars(prompt) <= budget
assert prompt.count(repeated) == 1
assert prompt.count(filler.text) == 1
assert prompt.count("---CHUNK ") == 31

def test_prompt_within_budget_keeps_every_occurrence_inline(self, make_chunk) -> None:
repeated = "Exact repeated instructions. " * 10
members = [make_chunk(heading=f"Section {index}", text=repeated) for index in range(3)]

prompt = build_user_prompt(ContentCluster(members, 0.95, 0.85, False, {"markdown"}))

assert prompt.count(f"Content:\n{repeated}") == 3
assert "SHARED CONTENT" not in prompt

def test_distinct_text_over_budget_is_never_dropped_or_shared(self, make_chunk) -> None:
members = [make_chunk(heading=f"Member {index}", text=f"{index}: " + "x" * 80) for index in range(500)]

prompt = build_user_prompt(ContentCluster(members, 0.95, 0.85, False, {"markdown"}))

assert _request_chars(prompt) > llm_analyzer.MAX_PROMPT_CHARS
assert "SHARED CONTENT" not in prompt
for member in members:
assert f"Section: {member.heading}\nLines: 1-5\nContent:\n{member.text}" in prompt

def test_sharing_is_skipped_when_it_does_not_shorten_the_prompt(self, make_chunk) -> None:
members = [make_chunk(heading=f"Distinct {index}", text=f"{index}: " + "d" * 2_500) for index in range(30)]
members += [make_chunk(heading=f"Short {index}", text="short repeated line") for index in range(2)]

prompt = build_user_prompt(ContentCluster(members, 0.95, 0.85, False, {"markdown"}))

assert _request_chars(prompt) > llm_analyzer.MAX_PROMPT_CHARS
assert "SHARED CONTENT" not in prompt
assert prompt.count("Content:\nshort repeated line") == 2

def test_contains_chunk_details(self, make_cluster) -> None:
cluster = make_cluster()
prompt = build_user_prompt(cluster)
Expand Down Expand Up @@ -112,6 +210,26 @@ def test_missing_verdict_raises(self, make_cluster) -> None:
with pytest.raises(LLMClientError, match="unknown verdict"):
analyze_cluster(mock_client, make_cluster())

def test_sends_the_shared_content_prompt_that_the_validator_measures(self, make_chunk) -> None:
repeated = "Exact repeated instructions. " * 10
members = [make_chunk(heading=f"Section {index}", text=repeated) for index in range(500)]
cluster = ContentCluster(members, 0.95, 0.85, False, {"markdown"})
mock_client = MagicMock(spec=LLMClient)
mock_client.extract_json_from_response.return_value = {
"verdict": "DUPLICATE",
"confidence": 0.9,
"rationale": "Same instructions in every section",
"suggestion": "Keep one copy",
}

analyze_cluster(mock_client, cluster)

system_prompt, user_prompt = mock_client.extract_json_from_response.call_args.args
assert system_prompt == SYSTEM_PROMPT
assert user_prompt == build_user_prompt(cluster)
assert user_prompt.count(repeated) == 1
assert _request_chars(user_prompt) <= llm_analyzer.MAX_PROMPT_CHARS

def test_requests_the_verdict_schema_and_reads_rationale(self, make_cluster) -> None:
mock_client = MagicMock(spec=LLMClient)
mock_client.extract_json_from_response.return_value = {
Expand Down
Loading
Loading