1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
//! Graph-based importance scoring using chunk_edges.
//!
//! This module implements PageRank-like importance scoring based on
//! incoming edges from the chunk_edges table. Different edge types
//! contribute different weights to the importance score.
use crate::config::SearchConfig;
use crate::db::traits::StoreGraph;
use crate::db::SqliteStore;
use crate::search::executor_types::{RankedResult, RankedResults, SearchSource};
use tracing::{debug, instrument};
/// Graph importance executor.
///
/// Calculates PageRank-like scores from chunk_edges table:
/// - Incoming calls: 0.3 weight
/// - Incoming imports: 0.2 weight
/// - Test coverage: 0.1 weight
///
/// Uses logarithmic scaling to dampen extreme values.
/// Over-fetches results (limit * 2) for fusion.
pub struct GraphExecutor;
impl GraphExecutor {
/// Execute graph importance query.
///
/// # Parameters
/// - `store`: Database store
/// - `repo_id`: Repository ID to filter results
/// - `worktree_id`: Optional worktree ID for additional filtering
/// - `limit`: Maximum number of results (will over-fetch by 2x)
/// - `config`: Optional search config to control quality-weighted scoring
///
/// # Returns
/// RankedResults with graph importance scores normalized to 0.0-1.0 range
///
/// # Quality-Weighted Mode
/// When `config.feature_flags.enable_quality_weighted_graph` is true,
/// uses quality-weighted edge scoring with configurable weights from
/// `config.graph_importance.edge_quality_weights` (SRCHREL-2002).
/// When false or config is None, uses legacy graph scoring.
///
/// # SQL Query (Legacy Mode)
/// ```sql
/// WITH edge_counts AS (
/// SELECT
/// dst_chunk_id as chunk_id,
/// COUNT(*) FILTER (WHERE type = 'calls') as callers,
/// COUNT(*) FILTER (WHERE type = 'imports') as importers,
/// COUNT(*) FILTER (WHERE type = 'test_of') as tests
/// FROM maproom.chunk_edges
/// GROUP BY dst_chunk_id
/// )
/// SELECT
/// c.id,
/// COALESCE(
/// LOG(2 + COALESCE(e.callers, 0)) * 0.3 +
/// LOG(2 + COALESCE(e.importers, 0)) * 0.2 +
/// LOG(2 + COALESCE(e.tests, 0)) * 0.1,
/// 0
/// ) as graph_score
/// FROM maproom.chunks c
/// JOIN maproom.files f ON f.id = c.file_id
/// LEFT JOIN edge_counts e ON e.chunk_id = c.id
/// WHERE f.repo_id = $1
/// AND ($2::bigint IS NULL OR f.worktree_id = $2)
/// ORDER BY graph_score DESC
/// LIMIT $3;
/// ```
#[instrument(skip(store, config))]
pub async fn execute(
store: &SqliteStore,
repo_id: i64,
worktree_id: Option<i64>,
limit: usize,
config: Option<&SearchConfig>,
) -> Result<RankedResults, GraphError> {
// Over-fetch by 2x for fusion (graph signals are less selective than FTS/vector)
let fetch_limit = (limit * 2) as i64;
// Extract feature flag, default to false if config not provided
let enable_quality = config
.map(|c| c.feature_flags.enable_quality_weighted_graph)
.unwrap_or(false);
// Extract edge quality weights from config, or use defaults (SRCHREL-2002)
let weights = config
.map(|c| c.graph_importance.edge_quality_weights.clone())
.unwrap_or_default();
debug!(
repo_id = repo_id,
worktree_id = ?worktree_id,
limit = limit,
enable_quality = enable_quality,
production_code_weight = weights.production_code,
test_code_weight = weights.test_code,
calls_weight = weights.calls,
"Executing graph importance query"
);
// Delegate to SqliteStore's graph importance calculation with configurable weights
let hits = store
.calculate_graph_importance(
repo_id,
worktree_id,
fetch_limit as usize,
enable_quality,
&weights,
)
.await
.map_err(|e| GraphError::Database(e.to_string()))?;
// Convert SearchHit to RankedResult
let results: Vec<RankedResult> = hits
.into_iter()
.enumerate()
.map(|(i, hit)| RankedResult::new(hit.chunk_id, hit.score as f32, i + 1))
.collect();
debug!("Graph search returned {} results", results.len());
Ok(RankedResults::new(results, SearchSource::Graph))
}
/// Execute graph importance query for specific chunk IDs.
///
/// This variant calculates graph scores only for a given set of chunks,
/// useful when combining with other search results.
#[instrument(skip(store, chunk_ids), fields(chunk_count = chunk_ids.len()))]
pub async fn execute_for_chunks(
store: &SqliteStore,
chunk_ids: &[i64],
repo_id: i64,
worktree_id: Option<i64>,
) -> Result<RankedResults, GraphError> {
if chunk_ids.is_empty() {
return Ok(RankedResults::empty(SearchSource::Graph));
}
debug!(
"Executing graph importance query for {} specific chunks",
chunk_ids.len()
);
// Delegate to SqliteStore's graph importance calculation for specific chunks
let hits = store
.calculate_graph_importance_for_chunks(chunk_ids, repo_id, worktree_id)
.await
.map_err(|e| GraphError::Database(e.to_string()))?;
// Convert SearchHit to RankedResult
let results: Vec<RankedResult> = hits
.into_iter()
.enumerate()
.map(|(i, hit)| RankedResult::new(hit.chunk_id, hit.score as f32, i + 1))
.collect();
debug!("Graph search for chunks returned {} results", results.len());
Ok(RankedResults::new(results, SearchSource::Graph))
}
}
/// Errors that can occur during graph query execution.
#[derive(Debug, thiserror::Error)]
pub enum GraphError {
/// Database query error
#[error("Database error: {0}")]
Database(String),
/// No edge data available
#[error("No graph data available")]
NoGraphData,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::FeatureFlags;
#[test]
fn test_graph_executor_exists() {
// Verify the executor type exists
let _executor = GraphExecutor;
}
#[test]
fn test_extract_quality_flag_none_config() {
// None config should default to false
let config: Option<&SearchConfig> = None;
let enable_quality = config
.map(|c| c.feature_flags.enable_quality_weighted_graph)
.unwrap_or(false);
assert!(!enable_quality, "None config should default to false");
}
#[test]
fn test_extract_quality_flag_disabled() {
// Config with flag disabled should return false
let config = SearchConfig::default();
assert!(
!config.feature_flags.enable_quality_weighted_graph,
"Default config should have quality flag disabled"
);
let enable_quality = Some(&config)
.map(|c| c.feature_flags.enable_quality_weighted_graph)
.unwrap_or(false);
assert!(!enable_quality, "Disabled flag should return false");
}
#[test]
fn test_extract_quality_flag_enabled() {
// Config with flag enabled should return true
let mut config = SearchConfig::default();
config.feature_flags.enable_quality_weighted_graph = true;
let enable_quality = Some(&config)
.map(|c| c.feature_flags.enable_quality_weighted_graph)
.unwrap_or(false);
assert!(enable_quality, "Enabled flag should return true");
}
#[test]
fn test_feature_flags_quality_graph_default() {
// Verify the FeatureFlags default for quality weighted graph
let flags = FeatureFlags::default();
assert!(
!flags.enable_quality_weighted_graph,
"enable_quality_weighted_graph should default to false"
);
}
// ===== SRCHREL-2002: Weight Extraction Tests =====
#[test]
fn test_extract_weights_none_config() {
// None config should use default weights (SRCHREL-2002)
let config: Option<&SearchConfig> = None;
let weights = config
.map(|c| c.graph_importance.edge_quality_weights.clone())
.unwrap_or_default();
assert!(
(weights.production_code - 1.0).abs() < f32::EPSILON,
"Default production_code weight should be 1.0"
);
assert!(
(weights.test_code - 0.5).abs() < f32::EPSILON,
"Default test_code weight should be 0.5"
);
assert!(
(weights.calls - 1.0).abs() < f32::EPSILON,
"Default calls weight should be 1.0"
);
}
#[test]
fn test_extract_weights_from_config() {
// Config with custom weights should extract correctly (SRCHREL-2002)
let mut config = SearchConfig::default();
config.graph_importance.edge_quality_weights.production_code = 2.0;
config.graph_importance.edge_quality_weights.test_code = 0.3;
config.graph_importance.edge_quality_weights.calls = 1.5;
let weights = Some(&config)
.map(|c| c.graph_importance.edge_quality_weights.clone())
.unwrap_or_default();
assert!(
(weights.production_code - 2.0).abs() < f32::EPSILON,
"Custom production_code weight should be 2.0"
);
assert!(
(weights.test_code - 0.3).abs() < f32::EPSILON,
"Custom test_code weight should be 0.3"
);
assert!(
(weights.calls - 1.5).abs() < f32::EPSILON,
"Custom calls weight should be 1.5"
);
}
#[test]
fn test_extract_weights_default_from_config() {
// Config with default weights should match EdgeQualityWeights::default() (SRCHREL-2002)
let config = SearchConfig::default();
let weights = Some(&config)
.map(|c| c.graph_importance.edge_quality_weights.clone())
.unwrap_or_default();
assert!(
weights.is_default(),
"Default config should have default weights"
);
}
// Note: Full integration tests with real database are in tests/search/executors_test.rs
}