Skip to content

armgit / ente

Public Imported from GitHub
0

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

Recover from ML utility process crashes instead of hanging

Manav Rathiaaed63f5bfd6
diff --git a/desktop/src/main/services/workers.ts b/desktop/src/main/services/workers.ts
index a67ddb9ce0..ad07f260f8 100644
--- a/desktop/src/main/services/workers.ts
+++ b/desktop/src/main/services/workers.ts
@@ -132,14 +132,12 @@ const forkWatchedUtilityProcess = (scriptName: string, logTag: string) => {
const child = utilityProcess.fork(path.join(__dirname, scriptName), [], {
stdio: "pipe",
});
- child.stdout?.on("data", (chunk: Buffer) => {
- process.stdout.write(chunk);
- log.info(`${logTag} ${String(chunk).trimEnd()}`);
- });
- child.stderr?.on("data", (chunk: Buffer) => {
- process.stderr.write(chunk);
- log.error(`${logTag} ${String(chunk).trimEnd()}`);
- });
+ child.stdout?.on("data", (chunk: Buffer) =>
+ log.info(`${logTag} ${String(chunk).trimEnd()}`),
+ );
+ child.stderr?.on("data", (chunk: Buffer) =>
+ log.warn(`${logTag} ${String(chunk).trimEnd()}`),
+ );
child.on("exit", (code) => {
log.error(`${logTag} utility process exited with code ${code}`);
});
diff --git a/web/packages/new/photos/services/ml/index.ts b/web/packages/new/photos/services/ml/index.ts
index c2421f0c12..852f1c1dcc 100644
--- a/web/packages/new/photos/services/ml/index.ts
+++ b/web/packages/new/photos/services/ml/index.ts
@@ -144,7 +144,11 @@ const worker = () =>
const createComlinkWorker = async () => {
const electron = ensureElectron();
- const delegate = { workerDidUpdateStatus, workerDidUnawaitedIndex };
+ const delegate = {
+ workerDidUpdateStatus,
+ workerDidUnawaitedIndex,
+ workerDidLoseElectronPort,
+ };
// Obtain a message port from the Electron layer.
const messagePort = await createUtilityProcess(electron, "ml");
@@ -354,24 +358,26 @@ export const mlSync = async (reason: ClusterFacesReason = "ml-sync") => {
if (_state.isSyncing) return;
_state.isSyncing = true;
- if (_state.needsResetFailures) {
- // CAS. See documentation for retryIndexingFailures why swapping the
- // flag before performing the operation is fine.
- _state.needsResetFailures = false;
- await resetFailedFileStatuses();
- }
-
- // Dependency order for the sync
- //
- // files -> faces -> cgroups -> clusters -> people
- //
+ try {
+ if (_state.needsResetFailures) {
+ // CAS. See documentation for retryIndexingFailures why swapping
+ // the flag before performing the operation is fine.
+ _state.needsResetFailures = false;
+ await resetFailedFileStatuses();
+ }
- // Fetch indexes, or index locally if needed.
- await worker().then((w) => w.index());
+ // Dependency order for the sync
+ //
+ // files -> faces -> cgroups -> clusters -> people
+ //
- await updateClustersAndPeople(reason);
+ // Fetch indexes, or index locally if needed.
+ await worker().then((w) => w.index());
- _state.isSyncing = false;
+ await updateClustersAndPeople(reason);
+ } finally {
+ _state.isSyncing = false;
+ }
};
const updateClustersAndPeople = async (reason: ClusterFacesReason) => {
@@ -407,6 +413,11 @@ const debounceUpdateClustersAndPeople = pDebounce(
30 * 1e3,
);
+const workerDidLoseElectronPort = () => {
+ log.error("Discarding the ML worker since its utility process exited");
+ void terminateMLWorker();
+};
+
const workerDidUnawaitedIndex = () =>
void debounceUpdateClustersAndPeople("live-upload-index");
diff --git a/web/packages/new/photos/services/ml/worker-types.ts b/web/packages/new/photos/services/ml/worker-types.ts
index 16153b3b2b..3aef8d2da8 100644
--- a/web/packages/new/photos/services/ml/worker-types.ts
+++ b/web/packages/new/photos/services/ml/worker-types.ts
@@ -26,6 +26,12 @@ export interface MLWorkerDelegate {
* some extra code to avoid updating the dependent state twice.
*/
workerDidUnawaitedIndex: () => void;
+ /**
+ * Called when the port that the worker was using to communicate with the
+ * ML utility process closes, which happens if the utility process exits
+ * (e.g. if it crashes). The worker is unusable after this point.
+ */
+ workerDidLoseElectronPort: () => void;
}
/**
diff --git a/web/packages/new/photos/services/ml/worker.ts b/web/packages/new/photos/services/ml/worker.ts
index 9f38fd5937..e5eb966353 100644
--- a/web/packages/new/photos/services/ml/worker.ts
+++ b/web/packages/new/photos/services/ml/worker.ts
@@ -115,8 +115,11 @@ export class MLWorker {
private liveQ: IndexableItem[] = [];
private idleTimeout: ReturnType<typeof setTimeout> | undefined;
private idleDuration = idleDurationStart; /* unit: seconds */
- /** Resolvers for pending promises returned from calls to {@link index}. */
- private onNextIdles: ((count: number) => void)[] = [];
+ /** Settlers for pending promises returned from calls to {@link index}. */
+ private onNextIdles: {
+ resolve: (count: number) => void;
+ reject: (e: Error) => void;
+ }[] = [];
/**
* Number of items processed since the last time {@link onNextIdles} was
* drained.
@@ -140,6 +143,27 @@ export class MLWorker {
init(port: MessagePort, delegate: MLWorkerDelegate) {
this.electron = wrap<ElectronMLWorker>(port);
this.delegate = delegate;
+ port.addEventListener("close", () => this.electronPortDidClose(), {
+ once: true,
+ });
+ }
+
+ /**
+ * Called when the port to the ML utility process closes, which happens if
+ * the utility process exits (e.g. if it crashes).
+ *
+ * Reject any pending promises returned by {@link index} so that a sync
+ * awaiting us doesn't hang forever, then inform the main thread, which
+ * will discard us. Anything else in flight dies with us; the next sync
+ * will retry with a new worker.
+ */
+ private electronPortDidClose() {
+ const onNextIdles = this.onNextIdles;
+ this.onNextIdles = [];
+ onNextIdles.forEach(({ reject }) =>
+ reject(new Error("The ML utility process exited")),
+ );
+ this.delegate?.workerDidLoseElectronPort();
}
/**
@@ -151,11 +175,12 @@ export class MLWorker {
* save it locally. Otherwise we index them.
*
* @return The count of items processed since the last last time we were
- * idle.
+ * idle. The returned promise rejects if the port to the ML utility process
+ * closes while we're indexing.
*/
index() {
- const nextIdle = new Promise<number>((resolve) =>
- this.onNextIdles.push(resolve),
+ const nextIdle = new Promise<number>((resolve, reject) =>
+ this.onNextIdles.push({ resolve, reject }),
);
this.wakeUp();
return nextIdle;
@@ -274,7 +299,7 @@ export class MLWorker {
const countSinceLastIdle = this.countSinceLastIdle;
this.onNextIdles = [];
this.countSinceLastIdle = 0;
- onNextIdles.forEach((f) => f(countSinceLastIdle));
+ onNextIdles.forEach(({ resolve }) => resolve(countSinceLastIdle));
// If no one was waiting, then let the main thread know via a different
// channel so that it can update the clusters and people.
diff --git a/web/packages/new/photos/services/search/index.ts b/web/packages/new/photos/services/search/index.ts
index da95a32bc1..1a5d3aa3b3 100644
--- a/web/packages/new/photos/services/search/index.ts
+++ b/web/packages/new/photos/services/search/index.ts
@@ -124,7 +124,10 @@ const clipSuggestion = async (
if (!isMLSupported) return undefined;
if (!isMLEnabled()) return undefined;
- const matches = await clipMatches(s);
+ const matches = await clipMatches(s).catch((e: unknown) => {
+ log.warn("Ignoring CLIP matches failure", e);
+ return undefined;
+ });
if (!matches) return undefined;
return { type: "clip", clipScoreForFileID: matches, label: searchString };
};