handoff

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 19 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package handoff implements graceful binary upgrades for CUDA processes, combining listener file-descriptor inheritance with CUDA Virtual Memory Management (VMM) POSIX file-descriptor slab handoff.

An Upgrader coordinates a parent process and its replacement child over an anonymous AF_UNIX control socketpair inherited across exec (or an optional 0600-permissioned Unix domain socket). On Upgrader.Upgrade, the parent transfers a JSON Manifest together with duplicated listener FDs and VMM POSIX_FD handles via SCM_RIGHTS.

The child adopts every listener and slab before signaling Upgrader.Ready. Adoption is fail-closed: a virtual-address collision under RequireSameVA, a device UUID or granularity mismatch, an FD count mismatch, or a corrupt manifest causes the child to unmap and release all partial state, report the error to the parent, and exit non-zero while the parent continues serving without interruption.

Basic usage:

u, err := handoff.New(handoff.Options{})
if err != nil {
	log.Fatal(err)
}
defer u.Close()

ln, err := u.Listen("tcp", "127.0.0.1:8080")
if err != nil {
	log.Fatal(err)
}
if err := u.Ready(); err != nil {
	log.Fatal(err)
}
// Serve on ln until <-u.Exit().

This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/cuda/handoff"
)

func main() {
	u, err := handoff.New(handoff.Options{RunID: "example-run"})
	if err != nil {
		panic(err)
	}
	defer u.Close()

	ln, err := u.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		panic(err)
	}
	defer ln.Close()

	if err := u.Ready(); err != nil {
		panic(err)
	}
	fmt.Printf("child=%v gen=%d run=%s\n", u.IsChild(), u.GenerationID(), u.RunID())
}
Output:
child=false gen=0 run=example-run

Index

Examples

Constants

View Source
const (
	// ManifestVersion is the wire format version of [Manifest].
	ManifestVersion = 1

	// EnvControlFD is the environment variable carrying the inherited control
	// socket file descriptor number from parent to child.
	EnvControlFD = "CUDA_HANDOFF_FD"

	// EnvParentPID is the environment variable carrying the parent process ID
	// expected by the child during handoff adoption.
	EnvParentPID = "CUDA_HANDOFF_PPID"
)

Variables

View Source
var (
	// ErrVACollision reports that a [RequireSameVA] slab could not be reserved
	// at its original virtual address.
	ErrVACollision = errors.New("handoff: virtual address collision")

	// ErrDeviceMismatch reports that the target device ordinal or UUID does not
	// match the handoff manifest.
	ErrDeviceMismatch = errors.New("handoff: device mismatch")

	// ErrGranularityMismatch reports that a slab's size or granularity does not
	// match the target device's VMM granularity.
	ErrGranularityMismatch = errors.New("handoff: granularity mismatch")

	// ErrFDCountMismatch reports that the number of file descriptors received
	// via SCM_RIGHTS does not match the manifest.
	ErrFDCountMismatch = errors.New("handoff: fd count mismatch")

	// ErrInvalidManifest reports a corrupt, unsupported, or invalid manifest.
	ErrInvalidManifest = errors.New("handoff: invalid manifest")

	// ErrUpgradeInProgress reports that [Upgrader.Upgrade] is already running.
	ErrUpgradeInProgress = errors.New("handoff: upgrade already in progress")

	// ErrClosed reports an operation on a closed [Upgrader].
	ErrClosed = errors.New("handoff: upgrader closed")

	// ErrAlreadyReady reports that [Upgrader.Ready] was called more than once.
	ErrAlreadyReady = errors.New("handoff: already ready")

	// ErrChildExited reports that the child process exited before signaling ready.
	ErrChildExited = errors.New("handoff: child exited before ready")
)

Functions

This section is empty.

Types

type ListenerSpec

type ListenerSpec struct {
	Name    string `json:"name"`
	Network string `json:"network"`
	Addr    string `json:"addr"`
	FD      int    `json:"-"`
}

ListenerSpec describes a network listener handed off to a child process.

type Manifest

type Manifest struct {
	Version      int            `json:"version"`
	RunID        string         `json:"run_id"`
	GenerationID uint64         `json:"generation_id"`
	ParentPID    int            `json:"parent_pid"`
	Listeners    []ListenerSpec `json:"listeners,omitempty"`
	Slabs        []SlabSpec     `json:"slabs,omitempty"`
}

