feat: port face clustering to Rust (rust_face_cluster) with A/B gating

- rust_face_cluster: seed-leader + agglomerative clustering port of
  fast_face_clustering_processor.py (Qdrant _faces scroll, trace aggregation,
  auto speaker bind, strict 2dp rounding parity)
- A/B verified vs Python on same Qdrant snapshot: both methods match on
  cluster membership/trace_id/confidence (leader + agglomerative)
- face_clustering.rs: USE_RUST_PROCESSORS switch with Python fallback
- executor.rs: run_rust_with_output_idx_and_frames (+ QDRANT env passthrough)
- appearance/pose: re-use rust runner path (previous migration)
- verify_face_cluster.py / verify_pose.py / verify_appearance.py: A/B harness
This commit is contained in:
Accusys
2026-09-16 21:50:07 +08:00
parent 362a735a91
commit e25c279eeb
14 changed files with 4473 additions and 27 deletions
+71 -26
View File
@@ -3,6 +3,7 @@ use serde::{Deserialize, Serialize};
use std::time::Duration;
use super::executor::PythonExecutor;
use crate::core::config::USE_RUST_PROCESSORS;
const APPEARANCE_TIMEOUT: Duration = Duration::from_secs(7200);
@@ -66,36 +67,80 @@ pub async fn process_appearance(
}
let executor = PythonExecutor::new()?;
let script_name = "appearance_processor.py";
let script_path = executor.script_path(script_name);
tracing::info!(
"[APPEARANCE] Starting appearance extraction: {}",
video_path
);
if *USE_RUST_PROCESSORS {
if let Some(rust_bin) = executor.rust_binary_path("rust_appearance") {
tracing::info!("[APPEARANCE] Using Rust binary: {:?}", rust_bin);
executor
.run_rust_with_output_idx_and_frames(
&rust_bin,
&[video_path, pose_path, output_path],
Some(2),
uuid,
frames,
"APPEARANCE",
Some(APPEARANCE_TIMEOUT),
)
.await
.with_context(|| format!("Failed to run Rust binary {:?}", rust_bin))?;
} else {
tracing::warn!(
"[APPEARANCE] MOMENTRY_USE_RUST_PROCESSORS=1 but rust_appearance binary not found, falling back to Python"
);
let script_name = "appearance_processor.py";
let script_path = executor.script_path(script_name);
if !script_path.exists() {
tracing::warn!("[APPEARANCE] Script not found, returning empty result");
return Ok(AppearanceResult {
frame_count: 0,
fps: 0.0,
frames: vec![],
});
}
executor
.run_with_output_idx_and_frames(
script_name,
&[video_path, pose_path, output_path],
uuid,
"APPEARANCE",
Some(APPEARANCE_TIMEOUT),
Some(2),
frames,
)
.await
.with_context(|| format!("Failed to run {:?}", script_path))?;
}
} else {
let script_name = "appearance_processor.py";
let script_path = executor.script_path(script_name);
if !script_path.exists() {
tracing::warn!("[APPEARANCE] Script not found, returning empty result");
return Ok(AppearanceResult {
frame_count: 0,
fps: 0.0,
frames: vec![],
});
if !script_path.exists() {
tracing::warn!("[APPEARANCE] Script not found, returning empty result");
return Ok(AppearanceResult {
frame_count: 0,
fps: 0.0,
frames: vec![],
});
}
tracing::info!(
"[APPEARANCE] Starting appearance extraction (Python): {}",
video_path
);
executor
.run_with_output_idx_and_frames(
script_name,
&[video_path, pose_path, output_path],
uuid,
"APPEARANCE",
Some(APPEARANCE_TIMEOUT),
Some(2),
frames,
)
.await
.with_context(|| format!("Failed to run {:?}", script_path))?;
}
executor
.run_with_output_idx_and_frames(
script_name,
&[video_path, pose_path, output_path],
uuid,
"APPEARANCE",
Some(APPEARANCE_TIMEOUT),
Some(2),
frames,
)
.await
.with_context(|| format!("Failed to run {:?}", script_path))?;
let json_str =
std::fs::read_to_string(output_path).context("Failed to read APPEARANCE output")?;
+191
View File
@@ -1159,6 +1159,197 @@ impl PythonExecutor {
}
}
/// Resolve the path to a compiled Rust processor binary.
/// Looks under `<scripts_dir>/rust_processors/target/release/` first, falling
/// back to `target/debug/` (mirrors the swift_processors layout convention).
pub fn rust_binary_path(&self, bin_name: &str) -> Option<PathBuf> {
let base = self.scripts_dir.join("rust_processors").join("target");
for profile in ["release", "debug"] {
let p = base.join(profile).join(bin_name);
if p.exists() {
return Some(p);
}
}
None
}
/// Run a Rust processor binary with the same output-tmp / timeout / process-group
/// semantics as the Python scripts. `output_idx` is the arg index for the output
/// JSON path; `uuid`/`frames` are appended as `--uuid=X` and `--frames=a,b,c`
/// when provided.
pub async fn run_rust_with_output_idx_and_frames(
&self,
bin_path: &std::path::Path,
args: &[&str],
output_idx: Option<usize>,
uuid: Option<&str>,
frames: Option<&[i64]>,
log_prefix: &str,
timeout_duration: Option<Duration>,
) -> Result<()> {
if !bin_path.exists() {
anyhow::bail!("Rust processor not found: {:?}", bin_path);
}
let output_path =
output_idx.and_then(|idx| args.get(idx).map(|p| std::path::PathBuf::from(p)));
let tmp_path = output_path.as_ref().map(|p| {
let mut tmp = p.to_path_buf();
tmp.set_extension("json.tmp");
tmp
});
let mut cmd = Command::new(bin_path);
cmd.env("MOMENTRY_OUTPUT_DIR", &*OUTPUT_DIR);
cmd.env("DATABASE_SCHEMA", &*DATABASE_SCHEMA);
cmd.env("MOMENTRY_DB_SCHEMA", &*DATABASE_SCHEMA);
cmd.env("MOMENTRY_REDIS_PREFIX", &*REDIS_KEY_PREFIX);
if let Ok(qdrant_url) = std::env::var("QDRANT_URL") {
cmd.env("QDRANT_URL", qdrant_url);
}
if let Ok(qdrant_api_key) = std::env::var("QDRANT_API_KEY") {
cmd.env("QDRANT_API_KEY", qdrant_api_key);
}
for (i, arg) in args.iter().enumerate() {
if Some(i) == output_idx {
if let Some(ref tmp) = tmp_path {
cmd.arg(tmp);
continue;
}
}
cmd.arg(arg);
}
if let Some(frames) = frames {
if !frames.is_empty() {
let frames_str = Self::format_frames_arg(frames);
cmd.arg("--frames").arg(&frames_str);
}
}
if let Some(u) = uuid {
cmd.arg("--uuid").arg(u);
}
cmd.stdout(Stdio::piped());
cmd.stderr(Stdio::piped());
cmd.kill_on_drop(true);
cmd.process_group(0);
tracing::info!("[{}] Starting rust: {:?}", log_prefix, cmd);
let mut child = cmd.spawn().with_context(|| {
format!("Failed to run Rust processor {:?}", bin_path)
})?;
let child_pid = child.id();
let stdout = child.stdout.take().context("Failed to capture stdout")?;
let stderr = child.stderr.take().context("Failed to capture stderr")?;
let mut stdout_reader = BufReader::new(stdout).lines();
let mut stderr_reader = BufReader::new(stderr).lines();
let run_future = async {
let mut stdout_done = false;
let mut stderr_done = false;
loop {
tokio::select! {
line = stdout_reader.next_line(), if !stdout_done => {
match line {
Ok(Some(line)) => {
if line.starts_with(&format!("{}_", log_prefix)) {
tracing::info!("[{}] {}", log_prefix, line);
}
}
Ok(None) => stdout_done = true,
Err(e) => tracing::warn!("[{}] stdout error: {}", log_prefix, e),
}
}
line = stderr_reader.next_line(), if !stderr_done => {
match line {
Ok(Some(line)) => {
if line.starts_with(&format!("{}_", log_prefix)) {
tracing::info!("[{}] {}", log_prefix, line);
} else if !line.trim().is_empty() {
tracing::warn!("[{} stderr] {}", log_prefix, line);
}
}
Ok(None) => stderr_done = true,
Err(e) => tracing::warn!("[{}] stderr error: {}", log_prefix, e),
}
}
status = child.wait() => {
match status {
Ok(status) => {
if !status.success() {
tracing::error!("[{}] Process failed: {}", log_prefix, status);
return Err(anyhow::anyhow!("{} exited with: {}", bin_path.display(), status));
}
tracing::info!("[{}] Completed successfully", log_prefix);
}
Err(e) => tracing::error!("[{}] wait error: {}", log_prefix, e),
}
break;
}
}
}
Ok(())
};
let mark_failed = || {
if let Some(tmp) = &tmp_path {
if tmp.exists() {
if let Some(out) = &output_path {
let is_valid = std::fs::read_to_string(tmp)
.ok()
.and_then(|c| serde_json::from_str::<serde_json::Value>(&c).ok())
.is_some();
if is_valid {
let mut partial_path = out.to_path_buf();
partial_path.set_extension("json.partial");
let _ = std::fs::rename(tmp, &partial_path);
} else {
let mut err_path = out.to_path_buf();
err_path.set_extension("json.err");
let _ = std::fs::rename(tmp, &err_path);
}
}
}
}
};
if let Some(duration) = timeout_duration {
match timeout(duration, run_future).await {
Ok(Ok(())) => {}
Ok(Err(e)) => {
mark_failed();
return Err(e);
}
Err(_) => {
mark_failed();
if let Some(pid) = child_pid {
unsafe {
libc::killpg(pid as i32, libc::SIGKILL);
}
}
child.kill().await.context("Failed to kill process")?;
anyhow::bail!("{} timed out after {:?}", log_prefix, duration);
}
}
} else if let Err(e) = run_future.await {
mark_failed();
return Err(e);
}
if let Some(tmp) = &tmp_path {
if tmp.exists() {
if let Some(out) = &output_path {
let _ = std::fs::rename(tmp, out);
}
}
}
Ok(())
}
pub fn script_path(&self, script_name: &str) -> PathBuf {
self.scripts_dir.join(script_name)
}
+34
View File
@@ -3,6 +3,7 @@ use serde::{Deserialize, Serialize};
use std::time::Duration;
use super::executor::PythonExecutor;
use crate::core::config::USE_RUST_PROCESSORS;
const FACE_CLUSTER_TIMEOUT: Duration = Duration::from_secs(3600);
@@ -92,6 +93,39 @@ pub async fn process_face_cluster(
);
}
// Rust processor path (MOMENTRY_USE_RUST_PROCESSORS=1)
if *USE_RUST_PROCESSORS {
if let Some(rust_bin) = executor.rust_binary_path("rust_face_cluster") {
tracing::info!("[FACE_CLUSTER] Using Rust binary: {:?}", rust_bin);
executor
.run_rust_with_output_idx_and_frames(
&rust_bin,
&args,
Some(1),
uuid,
frames,
"FACE_CLUSTER",
Some(FACE_CLUSTER_TIMEOUT),
)
.await
.with_context(|| format!("Failed to run Rust binary {:?}", rust_bin))?;
let json_str = std::fs::read_to_string(output_path)
.context("Failed to read FACE_CLUSTER output")?;
let result: FaceClusterResult =
serde_json::from_str(&json_str).context("Failed to parse FACE_CLUSTER output")?;
tracing::info!(
"[FACE_CLUSTER] Rust Result: {} clusters, {} frames",
result.clusters.len(),
result.frames.len()
);
return Ok(result);
}
tracing::warn!(
"[FACE_CLUSTER] MOMENTRY_USE_RUST_PROCESSORS=1 but rust_face_cluster binary not found, falling back to Python"
);
}
executor
.run_with_output_idx_and_frames(
"fast_face_clustering_processor.py",
+37 -1
View File
@@ -3,6 +3,7 @@ use serde::{Deserialize, Serialize};
use std::time::Duration;
use super::executor::PythonExecutor;
use crate::core::config::USE_RUST_PROCESSORS;
const POSE_TIMEOUT: Duration = Duration::from_secs(7200);
@@ -156,8 +157,43 @@ pub async fn process_pose(
total_video_frames
);
// Call Python pose_processor.py for interpolation
let executor = PythonExecutor::new()?;
// Rust processor path (MOMENTRY_USE_RUST_PROCESSORS=1)
if *USE_RUST_PROCESSORS {
if let Some(rust_bin) = executor.rust_binary_path("rust_pose") {
tracing::info!("[POSE] Using Rust binary: {:?}", rust_bin);
executor
.run_rust_with_output_idx_and_frames(
&rust_bin,
// rust_pose reads `video source_pose output`;
// output is routed to .tmp and promoted on success.
&[video_path, output_path, output_path],
Some(2),
uuid,
None,
"POSE",
Some(POSE_TIMEOUT),
)
.await
.with_context(|| format!("Failed to run Rust binary {:?}", rust_bin))?;
let json_str = std::fs::read_to_string(output_path)
.context("Failed to read interpolated POSE output")?;
let result: PoseResult = serde_json::from_str(&json_str)
.context("Failed to parse interpolated POSE output")?;
tracing::info!(
"[POSE] Rust interpolation completed: {} frames",
result.frames.len()
);
return Ok(result);
}
tracing::warn!(
"[POSE] MOMENTRY_USE_RUST_PROCESSORS=1 but rust_pose binary not found, falling back to Python"
);
}
// Call Python pose_processor.py for interpolation
let script_path = executor.script_path("pose_processor.py");
if script_path.exists() {