use serde_json::json;
use std::collections::HashSet;
use super::rank;
use super::recall::CHANNEL_FIELD;
use crate::db::graph::{QueryExt as _, RootCoverage};
use crate::db::vector::UuidProbe;
use crate::db::vector::VectorSearchExt as _;
pub(super) const TOP_ROOTS: usize = 8;
pub(crate) const PROBE_ROOTS_MAX: usize = 3;
const CALLER_LINK_LIMIT: usize = TOP_ROOTS * 32;
const CALLER_LINK_LIMIT_DEPTH2: usize = TOP_ROOTS * 16;
pub(super) fn seed_roots(
rows: &[serde_json::Value],
top_roots: usize,
probe_max: usize,
) -> Vec<String> {
let mut seedable: Vec<(&str, f32, &str, i64, bool)> = rows
.iter()
.filter_map(|row| {
let uuid = row.get("uuid").and_then(|v| v.as_str())?;
let kind = row.get("kind").and_then(|v| v.as_str()).unwrap_or("");
let path = row.get("file_path").and_then(|v| v.as_str()).unwrap_or("");
let ctx_flag = row
.get("is_test_context")
.and_then(|v| v.as_bool())
.unwrap_or(false);
if rank::kind_boost(kind) < 0.0 || rank::is_test_path(path) || ctx_flag {
return None;
}
let cosine = row.get("score").and_then(|v| v.as_f64()).unwrap_or(0.0) as f32;
let line = row.get("start_line").and_then(|v| v.as_i64()).unwrap_or(0);
let probe = row.get(CHANNEL_FIELD).and_then(|v| v.as_str()) == Some("probe");
Some((uuid, cosine, path, line, probe))
})
.collect();
seedable.sort_by(|a, b| {
b.1.partial_cmp(&a.1)
.unwrap_or(std::cmp::Ordering::Equal)
.then_with(|| a.2.cmp(b.2))
.then_with(|| a.3.cmp(&b.3))
.then_with(|| a.0.cmp(b.0))
});
let mut roots: Vec<String> = Vec::new();
let mut probes = 0usize;
for (uuid, _, _, _, probe) in &seedable {
if roots.len() == top_roots {
break;
}
if *probe {
if probes >= probe_max {
continue;
}
probes += 1;
}
roots.push((*uuid).to_string());
}
roots
}
pub(super) fn supersedes_caller(
caller_production: bool,
caller_direct: usize,
callee_direct: usize,
) -> bool {
caller_production && caller_direct >= 2 && caller_direct > callee_direct
}
pub(super) struct CallerBridge<'a> {
pub vector: &'a [f32],
pub roots: &'a [String],
pub seen_uuids: &'a HashSet<String>,
pub repo_names: &'a [String],
pub expanded_kinds: &'a [String],
pub ctx: &'a super::SearchContext<'a>,
}
impl CallerBridge<'_> {
pub async fn run(&self, pool_cap: usize) -> Vec<serde_json::Value> {
let direct_links = self
.ctx
.graph_db
.find_caller_links(self.roots, self.repo_names, CALLER_LINK_LIMIT)
.await
.unwrap_or_default();
if direct_links.is_empty() {
return Vec::new();
}
let mut caller_uuids: HashSet<String> = direct_links
.iter()
.map(|(caller, _)| caller.clone())
.collect();
let mut hits = self.fetch_callers(&caller_uuids, pool_cap).await;
if hits.len() < pool_cap {
let depth2_links = self
.ctx
.graph_db
.find_caller_links_depth2(self.roots, self.repo_names, CALLER_LINK_LIMIT_DEPTH2)
.await
.unwrap_or_default();
let before = caller_uuids.len();
for (caller, _) in depth2_links {
caller_uuids.insert(caller);
}
if caller_uuids.len() > before {
let mut depth2_hits = self
.fetch_callers(&caller_uuids, pool_cap - hits.len())
.await;
hits.append(&mut depth2_hits);
}
}
hits
}
async fn fetch_callers(
&self,
caller_uuids: &HashSet<String>,
limit: usize,
) -> Vec<serde_json::Value> {
if limit == 0 {
return Vec::new();
}
let visible: Vec<String> = caller_uuids
.iter()
.filter(|u| !self.seen_uuids.contains(*u))
.cloned()
.collect();
if visible.is_empty() {
return Vec::new();
}
let mut hits = self
.ctx
.vector_db
.search_by_uuids(UuidProbe {
vector: self.vector,
uuids: &visible,
repo_names: self.repo_names,
kinds: self.expanded_kinds,
limit,
})
.await
.unwrap_or_default();
hits.retain(|hit| {
hit.get("uuid")
.and_then(|v| v.as_str())
.is_some_and(|u| caller_uuids.contains(u))
});
hits
}
}
pub(super) async fn annotate_root_coverage(
pool: &mut [serde_json::Value],
top_roots: &[String],
repo_names: &[String],
ctx: &super::SearchContext<'_>,
) {
if pool.is_empty() || top_roots.is_empty() {
return;
}
let pool_uuids: Vec<String> = pool
.iter()
.filter_map(|hit| hit.get("uuid").and_then(|v| v.as_str()))
.map(String::from)
.collect();
if pool_uuids.is_empty() {
return;
}
let coverage = ctx
.graph_db
.fetch_root_coverage(&pool_uuids, top_roots, repo_names, pool_uuids.len())
.await
.unwrap_or_default();
if coverage.is_empty() {
return;
}
let by_uuid: std::collections::HashMap<&str, &RootCoverage> = coverage
.iter()
.map(|row| (row.uuid.as_str(), row))
.collect();
let pool_meta: std::collections::HashMap<&str, (&str, &str, bool)> = pool
.iter()
.filter_map(|hit| {
Some((
hit.get("uuid")?.as_str()?,
(
hit.get("kind")?.as_str()?,
hit.get("file_path")?.as_str()?,
hit.get("is_test_context")
.and_then(|v| v.as_bool())
.unwrap_or(false),
),
))
})
.collect();
let in_pool: HashSet<&str> = pool_uuids.iter().map(String::as_str).collect();
let mut superseded: HashSet<String> = HashSet::new();
if let Ok(links) = ctx
.graph_db
.find_caller_links(&pool_uuids, repo_names, pool_uuids.len() * 16)
.await
{
for (caller, callee) in links.iter().filter(|(caller, callee)| {
in_pool.contains(caller.as_str())
&& in_pool.contains(callee.as_str())
&& caller != callee
}) {
let (Some(caller_cov), Some(callee_cov)) =
(by_uuid.get(caller.as_str()), by_uuid.get(callee.as_str()))
else {
continue;
};
let caller_production =
pool_meta
.get(caller.as_str())
.is_some_and(|(kind, file_path, ctx_flag)| {
!rank::is_test_row(kind, file_path, *ctx_flag)
});
if supersedes_caller(
caller_production,
caller_cov.direct_roots,
callee_cov.direct_roots,
) {
superseded.insert(callee.clone());
}
}
}
for hit in pool.iter_mut() {
let uuid = hit.get("uuid").and_then(|v| v.as_str()).unwrap_or("");
let Some(row) = by_uuid.get(uuid) else {
continue;
};
let superseded_here = superseded.contains(uuid);
let Some(obj) = hit.as_object_mut() else {
continue;
};
obj.entry("fqn").or_insert_with(|| json!(row.fqn));
obj.insert("caller_roots".to_string(), json!(row.direct_roots));
obj.insert(
"caller_roots_transitive".to_string(),
json!(row.transitive_roots),
);
obj.insert("caller_root_total".to_string(), json!(top_roots.len()));
obj.insert("caller_out_degree".to_string(), json!(row.out_degree));
obj.insert("caller_superseded".to_string(), json!(superseded_here));
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn provenance_moves_only_to_full_orchestrator_signatures() {
assert!(supersedes_caller(true, 3, 2));
assert!(
!supersedes_caller(true, 2, 2),
"equal coverage must not halve the entry point"
);
assert!(!supersedes_caller(true, 1, 2), "subset caller never wins");
assert!(
!supersedes_caller(true, 1, 0),
"1-root caller is not an orchestrator"
);
}
#[test]
fn provenance_ignores_test_callers() {
assert!(!supersedes_caller(false, 5, 2));
}
}