Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
86c643f
Guard vGPU releases with live-instance claims
yummybomb Aug 6, 2026
b118883
Reconcile vendor VFIO vGPUs against a fail-closed instance inventory
yummybomb Aug 6, 2026
2b0caec
Fail closed on vGPU claim checks
yummybomb Aug 6, 2026
d6cd144
Retain only vGPU assignment after failed create
yummybomb Aug 6, 2026
28ff73a
Clear released vGPU assignment on start rollback
yummybomb Aug 6, 2026
b1151d9
Test start rollback vGPU cleanup
yummybomb Aug 6, 2026
2311f4a
Normalize legacy mdev paths in live-claim check
yummybomb Aug 7, 2026
ddc5b13
Bind the live-claimant test socket under /tmp for macOS
yummybomb Aug 7, 2026
3575621
Surface retained vGPU cleanup through a typed create error and manage…
yummybomb Aug 7, 2026
f5d8c55
Generalize the create vGPU error text
yummybomb Aug 7, 2026
37a674b
Scope vGPU claim scan to vendor VFIO and close reconcile gaps
yummybomb Aug 8, 2026
e372ff0
Harden the vendor VFIO release path
yummybomb Aug 9, 2026
76e58a6
Fail closed on retained vGPU cleanup
yummybomb Aug 9, 2026
808d990
Report surviving vGPU retention metadata
yummybomb Aug 9, 2026
6dbe19d
Return accurate vGPU cleanup guidance
yummybomb Aug 9, 2026
a908565
Clarify vGPU retention fallback
yummybomb Aug 9, 2026
ac052db
Pass hypervisor identity token to vGPU claim check
yummybomb Aug 10, 2026
444783c
Fail safely on ambiguous vGPU claims
yummybomb Aug 10, 2026
1e73f94
Expose retained vGPU instance IDs
yummybomb Aug 10, 2026
79406ab
Harden vGPU startup rollback recovery
yummybomb Aug 10, 2026
2350615
Preserve the create failure cause in vGPU cleanup errors
yummybomb Aug 10, 2026
0368880
Fix vGPU reconciliation edge cases
yummybomb Aug 10, 2026
1905eb3
Use boot-scoped hypervisor identities for vGPUs
yummybomb Aug 10, 2026
a98979c
Run vGPU rollback tests with QEMU
yummybomb Aug 10, 2026
92d8df5
Protect new vGPU assignments from stale PIDs
yummybomb Aug 10, 2026
10ca9cf
Persist vGPU assignments after create rollback failure
yummybomb Aug 10, 2026
cd18b55
Preserve vGPU lifecycle compatibility
yummybomb Aug 10, 2026
a6c04a7
Reconcile vGPU protection from raw metadata and restore GPUAssignedAt
yummybomb Aug 10, 2026
908867c
Surface pending vGPU cleanup from start as a typed error
yummybomb Aug 11, 2026
f3f2cc4
Cover retained-stub delete recovery and flag reconcile inventory fail…
yummybomb Aug 11, 2026
5eb6424
Reject vendor VFIO vGPUs on Cloud Hypervisor and improve wedge forensics
yummybomb Aug 11, 2026
a00f799
Surface retained rollback assignments from start as vgpu_cleanup_pending
yummybomb Aug 11, 2026
44f9eb9
Report retention as persisted when the mid-start save survives
yummybomb Aug 11, 2026
73aedca
Leave vGPU hypervisor selection to callers
yummybomb Aug 11, 2026
8f95b1a
Carry identity fields into the create-pending retention stub
yummybomb Aug 11, 2026
3cc1cfd
Grace recent dead-PID claims in the release scan like reconcile does
yummybomb Aug 11, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions cmd/api/api/instances.go
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,26 @@ func (s *ApiService) CreateInstance(ctx context.Context, request oapi.CreateInst

inst, err := s.InstanceManager.CreateInstance(ctx, domainReq)
if err != nil {
var vgpuPending *instances.VGPUCleanupPendingError
switch {
// Checked first: it wraps the original create error, so a later
// errors.Is case would match the cause and hide the pending vGPU cleanup.
case errors.As(err, &vgpuPending):
log.ErrorContext(ctx, "failed to create instance", "error", err, "image", request.Body.Image)
message := fmt.Sprintf("failed to create instance: %v; vGPU release failed during rollback and instance %s retains the assignment, delete it to retry", vgpuPending.Err, vgpuPending.InstanceID)
innerCode := "vgpu_retained_instance"
if !vgpuPending.Retained {
message = fmt.Sprintf("failed to create instance: %v; vGPU release failed during rollback and the retention record for instance %s could not be saved; the assignment is recovered on the next startup reconcile", vgpuPending.Err, vgpuPending.InstanceID)
innerCode = "vgpu_unretained_instance"
}
return oapi.CreateInstance500JSONResponse{
Code: "vgpu_cleanup_pending",
Message: message,
InnerError: &oapi.ErrorDetail{
Code: lo.ToPtr(innerCode),
Message: lo.ToPtr(vgpuPending.InstanceID),
},
}, nil
Comment thread
cursor[bot] marked this conversation as resolved.
case errors.Is(err, instances.ErrImageNotReady):
return oapi.CreateInstance400JSONResponse{
Code: "image_not_ready",
Expand Down Expand Up @@ -798,7 +817,26 @@ func (s *ApiService) StartInstance(ctx context.Context, request oapi.StartInstan

result, err := s.InstanceManager.StartInstance(ctx, inst.Id, startReq)
if err != nil {
var vgpuPending *instances.VGPUCleanupPendingError
switch {
// Checked first: it wraps the original start error, so a later
// errors.Is case would match the cause and hide the pending vGPU cleanup.
case errors.As(err, &vgpuPending):
log.ErrorContext(ctx, "failed to start instance", "error", err)
message := fmt.Sprintf("failed to start instance: %v; vGPU release failed during rollback and instance %s retains the assignment, delete it or retry start to release it", vgpuPending.Err, vgpuPending.InstanceID)
innerCode := "vgpu_retained_instance"
if !vgpuPending.Retained {
message = fmt.Sprintf("failed to start instance: %v; vGPU release failed during rollback and the retention record for instance %s could not be saved; the assignment is recovered on the next startup reconcile", vgpuPending.Err, vgpuPending.InstanceID)
innerCode = "vgpu_unretained_instance"
}
return oapi.StartInstance500JSONResponse{
Code: "vgpu_cleanup_pending",
Message: message,
InnerError: &oapi.ErrorDetail{
Code: lo.ToPtr(innerCode),
Message: lo.ToPtr(vgpuPending.InstanceID),
},
}, nil
case errors.Is(err, instances.ErrInvalidState):
return oapi.StartInstance409JSONResponse{
Code: "invalid_state",
Expand Down Expand Up @@ -1205,6 +1243,9 @@ func instanceToOAPI(inst instances.Instance) oapi.Instance {
if inst.GPUMdevUUID != "" {
gpu.MdevUuid = lo.ToPtr(inst.GPUMdevUUID)
}
if inst.GPUDevicePath != "" {
gpu.DevicePath = lo.ToPtr(inst.GPUDevicePath)
}
oapiInst.Gpu = gpu
}

Expand Down
130 changes: 130 additions & 0 deletions cmd/api/api/instances_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"github.com/kernel/hypeman/lib/instances"
"github.com/kernel/hypeman/lib/instances/phasetracking"
mw "github.com/kernel/hypeman/lib/middleware"
"github.com/kernel/hypeman/lib/network"
"github.com/kernel/hypeman/lib/oapi"
"github.com/kernel/hypeman/lib/paths"
restartpolicy "github.com/kernel/hypeman/lib/restart-policy"
Expand Down Expand Up @@ -46,6 +47,73 @@ func TestGetInstance_NotFound(t *testing.T) {
require.Error(t, err)
}

type createErrorInstanceManager struct {
instances.Manager
err error
}

func (m createErrorInstanceManager) CreateInstance(context.Context, instances.CreateInstanceRequest) (*instances.Instance, error) {
return nil, m.err
}

// A retained-assignment error must win over the mapping of the create error
// it wraps, or the response omits the instance the caller has to delete.
func TestCreateInstance_VGPUCleanupPendingBeatsWrappedErrorMapping(t *testing.T) {
t.Parallel()
svc := newTestService(t)
svc.InstanceManager = createErrorInstanceManager{err: &instances.VGPUCleanupPendingError{
InstanceID: "inst-1",
Retained: true,
Err: network.ErrNameExists,
}}

resp, err := svc.CreateInstance(ctx(), oapi.CreateInstanceRequestObject{
Body: &oapi.CreateInstanceRequest{Image: "test-image"},
})
require.NoError(t, err)

pending, ok := resp.(oapi.CreateInstance500JSONResponse)
require.True(t, ok, "expected 500 vgpu_cleanup_pending, got %T", resp)
assert.EqualValues(t, "vgpu_cleanup_pending", pending.Code)
assert.Contains(t, pending.Message, "inst-1")
assert.Contains(t, pending.Message, network.ErrNameExists.Error(),
"the underlying create failure must survive the cleanup guidance")
assert.Contains(t, pending.Message, "delete it to retry")
require.NotNil(t, pending.InnerError)
require.NotNil(t, pending.InnerError.Code)
assert.Equal(t, "vgpu_retained_instance", *pending.InnerError.Code)
require.NotNil(t, pending.InnerError.Message)
assert.Equal(t, "inst-1", *pending.InnerError.Message)
}

func TestCreateInstance_VGPUCleanupPendingWithoutRetentionUsesReconcileGuidance(t *testing.T) {
t.Parallel()
svc := newTestService(t)
svc.InstanceManager = createErrorInstanceManager{err: &instances.VGPUCleanupPendingError{
InstanceID: "inst-1",
Err: network.ErrNameExists,
}}

resp, err := svc.CreateInstance(ctx(), oapi.CreateInstanceRequestObject{
Body: &oapi.CreateInstanceRequest{Image: "test-image"},
})
require.NoError(t, err)

pending, ok := resp.(oapi.CreateInstance500JSONResponse)
require.True(t, ok, "expected 500 vgpu_cleanup_pending, got %T", resp)
assert.EqualValues(t, "vgpu_cleanup_pending", pending.Code)
assert.Contains(t, pending.Message, "retention record for instance inst-1 could not be saved")
assert.Contains(t, pending.Message, network.ErrNameExists.Error(),
"the underlying create failure must survive the cleanup guidance")
assert.Contains(t, pending.Message, "startup reconcile")
assert.NotContains(t, pending.Message, "delete")
require.NotNil(t, pending.InnerError)
require.NotNil(t, pending.InnerError.Code)
assert.Equal(t, "vgpu_unretained_instance", *pending.InnerError.Code)
require.NotNil(t, pending.InnerError.Message)
assert.Equal(t, "inst-1", *pending.InnerError.Message)
}

func TestCreateInstance_AutoPullImage(t *testing.T) {
t.Parallel()
if _, err := os.Stat("/dev/kvm"); os.IsNotExist(err) {
Expand Down Expand Up @@ -779,6 +847,68 @@ func (m *errActionInstanceManager) RestoreSnapshot(context.Context, string, stri
return nil, m.err
}

// A retained-assignment error must win over the mapping of the start error
// it wraps, or the response omits the pending vGPU cleanup the caller has to
// resolve.
func TestStartInstance_VGPUCleanupPendingBeatsWrappedErrorMapping(t *testing.T) {
t.Parallel()

resolved := &instances.Instance{
StoredMetadata: instances.StoredMetadata{Id: "inst-1", Name: "inst-1"},
State: instances.StateStopped,
}

t.Run("retained", func(t *testing.T) {
t.Parallel()
svc := newTestService(t)
svc.InstanceManager = &errActionInstanceManager{Manager: svc.InstanceManager, err: &instances.VGPUCleanupPendingError{
InstanceID: "inst-1",
Retained: true,
Err: fmt.Errorf("create vGPU for profile p: %w", instances.ErrInsufficientResources),
}}

resp, rerr := svc.StartInstance(mw.WithResolvedInstance(ctx(), resolved.Id, resolved), oapi.StartInstanceRequestObject{Id: resolved.Id})
require.NoError(t, rerr)

pending, ok := resp.(oapi.StartInstance500JSONResponse)
require.True(t, ok, "expected 500 vgpu_cleanup_pending, got %T", resp)
assert.EqualValues(t, "vgpu_cleanup_pending", pending.Code)
assert.Contains(t, pending.Message, "inst-1")
assert.Contains(t, pending.Message, instances.ErrInsufficientResources.Error(),
"the underlying start failure must survive the cleanup guidance")
assert.Contains(t, pending.Message, "delete it or retry start")
require.NotNil(t, pending.InnerError)
require.NotNil(t, pending.InnerError.Code)
assert.Equal(t, "vgpu_retained_instance", *pending.InnerError.Code)
require.NotNil(t, pending.InnerError.Message)
assert.Equal(t, "inst-1", *pending.InnerError.Message)
})

t.Run("unretained", func(t *testing.T) {
t.Parallel()
svc := newTestService(t)
svc.InstanceManager = &errActionInstanceManager{Manager: svc.InstanceManager, err: &instances.VGPUCleanupPendingError{
InstanceID: "inst-1",
Err: fmt.Errorf("create vGPU for profile p: %w", instances.ErrInsufficientResources),
}}

resp, rerr := svc.StartInstance(mw.WithResolvedInstance(ctx(), resolved.Id, resolved), oapi.StartInstanceRequestObject{Id: resolved.Id})
require.NoError(t, rerr)

pending, ok := resp.(oapi.StartInstance500JSONResponse)
require.True(t, ok, "expected 500 vgpu_cleanup_pending, got %T", resp)
assert.EqualValues(t, "vgpu_cleanup_pending", pending.Code)
assert.Contains(t, pending.Message, "retention record for instance inst-1 could not be saved")
assert.Contains(t, pending.Message, "startup reconcile")
assert.NotContains(t, pending.Message, "delete")
require.NotNil(t, pending.InnerError)
require.NotNil(t, pending.InnerError.Code)
assert.Equal(t, "vgpu_unretained_instance", *pending.InnerError.Code)
require.NotNil(t, pending.InnerError.Message)
assert.Equal(t, "inst-1", *pending.InnerError.Message)
})
}

func TestInstanceActions_ImageNotFoundMapsTo404(t *testing.T) {
t.Parallel()

Expand Down
66 changes: 60 additions & 6 deletions cmd/api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,63 @@ func configureUFFDGraduationController(cfg *config.Config, instanceManager insta
}, logger), nil
}

func liveInstanceVGPUDevicePaths(ctx context.Context, instanceManager instances.Manager) (map[string]struct{}, time.Duration, error) {
allInstances, err := instanceManager.ListInstancesForReconcile(ctx)
if err != nil {
return nil, 0, err
}
protected := make(map[string]struct{})
var retryAfter time.Duration
for _, inst := range allInstances {
if inst.GPUDevicePath == "" {
continue
}
if inst.HypervisorPID != nil && instances.HypervisorProcessIdentityExists(*inst.HypervisorPID, inst.HypervisorStartTime, inst.HypervisorBootID, inst.SocketPath) {
protected[inst.GPUDevicePath] = struct{}{}
continue
Comment thread
cursor[bot] marked this conversation as resolved.
}
if inst.GPUAssignedAt == nil {
continue
}
remaining := instances.VGPUAssignmentStartupGracePeriod - time.Since(*inst.GPUAssignedAt)
if remaining <= 0 {
continue
Comment thread
cursor[bot] marked this conversation as resolved.
}
protected[inst.GPUDevicePath] = struct{}{}
if retryAfter == 0 || remaining < retryAfter {
retryAfter = remaining
}
}
return protected, retryAfter, nil
}
Comment thread
cursor[bot] marked this conversation as resolved.

func reconcileVGPUs(ctx context.Context, instanceManager instances.Manager, logger *slog.Logger) {
protected, retryAfter, err := liveInstanceVGPUDevicePaths(ctx, instanceManager)
if err != nil {
// Operator-actionable: vendor VFIO reconciliation stays disabled
// host-wide (and releases fail closed on the same inventory) until
// the unreadable instance metadata is repaired.
logger.Error("failed to list instances for vGPU reconcile protection; reconciling mdev only", "error", err)
protected = nil
retryAfter = 0
}
Comment thread
cursor[bot] marked this conversation as resolved.
if err := devices.ReconcileVGPUs(ctx, protected); err != nil {
logger.Warn("failed to reconcile vGPU devices", "error", err)
}
if retryAfter <= 0 {
return
}
go func() {
timer := time.NewTimer(retryAfter)
defer timer.Stop()
select {
case <-ctx.Done():
case <-timer.C:
reconcileVGPUs(ctx, instanceManager, logger)
}
}()
}

func run() error {
startupStarted := time.Now()
slog.Info("starting hypeman initialization")
Expand Down Expand Up @@ -389,12 +446,9 @@ func run() error {
return fmt.Errorf("reconcile device state: %w", err)
}

// Reconcile mdev devices (clears orphaned vGPUs from previous runs)
logger.Info("Reconciling mdev devices...")
if err := devices.ReconcileMdevs(app.Ctx, nil); err != nil {
// Log but don't fail - mdev cleanup is best-effort
logger.Warn("failed to reconcile mdev devices", "error", err)
}
// Reconcile vGPU devices (clears orphaned vGPUs from previous runs)
logger.Info("Reconciling vGPU devices...")
reconcileVGPUs(ctx, app.InstanceManager, logger)

// Wire up resource validator for aggregate limit checking
// This enables the instance manager to validate CPU, memory, network, and GPU
Expand Down
38 changes: 38 additions & 0 deletions cmd/api/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,18 @@ package main

import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"net/url"
"os/exec"
"testing"
"time"

"github.com/getkin/kin-openapi/openapi3filter"
"github.com/go-chi/chi/v5"
"github.com/golang-jwt/jwt/v5"
"github.com/kernel/hypeman/lib/instances"
mw "github.com/kernel/hypeman/lib/middleware"
"github.com/kernel/hypeman/lib/oapi"
nethttpmiddleware "github.com/oapi-codegen/nethttp-middleware"
Expand Down Expand Up @@ -338,3 +341,38 @@ func TestImageNameWithSlashes_URLEncoding(t *testing.T) {
})
}
}

type vgpuReconcileManagerStub struct {
instances.Manager
list []instances.Instance
}

func (s vgpuReconcileManagerStub) ListInstancesForReconcile(context.Context) ([]instances.Instance, error) {
return s.list, nil
}

func TestLiveInstanceVGPUDevicePathsBoundsStartupProtection(t *testing.T) {
dead := exec.Command("true")
require.NoError(t, dead.Run())
deadPID := dead.Process.Pid
recent := time.Now().Add(-time.Minute)
stale := time.Now().Add(-instances.VGPUAssignmentStartupGracePeriod - time.Minute)

manager := vgpuReconcileManagerStub{list: []instances.Instance{
{StoredMetadata: instances.StoredMetadata{Id: "booting", GPUDevicePath: "/sys/bus/pci/devices/0000:82:00.4", GPUAssignedAt: &recent}},
{StoredMetadata: instances.StoredMetadata{Id: "orphaned", GPUDevicePath: "/sys/bus/pci/devices/0000:82:00.5", GPUAssignedAt: &stale}},
{StoredMetadata: instances.StoredMetadata{Id: "legacy", GPUDevicePath: "/sys/bus/pci/devices/0000:82:00.6"}},
{StoredMetadata: instances.StoredMetadata{Id: "dead", GPUDevicePath: "/sys/bus/pci/devices/0000:82:00.7", HypervisorPID: &deadPID}},
{StoredMetadata: instances.StoredMetadata{Id: "stale-pid-booting", GPUDevicePath: "/sys/bus/pci/devices/0000:82:00.8", HypervisorPID: &deadPID, GPUAssignedAt: &recent}},
}}

protected, retryAfter, err := liveInstanceVGPUDevicePaths(context.Background(), manager)
require.NoError(t, err)
require.Positive(t, retryAfter)
require.LessOrEqual(t, retryAfter, instances.VGPUAssignmentStartupGracePeriod)
assert.Contains(t, protected, "/sys/bus/pci/devices/0000:82:00.4")
assert.NotContains(t, protected, "/sys/bus/pci/devices/0000:82:00.5")
assert.NotContains(t, protected, "/sys/bus/pci/devices/0000:82:00.6")
assert.NotContains(t, protected, "/sys/bus/pci/devices/0000:82:00.7")
assert.Contains(t, protected, "/sys/bus/pci/devices/0000:82:00.8")
}
5 changes: 0 additions & 5 deletions integration/vgpu_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -324,11 +324,6 @@ func checkVGPUTestPrerequisites() (string, string) {
if framework == devices.VGPUFrameworkNone {
return "vGPU test requires SR-IOV VFs with an mdev or vendor VFIO vGPU framework", ""
}
if framework == devices.VGPUFrameworkVendorVFIO {
// CreateVGPU rejects vendor VFIO until the instance lifecycle
// integration lands.
return "vGPU test requires the vendor VFIO instance lifecycle integration", ""
}

// Check for available profiles
profiles, err := devices.ListGPUProfiles()
Expand Down
4 changes: 4 additions & 0 deletions lib/builds/manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@ func (m *mockInstanceManager) ListInstances(ctx context.Context, filter *instanc
return result, nil
}

func (m *mockInstanceManager) ListInstancesForReconcile(ctx context.Context) ([]instances.Instance, error) {
return m.ListInstances(ctx, nil)
}

func (m *mockInstanceManager) ListSnapshots(ctx context.Context, filter *instances.ListSnapshotsFilter) ([]instances.Snapshot, error) {
return nil, nil
}
Expand Down
5 changes: 1 addition & 4 deletions lib/devices/vgpu_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,7 @@ func CreateVGPU(ctx context.Context, profileName, instanceID string) (*VGPUDevic
MdevUUID: mdev.UUID,
}, nil
case VGPUFrameworkVendorVFIO:
// The instance lifecycle does not yet persist vendor VFIO assignments
// durably or guard their release against live claims, so keep the
// backend out of the create path until that integration lands.
return nil, fmt.Errorf("vendor VFIO vGPU support is not yet integrated with the instance lifecycle")
return hostVendorVFIO.create(ctx, profileName, instanceID)
default:
return nil, fmt.Errorf("vGPU framework not available")
}
Expand Down
Loading
Loading