Skip to content

armgit / facex

Public Imported from GitHub
0

Full face stack that runs entirely in the browser. Detection, 576-point 3D mesh, recognition, anti-spoof, smile — all WebAssembly, zero server. Apache 2.0.

Skip stale requests before face inference starts

Baurzhan Atynovabc177f28749
diff --git a/docker/server.py b/docker/server.py
index 5182bf9..39d952a 100644
--- a/docker/server.py
+++ b/docker/server.py
@@ -11,6 +11,7 @@ Usage:
gunicorn -w 2 -b 0.0.0.0:8080 server:app
"""
+from contextlib import contextmanager
import base64
import os
import subprocess
@@ -18,7 +19,7 @@ import threading
import time
import numpy as np
-from flask import Flask, request, jsonify
+from flask import Flask, g, request, jsonify
from PIL import Image
from facex import FaceX
@@ -73,6 +74,59 @@ _detector = None
_detector_lock = threading.Lock()
+QUEUE_WAIT_MS = int(os.environ.get("FACEX_QUEUE_WAIT_MS", "250"))
+if not 0 <= QUEUE_WAIT_MS <= 86_400_000:
+ raise ValueError("FACEX_QUEUE_WAIT_MS must be between 0 and 86400000")
+
+
+class InferenceBusy(Exception):
+ pass
+
+
[email protected](InferenceBusy)
+def inference_busy(_error):
+ return jsonify(error="Inference deadline expired", code="inference_busy"), 503
+
+
+def set_inference_deadline():
+ if request.endpoint not in ("detect", "embed") or request.method != "POST":
+ return
+ start = time.monotonic_ns()
+ g.inference_deadline = start + QUEUE_WAIT_MS * 1_000_000 if QUEUE_WAIT_MS else None
+ value = request.headers.get("X-FaceX-Deadline-Ms")
+ if value is not None:
+ if not (1 <= len(value) <= 15 and value.isascii() and value.isdigit()):
+ return jsonify(error="X-FaceX-Deadline-Ms must be a Unix timestamp in milliseconds"), 400
+ remaining = int(value) * 1_000_000 - time.time_ns()
+ if remaining <= 0:
+ raise InferenceBusy()
+ deadline = start + remaining
+ if g.inference_deadline is None or deadline < g.inference_deadline:
+ g.inference_deadline = deadline
+
+
+def check_inference_deadline():
+ if g.inference_deadline is not None and time.monotonic_ns() >= g.inference_deadline:
+ raise InferenceBusy()
+
+
+@contextmanager
+def inference_slot(lock):
+ deadline = g.inference_deadline
+ if deadline is None:
+ lock.acquire()
+ else:
+ remaining = deadline - time.monotonic_ns()
+ if remaining <= 0 or not lock.acquire(timeout=min(remaining / 1e9, threading.TIMEOUT_MAX)):
+ raise InferenceBusy()
+ try:
+ check_inference_deadline()
+ yield
+ finally:
+ lock.release()
+
+
def initialize_detector():
"""Load weights before forking or under the detector lock in a worker."""
global _detector
@@ -88,9 +142,10 @@ def initialize_detector():
def embed_in_worker(arr):
global _fx
# The binary protocol has no request IDs. Keep each write and read together.
- with _embed_lock:
+ with inference_slot(_embed_lock):
if _fx is None:
_fx = FaceXProcess()
+ check_inference_deadline()
try:
return _fx.embed(arr)
except OSError:
@@ -179,9 +234,10 @@ def detect():
return jsonify({'error': 'Invalid image'}), 400
start = time.perf_counter()
- with _detector_lock:
+ with inference_slot(_detector_lock):
try:
initialize_detector()
+ check_inference_deadline()
faces = _detector.detect(rgb, max_faces=32, embeddings=embeddings)
except (RuntimeError, OSError):
app.logger.exception("Face detection failed")
diff --git a/docs/research/multiface_requests.md b/docs/research/multiface_requests.md
index 3811abd..b49dded 100644
--- a/docs/research/multiface_requests.md
+++ b/docs/research/multiface_requests.md
@@ -22,8 +22,16 @@ With the native library, CLI and mounted weights configured, run from the reposi
~~~sh
PYTHONPATH=python:docker python tests/bench_multiface_response.py --batch-workers 4
-PYTHONPATH=python:docker python tests/bench_http_burst.py --wsgi-processes 2
-PYTHONPATH=python:docker python tests/bench_http_burst.py --wsgi-threads
+FACEX_QUEUE_WAIT_MS=0 PYTHONPATH=python:docker python tests/bench_http_burst.py --wsgi-processes 2
+FACEX_QUEUE_WAIT_MS=0 PYTHONPATH=python:docker python tests/bench_http_burst.py --wsgi-threads
~~~
For a running Gunicorn instance listening on a Unix socket, pass `--socket /path/to/socket` instead.
+
+## Inference admission deadline
+
+The Flask worker allows 250 ms by default from handler entry to starting inference on `/detect` and `/embed`. Set `FACEX_QUEUE_WAIT_MS` to a different budget in milliseconds, or zero for unlimited local waiting. An admitted inference runs to completion. A busy response is HTTP 503 with `code: inference_busy`. Live-video clients should discard the expired frame and submit a recent frame when ready.
+
+To include time already spent uploading or waiting at a proxy or a synchronous Gunicorn worker, clients can send `X-FaceX-Deadline-Ms` with the absolute Unix time in milliseconds after which processing the frame is no longer useful. This requires synchronized clocks. The earlier deadline applies. The worker checks expiration before accessing the multipart body and again before model execution. Queues outside Flask can still delay delivery of the 503 response.
+
+In a local 64-request burst with 32 clients, one threaded Flask process and eight real JPEGs, unlimited admission returned 64 successful responses with p95 1767 ms. A 250 ms budget admitted 10 (p95 313 ms) and rejected 54 (p95 253 ms). All admitted responses matched their image's sequential result. A subsequent request completed normally. These are WSGI timings for a single burst.
diff --git a/tests/test_inference_deadline.py b/tests/test_inference_deadline.py
new file mode 100644
index 0000000..7e11cd6
--- /dev/null
+++ b/tests/test_inference_deadline.py
@@ -0,0 +1,45 @@
+"""Exercise admission and recovery without model files."""
+import io
+from pathlib import Path
+import time
+import unittest
+from unittest.mock import Mock, patch
+
+import numpy as np
+
+import server
+
+
+class AdmissionTest(unittest.TestCase):
+ image = (Path(__file__).resolve().parents[1] / "data/test_face.jpg").read_bytes()
+
+ def post(self, endpoint, value=None):
+ headers = {} if value is None else {"X-FaceX-Deadline-Ms": value}
+ return server.app.test_client().post(endpoint, headers=headers,
+ data={"file": (io.BytesIO(self.image), "face.jpg")})
+
+ def test_both_routes(self):
+ for endpoint, name, lock in (("/detect", "_detector", server._detector_lock),
+ ("/embed", "_fx", server._embed_lock)):
+ engine = Mock()
+ engine.detect.return_value = []
+ engine.embed.return_value = np.zeros(512, dtype="f")
+ with patch.object(server, name, engine), patch.object(server, "QUEUE_WAIT_MS", 20):
+ self.assertEqual(self.post(endpoint, "invalid").status_code, 400)
+ self.assertEqual(self.post(endpoint, "1").json["code"], "inference_busy")
+ with lock:
+ future = str(time.time_ns() // 1_000_000 + 10000)
+ self.assertEqual(self.post(endpoint, future).json["code"], "inference_busy")
+ self.assertFalse(engine.method_calls)
+ self.assertEqual(self.post(endpoint, future).status_code, 200)
+ self.assertEqual(len(engine.method_calls), 1)
+
+ def test_client_deadline_with_no_server_limit(self):
+ with patch.object(server, "QUEUE_WAIT_MS", 0), server._detector_lock:
+ deadline = str(time.time_ns() // 1_000_000 + 30)
+ self.assertEqual(self.post("/detect", deadline).status_code, 503)
+ self.assertEqual(server.app.test_client().get("/health").status_code, 200)
+
+
+if __name__ == "__main__":
+ unittest.main()