Files
LocalAI/core/services/galleryop/enqueue.go
mudler's LocalAI [bot] f317da7c0f fix(galleryop): make admitted operations queryable and survive a failed op (#11044)
Two lifecycle defects observed on a 2-replica distributed cluster.

The install endpoints mint a job UUID, hand the operation to an unbuffered
channel, and answer HTTP 200 immediately. The gallery worker is a single
goroutine that processes operations serially, and the first status write
happens inside modelHandler/backendHandler — i.e. only once the worker
actually starts the work. An operation queued behind a running install
therefore had no status at all: GET /models/jobs/<uuid> answered
"could not find any status for ID" and GET /models/jobs did not list it,
so the endpoint reported success for work nothing could observe. On the
paths that sent directly rather than from a goroutine, the same unbuffered
channel blocked the HTTP handler for the whole duration of the in-flight
install, which is how a replica came to accept no /models/apply at all
while /readyz stayed green.

Admission now goes through EnqueueModelOp/EnqueueBackendOp, which publish a
"queued" status before handing the operation over, so a job ID is queryable
from the instant it is handed out. Delivery selects on the operation's
context, so cancelling a still-queued operation releases the delivery
goroutine instead of stranding it on a send that will never be received,
and an operation the worker never accepts becomes a terminal failure rather
than a silent leak.

The worker also had no panic containment. A panic in any handler propagated
out of the single consumer goroutine and killed the process, taking every
queued operation with it; it is now contained to the operation that caused
it. The two ignored galleryStore.Create errors are logged, and the model and
backend delete endpoints now run under the same ID they hand back — they
previously ran under an empty ID and returned a status URL for a job that
could never have a status.

Second, an operation orphaned by a controller replaced mid-download kept
reporting phase=downloading, processed=false, error=none while nothing was
downloading. The PostgreSQL side does recover on its own (FindDuplicate
ignores rows untouched for 30 minutes and CleanStale marks them failed), but
the reaper only ever corrected the database. The in-memory statuses map that
GET /models/jobs/<id> and /api/operations actually read was never corrected,
so every replica kept serving the frozen tick indefinitely. ReapStaleOperations
now reconciles the in-memory copy with the reap.

Note that operation ownership is still not tracked: gallery_operations has a
FrontendID column that nothing writes, so a live operation and one whose owner
died are distinguished only by a 30-minute staleness timeout. Narrowing that
window needs a lease/heartbeat mechanism and is out of scope here.


Assisted-by: Claude Code:claude-opus-4-8[1m] [Read] [Edit] [Bash]

Signed-off-by: Ettore Di Giacinto <mudler@localai.io>
Co-authored-by: Ettore Di Giacinto <mudler@localai.io>
2026-07-23 00:02:23 +02:00

107 lines
3.9 KiB
Go

package galleryop
import (
"context"
"fmt"
"github.com/mudler/LocalAI/core/gallery"
"github.com/mudler/xlog"
)
// queuedMessage is the status message an operation carries between admission
// (the HTTP handler minting the job ID) and the moment the worker starts it.
const queuedMessage = "queued"
// EnqueueModelOp admits a model operation: it registers a queryable "queued"
// status for op.ID and then hands the op to the gallery worker.
//
// Why the status is written here and not in modelHandler: the gallery channels
// are unbuffered and the worker processes one operation at a time, so an op
// submitted while another install is downloading sits in a blocked send for as
// long as that install takes. The admission handlers return HTTP 200 with the
// job ID immediately, so for that whole window the client held an ID that
// GET /models/jobs/<id> answered with "could not find any status for ID" and
// GET /models/jobs did not list at all — the endpoint reported success for work
// nothing could observe. Writing the status before the send makes the job
// queryable from the instant its ID is handed out.
//
// Delivery is asynchronous on purpose: a direct send would block the HTTP
// handler for the entire duration of the in-flight install (observed as a
// request that never gets a response while /readyz stays green).
func (g *GalleryService) EnqueueModelOp(op ManagementOp[gallery.GalleryModel, gallery.ModelConfig]) {
g.markQueued(op.ID, op.GalleryElementName, op.Delete)
go func() {
select {
case g.ModelGalleryChannel <- op:
case <-enqueueContext(op.Context).Done():
g.abandonQueued(op.ID, op.GalleryElementName)
}
}()
}
// EnqueueBackendOp is the BackendGalleryChannel sibling of EnqueueModelOp.
// Same rationale — see that comment.
func (g *GalleryService) EnqueueBackendOp(op ManagementOp[gallery.GalleryBackend, any]) {
g.markQueued(op.ID, op.GalleryElementName, op.Delete)
go func() {
select {
case g.BackendGalleryChannel <- op:
case <-enqueueContext(op.Context).Done():
g.abandonQueued(op.ID, op.GalleryElementName)
}
}()
}
// enqueueContext gives the delivery goroutine something to select on. Ops
// submitted without a context (the /models/apply path) simply wait for the
// worker; ops that carry one (every UI path) are released the moment the
// operation is cancelled, so cancelling a still-queued op no longer strands
// the goroutine on a send that will never be received.
func enqueueContext(ctx context.Context) context.Context {
if ctx == nil {
return context.Background()
}
return ctx
}
// markQueued publishes the pre-worker status for an admitted operation.
func (g *GalleryService) markQueued(id, elementName string, deletion bool) {
if id == "" {
return
}
g.UpdateStatus(id, &OpStatus{
Message: queuedMessage,
Phase: queuedMessage,
GalleryElementName: elementName,
Deletion: deletion,
Cancellable: !deletion,
})
}
// abandonQueued turns a queued operation that the worker never accepted into a
// terminal failure. Without it the op keeps claiming it is waiting to start
// while the goroutine that was supposed to deliver it is gone, which is the
// same phantom-operation shape as an op orphaned by a replica restart.
//
// A status that already reached a terminal state (a concurrent cancel is the
// common case) wins: we must not overwrite "cancelled" with a generic failure.
func (g *GalleryService) abandonQueued(id, elementName string) {
if id == "" {
return
}
g.Lock()
if st, ok := g.statuses[id]; ok && st.Processed {
g.Unlock()
return
}
g.Unlock()
xlog.Warn("Gallery operation was never picked up by the worker", "op_id", id, "element", elementName)
g.UpdateStatus(id, &OpStatus{
Processed: true,
Error: fmt.Errorf("operation was cancelled before the gallery worker could start it"),
Message: "error: operation was cancelled before the gallery worker could start it",
GalleryElementName: elementName,
})
}