Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Prune added comments

laurenspriem7d0baf6c38c4
diff --git a/rust/apps/codegen/src/main.rs b/rust/apps/codegen/src/main.rs
index 975f7efc6c..c811d7c706 100644
--- a/rust/apps/codegen/src/main.rs
+++ b/rust/apps/codegen/src/main.rs
@@ -207,16 +207,12 @@ fn generate_frb_package(package_dir: &Path) -> Result<(), DynError> {
Ok(())
}
-/// Builds the desktop Node addon and regenerates its JS type declarations
-/// into the gitignored `desktop/rust-bindings/` directory, via `@napi-rs/cli`
-/// (a devDependency of `desktop/`).
fn generate_napi() -> Result<(), DynError> {
let rust_root = rust_root()?;
let desktop_dir = repo_root()?.join("desktop");
let out_dir = desktop_dir.join("rust-bindings");
write_generated_gitignore(&out_dir)?;
- // On Windows npm is a .cmd shim, which CreateProcess doesn't resolve.
let npm = if cfg!(windows) { "npm.cmd" } else { "npm" };
let linux_cross_args = if cfg!(target_os = "linux") {
let target = match env::consts::ARCH {
diff --git a/rust/bindings/napi/photos/Cargo.toml b/rust/bindings/napi/photos/Cargo.toml
index 1b03a44353..c6d70f3091 100644
--- a/rust/bindings/napi/photos/Cargo.toml
+++ b/rust/bindings/napi/photos/Cargo.toml
@@ -6,12 +6,10 @@ edition = "2024"
crate-type = ["cdylib"]
[dependencies]
-# Keep usearch disabled: its C++17 code cannot use napi-cli's GCC 4.8 toolchain.
+# usearch requires a newer GCC than napi-cli provides.
ente-photos.workspace = true
napi = { version = "3", default-features = false, features = ["napi8"] }
napi-derive = "3"
-# Only used for ort::init_from; the execution-provider feature set is
-# declared by ente-photos' per-target sections.
ort = { workspace = true, features = ["load-dynamic"] }
[build-dependencies]
diff --git a/rust/bindings/napi/photos/src/lib.rs b/rust/bindings/napi/photos/src/lib.rs
index 13a4f8bc85..f3f675569a 100644
--- a/rust/bindings/napi/photos/src/lib.rs
+++ b/rust/bindings/napi/photos/src/lib.rs
@@ -1,7 +1,3 @@
-//! Node addon exposing the shared photos ML pipeline to the desktop app's
-//! Electron utility process. A thin mirror of the FRB surface in
-//! `bindings/frb/photos/src/api/ml_indexing_api.rs`.
-
use ente_photos::ml::{
error::MlError, indexing as shared_indexing, runtime::ModelPaths as SharedModelPaths,
types as shared_types,
@@ -9,8 +5,6 @@ use ente_photos::ml::{
use napi::bindgen_prelude::*;
use napi_derive::napi;
-/// Loads the ONNX Runtime dynamic library from `dylib_path`. Must be called
-/// once, before any other ML function.
#[napi]
pub fn init_ort(dylib_path: String) -> Result<()> {
ort::init_from(&dylib_path)
@@ -23,20 +17,16 @@ pub fn init_ort(dylib_path: String) -> Result<()> {
Ok(())
}
-/// Configures process-wide ML execution behavior. `enable_webgpu` enables the
-/// guarded WebGPU path on Linux and Windows; it is a no-op on macOS.
#[napi]
pub fn set_ml_execution_config(enable_webgpu: bool) {
shared_indexing::set_ml_execution_config(enable_webgpu);
}
-/// Pins the indexing model sessions resident for a batch of analyze calls.
#[napi]
pub fn init_ml_runtime(model_paths: ModelPaths) {
shared_indexing::init_ml_runtime(to_shared_model_paths(&model_paths));
}
-/// Releases the session residency taken by [`init_ml_runtime`].
#[napi]
pub fn release_ml_runtime() {
shared_indexing::release_ml_runtime();
@@ -59,15 +49,11 @@ pub struct ModelPaths {
#[napi(object)]
pub struct AnalyzeImageRequest {
pub file_id: i64,
- /// Filesystem path of the image. Exactly one of `image_path` and
- /// `image_bytes` must be set.
pub image_path: Option<String>,
- /// Encoded image bytes (any supported format; decoded in Rust).
pub image_bytes: Option<Buffer>,
pub run_faces: bool,
pub run_clip: bool,
pub run_pets: bool,
- /// When set, the result carries a JPEG face crop per detected face.
pub generate_face_crops: bool,
pub model_paths: ModelPaths,
}
@@ -81,10 +67,7 @@ pub struct Dimensions {
#[napi(object)]
pub struct FaceDetection {
pub score: f64,
- /// Relative [x_min, y_min, x_max, y_max].
pub box_xyxy: Vec<f64>,
- /// 5 relative [x, y] keypoints: leftEye, rightEye, nose, leftMouth,
- /// rightMouth.
pub keypoints: Vec<Vec<f64>>,
}
@@ -106,9 +89,7 @@ pub struct PetFaceResult {
pub pet_face_id: String,
pub score: f64,
pub box_xyxy: Vec<f64>,
- /// 3 relative [x, y] keypoints: leftEye, rightEye, nose.
pub keypoints: Vec<Vec<f64>>,
- /// 0 = dog, 1 = cat.
pub species: u32,
pub face_embedding: Float32Array,
}
@@ -118,7 +99,6 @@ pub struct PetBodyResult {
pub pet_body_id: String,
pub score: f64,
pub box_xyxy: Vec<f64>,
- /// COCO class: 15 = cat, 16 = dog.
pub coco_class: u32,
pub body_embedding: Float32Array,
}
@@ -128,15 +108,10 @@ pub struct AnalyzeImageResult {
pub file_id: i64,
pub decoded_image_size: Dimensions,
pub faces: Option<Vec<FaceResult>>,
- /// JPEG bytes, index-aligned with `faces`; present only when requested
- /// via `generate_face_crops`. Crop generation is best effort: a face
- /// whose crop could not be generated has a null slot.
pub face_crops: Option<Vec<Option<Buffer>>>,
pub clip: Option<ClipResult>,
pub pet_faces: Option<Vec<PetFaceResult>>,
pub pet_bodies: Option<Vec<PetBodyResult>>,
- /// True when any model that contributed to this result ran on the
- /// respective accelerated execution provider.
pub used_coreml: bool,
pub used_webgpu: bool,
}
@@ -162,9 +137,6 @@ impl Task for AnalyzeImageTask {
}
}
-/// Analyzes one image (decode + the requested face / CLIP / pet models). The
-/// work runs off the JS event loop; callers should keep at most one analyze
-/// in flight, since the underlying model sessions serialize anyway.
#[napi(ts_return_type = "Promise<AnalyzeImageResult>")]
pub fn analyze_image(req: AnalyzeImageRequest) -> Result<AsyncTask<AnalyzeImageTask>> {
let source = match (req.image_path, req.image_bytes) {
@@ -225,7 +197,6 @@ impl Task for RunClipTextTask {
}
}
-/// Computes the (L2-normalized) CLIP embedding of a text query.
#[napi(ts_return_type = "Promise<RunClipTextResult>")]
pub fn run_clip_text(req: RunClipTextRequest) -> AsyncTask<RunClipTextTask> {
AsyncTask::new(RunClipTextTask {
@@ -242,17 +213,12 @@ pub fn tokenize_clip_text(text: String, vocab_path: String) -> Result<Vec<i32>>
shared_indexing::tokenize_clip_text(&text, &vocab_path).map_err(ml_error_to_napi)
}
-/// A notable ML runtime event (execution provider fallback, golden self-test
-/// failure) buffered by the Rust runtime for app-side logging. `severity` is
-/// one of "info", "warning", or "severe".
#[napi(object)]
pub struct MlRuntimeEvent {
pub severity: String,
pub message: String,
}
-/// Drains buffered ML runtime events. The buffer is process-wide, so drain
-/// after ML operations and log each event at its severity.
#[napi]
pub fn take_ml_runtime_events() -> Vec<MlRuntimeEvent> {
ente_photos::ml::events::take_events()
@@ -264,10 +230,7 @@ pub fn take_ml_runtime_events() -> Vec<MlRuntimeEvent> {
.collect()
}
-/// Maps an [`MlError`] onto a JS error whose message starts with a stable
-/// `Kind:` tag. comlink only carries the message across the MessagePort, so
-/// callers match on the tag (notably `CorruptModel:`, whose detail is the
-/// model path to delete and redownload).
+// Error kind prefixes survive Comlink's MessagePort serialization.
fn ml_error_to_napi(error: MlError) -> Error {
let kind = match &error {
MlError::InvalidRequest(_) => "InvalidRequest",
diff --git a/rust/crates/photos/Cargo.toml b/rust/crates/photos/Cargo.toml
index 240f37b26e..f030ab2b58 100644
--- a/rust/crates/photos/Cargo.toml
+++ b/rust/crates/photos/Cargo.toml
@@ -49,8 +49,6 @@ ort = { workspace = true, features = [
"xnnpack",
] }
-# macOS desktop loads the custom CoreML-enabled dylib at runtime; CoreML is
-# the preferred execution provider like on iOS.
[target.'cfg(target_os = "macos")'.dependencies]
ort = { workspace = true, features = [
"ndarray",
diff --git a/rust/crates/photos/src/ml/error.rs b/rust/crates/photos/src/ml/error.rs
index 1427c03126..21c701eca8 100644
--- a/rust/crates/photos/src/ml/error.rs
+++ b/rust/crates/photos/src/ml/error.rs
@@ -8,9 +8,7 @@ pub enum MlError {
InvalidRequest(String),
#[error("decode error: {0}")]
Decode(String),
- /// A deterministic failure caused by this image's decoded contents or by
- /// image-derived geometry. Unlike generic preprocessing/postprocessing
- /// failures, callers may safely stop retrying this particular image.
+ /// A deterministic per-image failure that should not be retried.
#[error("image processing error: {0}")]
Image(String),
#[error("preprocess error: {0}")]
diff --git a/rust/crates/photos/src/ml/indexing.rs b/rust/crates/photos/src/ml/indexing.rs
index 9b81e1b913..be5a34de84 100644
--- a/rust/crates/photos/src/ml/indexing.rs
+++ b/rust/crates/photos/src/ml/indexing.rs
@@ -30,8 +30,6 @@ pub struct AnalyzeImageRequest {
pub run_faces: bool,
pub run_clip: bool,
pub run_pets: bool,
- /// When set, the result carries a JPEG face crop per detected face,
- /// generated from the same decode used for indexing.
pub generate_face_crops: bool,
pub model_paths: ModelPaths,
}
@@ -41,9 +39,6 @@ pub struct AnalyzeImageResult {
pub file_id: i64,
pub decoded_image_size: Dimensions,
pub faces: Option<Vec<FaceResult>>,
- /// Index-aligned with `faces`; present only when requested via
- /// `generate_face_crops`. Crop generation is best effort: a face whose
- /// crop could not be generated has `None` in its slot.
pub face_crops: Option<Vec<Option<Vec<u8>>>>,
pub clip: Option<ClipResult>,
pub pet_faces: Option<Vec<PetFaceResult>>,
@@ -68,11 +63,6 @@ pub struct RunClipTextResult {
/// Configures process-wide ML execution behavior. Must be called before the
/// first session is created to take effect for that session.
-///
-/// `enable_webgpu` is the app-side eligibility decision for Android, Linux and
-/// Windows. Rust additionally applies its durable crash canary before
-/// attempting the WebGPU execution provider. It has no effect on Apple
-/// platforms.
pub fn set_ml_execution_config(enable_webgpu: bool) {
webgpu::set_enabled(enable_webgpu);
}
@@ -127,9 +117,6 @@ pub fn analyze_image(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageResult> {
None
};
- // Crops are a cosmetic side artifact of indexing, so their generation
- // is best effort: a face whose crop fails is skipped (with a `None`
- // slot to keep the index alignment) instead of failing the analysis.
let face_crops = if generate_face_crops {
faces.as_ref().map(|face_results| {
face_results
diff --git a/rust/crates/photos/src/ml/onnx.rs b/rust/crates/photos/src/ml/onnx.rs
index e3d886a9ba..e243b91aaf 100644
--- a/rust/crates/photos/src/ml/onnx.rs
+++ b/rust/crates/photos/src/ml/onnx.rs
@@ -278,25 +278,15 @@ fn build_webgpu_session_with_canary(
};
#[cfg(target_os = "android")]
{
- // The Android adapter probe touches the Vulkan driver, so it runs
- // inside the armed canary window: a probe crash is recorded like any
- // other WebGPU crash.
match webgpu::check_adapter() {
webgpu::AdapterCheck::Allowed => {}
webgpu::AdapterCheck::Denied => {
- // A completed probe that denies the adapter is a clean policy
- // decision rather than a failed attempt, so the canary is
- // disarmed.
canary.disarm();
return Err(MlError::Ort(
"WebGPU skipped: GPU adapter is not on the allowlist".to_string(),
));
}
webgpu::AdapterCheck::Failed => {
- // The canary stays armed so the drop records a failed attempt:
- // a driver whose probe keeps failing quarantines like one that
- // keeps crashing, and cannot reset the consecutive-failure
- // counter of genuine crashes.
let error = MlError::Ort("WebGPU skipped: Vulkan adapter probe failed".to_string());
record_provider_attempt_failure(
ExecutionProvider::WebGpu,
@@ -681,8 +671,6 @@ fn platform_default_attempts(
let mut attempts = Vec::new();
if webgpu::attempt_permitted(model_path) && golden_entry_required(model_path, "WebGPU") {
attempts.push(ProviderAttempt {
- // EP priority follows registration order. Unsupported WebGPU nodes
- // fall through to CPU in the same session.
providers: vec![
webgpu_provider(),
CPU::default().with_arena_allocator(true).build(),
diff --git a/rust/crates/photos/src/ml/runtime.rs b/rust/crates/photos/src/ml/runtime.rs
index 111632f42d..6cb5e5ce14 100644
--- a/rust/crates/photos/src/ml/runtime.rs
+++ b/rust/crates/photos/src/ml/runtime.rs
@@ -291,9 +291,7 @@ impl MlRuntime {
// CoreML and WebGPU, making their mixed CPU/GPU execution slower
// than running the complete model on CPU.
clip_text: ModelSlot::new(cpu_only, "clip-text"),
- // Pet models previously had device-specific FP16 driver failures.
- // Keep them CPU-only until they have been validated on the GPU
- // execution providers of all supported platforms.
+ // Pet models stay CPU-only due to device-specific FP16 failures.
pet_face_detection: ModelSlot::new(cpu_only, "pet-face-detection"),
pet_face_embedding_dog: ModelSlot::new(cpu_only, "pet-face-embedding-dog"),
pet_face_embedding_cat: ModelSlot::new(cpu_only, "pet-face-embedding-cat"),
diff --git a/rust/crates/photos/src/ml/webgpu.rs b/rust/crates/photos/src/ml/webgpu.rs
index 907076a2a6..7379cc7ca1 100644
--- a/rust/crates/photos/src/ml/webgpu.rs
+++ b/rust/crates/photos/src/ml/webgpu.rs
@@ -1,12 +1,3 @@
-//! Platform guards for the WebGPU execution provider: a durable crash canary
-//! on Android, Linux and Windows, plus an Android GPU adapter allowlist.
-//!
-//! The canary prevents an infinite crash loop on machines where Dawn's native
-//! backend hard-crashes the process while a WebGPU session is built or first
-//! dispatched. On Android, the allowlist additionally permits WebGPU only on
-//! GPU vendors that Chromium ships WebGPU to, so Ente never runs Dawn on
-//! mobile driver stacks that Google's far larger fleet has not validated.
-//!
//! Mechanics: immediately before a WebGPU session is built, a per-model
//! counter file next to the model is incremented and fsynced ("armed"). After
//! the session has been built *and* has survived one warm-up inference, the
@@ -15,11 +6,6 @@
//! [`MAX_CONSECUTIVE_FAILURES`], WebGPU is no longer attempted for models in
//! that directory β€” durably, across process restarts.
//!
-//! A single interrupted attempt (e.g. the OS killing the app mid-indexing) is
-//! therefore tolerated: only consecutive failures with no intervening success
-//! trip the breaker, which a genuine crash loop does deterministically within
-//! a few launches.
-//!
//! Everything here is called from `onnx::build_session` while the caller
//! holds the per-model slot lock, so accesses to one model's counter file are
//! already serialized and no in-memory state is needed beyond the enable flag.
@@ -65,8 +51,6 @@ const CANARY_FILE_PREFIX: &str = ".ente-webgpu-canary-v1.";
))]
const MAX_CONSECUTIVE_FAILURES: u32 = 3;
-/// WebGPU is opt-in at the app boundary. Android additionally gates this on
-/// device eligibility; desktop enables it when its native addon is loaded.
#[cfg(any(target_os = "android", target_os = "linux", target_os = "windows"))]
static WEBGPU_ENABLED: AtomicBool = AtomicBool::new(false);
@@ -359,9 +343,7 @@ fn sync_parent(path: &Path) -> io::Result<()> {
"WebGPU canary path has no parent directory",
)
})?;
- // Rust's standard library can open and fsync directories on Unix. Windows
- // does not expose an equivalent portable operation; the counter file
- // itself is still flushed above, which preserves the breaker semantics.
+ // std cannot fsync directories on Windows.
#[cfg(not(target_os = "windows"))]
return File::open(parent)?.sync_all();
#[cfg(target_os = "windows")]
diff --git a/rust/crates/photos/tests/support/ml_indexing.rs b/rust/crates/photos/tests/support/ml_indexing.rs
index a517dcb7b0..0e73ff30f3 100644
--- a/rust/crates/photos/tests/support/ml_indexing.rs
+++ b/rust/crates/photos/tests/support/ml_indexing.rs
@@ -258,8 +258,6 @@ impl MlIndexingTestContext {
match analyze_image(req) {
Ok(result) => {
let face_count = result.faces.as_ref().map_or(0, Vec::len);
- // Count generated crops only; a `None` slot (best-effort
- // skip) must not happen for the test corpus.
let crop_count = result
.face_crops
.as_ref()