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.
C avx-512avx2biometricsc99computer-visioncpu-inferencedeep-learningedge-aiembedded-aiface-embeddingface-recognitionface-verificationlow-latencyonnx-runtimeproduction-readysimdzero-dependencies
Keep concurrent embedding requests isolated across cancellation
Baurzhan Atynov293ab658d912
diff --git a/.github/workflows/go-gallery.yml b/.github/workflows/go-gallery.ymlindex 00620bf..20f74b3 100644--- a/.github/workflows/go-gallery.yml+++ b/.github/workflows/go-gallery.yml@@ -59,3 +59,9 @@ jobs:PYcd go/facexgo test -v -run '^TestIdentityGalleryScale$' -count=1 ./...+ - name: Verify concurrent engine replies against serial inference+ working-directory: go/facex+ env:+ FACEX_POOL_TEST_EXE: ${{ github.workspace }}/facex-cli+ FACEX_POOL_TEST_WEIGHTS: ${{ runner.temp }}/edgeface_xs_fp32.bin+ run: go test -race -v -timeout=90s -run '^TestPoolRealEngine$' -count=1 ./...diff --git a/go/facex/facex.go b/go/facex/facex.goindex ee113bd..8e4c894 100644--- a/go/facex/facex.go+++ b/go/facex/facex.go@@ -15,8 +15,8 @@// // input: HWC float32 [-1, 1], exactly 3*112*112 = 37632 floats.// emb, err := fx.Embed(input) // []float32 length 512//-// Thread-safety: FaceX is NOT goroutine-safe. Create one instance per-// goroutine, or wrap with your own sync.Mutex.+// A FaceX instance serializes its calls. EmbedPool supports concurrent engines+// and context cancellation.package faceximport (@@ -51,7 +51,6 @@ type FaceX struct {cmd *exec.Cmdstdin io.WriteCloserstdout io.ReadCloser- stderr io.ReadClosermu sync.Mutexclosed bool}@@ -93,16 +92,16 @@ func New(cfg Config) (*FaceX, error) {}stdout, err := cmd.StdoutPipe()if err != nil {+ _ = stdin.Close()return nil, err}- stderr, err := cmd.StderrPipe()- if err != nil {- return nil, err- }+ // Leave Stderr nil so engine diagnostics cannot fill an unread pipe.if err := cmd.Start(); err != nil {+ _ = stdin.Close()+ _ = stdout.Close()return nil, err}- return &FaceX{cmd: cmd, stdin: stdin, stdout: stdout, stderr: stderr}, nil+ return &FaceX{cmd: cmd, stdin: stdin, stdout: stdout}, nil}// Embed runs a single forward pass. input must be exactly 3*112*112 floatsdiff --git a/go/facex/pool.go b/go/facex/pool.gonew file mode 100644index 0000000..27fc0aa--- /dev/null+++ b/go/facex/pool.go@@ -0,0 +1,150 @@+package facex++import (+ "context"+ "errors"+ "fmt"+ "math"+ "sync"+)++var (+ // ErrPoolBusy means all admitted work and waiting places are occupied.+ ErrPoolBusy = errors.New("facex: embedding pool busy")+ // ErrPoolClosed means pool shutdown has started.+ ErrPoolClosed = errors.New("facex: embedding pool closed")+)++// EmbedPool leases each binary stream to exactly one request at a time.+type EmbedPool struct {+ cfg Config+ slots chan *FaceX+ permits chan struct{}+ closed chan struct{}+ once sync.Once+}++// NewEmbedPool starts workers persistent processes and admits at most+// workers + maxWaiting calls. Use zero waiting places for immediate backpressure.+func NewEmbedPool(cfg Config, workers, maxWaiting int) (*EmbedPool, error) {+ if workers < 1 || maxWaiting < 0 || maxWaiting > math.MaxInt-workers {+ return nil, errors.New("facex: invalid embedding pool capacity")+ }+ p := &EmbedPool{+ cfg: cfg, slots: make(chan *FaceX, workers),+ permits: make(chan struct{}, workers+maxWaiting), closed: make(chan struct{}),+ }+ for i := 0; i < workers; i++ {+ fx, err := New(cfg)+ if err != nil {+ for j := 0; j < i; j++ {+ worker := <-p.slots+ stopWorker(worker)+ _ = worker.Close()+ }+ return nil, err+ }+ p.slots <- fx+ }+ return p, nil+}++// Close both descriptors to unblock either half of an in-flight exchange.+// The lease owner calls Wait through FaceX.Close after Embed has returned.+func stopWorker(fx *FaceX) {+ _ = fx.cmd.Process.Kill()+ _ = fx.stdin.Close()+ _ = fx.stdout.Close()+}++// Embed returns one 512-component embedding. An interrupted or broken stream+// is discarded before its slot can serve another caller. Failed requests are+// returned to the caller; a later request starts a fresh process in that slot.+func (p *EmbedPool) Embed(ctx context.Context, input []float32) ([]float32, error) {+ if ctx == nil || len(input) != InputSize {+ return nil, fmt.Errorf("facex: expected a context and %d input floats", InputSize)+ }+ if err := ctx.Err(); err != nil {+ return nil, err+ }+ select {+ case <-p.closed:+ return nil, ErrPoolClosed+ default:+ }+ select {+ case p.permits <- struct{}{}:+ defer func() { <-p.permits }()+ default:+ return nil, ErrPoolBusy+ }+ var fx *FaceX+ select {+ case <-ctx.Done():+ return nil, ctx.Err()+ case <-p.closed:+ return nil, ErrPoolClosed+ case fx = <-p.slots:+ }+ defer func() { p.slots <- fx }()+ if err := ctx.Err(); err != nil {+ return nil, err+ }+ select {+ case <-p.closed:+ return nil, ErrPoolClosed+ default:+ }+ if fx == nil {+ var err error+ fx, err = New(p.cfg)+ if err != nil {+ return nil, err+ }+ }++ type reply struct {+ vector []float32+ err error+ }+ finished := make(chan reply, 1)+ go func(worker *FaceX) {+ v, err := worker.Embed(input)+ finished <- reply{v, err}+ }(fx)++ var failure error+ select {+ case result := <-finished:+ if result.err == nil {+ return result.vector, nil+ }+ failure = result.err+ stopWorker(fx)+ case <-ctx.Done():+ failure = ctx.Err()+ stopWorker(fx)+ <-finished+ case <-p.closed:+ failure = ErrPoolClosed+ stopWorker(fx)+ <-finished+ }+ _ = fx.Close()+ fx = nil+ return nil, failure+}++// Close interrupts active requests, wakes waiters and reaps every subprocess.+// Multiple callers can close the pool concurrently.+func (p *EmbedPool) Close() {+ p.once.Do(func() {+ close(p.closed)+ for i := 0; i < cap(p.slots); i++ {+ if fx := <-p.slots; fx != nil {+ stopWorker(fx)+ _ = fx.Close()+ }+ }+ })+}diff --git a/go/facex/pool_test.go b/go/facex/pool_test.gonew file mode 100644index 0000000..b88692a--- /dev/null+++ b/go/facex/pool_test.go@@ -0,0 +1,213 @@+package facex++import (+ "bytes"+ "context"+ "encoding/binary"+ "errors"+ "fmt"+ "io"+ "math"+ "os"+ "path/filepath"+ "slices"+ "sync"+ "testing"+ "time"+)++// The helper speaks the real fixed-size wire protocol. A file marker lets+// tests cancel only after a partial reply has actually reached the pipe.+func TestMain(m *testing.M) {+ if os.Getenv("FACEX_POOL_TEST_CHILD") == "1" && len(os.Args) == 3 && os.Args[2] == "--server" {+ runPoolChild()+ os.Exit(0)+ }+ os.Exit(m.Run())+}++func runPoolChild() {+ input, output := make([]byte, InputBytes), make([]byte, OutputBytes)+ for {+ if _, err := io.ReadFull(os.Stdin, input); err != nil {+ return+ }+ switch math.Float32frombits(binary.LittleEndian.Uint32(input)) {+ case -1:+ _, _ = os.Stdout.Write(output[:13])+ if err := os.WriteFile("partial", []byte("ready"), 0600); err != nil {+ os.Exit(2)+ }+ time.Sleep(time.Minute)+ return+ case -2:+ _, _ = os.Stdout.Write(output[:13])+ return+ case -3:+ _, _ = os.Stderr.Write(bytes.Repeat([]byte{'x'}, 256<<10))+ }+ for j := 0; j < OutputSize; j++ {+ copy(output[4*j:4*j+4], input[4*j:4*j+4])+ }+ if _, err := os.Stdout.Write(output); err != nil {+ return+ }+ }+}++func poolInput(v float32) []float32 {+ data := make([]float32, InputSize)+ for i := range data {+ data[i] = v+ }+ return data+}++func newHelperPool(t *testing.T, workers, waiting int) (*EmbedPool, string) {+ t.Helper()+ t.Setenv("FACEX_POOL_TEST_CHILD", "1")+ exe, err := os.Executable()+ if err != nil {+ t.Fatal(err)+ }+ dir := t.TempDir()+ p, err := NewEmbedPool(Config{Exe: exe, Workdir: dir}, workers, waiting)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(p.Close)+ return p, dir+}++func waitPool(t *testing.T, ready func() bool) {+ t.Helper()+ limit := time.Now().Add(10 * time.Second)+ for !ready() {+ if time.Now().After(limit) {+ t.Fatal("timed out waiting for worker state")+ }+ time.Sleep(time.Millisecond)+ }+}++func TestPoolInterrupt(t *testing.T) {+ for _, shutdown := range []bool{false, true} {+ t.Run(fmt.Sprintf("shutdown=%t", shutdown), func(t *testing.T) {+ p, dir := newHelperPool(t, 1, 1)+ active, cancelActive := context.WithCancel(context.Background())+ defer cancelActive()+ busy := make(chan error, 1)+ go func() {+ _, err := p.Embed(active, poolInput(-1))+ busy <- err+ }()+ waitPool(t, func() bool {+ _, err := os.Stat(filepath.Join(dir, "partial"))+ return err == nil+ })+ waiting, cancelWaiting := context.WithCancel(context.Background())+ defer cancelWaiting()+ queued := make(chan error, 1)+ go func() {+ _, err := p.Embed(waiting, poolInput(7))+ queued <- err+ }()+ waitPool(t, func() bool { return len(p.permits) == 2 })+ if _, err := p.Embed(context.Background(), poolInput(8)); !errors.Is(err, ErrPoolBusy) {+ t.Fatalf("overflow: %v", err)+ }+ if shutdown {+ p.Close()+ if !errors.Is(<-busy, ErrPoolClosed) || !errors.Is(<-queued, ErrPoolClosed) {+ t.Fatal("shutdown did not interrupt active and queued calls")+ }+ return+ }+ cancelWaiting()+ if !errors.Is(<-queued, context.Canceled) {+ t.Fatal("queued context was ignored")+ }+ cancelActive()+ if !errors.Is(<-busy, context.Canceled) {+ t.Fatal("active context was ignored")+ }+ input := poolInput(11)+ out, err := p.Embed(context.Background(), input)+ if err != nil || !slices.Equal(out, input[:OutputSize]) {+ t.Fatal("partial reply leaked into the replacement stream", err)+ }+ })+ }+}++func TestPoolRecoveryAndConcurrentOwnership(t *testing.T) {+ p, _ := newHelperPool(t, 2, 32)+ if _, err := p.Embed(context.Background(), poolInput(-2)); !errors.Is(err, io.ErrUnexpectedEOF) {+ t.Fatalf("truncated reply: %v", err)+ }+ input := poolInput(-3)+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ if out, err := p.Embed(ctx, input); err != nil || !slices.Equal(out, input[:OutputSize]) {+ t.Fatal("stderr blocked the exchange", err)+ }+ var wg sync.WaitGroup+ for i := 0; i < 32; i++ {+ wg.Add(1)+ go func(i int) {+ defer wg.Done()+ input := poolInput(float32(i+1))+ out, err := p.Embed(ctx, input)+ if err != nil || !slices.Equal(out, input[:OutputSize]) {+ t.Errorf("request %d received a wrong reply: %v", i, err)+ }+ }(i)+ }+ wg.Wait()+}++func TestPoolRealEngine(t *testing.T) {+ weights := os.Getenv("FACEX_POOL_TEST_WEIGHTS")+ if weights == "" {+ t.Skip("set FACEX_POOL_TEST_WEIGHTS and FACEX_POOL_TEST_EXE to run the model check")+ }+ cfg := Config{Exe: os.Getenv("FACEX_POOL_TEST_EXE"), Weights: weights}+ serial, err := New(cfg)+ if err != nil {+ t.Fatal(err)+ }+ defer serial.Close()+ const count = 16+ inputs, want := make([][]float32, count), make([][]float32, count)+ for i := range inputs {+ input := make([]float32, InputSize)+ for j := range input {+ input[j] = float32(math.Sin(float64((j+1)*(i+1))*.001))+ }+ inputs[i] = input+ want[i], err = serial.Embed(input)+ if err != nil {+ t.Fatal(err)+ }+ if i > 0 && slices.Equal(want[0], want[i]) {+ t.Fatal("reference inputs produced identical embeddings")+ }+ }+ p, err := NewEmbedPool(cfg, 2, count)+ if err != nil {+ t.Fatal(err)+ }+ defer p.Close()+ var wg sync.WaitGroup+ for i := range inputs {+ wg.Add(1)+ go func(i int) {+ defer wg.Done()+ out, err := p.Embed(context.Background(), inputs[i])+ if err != nil || !slices.Equal(want[i], out) {+ t.Errorf("engine request %d differs from the serial reference: %v", i, err)+ }+ }(i)+ }+ wg.Wait()+}