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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .jules/bolt.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,7 @@
## 2026-05-16 - Pre-processing for RAG Retrieval
**Learning:** In RAG (Retrieval-Augmented Generation) systems with static or semi-static policy datasets, performing tokenization, regex substitution, and string formatting inside the retrieval loop is a significant bottleneck that scales with the number of policies.
**Action:** Move all deterministic operations (tokenization, formatting, regex matching prep) to a one-time initialization step to ensure the retrieval hot-path only performs necessary set intersections and similarity calculations.

## 2026-05-18 - Mathematical Set Operations for Jaccard Similarity
**Learning:** Calculating Jaccard similarity (|A ∩ B| / |A βˆͺ B|) using `set.union()` inside a retrieval loop incurs significant O(N) memory allocation and population overhead. Since |A βˆͺ B| = |A| + |B| - |A ∩ B|, the union size can be calculated via O(1) arithmetic if set sizes are pre-calculated.
**Action:** Pre-calculate set lengths for static data. In retrieval loops, use `isdisjoint()` for early exits and the inclusion-exclusion formula to avoid explicit set union operations.
Comment on lines +89 to +91
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟑 Minor

Avoid future-dating this note.

Line 89 uses 2026-05-18, which is after this PR’s current date. That makes the note order look inconsistent and can confuse readers/tools that sort these entries chronologically.

πŸ€– Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.jules/bolt.md around lines 89 - 91, The changelog entry titled "2026-05-18
- Mathematical Set Operations for Jaccard Similarity" is future-dated; update
the header date to the correct (non-future) date for this PR so entries remain
chronologically consistent, e.g., replace "2026-05-18" with today's or the PR
date in that header text, keeping the rest of the entry unchanged.

26 changes: 16 additions & 10 deletions backend/rag_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,12 @@ def _prepare_policies(self):
source = policy.get('source', 'Unknown')

content = f"{title} {text}"
content_tokens = self._tokenize(content)

self._prepared_policies.append({
'title_tokens': self._tokenize(title),
'content_tokens': self._tokenize(content),
'content_tokens': content_tokens,
'content_token_count': len(content_tokens),
'formatted': f"**{title}**: {text} (Source: {source})",
'original': policy
})
Expand All @@ -65,12 +67,14 @@ def retrieve(self, query: str, threshold: float = 0.05) -> Optional[str]:
"""
Retrieve the most relevant policy based on Jaccard similarity of tokens.
Returns the formatted policy string or None if below threshold.
Optimized: Uses pre-calculated token lengths and mathematical union to avoid O(N) union.
"""
if not query or not self._prepared_policies:
return None

query_tokens = self._tokenize(query)
if not query_tokens:
query_token_count = len(query_tokens)
if query_token_count == 0:
return None

best_score = 0.0
Expand All @@ -79,19 +83,21 @@ def retrieve(self, query: str, threshold: float = 0.05) -> Optional[str]:
for prepared in self._prepared_policies:
policy_tokens = prepared['content_tokens']

if not policy_tokens:
# Performance: Use isdisjoint for fast early-exit when there is no overlap
if query_tokens.isdisjoint(policy_tokens):
continue

# Jaccard Similarity
intersection = query_tokens.intersection(policy_tokens)
# Use pre-calculated set for union if possible?
# Union depends on query_tokens, so must be calculated.
union = query_tokens.union(policy_tokens)
# Jaccard Similarity: |A ∩ B| / |A βˆͺ B|
intersection_count = len(query_tokens.intersection(policy_tokens))

if not union:
# Performance: Use mathematical formula for union length: |A βˆͺ B| = |A| + |B| - |A ∩ B|
# This avoids O(N) allocation and population of a new union set.
union_count = query_token_count + prepared['content_token_count'] - intersection_count
Comment on lines +90 to +95
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟑 Minor

Replace the Unicode union symbol in the comment.

Ruff is already flagging βˆͺ; using plain ASCII here will keep the note portable and silence the warning.

Suggested tweak
-            # Jaccard Similarity: |A ∩ B| / |A βˆͺ B|
+            # Jaccard Similarity: |A ∩ B| / |A union B|
🧰 Tools
πŸͺ› Ruff (0.15.12)

[warning] 90-90: Comment contains ambiguous βˆͺ (UNION). Did you mean U (LATIN CAPITAL LETTER U)?

(RUF003)


[warning] 93-93: Comment contains ambiguous βˆͺ (UNION). Did you mean U (LATIN CAPITAL LETTER U)?

(RUF003)

πŸ€– Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/rag_service.py` around lines 90 - 95, The comment uses the Unicode
union symbol `βˆͺ` which triggers Ruff; update the comment above the union_count
calculation to use plain ASCII (e.g., "A U B" or the word "union") instead of
`βˆͺ`. Locate the block around variables intersection_count, query_tokens,
policy_tokens, query_token_count and prepared['content_token_count'] (the
union_count computation) and replace the Unicode symbol in the explanatory
comment with an ASCII alternative.


if union_count == 0:
continue

score = len(intersection) / len(union)
score = intersection_count / union_count

# Boost score if title words match (weighted)
title_tokens = prepared['title_tokens']
Expand Down
Loading