Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
8a854eb
Guard vGPU releases with live-instance claims
yummybomb Aug 6, 2026
d2ae015
Reconcile vendor VFIO vGPUs against a fail-closed instance inventory
yummybomb Aug 6, 2026
9379628
Fail closed on vGPU claim checks
yummybomb Aug 6, 2026
aeb99a0
Retain only vGPU assignment after failed create
yummybomb Aug 6, 2026
3b09a37
Clear released vGPU assignment on start rollback
yummybomb Aug 6, 2026
cbedc27
Test start rollback vGPU cleanup
yummybomb Aug 6, 2026
d6f7b3d
Normalize legacy mdev paths in live-claim check
yummybomb Aug 7, 2026
c32f71f
Bind the live-claimant test socket under /tmp for macOS
yummybomb Aug 7, 2026
15171c2
Surface retained vGPU cleanup through a typed create error and manage…
yummybomb Aug 7, 2026
f16711c
Generalize the create vGPU error text
yummybomb Aug 7, 2026
e03c74d
Scope vGPU claim scan to vendor VFIO and close reconcile gaps
yummybomb Aug 8, 2026
6e626e1
Harden the vendor VFIO release path
yummybomb Aug 9, 2026
d1e5d19
Fail closed on retained vGPU cleanup
yummybomb Aug 9, 2026
e25ce92
Report surviving vGPU retention metadata
yummybomb Aug 9, 2026
90c15f1
Return accurate vGPU cleanup guidance
yummybomb Aug 9, 2026
620e348
Clarify vGPU retention fallback
yummybomb Aug 9, 2026
8e7520c
Pass hypervisor identity token to vGPU claim check
yummybomb Aug 10, 2026
fe13886
Fail safely on ambiguous vGPU claims
yummybomb Aug 10, 2026
57a8e92
Expose retained vGPU instance IDs
yummybomb Aug 10, 2026
63a69b0
Harden vGPU startup rollback recovery
yummybomb Aug 10, 2026
7750629
Preserve the create failure cause in vGPU cleanup errors
yummybomb Aug 10, 2026
f33a1b7
Fix vGPU reconciliation edge cases
yummybomb Aug 10, 2026
8cb66d9
Use boot-scoped hypervisor identities for vGPUs
yummybomb Aug 10, 2026
be7be4b
Run vGPU rollback tests with QEMU
yummybomb Aug 10, 2026
20a894d
Protect new vGPU assignments from stale PIDs
yummybomb Aug 10, 2026
17308dd
Persist vGPU assignments after create rollback failure
yummybomb Aug 10, 2026
097a694
Preserve vGPU lifecycle compatibility
yummybomb Aug 10, 2026
b1db201
Reconcile vGPU protection from raw metadata and restore GPUAssignedAt
yummybomb Aug 10, 2026
ff89710
Surface pending vGPU cleanup from start as a typed error
yummybomb Aug 11, 2026
5f9752d
Cover retained-stub delete recovery and flag reconcile inventory fail…
yummybomb Aug 11, 2026
fe5637c
Reject vendor VFIO vGPUs on Cloud Hypervisor and improve wedge forensics
yummybomb Aug 11, 2026
22c60f4
Surface retained rollback assignments from start as vgpu_cleanup_pending
yummybomb Aug 11, 2026
641e424
Report retention as persisted when the mid-start save survives
yummybomb Aug 11, 2026
2420211
Leave vGPU hypervisor selection to callers
yummybomb Aug 11, 2026
abe9380
Carry identity fields into the create-pending retention stub
yummybomb Aug 11, 2026
f245009
Grace recent dead-PID claims in the release scan like reconcile does
yummybomb Aug 11, 2026
984038e
Reject start on vGPU retention records
yummybomb Aug 13, 2026
a7b4e39
Make vGPU retention records fully delete-only
yummybomb Aug 13, 2026
86f4459
Adapt vGPU liveness guards to the identity struct resolver
yummybomb Aug 14, 2026
c725413
Deep-copy the phase tracker into the start rollback snapshot
yummybomb Aug 17, 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.HypervisorMayBeAlive(inst.HypervisorProcessIdentity, 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 @@ -384,12 +441,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", HypervisorProcessIdentity: instances.HypervisorProcessIdentity{HypervisorPID: &deadPID}}},
{StoredMetadata: instances.StoredMetadata{Id: "stale-pid-booting", GPUDevicePath: "/sys/bus/pci/devices/0000:82:00.8", HypervisorProcessIdentity: instances.HypervisorProcessIdentity{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