Manifest is the JSON wire payload transferred alongside SCM_RIGHTS FDs.

type MappedSlab

type MappedSlab struct {
	Name          string
	DeviceOrdinal int
	DeviceUUID    string
	BaseVA        uint64
	RequestedVA   uint64
	Size          uint64
	Granularity   uint64
	Mode          SlabMode
	Access        SlabAccess
	SHA256        string
	FD            int
	// contains filtered or unexported fields
}

MappedSlab represents a VMM slab adopted and mapped by a child process. Call MappedSlab.Close when finished to unmap the VA range, free the VA reservation, and close the duplicated POSIX FD.

func (*MappedSlab) Close

func (s *MappedSlab) Close() error

Close unmaps the slab, frees its VA reservation, and closes its duplicated POSIX FD. Close is safe to call multiple times.

type Options

type Options struct {
	// UpgradeTimeout bounds how long [Upgrader.Upgrade] waits for the child
	// process to signal [Upgrader.Ready]. Defaults to 30s when <= 0.
	UpgradeTimeout time.Duration

	// ExecPath is the binary executed on [Upgrader.Upgrade]. Defaults to
	// [os.Executable] when empty.
	ExecPath string

	// Args are the command-line arguments passed to the child process
	// (excluding argv[0]). Defaults to os.Args[1:] when nil.
	Args []string

	// Env is the environment passed to the child process. Defaults to
	// [os.Environ] when nil. Handoff control variables are always stamped.
	Env []string

	// RunID identifies a logical server instance across upgrade generations.
	// Generated randomly on a fresh parent if empty.
	RunID string

	// VMM provides CUDA Virtual Memory Management operations. Defaults to
	// [DefaultVMM] when nil.
	VMM VMM

	// ControlFD optionally overrides [EnvControlFD] when > 0, allowing
	// in-process socketpair handoff without exec.
	ControlFD int

	// ExpectedParentPID optionally overrides [EnvParentPID] when ControlFD > 0.
	// When 0 and ControlFD > 0, parent PID verification is skipped.
	ExpectedParentPID int

	// ControlSocketPath optionally binds an AF_UNIX listener with 0600
	// permissions. When empty (the default), Upgrade uses an anonymous
	// socketpair inherited across exec.
	ControlSocketPath string
}

Options configures an Upgrader.

type SlabAccess

type SlabAccess int

SlabAccess controls the GPU page protection applied to a mapped VMM slab.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/cuda/handoff"
)

func main() {
	fmt.Println(handoff.AccessReadOnly, handoff.AccessReadWrite)
}
Output:
read_only read_write
const (
	// AccessReadOnly maps the slab with PROT_READ only (default for weight slabs).
	AccessReadOnly SlabAccess = iota

	// AccessReadWrite maps the slab with PROT_READ|PROT_WRITE (for KV-cache pools).
	AccessReadWrite
)

func (SlabAccess) MarshalJSON

func (a SlabAccess) MarshalJSON() ([]byte, error)

MarshalJSON encodes a as its canonical string name.

func (SlabAccess) String

func (a SlabAccess) String() string

String returns the canonical name of a.

func (*SlabAccess) UnmarshalJSON

func (a *SlabAccess) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes a from its canonical string name.

type SlabMode

type SlabMode int

SlabMode controls whether a VMM slab must map at its original virtual address.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/cuda/handoff"
)

func main() {
	fmt.Println(handoff.RequireSameVA, handoff.AllowRelocate)
}
Output:
require_same_va allow_relocate
const (
	// RequireSameVA requires the child to reserve the exact BaseVA from the
	// parent. If the driver cannot satisfy the reservation, adoption fails closed.
	RequireSameVA SlabMode = iota

	// AllowRelocate treats BaseVA as a hint and accepts a different virtual
	// address if the original range is occupied.
	AllowRelocate
)

func (SlabMode) MarshalJSON

func (m SlabMode) MarshalJSON() ([]byte, error)

MarshalJSON encodes m as its canonical string name.

func (SlabMode) String

func (m SlabMode) String() string

String returns the canonical name of m.

func (*SlabMode) UnmarshalJSON

func (m *SlabMode) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes m from its canonical string name.

type SlabSpec

