Merge pull request #3023 from ronibalthazar/codex/sam-worker-accept-recovery-current

LR-MASK-OBJECTS: recover from SAM worker accept errors
This commit is contained in:
FredApps authored and GitHub committed 2026-11-26 16:01:30 +01:00
commit 2bd29c6c2e
5 files changed
+128 -10

No files matched your search

+117 -9
View File
@@ -10,6 +10,7 @@ use serde::{Deserialize, Serialize};
const CONTROL_LIMIT: usize = 16 * 1024;
const RESPONSE_LIMIT: usize = 4 * 1024 * 1024;
const TIMEOUT: Duration = Duration::from_secs(9 * 60);
const ACCEPT_RETRY_DELAY: Duration = Duration::from_millis(100);
pub const ENV: &str = "LIGHTCRAFT_SAM3_REMOTE";
#[derive(Serialize, Deserialize)]
@@ -194,6 +195,30 @@ fn serve_client(stream: &mut TcpStream, dir: &Path, device: candle_core::Device)
}
}
fn serve_connections<I, C, H, S>(incoming: I, mut handle_client: H, mut retry_sleep: S)
where
I: IntoIterator<Item = io::Result<C>>,
H: FnMut(&mut C) -> Result<(), String>,
S: FnMut(Duration),
{
for connection in incoming {
let mut stream = match connection {
Ok(stream) => stream,
Err(error) => {
eprintln!("SAM3 accept failed: {error}");
retry_sleep(ACCEPT_RETRY_DELAY);
continue;
}
};
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| handle_client(&mut stream)));
match result {
Ok(Err(error)) => eprintln!("SAM3 session closed: {error}"),
Err(_) => eprintln!("SAM3 session panicked; model released"),
Ok(Ok(())) => {}
}
}
}
pub fn serve(address: SocketAddr, dir: &Path, device: candle_core::Device) -> Result<(), String> {
if !address.ip().is_loopback() || !device.is_metal() {
return Err("SAM worker requires a loopback address and a Metal device".into());
@@ -203,14 +228,97 @@ pub fn serve(address: SocketAddr, dir: &Path, device: candle_core::Device) -> Re
}
let listener = TcpListener::bind(address).map_err(|e| e.to_string())?;
eprintln!("SAM3 worker listening on {address}; device=Metal; idle unload=600s");
for stream in listener.incoming() {
let mut stream = stream.map_err(|e| e.to_string())?;
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| serve_client(&mut stream, dir, device.clone())));
match result {
Ok(Err(error)) => eprintln!("SAM3 session closed: {error}"),
Err(_) => eprintln!("SAM3 session panicked; model released"),
Ok(Ok(())) => {}
}
}
serve_connections(listener.incoming(), |stream| serve_client(stream, dir, device.clone()), std::thread::sleep);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn accept_error<T>() -> io::Result<T> {
Err(io::Error::new(io::ErrorKind::ConnectionAborted, "injected accept failure"))
}
#[test]
fn sam_accept_error_before_client_keeps_serving() {
let mut handled = Vec::new();
serve_connections(
[accept_error(), Ok(1_u8)],
|stream| {
handled.push(*stream);
Ok(())
},
|_| {},
);
assert_eq!(handled, [1]);
}
#[test]
fn sam_accept_error_between_clients_keeps_serving() {
let mut handled = Vec::new();
serve_connections(
[Ok(1_u8), accept_error(), Ok(2_u8)],
|stream| {
handled.push(*stream);
Ok(())
},
|_| {},
);
assert_eq!(handled, [1, 2]);
}
#[test]
fn sam_accept_repeated_errors_back_off() {
let mut handled = Vec::new();
let mut delays = Vec::new();
serve_connections(
[accept_error(), accept_error(), Ok(1_u8)],
|stream| {
handled.push(*stream);
Ok(())
},
|delay| delays.push(delay),
);
assert_eq!(handled, [1]);
assert_eq!(delays, [Duration::from_millis(100), Duration::from_millis(100)]);
}
#[test]
fn sam_accept_client_failure_keeps_serving() {
let mut handled = Vec::new();
let mut delays = Vec::new();
serve_connections(
[Ok(1_u8), Ok(2_u8)],
|stream| {
handled.push(*stream);
if *stream == 1 { Err("injected client failure".into()) } else { Ok(()) }
},
|delay| delays.push(delay),
);
assert_eq!(handled, [1, 2]);
assert!(delays.is_empty());
}
#[test]
fn sam_accept_client_panic_keeps_serving() {
let mut handled = Vec::new();
serve_connections(
[Ok(1_u8), Ok(2_u8)],
|stream| {
handled.push(*stream);
if *stream == 1 {
std::panic::resume_unwind(Box::new("injected client panic"));
}
Ok(())
},
|_| {},
);
assert_eq!(handled, [1, 2]);
}
}
+2
View File
@@ -164,6 +164,8 @@ stay in the local library, so later adjustments and exports work without the con
The worker requires Metal and accepts one editing connection at a time. It loads weights
on demand and releases them when the client disconnects or remains idle for ten minutes.
If the listener reports an accept error, the worker logs it, waits 100 ms, and retries; startup
validation and bind errors still stop the worker.
Both endpoints require loopback addresses: SSH provides authentication and encryption.
The listener has no independent authentication; do not expose it through a public proxy. Any
process of any user on the worker Mac can connect to it, and on the editing computer a local
+1
View File
@@ -100,6 +100,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w
| 2026-10-27 | minor | Gap 26: the loupe shows built previews (they were rendered again), photos ahead and the whole view are prepared in the background with settings per mode; gap not closed |
| 2026-10-27 | minor | Gap 26: culling speed measured and improved (progressive Local browse, camera previews made ahead, a CR3's smallest covering JPEG, camera JPEG first at 100 %); what is left listed; gap not closed |
| 2026-11-02 | minor | PERF-STEP-STALL: the catalog log is written and synced off the UI thread, so stepping and flagging never wait for the drive (a 300 ms sync: slowest flag 0.2 ms, was 305 ms); a failed write is held and retried, counted as unsaved, never dropped; gap 26 not closed |
| 2026-11-04 | patch | LR-MASK-OBJECTS, #2574: remote SAM worker logs and retries listener accept errors after 100 ms; startup and bind failures remain errors; gap ranking and readiness unchanged |
| 2026-10-28 | minor | Gap 8 shrinks: the desktop app offers lensfun's lens database (CC BY-SA, pinned) once on the first launch and downloads it on request and looks the library's raws up when it arrives; validation, a profile picker and own calibration remain |
| 2026-10-23 | patch | Gap 8: the Sigma 10–18 mm on the ILCE-6700 gets a measured lens exception at 10–10.5 mm (0.55 px worst over 99 photos, was about 1.4 px) |
| 2026-10-29 | minor | Import thumbnails render when the camera JPEG is too small, retaining preview-only/error fallbacks; import review: remembered thumbnail size and density-aware previews (#2237, part of #2056); pre-import loupe/keyboard culling remains open; no ranked gap closes |
+2 -1
View File
@@ -300,7 +300,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts).
| LR-MASK-SUBJECT | Select subject | P2 | 🟡 | `cmd:mask.add` (`subject`), `crates/pipeline/src/masks.rs` | saliency heuristic, no segmentation model; a photo that carries person mattes (DNG semantic masks: iPhone ProRAW portrait / skin / hair / teeth / glasses mattes) uses them instead (synthetic files only: no corpus file carries person mattes) |
| LR-MASK-SKY | Select sky | P2 | 🟡 | `cmd:mask.add` (`sky`), `crates/pipeline/src/masks.rs` (`Mattes`), `crates/raw/src/semantic.rs` | heuristic; a photo that carries a sky matte (DNG semantic mask, e.g. iPhone ProRAW) uses it instead, through orientation / crop / lens corrections, preview = export (checked on one CC0 iPhone 12 Pro ProRAW and synthetic files) |
| LR-MASK-BACKGROUND | Select background | P2 | 🟡 | `cmd:mask.add` (`background`) | inverse of the subject mask (heuristic, or the photo's person mattes) |
| LR-MASK-OBJECTS | Object selection | P2 | 🟡 | `cmd:mask.add` (`object`, `prompt`), `cmd:mask.objectPoint`, `cmd:mask.refineDetail`, `cmd:segment.prepare`, `cmd:segment.model.status`, `cmd:segment.settings`, `cmd:segment.model.download`, `cmd:segment.model.cancel`, `cmd:app.openSamModelFolder`, `crates/segment`, `crates/engine/src/segment.rs` | SAM 3 in pure Rust (candle; Metal on macOS; on Windows and Linux the image encoder, the two necks and the text detector's DETR encoder and mask decoder on the GPU through wgpu (`lightcraft-gpu` `sam3`) and the rest of the heads on the CPU; a description ~0.5–0.7 s with an RTX 5070, falling back to the CPU without a usable GPU or when the GPU is switched off; Settings ▸ Performance ▸ AI masks ▸ Run on: CPU puts all of it on the CPU on every platform (`segment.settings`); Settings ▸ Performance ▸ AI masks and `segment.model.status` → `backend` show where it runs and the last photo's time): Object tile → click to include, ⌥-click to leave out; Describe tile → a text prompt selects every instance ("sky", "the red car"); both also as Add/Subtract/Intersect components; + / − under the selected mask; comma lists (`car, road`); a zoomed-in detail pass for 5–10× finer edges on small objects; per-selection Edge (hard ↔ soft); the stored grid is enlarged along the photo's edges (a guided filter of its logits by log luminance, so no outline spills onto the background under a raised Exposure, #3272). The model runs on its own worker thread (the UI never waits; panics become errors; a job that fails on the Mac's GPU runs again on the CPU, which then serves the rest of the session, #1974), is unloaded after 10 min idle, and is optional: the segmentation is stored with the mask (288² logits), so renders and exports never need it. Weights are never bundled (SAM License): without them the app offers a consented background download (mirrors, resume, timeouts, SHA-256) — **but no default download location is configured yet** (users set `LIGHTCRAFT_SAM3_MIRRORS` or install by hand: the dialog names the three files, opens the configured model folder with the host opener, preserves setup on an open error, and links docs/ai-masks.md; Meta's original checkpoint installed in place of the Hugging Face one is named as such, #3378). Not verified against Lightroom's Select Object; no brush/box object mode; the first click on a photo waits for its analysis (~4 s on an M4 Pro, ~0.6 s with an RTX 5070 under Linux, ~32 s on a 12-core CPU) |
| LR-MASK-OBJECTS | Object selection | P2 | 🟡 | `cmd:mask.add` (`object`, `prompt`), `cmd:mask.objectPoint`, `cmd:mask.refineDetail`, `cmd:segment.prepare`, `cmd:segment.model.status`, `cmd:segment.settings`, `cmd:segment.model.download`, `cmd:segment.model.cancel`, `cmd:app.openSamModelFolder`, `crates/segment`, `crates/engine/src/segment.rs` | SAM 3 in pure Rust (candle; Metal on macOS; on Windows and Linux the image encoder, the two necks and the text detector's DETR encoder and mask decoder on the GPU through wgpu (`lightcraft-gpu` `sam3`) and the rest of the heads on the CPU; a description ~0.5–0.7 s with an RTX 5070, falling back to the CPU without a usable GPU or when the GPU is switched off; Settings ▸ Performance ▸ AI masks ▸ Run on: CPU puts all of it on the CPU on every platform (`segment.settings`); Settings ▸ Performance ▸ AI masks and `segment.model.status` → `backend` show where it runs and the last photo's time): Object tile → click to include, ⌥-click to leave out; Describe tile → a text prompt selects every instance ("sky", "the red car"); both also as Add/Subtract/Intersect components; + / − under the selected mask; comma lists (`car, road`); a zoomed-in detail pass for 5–10× finer edges on small objects; per-selection Edge (hard ↔ soft); the stored grid is enlarged along the photo's edges (a guided filter of its logits by log luminance, so no outline spills onto the background under a raised Exposure, #3272). The model runs on its own worker thread (the UI never waits; panics become errors; a job that fails on the Mac's GPU runs again on the CPU, which then serves the rest of the session, #1974), is unloaded after 10 min idle; the remote worker retries listener accept errors after 100 ms (#2574), isolating client failures; it is optional: the segmentation is stored with the mask (288² logits), so renders and exports never need it. Weights are never bundled (SAM License): without them the app offers a consented background download (mirrors, resume, timeouts, SHA-256) — **but no default download location is configured yet** (users set `LIGHTCRAFT_SAM3_MIRRORS` or install by hand: the dialog names the three files, opens the configured model folder with the host opener, preserves setup on an open error, and links docs/ai-masks.md; Meta's original checkpoint installed in place of the Hugging Face one is named as such, #3378). Not verified against Lightroom's Select Object; no brush/box object mode; the first click on a photo waits for its analysis (~4 s on an M4 Pro, ~0.6 s with an RTX 5070 under Linux, ~32 s on a 12-core CPU) |
| LR-MASK-PEOPLE | People parts | P2 | ⬜ | | shape exists (no UI): uses the photo's person / skin / hair / teeth / glasses mattes when it carries them (DNG semantic masks), else the subject heuristic |
| LR-MASK-LANDSCAPE | Landscape classes | P2 | ⬜ | | shape exists, evaluates empty |
| LR-MASK-BRUSH | Brush mask | P0 | 🟡 | `cmd:tool.brush`, `cmd:mask.brushStroke` (`autoMask`), `crates/pipeline/src/masks.rs`, `crates/ui-egui/src/brush_live.rs` | size/feather/flow/density/erase; Create New Mask starts a separate brush in paint mode; the stroke shows while the button is held with the committed stroke's dab spacing, feather and flow, so fast strokes have no gaps (#517); with the mask overlay hidden (O / the eye, or after a mask slider hid it) or a colour overlay at opacity 0 it is not tinted while painting either, so dodging and burning is judged on the photo, and its effect shows once the stroke is committed (#2549); coverage builds up by passes, not hold time (holding the brush still adds nothing, live or committed, #518); oversized path segments skip intermediate dabs instead of allocating a million samples; Auto Mask: dabs weighted by similarity to the colour under the dab centre, refined by a guided filter on luminance (CPU + GPU); ⇧-click draws a straight stroke from where the last stroke ended (`connect`), tapering size, feather and flow from that stroke's values when they changed; no A/B brushes; pen pressure (Brush ▸ Pen Pressure, on by default; `pressure` per point in `mask.brushStroke`) scales each dab's size (a tenth to all of it) and flow, live and committed alike, where winit reports a pen force (Windows; not macOS / Linux tablets yet); no tilt |
@@ -824,6 +824,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove
| 2026-10-27 | minor | LRC-LIB-PREVIEWS: the loupe shows built and prepared previews instead of rendering again, builds skip what is there and Build Previews with one photo open builds the view; LRC-PERF-PREP new (🟡): preparing photos in the background per mode |
| 2026-10-27 | minor | Culling speed: LR-IMP-LOCAL browsing shows the first photos within a second; LR-IMP-PREVIEW-READ a CR3's smallest covering JPEG, plain sRGB JPEGs straight to 8-bit, camera-JPEG thumbnails kept; LR-VIEW-DETAIL camera previews made ahead of the step, “Camera preview” label, camera JPEG first at 100 %; statuses unchanged |
| 2026-11-02 | minor | LR-LIB-FLAG (PERF-STEP-STALL): flags, ratings and edits are written and synced to the catalog log off the UI thread (a 300 ms sync: slowest flag 0.2 ms, was 305 ms); a failed write is held and retried, never dropped |
| 2026-11-04 | patch | LR-MASK-OBJECTS, #2574: remote SAM worker retries transient listener accept errors after 100 ms; client failures remain isolated; feature counts unchanged |
| 2026-10-28 | minor | LR-EDIT-OPTICS-PROFILE: lensfun's database offered once on the first launch and downloaded on request (Download / Not Now, Settings) (pinned, CC BY-SA, never bundled), the library looked up when it arrives or Enable Lens Corrections is ticked, the Optics panel names the profile or the lens without one; status unchanged (🟡) |
| 2026-10-30 | patch | LR-BEHAV-ACCESS: the Flatpak manifests grant `--talk-name=org.a11y.Bus`, so AccessKit can find out whether a screen reader is running and publish the window inside the sandbox; packaging lint requires it in both manifests; status unchanged (🟡), not tried with Orca |
| 2026-10-27 | patch | LR-LIB-LABEL, MENU-PHOTO-LABEL, KEY-LABELS: Clear Color Label (`photo.clearLabel`) is a command of its own, so Help → Keyboard Shortcuts can give it a key (#2980); the Photo ▸ Set Color Label ▸ None row runs it; status unchanged |
+6
View File
@@ -171,6 +171,12 @@
- Importing a backup of a catalog you already imported no longer adds every collection a second time: collections
are matched by the catalog's own id, which its backups keep, instead of by the catalog file's path.
## 2026-11-04
### Remote SAM worker recovers from accept errors
- A transient connection-accept error is logged and retried after a short pause, so one failed accept no longer
stops the remote Metal worker (#2574). Startup validation and bind failures still report an error.
### Reference View's empty state paints on every platform
- Its instruction now uses the supported menu arrow symbol, avoiding a missing-glyph panic while the view is drawn.
## 2026-10-30
### Lightroom catalogs with a print inside a collection import their collections