Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
b1374e4
Delete forks that a restart interrupted
yummybomb Nov 11, 2026
f7b5f7d
Only delete a pending fork once the process making it is gone
yummybomb Nov 12, 2026
dc6ce27
Delete a failed running fork at once and recover interrupted forks in…
yummybomb Nov 13, 2026
b582b1c
Keep a finished compression job from restoring a fork's pending mark
yummybomb Nov 13, 2026
5c7f25a
Merge remote-tracking branch 'origin/main' into hypeship/recover-inte…
yummybomb Nov 13, 2026
95fc3c5
Delete a running fork from one place when its source does not come back
yummybomb Nov 13, 2026
bfee62a
Do not restart standby compression for a fork that is still pending
yummybomb Nov 13, 2026
28da785
Do not delete by a pending mark that came with a copied directory
yummybomb Nov 15, 2026
b1bb0cc
Sync a fork's cleared mark to disk before its request succeeds
yummybomb Nov 15, 2026
df92f24
Read a fork's mark again once its owner is known to be gone
yummybomb Nov 15, 2026
2b3b51c
Mark a fork pending again when clearing its mark cannot be synced
yummybomb Nov 15, 2026
6f0bc71
Protect fork recovery from stale writers and inherited state
yummybomb Nov 18, 2026
ca207d1
Replace a dangling snapshot source alias left by a killed restore
yummybomb Nov 20, 2026
c2597cc
Recover a parked fork source whose link dangles
yummybomb Nov 20, 2026
0857a2d
Sync a fork's cleared mark without holding the alias lock
yummybomb Nov 20, 2026
24ecebb
Delete a failed fork even when its request was cancelled
yummybomb Nov 20, 2026
51fea64
Count interrupted forks found at startup
yummybomb Nov 20, 2026
1b5e91a
Verify guest identity and keep interrupted fork cleanup retryable
yummybomb Nov 20, 2026
b22efa8
Delete an interrupted fork even when its TAP cannot be released
yummybomb Nov 23, 2026
74cb091
Free a passthrough device when a delete cannot release it
yummybomb Nov 23, 2026
eba917e
Skip guest shutdown when recovering a fork without a passthrough device
yummybomb Nov 23, 2026
af5d44e
Stop shadowing syncDir and exporting a reassignable ServerConfig
yummybomb Nov 23, 2026
4a2aca6
Keep a partial fork copy from failing vGPU claims and reconciles
yummybomb Nov 23, 2026
52e360f
Start the API when a parked fork source cannot be recovered
yummybomb Nov 23, 2026
2063699
Refuse to start or restore a fork that is waiting to be deleted
yummybomb Nov 23, 2026
cd62612
Guard pending fork transitions and verify cleanup ownership
yummybomb Nov 23, 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
1 change: 1 addition & 0 deletions DEVELOPMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,7 @@ The server will start on port 4973 (configurable via `port` in config.yaml).
### Shared-Machine Local Config

When developing on a shared host, avoid global paths like `/etc/hypeman` and `/var/lib/hypeman`.
Only one API process can use a data directory at a time. Stop the old process before upgrading or downgrading; older versions do not take the directory lock.
Use a workspace-local config and data directory instead:

