Documentation
¶
Overview ¶
Package artifact provides deterministic manifests, multi-root tar bundling, settle-gated publication, pod-local install coordination, and bounded chunk lease management for compiled GPU caches (such as CUDA graphs, Triton, DeepGEMM, FlashInfer, CuTe DSL, and torch.compile caches).
BuildManifest walks a directory tree, skips symlinks, computes per-file and per-chunk Castagnoli CRC32C checksums, and seals the canonical JSON encoding with SHA-256 via Manifest.Seal. PackRoots and ExtractTar bundle and validate multi-root tar archives with path-traversal, symlink-escape, and byte-limit guards. SettleGate gates publication on engine readiness and a stable directory signature window. Coordinator serializes pod-local install-once markers and non-blocking publish leases using file locks keyed by an opaque source ID. ChunkLeasePool bounds concurrent in-flight chunk leases with TTL expiration over pluggable Transport backends.
File locking uses POSIX flock on Unix platforms and returns an error wrapping github.com/tmc/lib/nvidia/x/cuda.ErrUnsupported on platforms without flock. RDMA or device-backed Transport implementations are outside this package and should wrap github.com/tmc/lib/nvidia/x/cuda.ErrHardwarePending or github.com/tmc/lib/nvidia/x/cuda.ErrUnsupported as appropriate.
This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.
Index ¶
- Constants
- Variables
- func ExtractTar(r io.Reader, targetDir string, maxBytes int64) error
- func VerifyChunk(data []byte, chunk ChunkEntry) error
- type CacheRoot
- type ChunkEntry
- type ChunkLease
- type ChunkLeasePool
- type Coordinator
- type FileEntry
- type InstallState
- type InstallStatus
- type Manifest
- type SettleGate
- type SourceKind
- type Transport
Examples ¶
Constants ¶
const ( // ManifestVersion is the schema version emitted by BuildManifest. ManifestVersion = 1 // DefaultChunkSize is the default chunk size (64 MiB) used when chunkSize is 0. DefaultChunkSize int64 = 64 << 20 // MaxChunkSize is the maximum permitted chunk size (4 GiB). MaxChunkSize int64 = 4 << 30 )
Variables ¶
var ( // ErrPoolExhausted reports that all buffer slots in a ChunkLeasePool are currently leased. ErrPoolExhausted = errors.New("artifact: chunk lease pool exhausted") // ErrLeaseNotFound reports that a lease ID is unknown, already released, or expired. ErrLeaseNotFound = errors.New("artifact: chunk lease not found") )
var ( // ErrUnsafePath reports a tar member or link target that escapes its target directory. ErrUnsafePath = errors.New("artifact: unsafe path") // ErrExtractTooLarge reports that extracting a tar archive would exceed the configured byte limit. ErrExtractTooLarge = errors.New("artifact: extracted size exceeds limit") )
var ErrChecksumMismatch = errors.New("artifact: chunk checksum mismatch")
ErrChecksumMismatch reports that chunk data did not match its expected CRC32C checksum.
Functions ¶
func ExtractTar ¶
ExtractTar extracts a tar stream from r into targetDir after validating every entry against path traversal, absolute paths, symlink/hardlink escapes, special device entries, and an optional cumulative byte limit (maxBytes > 0).
func VerifyChunk ¶
func VerifyChunk(data []byte, chunk ChunkEntry) error
VerifyChunk validates that data matches chunk.Length and chunk.CRC32C.
Types ¶
type CacheRoot ¶
CacheRoot pairs a named source directory and target directory for multi-root bundling and readiness checks.
type ChunkEntry ¶
type ChunkEntry struct {
ChunkIndex uint32 `json:"chunk_index"`
FileIndex uint32 `json:"file_index"`
FileOffset int64 `json:"file_offset"`
Length int64 `json:"length"`
CRC32C string `json:"checksum"`
}
ChunkEntry describes one byte range of a FileEntry in a Manifest.
type ChunkLease ¶
type ChunkLease struct {
LeaseID string
ArtifactID string
Chunk ChunkEntry
Slot int
ExpiresAt time.Time
}
ChunkLease represents a bounded-TTL slot reservation for one artifact chunk.
type ChunkLeasePool ¶
type ChunkLeasePool struct {
// contains filtered or unexported fields
}
ChunkLeasePool bounds concurrent in-flight chunk leases with TTL expiration.
Example ¶
package main
import (
"fmt"
"time"
"github.com/tmc/lib/nvidia/x/compile/artifact"
)
func main() {
now := time.Date(2026, 11, 24, 12, 0, 0, 0, time.UTC)
pool, err := artifact.NewChunkLeasePool(2, 30*time.Second, func() time.Time { return now })
if err != nil {
fmt.Println("error:", err)
return
}
chunk := artifact.ChunkEntry{ChunkIndex: 0, Length: 1024, CRC32C: "00000000"}
lease, err := pool.Acquire("artifact-1", chunk)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("active=%d slot=%d\n", pool.Active(), lease.Slot)
if _, err := pool.Release(lease.LeaseID); err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("active=%d\n", pool.Active())
}
Output: active=1 slot=0 active=0
func NewChunkLeasePool ¶
func NewChunkLeasePool(maxSlots int, ttl time.Duration, now func() time.Time) (*ChunkLeasePool, error)
NewChunkLeasePool constructs a ChunkLeasePool with maxSlots slots and lease lifetime ttl. If now is nil, time.Now is used.
func (*ChunkLeasePool) Acquire ¶
func (p *ChunkLeasePool) Acquire(artifactID string, chunk ChunkEntry) (ChunkLease, error)
Acquire reserves a free slot for (artifactID, chunk), expiring any stale leases first. It returns ErrPoolExhausted if no slot is available.
func (*ChunkLeasePool) Active ¶
func (p *ChunkLeasePool) Active() int
Active returns the number of unexpired leases currently held in p.
func (*ChunkLeasePool) Release ¶
func (p *ChunkLeasePool) Release(leaseID string) (ChunkLease, error)
Release releases leaseID and returns its slot to the pool. If leaseID is unknown, already released, or already expired, Release returns ErrLeaseNotFound.
type Coordinator ¶
type Coordinator struct {
// contains filtered or unexported fields
}
Coordinator serializes pod-local install-once markers and non-blocking publication leases under lockDir using OS file locks.
func NewCoordinator ¶
func NewCoordinator(lockDir string) (*Coordinator, error)
NewCoordinator creates a Coordinator rooted at lockDir.
func (*Coordinator) InstallOnce ¶
func (c *Coordinator) InstallOnce(ctx context.Context, sourceID string, fn func(context.Context, *InstallState) (InstallState, error)) (InstallState, error)
InstallOnce serializes installation attempts for an opaque sourceID under an exclusive file lock.
If a marker already records StatusInstalled, InstallOnce returns that state without invoking fn. Otherwise it passes the existing marker state (or nil if absent) to fn, atomically persists StatusAttempted before calling fn when no marker existed, and atomically persists the state returned by fn.
func (*Coordinator) TryPublishLease ¶
func (c *Coordinator) TryPublishLease(sourceID string) (release func() error, acquired bool, err error)
TryPublishLease attempts to acquire a non-blocking exclusive publish lease for an opaque sourceID. When another caller already holds the lease, it returns (nil, false, nil).
type FileEntry ¶
type FileEntry struct {
FileIndex uint32 `json:"file_index"`
Path string `json:"path"`
Size int64 `json:"size"`
CRC32C string `json:"checksum"`
}
FileEntry describes one regular file in a Manifest.
type InstallState ¶
type InstallState struct {
Status InstallStatus `json:"status"`
ArtifactID string `json:"artifact_id,omitempty"`
Transport string `json:"transport,omitempty"`
OwnerPID int `json:"pid,omitempty"`
}
InstallState is the JSON marker persisted by Coordinator.InstallOnce.
type InstallStatus ¶
type InstallStatus string
InstallStatus describes the persisted state of a pod-local artifact install attempt.
const ( StatusAttempted InstallStatus = "attempted" StatusMiss InstallStatus = "miss" StatusInstalled InstallStatus = "installed" )
type Manifest ¶
type Manifest struct {
Version int `json:"manifest_version"`
Kind SourceKind `json:"mx_source_type"`
ChunkSize int64 `json:"chunk_size"`
Files []FileEntry `json:"files"`
Chunks []ChunkEntry `json:"chunks"`
}
Manifest is a deterministic, content-addressed file and chunk inventory of a directory tree.
func BuildManifest ¶
BuildManifest walks root, skips symlinks, rejects files escaping root, sorts regular files lexicographically by clean slash-separated relative path, computes per-file and per-chunk Castagnoli CRC32C checksums, and returns the Manifest together with its 64-hex-character SHA-256 artifact ID.
Zero-byte regular files are included in Files with checksum "00000000" and produce no entries in Chunks.
Example ¶
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/tmc/lib/nvidia/x/compile/artifact"
)
func main() {
dir, err := os.MkdirTemp("", "artifact-example-*")
if err != nil {
fmt.Println("error:", err)
return
}
defer os.RemoveAll(dir)
if err := os.WriteFile(filepath.Join(dir, "kernel.ptx"), []byte("xyz"), 0o644); err != nil {
fmt.Println("error:", err)
return
}
m, artifactID, err := artifact.BuildManifest(dir, artifact.KindTritonCache, 4)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("files=%d chunks=%d crc32c=%s id_len=%d\n", len(m.Files), len(m.Chunks), m.Files[0].CRC32C, len(artifactID))
}
Output: files=1 chunks=1 crc32c=25236885 id_len=64
func PackRoots ¶
func PackRoots(roots []CacheRoot, bundleDir string, kind SourceKind, chunkSize int64) (*Manifest, string, error)
PackRoots archives each root in roots into a dedicated bundleDir and returns the sealed Manifest and 64-hex-character ArtifactID for bundleDir.
The primary root (roots[0]) is archived as "artifact.tar"; each subsequent root is archived as "<root.Name>.tar". PackRoots rejects bundleDir when it is equal to or inside any SourceRoot, or when bundleDir already contains unexpected files. Optional roots that do not exist produce an empty tar archive. Symlinks inside source roots are skipped.
func (*Manifest) ChunkPage ¶
func (m *Manifest) ChunkPage(start, limit int) (chunks []ChunkEntry, nextStart int, err error)
ChunkPage returns up to limit chunks starting at index start, together with nextStart (or 0 when no more chunks remain).
type SettleGate ¶
type SettleGate struct {
// contains filtered or unexported fields
}
SettleGate reports ready only after an engine readiness predicate succeeds and the regular-file signature (count, total bytes, maximum modification time) across roots remains non-empty and unchanged for a settle window.
Example ¶
package main
import (
"fmt"
"os"
"path/filepath"
"time"
"github.com/tmc/lib/nvidia/x/compile/artifact"
)
func main() {
dir, err := os.MkdirTemp("", "artifact-settle-example-*")
if err != nil {
fmt.Println("error:", err)
return
}
defer os.RemoveAll(dir)
if err := os.WriteFile(filepath.Join(dir, "cache.bin"), []byte("data"), 0o644); err != nil {
fmt.Println("error:", err)
return
}
now := time.Date(2026, 11, 24, 12, 0, 0, 0, time.UTC)
gate := artifact.NewSettleGate(
[]artifact.CacheRoot{{Name: "primary", SourceRoot: dir}},
func() bool { return true },
5*time.Second,
func() time.Time { return now },
)
first := gate.Ready()
now = now.Add(5 * time.Second)
second := gate.Ready()
fmt.Printf("first=%v second=%v\n", first, second)
}
Output: first=false second=true
func NewSettleGate ¶
func NewSettleGate(roots []CacheRoot, readyFn func() bool, settle time.Duration, now func() time.Time) *SettleGate
NewSettleGate returns a SettleGate for roots. If readyFn is nil, the engine is treated as already ready. If now is nil, time.Now is used.
func (*SettleGate) Ready ¶
func (g *SettleGate) Ready() bool
Ready evaluates engine readiness and directory signature stability.
type SourceKind ¶
type SourceKind int32
SourceKind identifies the compiled cache kind carried by a Manifest. Numeric values match ModelExpress MxSourceType for wire-level manifest sealing compatibility.
const ( KindWeights SourceKind = 0 KindLoRA SourceKind = 1 KindCUDAGraph SourceKind = 2 KindTorchCompileCache SourceKind = 3 KindTritonCache SourceKind = 4 KindDeepGEMMCache SourceKind = 5 KindTileLangCache SourceKind = 6 KindCuTeDSLCache SourceKind = 7 KindFlashInferCache SourceKind = 8 KindTVMFFICache SourceKind = 9 )
func (SourceKind) String ¶
func (k SourceKind) String() string
String returns the canonical snake_case name of k.
type Transport ¶
type Transport interface {
FetchChunk(ctx context.Context, artifactID string, chunk ChunkEntry, w io.Writer) error
}
Transport fetches a single artifact chunk into w. Implementations that require GPU or RDMA hardware should return an error wrapping cuda.ErrHardwarePending when unprobed or cuda.ErrUnsupported when probed and unavailable.