π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[rust][photos] Log ML errors and slow analyses
laurenspriem97375f248f02
diff --git a/rust/crates/photos/src/ml/diagnostics.rs b/rust/crates/photos/src/ml/diagnostics.rsnew file mode 100644index 0000000000..b59f6acb80--- /dev/null+++ b/rust/crates/photos/src/ml/diagnostics.rs@@ -0,0 +1,497 @@+use std::{+ collections::HashMap,+ sync::{+ Arc, Condvar, Mutex, MutexGuard,+ atomic::{AtomicU64, Ordering},+ },+ time::{Duration, Instant},+};++use once_cell::sync::Lazy;++use super::error::{MlError, MlResult};++const SLOW_ANALYSIS_THRESHOLD: Duration = Duration::from_secs(60);++static NEXT_ANALYSIS_ID: AtomicU64 = AtomicU64::new(0);+static ANALYSIS_MONITOR: Lazy<Arc<AnalysisMonitor>> = Lazy::new(|| {+ let monitor = Arc::new(AnalysisMonitor::new(SLOW_ANALYSIS_THRESHOLD));+ let worker = Arc::clone(&monitor);+ if let Err(error) = std::thread::Builder::new()+ .name("ente-ml-watchdog".to_string())+ .spawn(move || worker.run())+ {+ log::error!("failed to start ML analysis watchdog: {error}");+ }+ monitor+});++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) struct AnalysisContext {+ pub(crate) file_id: i64,+ pub(crate) run_faces: bool,+ pub(crate) run_clip: bool,+ pub(crate) run_pets: bool,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum AnalysisStage {+ ValidateRequest,+ RuntimeSetup,+ DecodeImage,+ YoloPreprocess,+ FaceDetection,+ FaceAlignment,+ FaceEmbedding,+ FaceCrops,+ ClipEmbedding,+ PetFaceDetection,+ PetBodyDetection,+ PetFaceAlignment,+ PetFaceEmbedding,+ PetBodyEmbedding,+ Finalize,+}++impl AnalysisStage {+ fn label(self) -> &'static str {+ match self {+ Self::ValidateRequest => "validate_request",+ Self::RuntimeSetup => "runtime_setup",+ Self::DecodeImage => "decode_image",+ Self::YoloPreprocess => "yolo_preprocess",+ Self::FaceDetection => "face_detection",+ Self::FaceAlignment => "face_alignment",+ Self::FaceEmbedding => "face_embedding",+ Self::FaceCrops => "face_crops",+ Self::ClipEmbedding => "clip_embedding",+ Self::PetFaceDetection => "pet_face_detection",+ Self::PetBodyDetection => "pet_body_detection",+ Self::PetFaceAlignment => "pet_face_alignment",+ Self::PetFaceEmbedding => "pet_face_embedding",+ Self::PetBodyEmbedding => "pet_body_embedding",+ Self::Finalize => "finalize",+ }+ }+}++pub(crate) struct AnalysisOperation {+ id: u64,+ context: AnalysisContext,+ stage: AnalysisStage,+ started_at: Instant,+ finished: bool,+}++impl AnalysisOperation {+ pub(crate) fn start(context: AnalysisContext) -> Self {+ let id = NEXT_ANALYSIS_ID.fetch_add(1, Ordering::Relaxed);+ let started_at = Instant::now();+ let stage = AnalysisStage::ValidateRequest;+ ANALYSIS_MONITOR.register(id, context, stage, started_at);+ Self {+ id,+ context,+ stage,+ started_at,+ finished: false,+ }+ }++ pub(crate) fn set_stage(&mut self, stage: AnalysisStage) {+ self.stage = stage;+ ANALYSIS_MONITOR.update_stage(self.id, stage);+ }++ pub(crate) fn finish<T>(&mut self, result: &MlResult<T>) {+ let completed_at = Instant::now();+ let active = ANALYSIS_MONITOR.complete(self.id);+ self.finished = true;++ if let Err(error) = result {+ log_analysis_error(+ "analyze_image",+ Some(self.context),+ Some(self.stage),+ completed_at.duration_since(self.started_at),+ error,+ );+ } else if active.is_some_and(|analysis| analysis.slow_reported) {+ log::info!(+ "Rust ML slow operation: operation=analyze_image event=completed file_id={} stage={} elapsed_ms={} run_faces={} run_clip={} run_pets={}",+ self.context.file_id,+ self.stage.label(),+ completed_at.duration_since(self.started_at).as_millis(),+ self.context.run_faces,+ self.context.run_clip,+ self.context.run_pets,+ );+ }+ }+}++impl Drop for AnalysisOperation {+ fn drop(&mut self) {+ if self.finished {+ return;+ }+ let Some(active) = ANALYSIS_MONITOR.complete(self.id) else {+ return;+ };+ if active.slow_reported {+ log::warn!(+ "Rust ML slow operation: operation=analyze_image event=ended_without_result file_id={} stage={} elapsed_ms={} run_faces={} run_clip={} run_pets={}",+ self.context.file_id,+ self.stage.label(),+ self.started_at.elapsed().as_millis(),+ self.context.run_faces,+ self.context.run_clip,+ self.context.run_pets,+ );+ }+ }+}++pub(crate) fn log_public_ml_error(operation: &'static str, error: &MlError) {+ log_analysis_error(operation, None, None, Duration::ZERO, error);+}++fn log_analysis_error(+ operation: &'static str,+ context: Option<AnalysisContext>,+ stage: Option<AnalysisStage>,+ elapsed: Duration,+ error: &MlError,+) {+ let context = context.map_or_else(String::new, |context| {+ format!(+ " file_id={} run_faces={} run_clip={} run_pets={}",+ context.file_id, context.run_faces, context.run_clip, context.run_pets+ )+ });+ let stage = stage.map_or_else(String::new, |stage| format!(" stage={}", stage.label()));+ let elapsed = if elapsed != Duration::ZERO {+ format!(" elapsed_ms={}", elapsed.as_millis())+ } else {+ String::new()+ };+ let message = format!(+ "Rust ML operation failed: operation={operation}{context}{stage}{elapsed} error_kind={} error={error}",+ error_kind(error)+ );++ match error {+ MlError::Decode(_) | MlError::Image(_) => log::warn!("{message}"),+ MlError::InvalidRequest(_)+ | MlError::Preprocess(_)+ | MlError::Ort(_)+ | MlError::CorruptModel(_)+ | MlError::Postprocess(_)+ | MlError::Runtime(_) => log::error!("{message}"),+ }+}++fn error_kind(error: &MlError) -> &'static str {+ match error {+ MlError::InvalidRequest(_) => "invalid_request",+ MlError::Decode(_) => "decode",+ MlError::Image(_) => "image",+ MlError::Preprocess(_) => "preprocess",+ MlError::Ort(_) => "ort",+ MlError::CorruptModel(_) => "corrupt_model",+ MlError::Postprocess(_) => "postprocess",+ MlError::Runtime(_) => "runtime",+ }+}++struct AnalysisMonitor {+ threshold: Duration,+ state: Mutex<MonitorState>,+ changed: Condvar,+}++impl AnalysisMonitor {+ fn new(threshold: Duration) -> Self {+ Self {+ threshold,+ state: Mutex::new(MonitorState::default()),+ changed: Condvar::new(),+ }+ }++ fn register(+ &self,+ id: u64,+ context: AnalysisContext,+ stage: AnalysisStage,+ started_at: Instant,+ ) {+ self.lock_state().register(id, context, stage, started_at);+ self.changed.notify_one();+ }++ fn update_stage(&self, id: u64, stage: AnalysisStage) {+ let should_wake = self.lock_state().update_stage(id, stage);+ if should_wake {+ self.changed.notify_one();+ }+ }++ fn complete(&self, id: u64) -> Option<ActiveAnalysis> {+ let active = self.lock_state().complete(id);+ self.changed.notify_one();+ active+ }++ fn run(&self) {+ let mut state = self.lock_state();+ loop {+ let now = Instant::now();+ let events = state.collect_events(now, self.threshold);+ if !events.is_empty() {+ drop(state);+ for event in events {+ event.log();+ }+ state = self.lock_state();+ continue;+ }++ state = match state.next_wait(now, self.threshold) {+ Some(wait) => match self.changed.wait_timeout(state, wait) {+ Ok((state, _)) => state,+ Err(poisoned) => poisoned.into_inner().0,+ },+ None => match self.changed.wait(state) {+ Ok(state) => state,+ Err(poisoned) => poisoned.into_inner(),+ },+ };+ }+ }++ fn lock_state(&self) -> MutexGuard<'_, MonitorState> {+ self.state+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ }+}++#[derive(Default)]+struct MonitorState {+ active: HashMap<u64, ActiveAnalysis>,+}++impl MonitorState {+ fn register(+ &mut self,+ id: u64,+ context: AnalysisContext,+ stage: AnalysisStage,+ started_at: Instant,+ ) {+ self.active.insert(+ id,+ ActiveAnalysis {+ context,+ started_at,+ stage,+ slow_reported: false,+ last_reported_stage: None,+ },+ );+ }++ fn update_stage(&mut self, id: u64, stage: AnalysisStage) -> bool {+ let Some(active) = self.active.get_mut(&id) else {+ return false;+ };+ active.stage = stage;+ active.slow_reported && active.last_reported_stage != Some(stage)+ }++ fn complete(&mut self, id: u64) -> Option<ActiveAnalysis> {+ self.active.remove(&id)+ }++ fn collect_events(&mut self, now: Instant, threshold: Duration) -> Vec<SlowAnalysisEvent> {+ let mut events = Vec::new();+ for active in self.active.values_mut() {+ if !active.slow_reported+ && now.saturating_duration_since(active.started_at) >= threshold+ {+ active.slow_reported = true;+ active.last_reported_stage = Some(active.stage);+ events.push(active.event(SlowEventKind::ThresholdExceeded, now));+ } else if active.slow_reported && active.last_reported_stage != Some(active.stage) {+ active.last_reported_stage = Some(active.stage);+ events.push(active.event(SlowEventKind::StageChanged, now));+ }+ }+ events+ }++ fn next_wait(&self, now: Instant, threshold: Duration) -> Option<Duration> {+ self.active+ .values()+ .filter(|active| !active.slow_reported)+ .map(|active| {+ threshold.saturating_sub(now.saturating_duration_since(active.started_at))+ })+ .min()+ }+}++struct ActiveAnalysis {+ context: AnalysisContext,+ started_at: Instant,+ stage: AnalysisStage,+ slow_reported: bool,+ last_reported_stage: Option<AnalysisStage>,+}++impl ActiveAnalysis {+ fn event(&self, kind: SlowEventKind, now: Instant) -> SlowAnalysisEvent {+ SlowAnalysisEvent {+ kind,+ context: self.context,+ stage: self.stage,+ elapsed: now.saturating_duration_since(self.started_at),+ }+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum SlowEventKind {+ ThresholdExceeded,+ StageChanged,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+struct SlowAnalysisEvent {+ kind: SlowEventKind,+ context: AnalysisContext,+ stage: AnalysisStage,+ elapsed: Duration,+}++impl SlowAnalysisEvent {+ fn log(self) {+ let message = format!(+ "file_id={} stage={} elapsed_ms={} run_faces={} run_clip={} run_pets={}",+ self.context.file_id,+ self.stage.label(),+ self.elapsed.as_millis(),+ self.context.run_faces,+ self.context.run_clip,+ self.context.run_pets,+ );+ match self.kind {+ SlowEventKind::ThresholdExceeded => log::warn!(+ "Rust ML slow operation: operation=analyze_image event=threshold_exceeded threshold_ms={} {message}",+ SLOW_ANALYSIS_THRESHOLD.as_millis()+ ),+ SlowEventKind::StageChanged => {+ log::info!(+ "Rust ML slow operation: operation=analyze_image event=stage_changed {message}"+ )+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn context(file_id: i64) -> AnalysisContext {+ AnalysisContext {+ file_id,+ run_faces: true,+ run_clip: true,+ run_pets: false,+ }+ }++ #[test]+ fn fast_analysis_emits_no_watchdog_events() {+ assert_eq!(SLOW_ANALYSIS_THRESHOLD, Duration::from_secs(60));+ let started_at = Instant::now();+ let mut state = MonitorState::default();+ state.register(1, context(42), AnalysisStage::DecodeImage, started_at);++ assert!(+ state+ .collect_events(+ started_at + Duration::from_secs(59),+ Duration::from_secs(60)+ )+ .is_empty()+ );+ assert!(!state.complete(1).unwrap().slow_reported);+ }++ #[test]+ fn slow_analysis_reports_current_and_later_stages_once() {+ let started_at = Instant::now();+ let threshold = Duration::from_secs(60);+ let mut state = MonitorState::default();+ state.register(1, context(42), AnalysisStage::FaceDetection, started_at);++ assert_eq!(+ state.collect_events(started_at + threshold, threshold),+ vec![SlowAnalysisEvent {+ kind: SlowEventKind::ThresholdExceeded,+ context: context(42),+ stage: AnalysisStage::FaceDetection,+ elapsed: threshold,+ }]+ );+ assert!(+ state+ .collect_events(started_at + threshold, threshold)+ .is_empty()+ );++ assert!(state.update_stage(1, AnalysisStage::FaceEmbedding));+ assert_eq!(+ state.collect_events(started_at + Duration::from_secs(61), threshold),+ vec![SlowAnalysisEvent {+ kind: SlowEventKind::StageChanged,+ context: context(42),+ stage: AnalysisStage::FaceEmbedding,+ elapsed: Duration::from_secs(61),+ }]+ );+ assert!(!state.update_stage(1, AnalysisStage::FaceEmbedding));+ }++ #[test]+ fn watchdog_waits_for_the_earliest_active_analysis() {+ let started_at = Instant::now();+ let threshold = Duration::from_secs(60);+ let mut state = MonitorState::default();+ state.register(1, context(1), AnalysisStage::DecodeImage, started_at);+ state.register(+ 2,+ context(2),+ AnalysisStage::DecodeImage,+ started_at + Duration::from_secs(20),+ );++ assert_eq!(+ state.next_wait(started_at + Duration::from_secs(30), threshold),+ Some(Duration::from_secs(30))+ );+ }++ #[test]+ fn error_kinds_are_stable_for_log_filtering() {+ assert_eq!(error_kind(&MlError::Decode("bad image".into())), "decode");+ assert_eq!(error_kind(&MlError::Ort("failed".into())), "ort");+ assert_eq!(+ error_kind(&MlError::CorruptModel("model.onnx".into())),+ "corrupt_model"+ );+ }+}diff --git a/rust/crates/photos/src/ml/indexing.rs b/rust/crates/photos/src/ml/indexing.rsindex b58405c564..1bb361660b 100644--- a/rust/crates/photos/src/ml/indexing.rs+++ b/rust/crates/photos/src/ml/indexing.rs@@ -1,5 +1,6 @@use crate::ml::{clip::{run_clip_image, run_clip_text_query, tokenize_clip_text as tokenize_clip_text_impl},+ diagnostics::{AnalysisContext, AnalysisOperation, AnalysisStage, log_public_ml_error},error::{MlError, MlResult},face::{run_face_alignment, run_face_detection, run_face_embedding,@@ -72,6 +73,22 @@ pub fn release_ml_runtime() {}pub fn analyze_image(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageResult> {+ let context = AnalysisContext {+ file_id: req.file_id,+ run_faces: req.run_faces,+ run_clip: req.run_clip,+ run_pets: req.run_pets,+ };+ let mut operation = AnalysisOperation::start(context);+ let result = analyze_image_inner(req, &mut operation);+ operation.finish(&result);+ result+}++fn analyze_image_inner(+ req: AnalyzeImageRequest,+ operation: &mut AnalysisOperation,+) -> MlResult<AnalyzeImageResult> {validate_request_model_paths(&req)?;let AnalyzeImageRequest {@@ -84,17 +101,23 @@ pub fn analyze_image(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageResult> {model_paths,} = req;+ operation.set_stage(AnalysisStage::RuntimeSetup);runtime::with_runtime(&model_paths, |runtime| {+ operation.set_stage(AnalysisStage::DecodeImage);let mut decoded = match &source {ImageSource::Path(path) => decode_image_from_path(path)?,ImageSource::Bytes(bytes) => decode_image_from_bytes(bytes)?,};let dims = decoded.dimensions.clone();- let detector_input = (run_faces || run_pets)- .then(|| preprocess::preprocess_yolo(&decoded))- .transpose()?;+ let detector_input = if run_faces || run_pets {+ operation.set_stage(AnalysisStage::YoloPreprocess);+ Some(preprocess::preprocess_yolo(&decoded)?)+ } else {+ None+ };let faces = if run_faces {+ operation.set_stage(AnalysisStage::FaceDetection);let detections = run_face_detection(runtime,detector_input@@ -104,8 +127,10 @@ pub fn analyze_image(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageResult> {if detections.is_empty() {Some(Vec::new())} else {+ operation.set_stage(AnalysisStage::FaceAlignment);let (aligned, mut face_results) =run_face_alignment(file_id, &mut decoded, detections)?;+ operation.set_stage(AnalysisStage::FaceEmbedding);run_face_embedding(runtime, aligned, &mut face_results)?;Some(face_results)}@@ -114,6 +139,7 @@ pub fn analyze_image(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageResult> {};let face_crops = if generate_face_crops {+ operation.set_stage(AnalysisStage::FaceCrops);faces.as_ref().map(|face_results| {face_results.iter()@@ -140,6 +166,7 @@ pub fn analyze_image(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageResult> {};let clip = if run_clip {+ operation.set_stage(AnalysisStage::ClipEmbedding);Some(run_clip_image(runtime, &decoded)?)} else {None@@ -149,12 +176,16 @@ pub fn analyze_image(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageResult> {let detector_input = detector_input.as_ref().expect("detector input is prepared when pet indexing is enabled");+ operation.set_stage(AnalysisStage::PetFaceDetection);let pet_face_detections = run_pet_face_detection(runtime, detector_input)?;+ operation.set_stage(AnalysisStage::PetBodyDetection);let body_detections = run_pet_body_detection(runtime, detector_input)?;let pet_face_results = if !pet_face_detections.is_empty() {+ operation.set_stage(AnalysisStage::PetFaceAlignment);let (aligned, mut pet_results) =run_pet_face_alignment(file_id, &decoded, pet_face_detections)?;+ operation.set_stage(AnalysisStage::PetFaceEmbedding);run_pet_face_embedding(runtime, aligned, &mut pet_results)?;pet_results} else {@@ -175,7 +206,8 @@ pub fn analyze_image(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageResult> {.collect();if !body_results.is_empty() {- run_pet_body_embedding(runtime, &decoded, &mut body_results)?;+ operation.set_stage(AnalysisStage::PetBodyEmbedding);+ run_pet_body_embedding(runtime, file_id, &decoded, &mut body_results)?;}(Some(pet_face_results), Some(body_results))@@ -183,6 +215,7 @@ pub fn analyze_image(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageResult> {(None, None)};+ operation.set_stage(AnalysisStage::Finalize);let used_providers = runtime.used_providers();Ok(AnalyzeImageResult {file_id,@@ -199,51 +232,62 @@ pub fn analyze_image(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageResult> {}pub fn run_clip_text(req: RunClipTextRequest) -> MlResult<RunClipTextResult> {- let RunClipTextRequest {- text,- model_path,- vocab_path,- } = req;-- if model_path.trim().is_empty() {- return Err(MlError::InvalidRequest(- "missing model path: clipTextModelPath".to_string(),- ));- }- if vocab_path.trim().is_empty() {- return Err(MlError::InvalidRequest(- "missing model path: clipTextVocabPath".to_string(),- ));- }+ let result = (|| {+ let RunClipTextRequest {+ text,+ model_path,+ vocab_path,+ } = req;++ if model_path.trim().is_empty() {+ return Err(MlError::InvalidRequest(+ "missing model path: clipTextModelPath".to_string(),+ ));+ }+ if vocab_path.trim().is_empty() {+ return Err(MlError::InvalidRequest(+ "missing model path: clipTextVocabPath".to_string(),+ ));+ }- let model_paths = ModelPaths {- face_detection: String::new(),- face_embedding: String::new(),- clip_image: String::new(),- clip_text: model_path,- pet_face_detection: String::new(),- pet_face_embedding_dog: String::new(),- pet_face_embedding_cat: String::new(),- pet_body_detection: String::new(),- pet_body_embedding_dog: String::new(),- pet_body_embedding_cat: String::new(),- };+ let model_paths = ModelPaths {+ face_detection: String::new(),+ face_embedding: String::new(),+ clip_image: String::new(),+ clip_text: model_path,+ pet_face_detection: String::new(),+ pet_face_embedding_dog: String::new(),+ pet_face_embedding_cat: String::new(),+ pet_body_detection: String::new(),+ pet_body_embedding_dog: String::new(),+ pet_body_embedding_cat: String::new(),+ };- runtime::with_runtime(&model_paths, |runtime| {- let clip = run_clip_text_query(runtime, &text, &vocab_path)?;- Ok(RunClipTextResult {- embedding: clip.embedding,+ runtime::with_runtime(&model_paths, |runtime| {+ let clip = run_clip_text_query(runtime, &text, &vocab_path)?;+ Ok(RunClipTextResult {+ embedding: clip.embedding,+ })})- })+ })();+ if let Err(error) = &result {+ log_public_ml_error("run_clip_text", error);+ }+ result}pub fn tokenize_clip_text(text: &str, vocab_path: &str) -> MlResult<Vec<i32>> {- if vocab_path.trim().is_empty() {- return Err(MlError::InvalidRequest(+ let result = if vocab_path.trim().is_empty() {+ Err(MlError::InvalidRequest("missing model path: clipTextVocabPath".to_string(),- ));+ ))+ } else {+ tokenize_clip_text_impl(text, vocab_path)+ };+ if let Err(error) = &result {+ log_public_ml_error("tokenize_clip_text", error);}- tokenize_clip_text_impl(text, vocab_path)+ result}fn validate_request_model_paths(req: &AnalyzeImageRequest) -> MlResult<()> {diff --git a/rust/crates/photos/src/ml/mod.rs b/rust/crates/photos/src/ml/mod.rsindex 140e019846..4068c879cc 100644--- a/rust/crates/photos/src/ml/mod.rs+++ b/rust/crates/photos/src/ml/mod.rs@@ -1,5 +1,6 @@pub mod assets;mod clip;+mod diagnostics;pub mod error;pub mod face;pub mod golden;diff --git a/rust/crates/photos/src/ml/pet/embed.rs b/rust/crates/photos/src/ml/pet/embed.rsindex 60f5cda0ad..745e377159 100644--- a/rust/crates/photos/src/ml/pet/embed.rs+++ b/rust/crates/photos/src/ml/pet/embed.rs@@ -78,6 +78,7 @@ pub(crate) fn run_pet_face_embedding(pub(crate) fn run_pet_body_embedding(runtime: &MlRuntimeView<'_>,+ file_id: i64,decoded: &DecodedImage,body_results: &mut [PetBodyResult],) -> MlResult<()> {@@ -87,8 +88,6 @@ pub(crate) fn run_pet_body_embedding(let per_body_len = PET_EMBEDDING_INPUT_SIZE * PET_EMBEDDING_INPUT_SIZE * PET_EMBEDDING_CHANNELS;- // Skip detections whose crop is invalid (e.g. zero-area edge boxes)- // rather than aborting the whole image.let cat_count = body_results.iter().filter(|result| result.detection.coco_class == COCO_CAT)@@ -97,6 +96,8 @@ pub(crate) fn run_pet_body_embedding(let mut dog_batch = IndexedEmbeddingBatch::new(dog_count, per_body_len);let mut cat_batch = IndexedEmbeddingBatch::new(cat_count, per_body_len);let mut preprocessor = PetEmbeddingPreprocessor::new();+ let mut skipped_count = 0;+ let mut first_error = None;for (i, body_result) in body_results.iter().enumerate() {let batch = if body_result.detection.coco_class == COCO_CAT {@@ -105,16 +106,22 @@ pub(crate) fn run_pet_body_embedding(&mut dog_batch};let original_len = batch.input.len();- if preprocessor- .append(decoded, &body_result.detection.box_xyxy, &mut batch.input)- .is_ok()- {- batch.indices.push(i);- } else {- batch.input.truncate(original_len);+ match preprocessor.append(decoded, &body_result.detection.box_xyxy, &mut batch.input) {+ Ok(()) => batch.indices.push(i),+ Err(error) => {+ batch.input.truncate(original_len);+ skipped_count += 1;+ first_error.get_or_insert(error);+ }}}+ if let Some(error) = first_error {+ log::warn!(+ "skipped {skipped_count} invalid pet body crop(s): file_id={file_id} first_error={error}"+ );+ }+for (is_cat, batch) in [(false, dog_batch), (true, cat_batch)] {if batch.is_empty() {continue;