Skip to content

Commit 8af9698

Browse files
committed
Fix CodeRabbit review issues in EXPLAIN command
- Remove random state mutations from explain methods (deterministic now) - Fix type hint: Dict[str, any] -> Dict[str, Any] - Add smart query truncation (only when needed) - Improve cached query display formatting - Add missing Any import in rl_agent.py All explain methods now have no side effects and provide consistent output.
1 parent a37a88b commit 8af9698

2 files changed

Lines changed: 37 additions & 15 deletions

File tree

nexum_ai/optimizer.py

Lines changed: 32 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -256,8 +256,15 @@ def explain_query(self, query: str) -> Dict[str, Any]:
256256

257257
for entry in self.cache:
258258
similarity = self.cosine_similarity(query_vec, entry['vector'])
259+
# Smart truncation for cached query display
260+
cached_query = entry['query']
261+
if len(cached_query) > 50:
262+
display_query = cached_query[:50] + '...'
263+
else:
264+
display_query = cached_query
265+
259266
cache_analysis.append({
260-
'cached_query': entry['query'][:50] + ('...' if len(entry['query']) > 50 else ''),
267+
'cached_query': display_query,
261268
'similarity': round(similarity, 4),
262269
'would_hit': similarity >= self.similarity_threshold
263270
})
@@ -268,11 +275,17 @@ def explain_query(self, query: str) -> Dict[str, Any]:
268275
# Sort by similarity descending
269276
cache_analysis.sort(key=lambda x: x['similarity'], reverse=True)
270277

278+
# Smart truncation for best match
279+
if best_match and len(best_match) > 50:
280+
best_match_display = best_match[:50] + '...'
281+
else:
282+
best_match_display = best_match
283+
271284
return {
272285
'query': query,
273286
'cache_entries_checked': len(self.cache),
274287
'similarity_threshold': self.similarity_threshold,
275-
'best_match': best_match[:50] + '...' if best_match and len(best_match) > 50 else best_match,
288+
'best_match': best_match_display,
276289
'best_similarity': round(best_similarity, 4),
277290
'would_hit_cache': best_similarity >= self.similarity_threshold,
278291
'top_matches': cache_analysis[:5] # Top 5 similar cached queries
@@ -360,15 +373,14 @@ def explain_action(self, query: str, available_actions: List[str]) -> Dict[str,
360373
q_values = {a: 0.0 for a in available_actions}
361374

362375
best_action = max(available_actions, key=lambda a: q_values.get(a, 0.0))
363-
would_explore = np.random.random() < self.epsilon
364376

365377
return {
366378
'state': state,
367379
'q_values': q_values,
368380
'best_action': best_action,
369381
'epsilon': self.epsilon,
370-
'would_explore': would_explore,
371-
'exploration_note': 'Random action possible' if would_explore else 'Would use best action'
382+
'would_explore': self.epsilon > 0,
383+
'exploration_note': f'Random action possible (ε={self.epsilon})' if self.epsilon > 0 else 'Would use best action'
372384
}
373385

374386

@@ -470,7 +482,15 @@ def format_explain_output(explain_result: Dict[str, Any]) -> str:
470482
lines.append("=" * 70)
471483
lines.append("QUERY EXECUTION PLAN")
472484
lines.append("=" * 70)
473-
lines.append(f"Query: {explain_result['query'][:60]}...")
485+
486+
# Smart query truncation
487+
query = explain_result['query']
488+
if len(query) > 60:
489+
display_query = query[:60] + "..."
490+
else:
491+
display_query = query
492+
493+
lines.append(f"Query: {display_query}")
474494
lines.append("")
475495

476496
# Parsing section
@@ -491,14 +511,18 @@ def format_explain_output(explain_result: Dict[str, Any]) -> str:
491511
for match in c['top_matches'][:3]:
492512
sim = match['similarity']
493513
hit = "✓" if match['would_hit'] else "✗"
494-
lines.append(f"│ {hit} {sim:.4f} - {match['cached_query'][:45]:<45} │")
514+
# Smart truncation for cached queries
515+
cached_query = match['cached_query']
516+
if not cached_query.endswith('...') and len(cached_query) > 45:
517+
cached_query = cached_query[:42] + "..."
518+
lines.append(f"│ {hit} {sim:.4f} - {cached_query:<45} │")
495519
lines.append("└───────────────────────────────────────────────────────────────────┘")
496520
lines.append("")
497521

498522
# RL Agent section
499523
lines.append("┌─ RL AGENT ────────────────────────────────────────────────────────┐")
500524
r = explain_result['rl_agent']
501-
lines.append(f"│ State: {r['state']:<30} Epsilon: {r['epsilon']:<6} │")
525+
lines.append(f"│ State: {r['state']:<30} Epsilon: {r.get('epsilon', r.get('exploration_probability', 0)):<6} │")
502526
lines.append(f"│ Best action: {r['best_action']:<20} │")
503527
lines.append("│ Q-values: │")
504528
for action, qval in r['q_values'].items():

nexum_ai/rl_agent.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
"""
55

66
import numpy as np
7-
from typing import Dict, Optional
7+
from typing import Dict, Optional, Any
88

99

1010
class QLearningAgent:
@@ -173,7 +173,7 @@ def get_stats(self) -> Dict[str, float]:
173173
'avg_reward': np.mean([h['reward'] for h in self.training_history[-100:]]) if self.training_history else 0.0
174174
}
175175

176-
def explain_action(self, query_length: int, cache_hit: bool, complexity: int) -> Dict[str, any]:
176+
def explain_action(self, query_length: int, cache_hit: bool, complexity: int) -> Dict[str, Any]:
177177
"""
178178
Explain what action would be taken without executing
179179
Returns Q-values, state analysis, and predicted action for EXPLAIN command
@@ -189,9 +189,6 @@ def explain_action(self, query_length: int, cache_hit: bool, complexity: int) ->
189189
# Determine best action
190190
best_action = max(self.actions, key=lambda a: q_values.get(a, 0.0))
191191

192-
# Check if exploration would occur
193-
would_explore = np.random.random() < self.epsilon
194-
195192
return {
196193
'state': state,
197194
'state_breakdown': {
@@ -202,8 +199,9 @@ def explain_action(self, query_length: int, cache_hit: bool, complexity: int) ->
202199
'q_values': q_values,
203200
'best_action': best_action,
204201
'epsilon': round(self.epsilon, 4),
205-
'would_explore': would_explore,
206-
'predicted_action': np.random.choice(self.actions) if would_explore else best_action,
202+
'would_explore': self.epsilon > 0,
203+
'predicted_action': best_action, # Deterministic for explain
204+
'exploration_probability': round(self.epsilon, 4),
207205
'agent_stats': {
208206
'total_states_learned': len(self.q_table),
209207
'total_updates': len(self.training_history),

0 commit comments

Comments
 (0)