```bash
Expand Down
28 changes: 28 additions & 0 deletions cmd/api/data_dir_lock.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package main

import (
"errors"
"fmt"
"os"
"syscall"
)

// Instance metadata locks are process-local. Hold the directory inode locked
// until shutdown, before any startup scan can read and write instance records.
func lockDataDir(path string) (*os.File, error) {
if err := os.MkdirAll(path, 0755); err != nil {
return nil, err
}
dir, err := os.Open(path)
if err != nil {
return nil, err
}
if err := syscall.Flock(int(dir.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
dir.Close()
if errors.Is(err, syscall.EWOULDBLOCK) {
return nil, fmt.Errorf("another Hypeman process is using this directory: %w", err)
}
return nil, err
}
return dir, nil
}
41 changes: 41 additions & 0 deletions cmd/api/data_dir_lock_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package main

import (
"os"
"os/exec"
"path/filepath"
"syscall"
"testing"

"github.com/stretchr/testify/require"
)

func TestServerRefusesSecondWriterBeforeStartup(t *testing.T) {
const subprocess = "HYPEMAN_TEST_LOCKED_STARTUP"
if os.Getenv(subprocess) == "1" {
require.ErrorIs(t, run(), syscall.EWOULDBLOCK)
return
}

path := filepath.Join(t.TempDir(), "data")
owner, err := lockDataDir(path)
require.NoError(t, err)
t.Cleanup(func() { owner.Close() })

alias := filepath.Join(t.TempDir(), "same-data")
require.NoError(t, os.Symlink(path, alias))
cfg := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(cfg, []byte("data_dir: "+alias+"\njwt_secret: local-test-secret-for-data-dir-lock\n"), 0600))
cmd := exec.CommandContext(t.Context(), os.Args[0], "-test.run=^TestServerRefusesSecondWriterBeforeStartup$")
cmd.Env = append(os.Environ(), subprocess+"=1", "CONFIG_PATH="+cfg, "DATA_DIR="+alias)
out, err := cmd.CombinedOutput()
require.NoError(t, err, "%s", out)
entries, err := os.ReadDir(path)
require.NoError(t, err)
require.Empty(t, entries, "the second API must not initialize or recover anything")

require.NoError(t, owner.Close())
next, err := lockDataDir(alias)
require.NoError(t, err)
require.NoError(t, next.Close())
}
30 changes: 21 additions & 9 deletions cmd/api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import (
"github.com/kernel/hypeman/lib/ocicachegc"
"github.com/kernel/hypeman/lib/otel"
"github.com/kernel/hypeman/lib/paths"
"github.com/kernel/hypeman/lib/providers"
"github.com/kernel/hypeman/lib/registry"
"github.com/kernel/hypeman/lib/scopes"
"github.com/kernel/hypeman/lib/tokenrevocation"
Expand Down Expand Up @@ -164,17 +165,19 @@ func run() error {
startupStarted := time.Now()
slog.Info("starting hypeman initialization")

// Load config early for OTel initialization
// Config path can be specified via CONFIG_PATH env var or defaults to platform-specific locations
configPath := os.Getenv("CONFIG_PATH")
cfg, err := config.Load(configPath)
cfg, err := providers.ServerConfig()
if err != nil {
return fmt.Errorf("failed to load config: %w", err)
return err
}

// Validate configuration before proceeding
if err := cfg.Validate(); err != nil {
return fmt.Errorf("invalid configuration: %w", err)
dataDir, err := lockDataDir(cfg.DataDir)
if err != nil {
return fmt.Errorf("lock data directory %q: %w", cfg.DataDir, err)
}
defer dataDir.Close()
// A source that cannot be put back is left as it is and never resolves
// to another guest, so the rest of the host starts without it.
if err := instances.RecoverParkedForkSources(paths.New(cfg.DataDir)); err != nil {
slog.Error("failed to recover parked fork sources; they are left as they are until repaired", "error", err)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Parked backups listed as unknown guests

Medium Severity

Startup now continues when RecoverParkedForkSources cannot put a source back, so *.fork-bak.* directories stay on disk while the API serves. walkMetadataFiles treats those backups as guests, and ListInstances reports each as Unknown because loadMetadata rejects the ID mismatch. Exact lookup maps that same mismatch to 404, so the ghosts appear in the list but cannot be fetched or deleted through the API.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 2063699. Configure here.

}

// Configure GPU profile cache TTL
Expand Down Expand Up @@ -365,6 +368,15 @@ func run() error {
return fmt.Errorf("reconcile device state: %w", err)
}

// A fork that a crash cut short still holds its VMM, memory and vGPU.
// Delete those before the vGPU reconciler counts their claims.
logger.Info("Recovering interrupted forks...")
if r, ok := app.InstanceManager.(interface{ RecoverInterruptedForks(context.Context) }); ok {
r.RecoverInterruptedForks(app.Ctx)
} else {
logger.Warn("instance manager does not implement RecoverInterruptedForks")
}

logger.Info("Reconciling vGPU devices...")
if r, ok := app.InstanceManager.(interface{ StartVGPUReconciler(context.Context) }); ok {
r.StartVGPUReconciler(ctx)
Expand Down
133 changes: 93 additions & 40 deletions lib/devices/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package devices
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"runtime"
Expand Down Expand Up @@ -65,6 +66,12 @@ type Manager interface {
// MarkDetached marks a device as detached from an instance
MarkDetached(ctx context.Context, deviceID string) error

// ReleaseInstanceDevice detaches and unbinds a passthrough device only if this instance owns it.
ReleaseInstanceDevice(ctx context.Context, deviceID, instanceID string) error

// DetachInstanceDevice clears the attachment without unbinding, only if this instance owns it.
DetachInstanceDevice(ctx context.Context, deviceID, instanceID string) error

// ReconcileDevices cleans up stale device state on startup.
// It detects devices with AttachedTo referencing non-existent instances
// and clears the orphaned attachment state.
Expand All @@ -75,9 +82,21 @@ type Manager interface {
SetLivenessChecker(checker InstanceLivenessChecker)
}

type deviceBinder interface {
deviceBoundToVFIO(string) (bool, error)
IsDeviceBoundToVFIO(string) bool
BindToVFIO(string) error
UnbindFromVFIO(string) error
CheckIOMMUGroupSafe(string, []string) error
unbindFromDriver(string, string) error
setDriverOverride(string, string) error
triggerDriverProbe(string) error
startNvidiaPersistenced() error
}

type manager struct {
paths *paths.Paths
vfioBinder *VFIOBinder
vfioBinder deviceBinder
livenessChecker InstanceLivenessChecker
mu sync.RWMutex
}
Expand Down Expand Up @@ -322,8 +341,6 @@ func (m *manager) BindToVFIO(ctx context.Context, id string) error {
}

func (m *manager) UnbindFromVFIO(ctx context.Context, id string) error {
log := logger.FromContext(ctx)

m.mu.Lock()
defer m.mu.Unlock()

Expand All @@ -341,8 +358,8 @@ func (m *manager) UnbindFromVFIO(ctx context.Context, id string) error {
return ErrInUse
}

// Unbind from VFIO
if err := m.vfioBinder.UnbindFromVFIO(device.PCIAddress); err != nil {
log := logger.FromContext(ctx)
if err := m.unbindAndVerify(device.PCIAddress); err != nil {
return err
}

Expand Down Expand Up @@ -397,11 +414,68 @@ func (m *manager) MarkDetached(ctx context.Context, deviceID string) error {
return m.saveDevice(device)
}

// The driver probe can bind the device straight back to vfio-pci. Check
// sysfs before recording the release or dropping the owner that can retry it.
func (m *manager) unbindAndVerify(pciAddress string) error {
if err := m.vfioBinder.UnbindFromVFIO(pciAddress); err != nil {
return err
}
bound, err := m.vfioBinder.deviceBoundToVFIO(pciAddress)
if err != nil {
return fmt.Errorf("verify VFIO release of %s: %w", pciAddress, err)
}
if bound {
return fmt.Errorf("device %s is still bound to vfio-pci", pciAddress)
}
return nil
}

// ReleaseInstanceDevice checks the recorded owner under the same lock as the unbind.
// A fork's device list can name a passthrough device still owned by its source.
func (m *manager) ReleaseInstanceDevice(ctx context.Context, deviceID, instanceID string) error {
m.mu.Lock()
defer m.mu.Unlock()
device, err := m.loadDevice(deviceID)
if err != nil {
return err
}
if device.AttachedTo == nil || *device.AttachedTo != instanceID {
return nil
}
// A retry after the unbind but before the save sees ErrNotBound.
if err := m.unbindAndVerify(device.PCIAddress); err != nil && !errors.Is(err, ErrNotBound) {
return err
}
device.AttachedTo = nil
device.BoundToVFIO = false
return m.saveDevice(device)
}

// DetachInstanceDevice frees a device whose owner is being deleted after its
// release failed. Nothing retries a release once the owner is gone, and
// nothing but a restart clears an attachment to a missing instance.
func (m *manager) DetachInstanceDevice(ctx context.Context, deviceID, instanceID string) error {
m.mu.Lock()
defer m.mu.Unlock()
device, err := m.loadDevice(deviceID)
if err != nil {
return err
}
if device.AttachedTo == nil || *device.AttachedTo != instanceID {
return nil
}
device.AttachedTo = nil
// The failed release may or may not have unbound the device, and the next
// attach binds it only if this says it is unbound.
device.BoundToVFIO = m.vfioBinder.IsDeviceBoundToVFIO(device.PCIAddress)
return m.saveDevice(device)
}

// ReconcileDevices cleans up stale device state on startup.
// It performs safe-by-default reconciliation:
// 1. Detects orphaned device attachments (instance missing or not running)
// 2. Clears orphaned AttachedTo metadata
// 3. Runs GPU-reset-lite for orphaned devices (unbind VFIO, clear override, probe driver)
// 2. Runs GPU-reset-lite for orphaned devices (unbind VFIO, clear override, probe driver)
// 3. Clears the attachment once the device is no longer bound to VFIO
// 4. Logs mismatches between instance→device and device→instance references
// 5. Detects suspicious cloud-hypervisor processes
func (m *manager) ReconcileDevices(ctx context.Context) error {
Expand Down Expand Up @@ -471,19 +545,6 @@ func (m *manager) ReconcileDevices(ctx context.Context) error {
"orphaned_instance_id", instanceID,
)

// Clear the orphaned attachment
device.AttachedTo = nil
if err := m.saveDevice(device); err != nil {
log.ErrorContext(ctx, "failed to save device after clearing attachment",
"device_id", device.Id,
"error", err,
)
stats.errors++
continue
}
stats.orphanedCleared++

// Run GPU-reset-lite for orphaned device
m.resetOrphanedDevice(ctx, device, &stats)
}
}
Expand Down Expand Up @@ -695,30 +756,22 @@ func (m *manager) resetOrphanedDevice(ctx context.Context, device *Device, stats
}

// Verify the device is now unbound from VFIO
stillBoundToVFIO := m.vfioBinder.IsDeviceBoundToVFIO(device.PCIAddress)
if stillBoundToVFIO {
log.WarnContext(ctx, "device still bound to VFIO after reset-lite",
"device_id", device.Id,
"pci_address", device.PCIAddress,
)
bound, err := m.vfioBinder.deviceBoundToVFIO(device.PCIAddress)
if err != nil || bound {
log.WarnContext(ctx, "cannot confirm device was unbound after reset-lite; keeping attachment",
"device_id", device.Id, "pci_address", device.PCIAddress, "bound_to_vfio", bound, "error", err)
stats.resetFailed++
} else {
log.InfoContext(ctx, "GPU-reset-lite completed for orphaned device",
"device_id", device.Id,
"device_name", device.Name,
"pci_address", device.PCIAddress,
)
stats.resetSucceeded++
return
}

// Update device metadata to reflect new VFIO state
device.BoundToVFIO = stillBoundToVFIO
stats.resetSucceeded++
device.AttachedTo = nil
device.BoundToVFIO = false
if err := m.saveDevice(device); err != nil {
log.WarnContext(ctx, "failed to save device after reset-lite",
"device_id", device.Id,
"error", err,
)
log.WarnContext(ctx, "failed to save device after reset-lite", "device_id", device.Id, "error", err)
stats.errors++
return
}
stats.orphanedCleared++
}

// Helper methods
Expand Down
Loading
Loading