type SlabSpec struct {
	Name          string     `json:"name"`
	DeviceOrdinal int        `json:"device_ordinal"`
	DeviceUUID    string     `json:"device_uuid"`
	BaseVA        uint64     `json:"base_va"`
	Size          uint64     `json:"size"`
	Granularity   uint64     `json:"granularity"`
	Mode          SlabMode   `json:"mode"`
	Access        SlabAccess `json:"access"`
	SHA256        string     `json:"sha256,omitempty"`
	FD            int        `json:"-"`
}

SlabSpec describes a resident CUDA VMM memory slab to hand off to a child.

type Upgrader

type Upgrader struct {
	// contains filtered or unexported fields
}

Upgrader manages listener and CUDA VMM slab handoff across graceful binary upgrades.

func New

func New(opts Options) (*Upgrader, error)

New creates an Upgrader. If the process was spawned by a parent's Upgrader.Upgrade (detected via EnvControlFD or Options.ControlFD), New receives the manifest and SCM_RIGHTS FDs, validates every listener and VMM slab, and maps all slabs before returning.

If any adoption step fails, New rolls back all partial mappings and closes all received FDs, sends the error to the parent, and returns a non-nil error.

func (*Upgrader) AdoptedSlab

func (u *Upgrader) AdoptedSlab(name string) (*MappedSlab, bool)

AdoptedSlab returns the mapped VMM slab adopted during New under name.

func (*Upgrader) Close

func (u *Upgrader) Close() error

Close releases all resources owned by the Upgrader, including duplicated slab export FDs, unclaimed adopted listeners, and any unclosed adopted slabs.

func (*Upgrader) Exit

func (u *Upgrader) Exit() <-chan struct{}

Exit returns a channel that is closed when a replacement child signals Upgrader.Ready or when Upgrader.Stop / Upgrader.Close is called.

func (*Upgrader) GenerationID

func (u *Upgrader) GenerationID() uint64

GenerationID returns the zero-based upgrade generation (0 for a fresh parent).

func (*Upgrader) IsChild

func (u *Upgrader) IsChild() bool

IsChild reports whether this Upgrader adopted state from a parent process.

func (*Upgrader) Listen

func (u *Upgrader) Listen(network, addr string) (net.Listener, error)

Listen returns a handed-off listener matching (network, addr) if one was adopted from the parent, or binds a fresh listener otherwise. The returned listener is automatically registered for subsequent upgrades.

func (*Upgrader) Ready

func (u *Upgrader) Ready() error

Ready signals the parent process that this child has adopted all listeners and VMM slabs and passed startup/parity checks. Calling Ready on a fresh parent is a no-op.

func (*Upgrader) RegisterSlab

func (u *Upgrader) RegisterSlab(spec SlabSpec, exportFD int) error

RegisterSlab registers a resident VMM slab and its exported POSIX FD to be handed off during Upgrader.Upgrade. The Upgrader duplicates exportFD with FD_CLOEXEC so the caller retains independent ownership of exportFD.

func (*Upgrader) RunID

func (u *Upgrader) RunID() string

RunID returns the stable identifier for this server across generations.

func (*Upgrader) Stop

func (u *Upgrader) Stop()

Stop signals the process to stop accepting new work and drain.

func (*Upgrader) Upgrade

func (u *Upgrader) Upgrade(ctx context.Context) error

Upgrade spawns a replacement child binary, transfers the manifest, listener FDs, and VMM POSIX_FD handles via SCM_RIGHTS, and waits for the child to call Upgrader.Ready.

On success, Upgrade closes Upgrader.Exit and returns nil. If the child fails validation, crashes, or exceeds UpgradeTimeout/ctx before Ready, Upgrade aborts cleanly and returns an error while leaving this parent live and able to retry later.

type VMM

type VMM interface {
	DeviceUUID(deviceOrdinal int) (string, error)
	Granularity(deviceOrdinal int) (uint64, error)
	ImportPOSIXFD(fd int) (uint64, error)
	AddressReserve(size, alignment, requestedBaseVA uint64) (uint64, error)
	Map(va, size, handle uint64) error
	SetAccess(va, size uint64, deviceOrdinal int, access SlabAccess) error
	Unmap(va, size uint64) error
	AddressFree(va, size uint64) error
	ReleaseHandle(handle uint64) error
}

VMM abstracts the CUDA Virtual Memory Management driver operations required to import, reserve, map, protect, and release GPU memory slabs.

func DefaultVMM

func DefaultVMM() VMM

DefaultVMM returns a VMM backed by the Linux CUDA driver API via purego.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL