sys

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: 31 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 sys provides read-only file mapping, CLI flag hygiene checks, keyed text redaction, run identifiers, and deterministic virtual and test clocks.

It groups zero-copy read-only file views ([Map]), flag validation (CheckArgs, ParseGoTest), keyed hostname/token redaction (Redactor, NewRedactor), run ID formatting (ID), step-driven virtual clocks (VirtualClock, NewVirtualClock), and synthetic monotonic clocks (TestClock).

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"
	"log"
	"os"
	"path/filepath"

	"github.com/tmc/lib/nvidia/x/host/sys"
)

func main() {
	dir, err := os.MkdirTemp("", "filemap")
	if err != nil {
		log.Fatal(err)
	}
	defer os.RemoveAll(dir)
	name := filepath.Join(dir, "weights.bin")
	if err := os.WriteFile(name, []byte("weights"), 0o644); err != nil {
		log.Fatal(err)
	}

	f, err := sys.Open(name)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()
	fmt.Printf("%d bytes: %s\n", f.Len(), f.Bytes())
}
Output:
7 bytes: weights
Example (Clocktest)
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/host/sys"
)

func main() {
	// NTP slews CLOCK_MONOTONIC by -90 ppm; the device clock ticks in 32 ns.
	c := sys.TestClock{SlewPPM: -90, TickNs: 32}
	const t = 500_000_000 // 0.5 s
	fmt.Println(c.Raw(t), c.Mono(t), c.Device(t+31))
}
Output:
500000000 499955000 500000000
Example (Redact)
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/host/sys"
)

func main() {
	r := sys.NewRedactor([]byte("example key 0123"), []string{"gpu-node-17"}, nil)
	out := r.Replace([]byte(`{"span":"step","peer":"10.1.2.3","note":"ran on gpu-node-17"}`))
	fmt.Printf("%s\n", out)
	fmt.Println(r.Scan(out))
}
Output:
{"span":"step","peer":"[ipv4-b1ef73dc]","note":"ran on [site-963ee284]"}
map[]
Example (Runid)
package main

import (
	"fmt"
	"strings"

	"github.com/tmc/lib/nvidia/x/host/sys"
)

func main() {
	settings, err := sys.SumJSON(map[string]any{"chunk_tokens": 512})
	if err != nil {
		fmt.Println(err)
		return
	}
	a := sys.ID{Commit: strings.Repeat("a", 40), Settings: settings, Arch: "sm_89"}
	b := a
	b.Settings, _ = sys.SumJSON(map[string]any{"chunk_tokens": 1024})
	fmt.Println(a.Digest() == b.Digest())
	for _, c := range sys.Diff(a, b) {
		fmt.Println(c.Field)
	}
}
Output:
false
settings
Example (Virtualclock)

This example bounds a wait for a flag that is never set. With a 1µs step and a 1ms budget the wait gives up after the same number of polls on any host.

package main

import (
	"fmt"
	"time"

	"github.com/tmc/lib/nvidia/x/host/sys"
)

func main() {
	c := sys.NewVirtualClock(time.Microsecond)
	ready := func() bool { return false }
	budget := uint64(time.Millisecond)
	polls := 0
	for start := c.Now(); !ready(); polls++ {
		if c.Now()-start > budget {
			break
		}
	}
	fmt.Println("gave up after", polls, "polls at", c.Elapsed())
}
Output:
gave up after 1000 polls at 1.002ms

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Build

func Build() (commit string, modified bool)

Build returns the VCS revision the running binary was built from and whether its tree had uncommitted changes. The revision is empty when the build recorded none. A modified tree's revision does not identify the source; set ID.TreeHash too.

func HostValues

func HostValues() []string

HostValues returns the literal values of this host that identify it: its name, short and full, and the current user's name and home directory, from the system and from USER, LOGNAME and HOME.

func Load

func Load(ctx context.Context, t Target, k Kind, pkg string) (map[string]Set, error)

Load returns the flags of the binary of kind k built from pkg for t, keyed by import path; pkg may be a pattern such as ./x/... that names several packages. A package with no test files has no test binary and no Test set. A Command's set holds every flag its source registers, on flag.CommandLine or on any FlagSet. A Test set holds the flags registered on flag.CommandLine by the package, its tests, the testing package and every non-standard package they import.

func LoadKey

func LoadKey(file string) ([]byte, error)

LoadKey returns the key in file, a hex string of at least 16 bytes. If file does not exist, LoadKey creates it with a new random 32-byte key, readable only by its owner, so later runs share the key and the tokens for equal values stay equal. If file is "", the key is random and lasts only as long as the caller keeps it.

func ParseGoTest

func ParseGoTest(args []string) (GoTest, []Problem)

ParseGoTest splits args, the arguments after "go test", and reports the flags placed where go test fails on them: an unknown flag before the package list, which go test reads as a path.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/tmc/lib/nvidia/x/host/sys"
)

func main() {
	// A test flag before the package list is a mistake go test reports
	// only on the GPU host, as a missing package.
	_, probs := sys.ParseGoTest(strings.Fields("-count=1 -update-census ./x/cudasass"))
	for _, p := range probs {
		fmt.Println(p)
	}
	g, _ := sys.ParseGoTest(strings.Fields("-count=1 ./x/cudasass -update-census -args -v"))
	fmt.Printf("packages %q, to the binary %q, after -args %q\n", g.Packages, g.Binary, g.Args)
}
Output:
-update-census: unknown to go test before the package list, where go test cannot parse it; move it after the packages or after -args
packages ["./x/cudasass"], to the binary ["-update-census"], after -args ["-v"]

func ReadDenyFile

func ReadDenyFile(file string) ([]string, error)

ReadDenyFile returns the deny terms in file, one per line. Blank lines and lines beginning with # are skipped.

func Sum

func Sum(r io.Reader) (string, error)

Sum returns the hex SHA-256 of r's contents.

func SumJSON

func SumJSON(v any) (string, error)

SumJSON returns the hex SHA-256 of v's JSON encoding. Map keys are sorted by encoding/json, so equal settings maps sum equally.

func Wall

func Wall() func() uint64

Wall returns a function that reads the host's monotonic clock in nanoseconds since the call to Wall, for code that takes either clock.

Types

type Change

type Change struct {
	Field string `json:"field"`
	A     string `json:"a"`
	B     string `json:"b"`
}

A Change is one field that differs between two IDs.

func Diff

func Diff(a, b ID) []Change

Diff returns the fields that differ between a and b, in field order. It returns nil exactly when a and b have the same digest.

func (Change) String

func (c Change) String() string

type File

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

A File is a read-only view of a whole file's contents. The zero value is not usable; construct one with Open.

func Open

func Open(name string) (*File, error)

Open maps the named file read-only. An empty file or a directory is an error: neither can be mapped.

func (*File) Bytes

func (f *File) Bytes() []byte

Bytes returns the file's contents. The slice must not be written, and it is invalid after Close. Bytes returns nil after Close.

func (*File) Close

func (f *File) Close() error

Close releases the mapping. It is safe to call more than once.

func (*File) Len

func (f *File) Len() int

Len returns the file's size in bytes, or 0 after Close.

func (*File) Mapped

func (f *File) Mapped() bool

Mapped reports whether the contents are a memory mapping of the file rather than a copy of it in the Go heap.

func (*File) ReadAt

func (f *File) ReadAt(p []byte, off int64) (int, error)

ReadAt implements io.ReaderAt over the file's contents.

type GoTest

type GoTest struct {
	Flags    []string // go test's own, build and test flags, with their values
	Packages []string // the package list
	Binary   []string // flags after the package list that go test passes to every test binary
	Args     []string // everything after -args
	Tags     string   // the -tags value, if any
	Dir      string   // the -C value, if any
}

A GoTest is a go test command line split as go test splits it.

type Hit

type Hit struct {
	File  string `json:"file"`
	Class string `json:"class"`
	Count int    `json:"count"`
}

A Hit is one detection, by file and class; it never holds the value.

type Host

type Host struct {
	OS   string `json:"os,omitempty"`
	Arch string `json:"arch,omitempty"`
	CPUs int    `json:"cpus,omitempty"`
}

Host identifies the class of machine a run used.

func CurrentHost

func CurrentHost() Host

CurrentHost returns the host class of the running process.

type ID

type ID struct {
	Commit   string   `json:"commit,omitempty"`    // source revision
	TreeHash string   `json:"tree_hash,omitempty"` // source tree built, including uncommitted changes
	Weights  string   `json:"weights,omitempty"`   // model weights
	Config   string   `json:"config,omitempty"`    // model configuration
	Settings string   `json:"settings,omitempty"`  // run settings, such as server flags
	Plan     string   `json:"plan,omitempty"`      // execution plan, such as a launch schedule
	Modules  []string `json:"modules,omitempty"`   // loaded device module images, in any order
	Arch     string   `json:"arch,omitempty"`      // device architecture, such as "sm_89"
	Driver   string   `json:"driver,omitempty"`    // driver version
	Host     Host     `json:"host"`
}

An ID identifies the inputs of one run. Digest fields hold lowercase hex SHA-256 digests; Commit and TreeHash hold a 40- or 64-digit git object name. An empty field is unknown.

func (ID) Digest

func (id ID) Digest() string

Digest returns a hex SHA-256 over every field of id. The order of Modules does not affect it.

func (ID) Missing

func (id ID) Missing() []string

Missing returns the names of the fields of id that are unknown.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/host/sys"
)

func main() {
	id := sys.ID{Arch: "sm_89", Driver: "580.173.02"}
	fmt.Println(id.Missing())
}
Output:
[commit tree_hash weights config settings plan modules host.os host.arch host.cpus]

func (ID) Validate

func (id ID) Validate() error

Validate reports whether every known field of id is well formed.

type Kind

type Kind int

A Kind is the kind of binary whose flags Load reads.

const (
	Command Kind = iota // a main package
	Test                // a package's test binary
)

type Problem

type Problem struct {
	Flag    string // the argument, such as -update
	Package string // the package whose binary rejects it, if any
	Reason  string
}

A Problem is a flag a command line uses wrongly.

func CheckArgs

func CheckArgs(s Set, args []string) []Problem

CheckArgs reports the flags in args that s does not define. A value following a non-boolean flag is skipped, and so is everything after the first argument that is not a flag, or after "--", where a flag package stops parsing.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/host/sys"
)

func main() {
	s := sys.Set{"json": true, "out": false}
	fmt.Println(sys.CheckArgs(s, []string{"-json", "-out", "facts.json", "-compile=false"}))
}
Output:
[-compile=false: flag provided but not defined]

func CheckGoTest

func CheckGoTest(ctx context.Context, t Target, args []string) ([]Problem, error)

CheckGoTest checks a go test command line, the arguments after "go test", run in t.Dir: the placements ParseGoTest reports, then the flags go test passes to each package's test binary against that binary's flags. A package flag go test takes for itself, such as -n or -v, is reported unless it follows -args. Packages are resolved with t, and the line's -tags and -C apply.

func (Problem) String

func (p Problem) String() string

type RateStep

type RateStep struct {
	AtNs int64
	PPM  float64
}

A RateStep adds PPM to CLOCK_MONOTONIC's rate offset from AtNs on.

type Redactor

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

A Redactor replaces identifiers with keyed hashes and scans for what must not leave the site. A Redactor is not safe for concurrent use.

func NewRedactor

func NewRedactor(key []byte, site, deny []string) *Redactor

New returns a Redactor whose tokens are keyed by key. Site values are literal strings from this host, such as its name and the paths of its files, that must not leave it; values shorter than three bytes are ignored. Deny terms are never replaced: Scan reports them, matching case-insensitively. A Redactor used only to Scan needs no key.

func (*Redactor) Replace

func (r *Redactor) Replace(data []byte) []byte

Replace returns data with every identifier and site value replaced by a token of the form [class-xxxxxxxx], a keyed hash of the value, so equal values get equal tokens. Replacing a token leaves it unchanged.

func (*Redactor) Replaced

func (r *Redactor) Replaced() map[string]int

Replaced returns the number of values Replace has replaced, by class.

func (*Redactor) Scan

func (r *Redactor) Scan(data []byte) map[string]int

Scan counts what must not appear in data, by class: identifiers that Replace would replace, secrets such as private keys and API tokens, site values, and deny terms. Deny terms match as case-insensitive substrings. Site values of six or more bytes do too, wider than replace's whole-word rule; shorter ones (a user name such as "dev") match whole words only, or every "device" would fail the scan.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/host/sys"
)

func main() {
	r := sys.NewRedactor(nil, nil, []string{"ProjectRedwood"})
	fmt.Println(r.Scan([]byte("codename projectredwood\n-----BEGIN OPENSSH PRIVATE KEY-----")))
}
Output:
map[deny:1 secret:1]

func (*Redactor) ScanTree

func (r *Redactor) ScanTree(dir string) ([]Hit, int, error)

ScanTree scans every file and file name under dir, and returns the hits sorted by file and class, and the number of files. A file whose name holds a hit is reported as "(file name withheld)". Every file under dir must be a regular file.

func (*Redactor) SiteValues

func (r *Redactor) SiteValues() []string

SiteValues returns the site values r replaces, after New dropped short and duplicate values, longest first.

type Set

type Set map[string]bool

A Set is the flags a binary defines, by name. The value reports whether the flag is a boolean, which may be given without a value.

func (Set) Has

func (s Set) Has(name string) bool

Has reports whether s defines name.

type Target

type Target struct {
	Dir    string   // directory go list runs in, inside the module
	GOOS   string   // empty means the host's
	GOARCH string   // empty means the host's
	Env    []string // more environment, such as CGO_ENABLED=0 or GOFLAGS=-tags=cuda
	Tags   string   // the -tags build flag, if any
}

A Target is the build a binary's flags are read for.

type TestClock

type TestClock struct {
	// RawBase, MonoBase and DeviceBase are the readings at t = 0.
	RawBase, MonoBase, DeviceBase uint64

	// SlewPPM is CLOCK_MONOTONIC's constant rate offset from the raw
	// clock in parts per million, such as an NTP frequency correction.
	SlewPPM float64

	// DecayPPM is a further rate offset at t = 0 that decays as
	// exp(-t/DecayTauNs), as the kernel slews out a pending NTP offset.
	// It applies only when DecayTauNs > 0.
	DecayPPM   float64
	DecayTauNs float64

	// Steps change CLOCK_MONOTONIC's rate offset at given times, as an
	// NTP frequency update does.
	Steps []RateStep

	// DevicePPM is the device clock's rate offset from the raw clock.
	DevicePPM float64

	// TickNs is the device clock's quantum: readings are rounded down to
	// a multiple of it. When 0, readings are not quantized.
	TickNs uint64
}

Clock is a synthetic CLOCK_MONOTONIC_RAW, CLOCK_MONOTONIC and device clock. Its methods take the true time t in nanoseconds from the clock's origin, which may be negative, and are pure functions of it.

The zero Clock is usable: all three clocks read t.

func (TestClock) Device

func (c TestClock) Device(t int64) uint64

Device returns the device clock reading at t, rounded down to TickNs.

func (TestClock) Mono

func (c TestClock) Mono(t int64) uint64

Mono returns the CLOCK_MONOTONIC reading at t: MonoBase plus t plus the integral of the rate offset from 0 to t, rounded to the nearest nanosecond.

func (TestClock) Raw

func (c TestClock) Raw(t int64) uint64

Raw returns the CLOCK_MONOTONIC_RAW reading at t.

func (TestClock) SlewAt

func (c TestClock) SlewAt(t int64) float64

SlewAt returns CLOCK_MONOTONIC's rate offset from the raw clock at t, in parts per million.

func (TestClock) WithStep

func (c TestClock) WithStep(atNs int64, ppm float64) TestClock

WithStep returns a copy of c with a rate step of ppm at atNs added.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/host/sys"
)

func main() {
	// An NTP frequency update at 1 s moves the slew from -90 to -20 ppm.
	c := sys.TestClock{SlewPPM: -90}.WithStep(1_000_000_000, 70)
	fmt.Println(c.SlewAt(0), c.SlewAt(2_000_000_000), c.Mono(2_000_000_000))
}
Output:
-90 -20 1999890000

type VirtualClock

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

A Clock is a virtual clock. It is safe for concurrent use: every read, from any goroutine, advances the one shared time.

func NewVirtualClock

func NewVirtualClock(step time.Duration) *VirtualClock

New returns a clock at time zero that advances by step on each read. It panics if step is not positive, which is a programming error.

func (*VirtualClock) Advance

func (c *VirtualClock) Advance(d time.Duration)

Advance moves the clock forward by d without counting as a read. Negative d is ignored: the clock never goes back.

func (*VirtualClock) Elapsed

func (c *VirtualClock) Elapsed() time.Duration

Elapsed returns the clock's time without advancing it.

func (*VirtualClock) Now

func (c *VirtualClock) Now() uint64

Now advances the clock by its step and returns the new time in nanoseconds.

func (*VirtualClock) Step

func (c *VirtualClock) Step() time.Duration

Step returns the amount each read advances the clock.

Jump to

Keyboard shortcuts

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