Documentation
¶
Overview ¶
Package httpapi exposes cudahotswap.Service as bounded JSON over HTTP.
New accepts an application service and registries of named native resources. Clients receive opaque lifetime handles, never raw CUDA pointers. The application must keep its resources live until Handler.Close succeeds. Optional StageService endpoints use application-owned StageBinding entries. A caller supplies stage_code, never compiler paths, context schemas or native pointers. RunStage returns only a completion handle; wait releases its owners.
Listen accepts unix:/absolute/socket or tcp:host:port. Use an SSH forward for remote TCP access; this package does not provide authentication or TLS. Subscribe uses /v1/events with a since cursor, as SSE or JSON lines selected by Accept: application/x-ndjson. Client.Events owns the response body and must be closed on disconnect.
This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.
Index ¶
- func Endpoints() map[string]string
- func Listen(address string) (net.Listener, error)
- func NewPromotionAuthorizer(r io.Reader, trustedSHA256, cohort string) (func(context.Context, string) error, error)
- type AdmissionGate
- type Argument
- type Buffer
- type Client
- type EventStream
- type Failure
- type Frame
- type Graph
- type Handler
- type QualifiedStageService
- type Request
- type Resources
- type Response
- type Service
- type StageBinding
- type StageQualification
- type StageService
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Endpoints ¶
Endpoints returns the HTTP endpoint for each exported Service method. Additional endpoints release_pin, wait and close_fixture release owners.
func Listen ¶
Listen listens on unix:/absolute/socket, or tcp:host:port. An empty address selects unix:/var/run/cudahotswap.sock. Existing socket paths are not removed. The embedding application controls directory permissions and shutdown.
func NewPromotionAuthorizer ¶
func NewPromotionAuthorizer(r io.Reader, trustedSHA256, cohort string) (func(context.Context, string) error, error)
NewPromotionAuthorizer uses a retained cudaprof hillclimb JSONL snapshot as an AdmissionGate.Authorize policy. The embedding application must supply the trusted SHA-256 of the complete file from an independent trust source and the cohort it serves. Computing a pin from an untrusted upload does not establish authority. The returned policy retains no reader or file.
The latest row carrying each receipt digest controls that receipt. A refusal with that digest revokes it. A refusal without a receipt digest, such as a Stage 1 failure, cannot identify or revoke an earlier approval.
Example ¶
The pin is supplied by a trusted deployment configuration.
const snapshot = `{"schema":"cudaprof-hillclimb-step/v1","cohort":"sm_121a","kernel":"kernel","stage":1,"promoted":false,"dead_end":"candidate_static_rejected"}` + "\n"
const trustedPin = "sha256:76ba363f36902b5c09ef71dfc0aa041523979a797f94b1193cd81b736beed4d5"
authorize, err := NewPromotionAuthorizer(strings.NewReader(snapshot), trustedPin, "sm_121a")
fmt.Println(err)
fmt.Println(authorize(context.Background(), receipt.DigestBytes([]byte("unapproved receipt"))))
Output: <nil> receipt is not promoted in the pinned snapshot
Types ¶
type AdmissionGate ¶
type AdmissionGate struct {
// Authorize receives the SHA-256 digest of Receipt.MarshalIndent.
Authorize func(context.Context, string) error
// LaunchContract returns the application-owned launch contract for the
// current kernel state. A receipt must describe this exact contract.
LaunchContract func(context.Context, hotswap.State) (receipt.LaunchContract, error)
Static kernelcheck.Checker
// SASS can supply a trusted disassembly by CUBIN digest on hosts without
// a native decoder or nvdisasm. The checker rechecks its instruction bytes.
SASS func(cubinSHA256 string) string
// PTX can supply candidate PTX by CUBIN digest when neither the compiled
// candidate nor the request carries PTX inline.
PTX func(cubinSHA256 string) string
// SyncLaunch optionally customizes the layout.SyncLaunch passed to
// layout.CheckSync when candidate PTX is verified. When nil, Block and
// fixed Grid dimensions are derived from the receipt launch contract.
SyncLaunch func(context.Context, hotswap.State, receipt.LaunchContract) (layout.SyncLaunch, error)
}
AdmissionGate checks uploaded receipt evidence and host static safety before a candidate can load. Authorize must accept only receipt digests obtained from a trusted evidence producer: kernelreceipt/v0 is unsigned.
func (AdmissionGate) Candidate ¶
func (g AdmissionGate) Candidate(ctx context.Context, entry string, evidence []byte) (hotswap.CandidateAdmission, error)
Candidate checks reviewed evidence and returns the admission function for a trusted embedding application to pass to Service.PushWithAdmission.
type Argument ¶
type Argument struct {
Type string `json:"type"`
Name string `json:"name,omitempty"`
Value json.RawMessage `json:"value,omitempty"`
}
Argument is a typed scalar or a named application buffer. Supported scalar types are u32, i32, u64, i64, f32 and f64. Buffer arguments have Type "buffer" and Name, with no Value. Pointer integers are never accepted.
type Buffer ¶
type Buffer struct {
Name string `json:"name"`
Arg int `json:"arg"`
Bytes int `json:"bytes"`
Stable bool `json:"stable"`
}
Buffer describes a fixture buffer by its server registry name and byte extent.
type Client ¶
Client calls the HTTP service. HTTP is the only wire protocol used by the CLI and MCP adapter. A service Failure is returned in Response, not hidden.
func NewClient ¶
NewClient accepts unix:/absolute/socket or tcp:host:port. TCP is plain HTTP; use an SSH forward for remote hosts. The default address is application-owned.
func (*Client) Call ¶
Call round-trips a named endpoint. Non200 statuses return both the structured response and an error. A failed candidate check is a200 with Failure and Push.
Example ¶
h, _ := New(new(fakeService), Resources{})
server := httptest.NewServer(h)
defer server.Close()
client := &Client{URL: server.URL, HTTP: server.Client()}
response, err := client.Call(context.Background(), "status", Request{Name: "kernel"})
fmt.Println(response.State.Generation, response.State.ConfigRevision, err)
Output: 9 7 <nil>
type EventStream ¶
type EventStream struct {
// contains filtered or unexported fields
}
EventStream owns a streaming HTTP body. Close disconnects and releases the server subscription. Read is serial; Close may run concurrently to stop it.
func (*EventStream) Read ¶
func (s *EventStream) Read() (Frame, error)
Read reads one bounded frame, including explicit retention gaps.
type Failure ¶
type Failure struct {
Code string `json:"code,omitempty"`
Message string `json:"message"`
Outcome hotswap.Outcome `json:"outcome"`
Poisoned bool `json:"poisoned,omitempty"`
}
Failure preserves a service failure without turning a failed check into a transport success. Admission refusals use HTTP 422; other non-poisoning service failures use 200.
type Frame ¶
type Frame struct {
Event *hotswap.Event `json:"event,omitempty"`
Result *Response `json:"result,omitempty"`
}
Frame contains one report event, watched push result, or terminal failure.
type Graph ¶
type Graph struct {
Exec *graph.Exec
Node *graph.Node
Stream *cuda.Stream
Grid driver.Dim3
Args []any
}
Graph names an application-owned graph binding. Args and all referenced native allocations must remain live until Handler.Close succeeds.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler owns transport lifetime handles, but not the application's native resources. Close must succeed before the application destroys those resources. It bounds handles to128 and streams to32. A disconnected caller does not release submitted work; opaque handles remain retained for retry or Close.
func (*Handler) Close ¶
Close cancels transport streams, drains completion handles, releases pins, then closes the Service. It waits for in-flight requests to return before releasing owners. Cancellation leaves those requests and owners retained for a later Close; callers must not destroy application resources until it succeeds.
func (*Handler) HasAdmissionGate ¶
HasAdmissionGate reports whether this handler requires admission receipts.
func (*Handler) QualifiedStagesOnly ¶
QualifiedStagesOnly reports whether the handler restricts mutations to registration and push of application-qualified stages.
type QualifiedStageService ¶
type QualifiedStageService interface {
RegisterQualifiedStage(context.Context, string, *stage.Builder, stage.Source, hotswap.StageSpec, string, string, ...hotswap.StageKernelArtifact) (hotswap.State, error)
PushQualifiedStage(context.Context, string, stage.Source, hotswap.StageSpec, string, string, ...hotswap.StageKernelArtifact) (*hotswap.PushResult, error)
}
QualifiedStageService binds stage publication to an exact compiled library.
type Request ¶
type Request struct {
Name string `json:"name,omitempty"`
Label string `json:"label,omitempty"`
Source hotswap.Source `json:"source,omitempty"`
PTX string `json:"ptx,omitempty"`
Receipt json.RawMessage `json:"receipt,omitempty"`
StageCode string `json:"stage_code,omitempty"`
Version uint64 `json:"version,omitempty"`
Flags []string `json:"flags,omitempty"`
Geometry *hotswap.LaunchGeometry `json:"geometry,omitempty"`
Paths *hotswap.WatchPaths `json:"paths,omitempty"`
Checker string `json:"checker,omitempty"`
Fixture string `json:"fixture,omitempty"`
Policy *hotswap.ReplayPolicy `json:"policy,omitempty"`
KeepOnFailure bool `json:"keep_on_failure,omitempty"`
Stream string `json:"stream,omitempty"`
Graph string `json:"graph,omitempty"`
Args []Argument `json:"args,omitempty"`
Buffers []Buffer `json:"buffers,omitempty"`
Outputs []hotswap.FixtureOutput `json:"outputs,omitempty"`
Watch hotswap.WatchConfig `json:"watch,omitempty"`
Handle string `json:"handle,omitempty"`
StageQualification string `json:"stage_qualification,omitempty"`
}
Request is the bounded JSON request shared by endpoints. An endpoint checks required fields before calling its corresponding service method.
type Resources ¶
type Resources struct {
// AdmissionGate requires trusted receipts on push. Nil leaves the
// application's existing admission behavior unchanged.
AdmissionGate *AdmissionGate
// Arguments fixes each kernel's application-declared argument kinds.
// PTX integer storage alone does not prove scalar versus pointer intent.
// Launch and RecordFixture fail closed without this binding.
Arguments map[string][]string
Checkers map[string]hotswap.Checker
Buffers map[string]cuda.Slice[byte]
Streams map[string]*cuda.Stream
Graphs map[string]Graph
// Stages fixes each stage's builder, schema and named launch resources.
// All owners remain live until Handler.Close succeeds.
Stages map[string]StageBinding
// QualifiedStagesOnly serves qualified stage registration and pushes plus
// read-only status endpoints. Every stage must opt into qualifications.
QualifiedStagesOnly bool
// ReplayLimits bounds the replay policy a client requests in set_check,
// record_fixture and record_stage_fixture, since that policy judges the
// client's own pushes. Each tolerance is clamped to at most the limit's,
// Rounds to at least the limit's, and an Exact limit forces exact
// comparison. Nil means cudahotswap.DefaultReplayPolicy.
ReplayLimits *hotswap.ReplayPolicy
// AllowKeepOnFailure honors a client's keep_on_failure. Otherwise it is
// cleared, and a failed application check rolls the push back.
AllowKeepOnFailure bool
}
Resources names objects supplied by the embedding application. Clients cannot supply device addresses, Go functions, streams or graph handles. The handler copies the maps; the application keeps the native owners alive and excludes concurrent buffer writes until Handler.Close succeeds. Checkers implement the application's reference policy; a transport never invents a correctness hook.
type Response ¶
type Response struct {
// RequestLabel identifies the transport request. It never replaces the
// service's State.Label or invents a generation or configuration revision.
RequestLabel string `json:"request_label,omitempty"`
State *hotswap.State `json:"state,omitempty"`
States []hotswap.State `json:"states,omitempty"`
Waiting []hotswap.LockWait `json:"waiting,omitempty"`
Versions []hotswap.Version `json:"versions,omitempty"`
Push *hotswap.PushResult `json:"push,omitempty"`
Paths *hotswap.WatchPaths `json:"paths,omitempty"`
Handle string `json:"handle,omitempty"`
Failure *Failure `json:"failure,omitempty"`
}
Response returns service values and opaque lifetime handles. A nonempty Handle with Failure still owns resources and must be waited or released.
type Service ¶
type Service interface {
Err() error
Register(context.Context, string, hotswap.Source, string) (hotswap.State, error)
Push(context.Context, string, hotswap.Source, string) (*hotswap.PushResult, error)
List() []hotswap.State
Status(string) (hotswap.State, error)
Versions(string) ([]hotswap.Version, error)
Select(context.Context, string, uint64, string) (hotswap.State, error)
Revert(context.Context, string, string) (hotswap.State, error)
SetCompileFlags(string, []string, string) (hotswap.State, error)
SetGeometry(string, *hotswap.LaunchGeometry, string) (hotswap.State, error)
SetCheck(string, hotswap.CheckConfig, string) (hotswap.State, error)
SetWatchPaths(string, *hotswap.WatchPaths, string) (hotswap.State, error)
WatchPaths(string) (*hotswap.WatchPaths, error)
Watch(context.Context, hotswap.WatchConfig, func(string, *hotswap.PushResult, error) error) error
Subscribe(context.Context, uint64) (*hotswap.Subscription, error)
Pin(string) (*hotswap.Pin, error)
Launch(context.Context, string, cuda.Config, ...any) (*hotswap.PendingLaunch, error)
RecordFixture(context.Context, string, hotswap.FixtureConfig) (*hotswap.Fixture, error)
RegisterGraph(context.Context, string, *graph.Exec, *graph.Node, *cuda.Stream, driver.Dim3, ...any) (hotswap.State, error)
LaunchGraph(context.Context, *graph.Exec) (*hotswap.GraphLaunch, error)
Close(context.Context) error
}
Service is the transport's complete service surface. Implementations must preserve the ownership and completion contracts of cudahotswap.Service.
type StageBinding ¶
type StageBinding struct {
Builder *stage.Builder
Schema hotswap.StageSpec
BufferNames []string
Stream string
CUDA bool
Flags []string
// Qualifications, when non-nil, restrict register_stage and push_stage
// to the exact source, library and named function artifacts approved by the application.
// An empty non-nil slice admits neither operation.
Qualifications []StageQualification
}
StageBinding fixes one application-owned stage's compilation and context. Builder, its generation directories and all named owners must remain live until Handler.Close succeeds. BufferNames is in Schema.Buffers order. Stream names an application stream. HostOnly requires no stream or device bindings. CUDA and Flags are fixed by the application, never by the HTTP caller.
Example ¶
// Supply the application's retained Builder before passing this binding
// to New. A host-only C stage has no buffers, functions or CUDA stream.
binding := StageBinding{Schema: hotswap.StageSpec{HostOnly: true}}
fmt.Println(binding.Schema.HostOnly, len(binding.BufferNames), binding.CUDA)
Output: true 0 false
type StageQualification ¶
type StageQualification struct {
// contains filtered or unexported fields
}
StageQualification authorizes one exact source and compile configuration. Its zero value is invalid. The embedding application supplies qualifications from its trusted receipt store.
func QualifyStage ¶
func QualifyStage(source stage.Source, candidate []byte, r *receipt.Receipt, kernels ...hotswap.StageKernelArtifact) (StageQualification, error)
QualifyStage validates a passing receipt against the retained candidate artifact and binds it to the supplied stage source. The caller attests that source and artifact correspond. This check does not reproduce compilation, timings or correctness. For a native stage, the caller also supplies the approved CUBIN digest and entry for each named function.
func (StageQualification) ID ¶
func (q StageQualification) ID() string
ID returns the selection digest of an application-owned approval. A caller may select this approval only when it is present in the stage binding.
type StageService ¶
type StageService interface {
RegisterStage(context.Context, string, *stage.Builder, stage.Source, hotswap.StageSpec, string) (hotswap.State, error)
PushStage(context.Context, string, stage.Source, hotswap.StageSpec, string) (*hotswap.PushResult, error)
RevertStage(context.Context, string, string) (hotswap.State, error)
RunStage(context.Context, string, hotswap.StageLaunch) (*hotswap.PendingStage, error)
RecordStageFixture(context.Context, string, hotswap.FixtureConfig) (*hotswap.Fixture, error)
}
StageService is the optional host-stage extension of Service. An application without this extension refuses stage calls; existing kernel calls still work.
Example ¶
// The real service implements the optional extension without adding
// stage methods to kernel-only transport implementations.
var service StageService = (*hotswap.Service)(nil)
fmt.Printf("%T\n", service)
Output: *hotswap.Service