Documentation
¶
Overview ¶
Package machine discovers what the machine has (cores, memory, disk, GPUs) and how loaded it is (load, pressure), and turns it into the number of workers Djinn runs at once, whether a new worker or a gate may start now, and whether a local model can run.
Index ¶
- Constants
- Variables
- func Add(c *machinev1.CommandCost, run *machinev1.CommandServiceRecordRequest)
- func AgentPath(goos, path, home, shell string) string
- func AskLoginShell() error
- func BaseSlots(s Snapshot) int
- func CgroupPIDs(dir string) ([]int, error)
- func CostsHandler(db *store.Store) (string, http.Handler)
- func ExtendPath()
- func FreezeCgroup(dir string, frozen bool) error
- func GroupPIDs(procs []proc, pid int) []int
- func Handler(m *Monitor, running func() int, uses func() []*machinev1.WorkerUse, ...) (string, http.Handler)
- func KillCgroup(dir string) error
- func LoadHandler(home string, m *Monitor, setPolicy func(Policy), ...) (string, http.Handler)
- func LookPath(name, path string) (string, error)
- func LowPriority(notch djinnv1.LoadNotch) bool
- func NotchIndex(n djinnv1.LoadNotch) int
- func NotchName(notch djinnv1.LoadNotch) string
- func NotchTitle(notch djinnv1.LoadNotch) string
- func ParseNotch(s string) (djinnv1.LoadNotch, error)
- func Project(ctx context.Context, db *store.Store, taskID, dir string) (id, name string, err error)
- func ReadNotch(home string) djinnv1.LoadNotch
- func Reader(dir string) func() (Snapshot, error)
- func SetCgroupWeight(dir string, weight int) error
- func SetWatchInterval(d time.Duration) func()
- func WorkerPIDs(pid int, cgroup string) ([]int, error)
- func WriteNotch(home string, notch djinnv1.LoadNotch) error
- type ActivitySignal
- type AutoController
- func (c *AutoController) Chosen() djinnv1.LoadNotch
- func (c *AutoController) Effective() djinnv1.LoadNotch
- func (c *AutoController) IsAuto() bool
- func (c *AutoController) LastChange() time.Time
- func (c *AutoController) SetNotch(notch djinnv1.LoadNotch) (effective djinnv1.LoadNotch, changed bool)
- func (c *AutoController) Tick() (bool, djinnv1.LoadNotch)
- type AutoOption
- func WithAutoActiveThreshold(d time.Duration) AutoOption
- func WithAutoChosen(notch djinnv1.LoadNotch) AutoOption
- func WithAutoClock(clock func() time.Time) AutoOption
- func WithAutoIdleSource(source IdleSource) AutoOption
- func WithAutoIdleThreshold(d time.Duration) AutoOption
- func WithAutoOnChange(onChange func(djinnv1.LoadNotch)) AutoOption
- func WithAutoSignal(signal ActivitySignal) AutoOption
- func WithAutoStepDuration(d time.Duration) AutoOption
- type Disk
- type GPU
- type Group
- type HandlerOption
- type History
- func (h *History) Flush(ctx context.Context)
- func (h *History) Machine(p *machinev1.MachinePoint)
- func (h *History) MachinePoints(ctx context.Context, from, to time.Time) []*machinev1.MachinePoint
- func (h *History) Worker(taskID string, p *machinev1.WorkerPoint)
- func (h *History) WorkerPoints(ctx context.Context, taskID string, from, to time.Time) []*machinev1.WorkerPoint
- type IdleSource
- type LoadOption
- func WithLoadAutoController(ac *AutoController) LoadOption
- func WithLoadClock(clock func() time.Time) LoadOption
- func WithLoadForcedWorkers(forced func() int) LoadOption
- func WithLoadIdleSource(source IdleSource) LoadOption
- func WithLoadLowerPauses(pauses func() bool) LoadOption
- func WithLoadPausedWorkers(paused func() int) LoadOption
- func WithLoadRunningWorkers(running func() int) LoadOption
- func WithLoadSignal(signal ActivitySignal) LoadOption
- func WithLoadStepDuration(d time.Duration) LoadOption
- func WithLoadStreamer(attach func(...)) LoadOption
- func WithLoadTickInterval(d time.Duration) LoadOption
- func WithLoadWorkerForecast(forecast func() uint64) LoadOption
- type Monitor
- func (m *Monitor) Available() uint64
- func (m *Monitor) BarSlots(n djinnv1.LoadNotch) int
- func (m *Monitor) Capacity() (slots int, rule, pressure string)
- func (m *Monitor) NotchSlots() []NotchSlots
- func (m *Monitor) Policy() Policy
- func (m *Monitor) Pressure() string
- func (m *Monitor) SetPolicy(p Policy)
- func (m *Monitor) SetWorkerMemory(resident func() uint64)
- func (m *Monitor) Snapshot() Snapshot
- func (m *Monitor) Total() uint64
- type NotchSlots
- type Peaks
- type Policy
- func (p Policy) AvailableMemory(s Snapshot) uint64
- func (p Policy) BarSlots(s Snapshot) int
- func (p Policy) BaseSlots(s Snapshot, peaks ...uint64) (int, string)
- func (p Policy) BindingResource(s Snapshot, peaks ...uint64) string
- func (p Policy) CPUSlots(s Snapshot) int
- func (p Policy) CommitMemory(s Snapshot) uint64
- func (p Policy) CommittableLimit(available uint64) uint64
- func (p Policy) EngagedAt() string
- func (p Policy) LocalModel(s Snapshot) (bool, string)
- func (p Policy) LowPriority() bool
- func (p Policy) MemoryPercentile() int
- func (p Policy) MemorySlots(s Snapshot, peaks ...uint64) int
- func (p Policy) NotchName() string
- func (p Policy) NotchTitle() string
- func (p Policy) Pressure(s Snapshot) string
- func (p Policy) Room(s Snapshot, command string, peak, held uint64) string
- func (p Policy) RuleMemory(total uint64) uint64
- func (p Policy) Slots(s Snapshot, peaks ...uint64) (int, string)
- func (p Policy) Typical(peaks []uint64) (uint64, int)
- func (p Policy) UsableMemory(s Snapshot) uint64
- func (p Policy) WorkerForecast(peaks ...uint64) uint64
- func (p Policy) WorkerMemoryCeiling(peak uint64, measured int) uint64
- func (p Policy) WorkerMemoryMax(factor float64, peak uint64, measured int) uint64
- func (p Policy) WorkerRoom(total, available, resident, held, engaged uint64, provider string, peak uint64, ...) string
- type Pressure
- type Scope
- type Scopes
- type SeriesRecorder
- func (r *SeriesRecorder) AddPoint(p *machinev1.MachinePoint)
- func (r *SeriesRecorder) Keep(h *History)
- func (r *SeriesRecorder) Points(cutoff time.Time) []*machinev1.MachinePoint
- func (r *SeriesRecorder) ReadSelf(read func() (Group, error))
- func (r *SeriesRecorder) Sample()
- func (r *SeriesRecorder) SetFS(fsys fs.FS)
- type Snapshot
- type WorkerMemoryFunc
Constants ¶
const ( // DefaultAutoHysteresis is the minimum time that must elapse between notch changes in auto mode. DefaultAutoHysteresis = 1 * time.Minute // DefaultActiveThreshold is the maximum idle time before the user is considered actively working. // Recent keyboard or mouse activity (< 30s) drops the operating load notch to Minimal. DefaultActiveThreshold = 30 * time.Second // DefaultIdleThreshold is the minimum idle time before the user is considered at rest. // Inactivity for 3 minutes or more with little host load allows the operating load to climb. DefaultIdleThreshold = 3 * time.Minute )
Operating load Auto mode thresholds.
const ( MiB = 1 << 20 GiB = 1 << 30 )
MiB is a mebibyte; GiB is a gibibyte.
const ( MemoryWarning = 2 MemoryCritical = 4 )
macOS's memory pressure levels that may hold new workers: warning at the Minimal notch, critical from Medium up.
const Delegate = "an administrator adds Delegate=cpu cpuset io memory pids to user@.service, once"
Delegate is what an administrator does, once, for systemd to give a user the controllers.
const MaxSeriesPoints = 1500
MaxSeriesPoints is the most points a series is sent with: a longer range is read by buckets, each its highest values, so that a peak stays readable.
const NotMeasured = ""
NotMeasured is why the workers' CPU and memory are not measured here; empty: they are.
Variables ¶
var ErrNoCPULimit = errors.New("CPU limits per worker are off")
ErrNoCPULimit is why the CPU of a worker cannot be capped here: a note of ProbeScopes starts with it.
var ErrNoMemoryLimit = errors.New("memory limits per worker are off")
ErrNoMemoryLimit is why the memory of a worker cannot be capped here: a note of ProbeScopes starts with it.
var ErrNoScope = errors.New("no systemd scope per worker")
ErrNoScope is why workers do not run in a systemd scope of their own here: ProbeScopes wraps it, and Djinn runs them in their process group.
var HistoryRetention = store.Retention{Fine: 24 * time.Hour, Keep: 7 * 24 * time.Hour, Max: 400_000}
HistoryRetention is how long the series are kept in the store: the readings of every 5 s for a day, then the highest of each minute for a week; 400,000 samples at most (some 30 MB), the oldest going first.
var ManualNotches = []djinnv1.LoadNotch{ djinnv1.LoadNotch_LOAD_NOTCH_MINIMAL, djinnv1.LoadNotch_LOAD_NOTCH_MEDIUM, djinnv1.LoadNotch_LOAD_NOTCH_HIGH, djinnv1.LoadNotch_LOAD_NOTCH_MAX, djinnv1.LoadNotch_LOAD_NOTCH_OVERCLOCK, }
ManualNotches is the ordered list of 5 manual operating load notches.
var NvidiaSMIArgs = []string{"--query-gpu=name,memory.total,driver_version", "--format=csv,noheader,nounits"}
NvidiaSMIArgs are the arguments ReadGPUs expects nvidia-smi to run with.
var PSArgs = []string{"-A", "-o", "pid=,ppid=,pgid=,rss=,time="}
PSArgs are the arguments of ps that ParsePS reads: every process, its parent, its group, its resident memory in KiB and its CPU time.
var SeriesMinutes = []int32{10, 30, 120, 24 * 60, 7 * 24 * 60}
SeriesMinutes are the ranges a series may be asked for: 10 and 30 minutes, 2 hours, a day, a week.
Functions ¶
func Add ¶
func Add(c *machinev1.CommandCost, run *machinev1.CommandServiceRecordRequest)
Add counts a run in what the command costs: the means move, the peak keeps the highest, wait and held times are tracked, percentiles computed, and recent runs recorded (up to 200).
func AgentPath ¶ added in v0.1.1
AgentPath is path, then the folders of shell (the login shell's PATH), then those of agentDirs that exist, each once: what is on path keeps its place and wins.
func AskLoginShell ¶ added in v0.1.1
func AskLoginShell() error
AskLoginShell asks the user's login shell for its PATH, which ExtendPath adds from then on. djinn up asks it once, when a launcher started it (a menu entry, the Dock, Finder): a graphical session gives its apps its own PATH, without what the user's shell profiles add (~/.zshrc's go/bin, nvm's node, an agent's own folder), so a watcher would not find gh, nor a lead go. A terminal reads those profiles, and a djinn up started from one has its PATH already. Nothing to ask on Windows, which passes the user's PATH to its apps.
func BaseSlots ¶ added in v0.1.1
BaseSlots returns the number of slots given by the current machine rule without notch scaling.
func CgroupPIDs ¶
CgroupPIDs lists the processes in the cgroup folder dir; an error when it does not exist (yet, or any more).
func CostsHandler ¶
CostsHandler returns the Connect handler of CommandService on the store, and its path prefix: what the commands of each project cost, as djinn gate run measures them.
func ExtendPath ¶ added in v0.1.1
func ExtendPath()
ExtendPath gives Djinn's own PATH the folders where the agents are, as they are now: AgentPath with the login shell's PATH (AskLoginShell), and the folders of the applications that ship an agent. Djinn calls it as djinn up starts and before it starts a worker or a lead, so that an agent installed while Djinn runs is found at once. It asks no shell: it only looks at folders.
func FreezeCgroup ¶
FreezeCgroup freezes every process in the cgroup folder dir where it is, or thaws them: one write, which a process forking meanwhile does not escape. A frozen process still dies of SIGKILL.
func GroupPIDs ¶ added in v0.1.1
GroupPIDs returns the list of process IDs belonging to the process group pid or its descendants.
func Handler ¶
func Handler(m *Monitor, running func() int, uses func() []*machinev1.WorkerUse, opts ...HandlerOption) (string, http.Handler)
Handler returns the Connect handler of MachineService on m, and its path prefix. running counts the workers that run now, uses lists what each one uses; nil counts and lists none.
func KillCgroup ¶
KillCgroup kills every process in the cgroup folder dir, at once (cgroup.kill, since Linux 5.14).
func LoadHandler ¶ added in v0.1.1
func LoadHandler( home string, m *Monitor, setPolicy func(Policy), broadcast func(djinnv1.LoadNotch), workerMemory WorkerMemoryFunc, opts ...LoadOption, ) (string, http.Handler)
LoadHandler returns the Connect handler of LoadService and its path prefix.
func LookPath ¶ added in v0.1.1
LookPath finds name in the folders of path, as exec.LookPath does for a worker: only absolute folders count.
func LowPriority ¶ added in v0.1.1
LowPriority reports whether the load notch runs workers with low CPU priority. Minimal and medium notches run with low CPU priority to yield CPU to developer applications; high, max, and overclock run with standard priority.
func NotchIndex ¶ added in v0.1.1
NotchIndex returns the index of a notch among the manual notches (0 to 4), mapping LIGHT to MEDIUM (1).
func NotchTitle ¶ added in v0.1.1
NotchTitle returns the title-case name of a notch (e.g. "Minimal", "Medium", "High", "Max", "Overclock", "Auto").
func ParseNotch ¶ added in v0.1.1
ParseNotch parses a string into a LoadNotch.
func Project ¶ added in v0.1.1
Project gives the ID and name of the project the command ran in: the task's, or the one whose folder holds dir, the deepest first; "", "" outside any project.
func ReadNotch ¶ added in v0.1.1
ReadNotch reads the operating load notch from settings.json in home. It returns LOAD_NOTCH_MEDIUM if the file does not exist, cannot be read, or notch is unspecified. An old saved "light" maps to Medium.
func Reader ¶
Reader reads this machine for a monitor: Read, then the disk of dir at each reading, and the GPUs once. Reading the GPUs starts now, in the background: asking a driver may take a moment.
func SetCgroupWeight ¶ added in v0.1.1
SetCgroupWeight sets the CPU weight of the cgroup folder dir (1 to 10000, 100 is default, 10 for low priority).
func SetWatchInterval ¶ added in v0.1.1
SetWatchInterval sets the minimum interval between Watch stream messages for tests.
func WorkerPIDs ¶ added in v0.1.1
WorkerPIDs returns the list of process IDs belonging to a worker (from its cgroup if available, or process tree).
Types ¶
type ActivitySignal ¶ added in v0.1.1
type ActivitySignal func() bool
ActivitySignal returns true if the developer is actively working on the machine, or false if the machine is at rest.
func SystemActivitySignal ¶ added in v0.1.1
func SystemActivitySignal(m *Monitor) ActivitySignal
SystemActivitySignal returns an ActivitySignal based on host CPU load and memory pressure. Outside Djinn processes, CPU and memory load is the only reliable, unprivileged, cross-platform signal across Linux (Wayland, X11, headless, SSH, containers), macOS, and Windows.
type AutoController ¶ added in v0.1.1
type AutoController struct {
// contains filtered or unexported fields
}
AutoController manages the operating load notch in auto mode. In auto mode, it dynamically moves between Minimal and the notch the developer chose, based on developer activity: Minimal when working, slowly climbing towards the chosen notch at rest, with hysteresis (no change more than once per step duration) to prevent oscillation.
Activity combines the desktop session's idle time (keyboard and mouse inactivity) with the load of programs other than Djinn (CPU wait/load and memory pressure): - Active at keyboard or mouse (< ActiveThreshold): drops notch directly to Minimal. - Heavy host load from other programs: drops notch directly to Minimal. - Idle for a few minutes (>= IdleThreshold) with little load: climbs (+1 notch per step duration). - Where no desktop idle source is available: falls back to host load alone.
In Auto mode, lowering the notch lowers CPU priority and stops starting new workers, never pausing or terminating running workers (Decision Q124 (C)).
func NewAutoController ¶ added in v0.1.1
func NewAutoController(initial djinnv1.LoadNotch, opts ...AutoOption) *AutoController
NewAutoController creates an AutoController with the given initial notch and options.
func (*AutoController) Chosen ¶ added in v0.1.1
func (c *AutoController) Chosen() djinnv1.LoadNotch
Chosen returns the ceiling notch for auto mode.
func (*AutoController) Effective ¶ added in v0.1.1
func (c *AutoController) Effective() djinnv1.LoadNotch
Effective returns the operating load notch currently in effect.
func (*AutoController) IsAuto ¶ added in v0.1.1
func (c *AutoController) IsAuto() bool
IsAuto reports whether auto mode is active.
func (*AutoController) LastChange ¶ added in v0.1.1
func (c *AutoController) LastChange() time.Time
LastChange returns the time of the last notch change.
func (*AutoController) SetNotch ¶ added in v0.1.1
func (c *AutoController) SetNotch(notch djinnv1.LoadNotch) (effective djinnv1.LoadNotch, changed bool)
SetNotch updates the notch setting. If notch is LOAD_NOTCH_AUTO, auto mode is enabled; if notch is a manual notch (Minimal to Overclock), auto mode is disabled and chosen is updated.
func (*AutoController) Tick ¶ added in v0.1.1
func (c *AutoController) Tick() (bool, djinnv1.LoadNotch)
Tick evaluates developer activity and updates the effective notch if hysteresis allows. In auto mode: - If developer is working (active typing/mouse or heavy load): drops fast directly to Minimal. - If machine is at rest (idle for minutes with little load): climbs slowly (+1 notch per stepDuration) towards chosen notch. - Never climbs above the notch the developer chose. - No change is made if less than stepDuration has elapsed since the last change.
type AutoOption ¶ added in v0.1.1
type AutoOption func(*AutoController)
AutoOption configures an AutoController.
func WithAutoActiveThreshold ¶ added in v0.1.1
func WithAutoActiveThreshold(d time.Duration) AutoOption
WithAutoActiveThreshold sets the maximum idle duration considered active keyboard or mouse input.
func WithAutoChosen ¶ added in v0.1.1
func WithAutoChosen(notch djinnv1.LoadNotch) AutoOption
WithAutoChosen sets the ceiling notch for auto mode.
func WithAutoClock ¶ added in v0.1.1
func WithAutoClock(clock func() time.Time) AutoOption
WithAutoClock sets the clock function (used for testing with a fake clock).
func WithAutoIdleSource ¶ added in v0.1.1
func WithAutoIdleSource(source IdleSource) AutoOption
WithAutoIdleSource sets the desktop session idle time source.
func WithAutoIdleThreshold ¶ added in v0.1.1
func WithAutoIdleThreshold(d time.Duration) AutoOption
WithAutoIdleThreshold sets the minimum idle duration before the user is considered at rest.
func WithAutoOnChange ¶ added in v0.1.1
func WithAutoOnChange(onChange func(djinnv1.LoadNotch)) AutoOption
WithAutoOnChange sets a callback invoked whenever the effective notch changes.
func WithAutoSignal ¶ added in v0.1.1
func WithAutoSignal(signal ActivitySignal) AutoOption
WithAutoSignal sets the activity signal function (used for testing with a fake signal).
func WithAutoStepDuration ¶ added in v0.1.1
func WithAutoStepDuration(d time.Duration) AutoOption
WithAutoStepDuration sets the hysteresis minimum interval between notch changes.
type GPU ¶
type GPU struct {
Vendor string // nvidia, amd, intel, apple, or the PCI vendor identifier of another
Name string // as its driver gives it; its PCI identifiers when none does
Driver string // nvidia, nouveau, amdgpu, i915, xe; metal on Apple Silicon; "" when none is bound
DriverVersion string // "" when unknown
Memory uint64 // bytes of its own; with unified memory, the machine's; 0 when unknown
Unified bool // it shares the machine's memory (Apple Silicon)
}
GPU is a graphics processor of the machine.
func AppleGPU ¶
AppleGPU is the GPU of an Apple Silicon chip: its name is the chip's (machdep.cpu.brand_string), and it shares the machine's memory, through Metal.
func ReadGPUs ¶
ReadGPUs reads the GPUs of a Linux machine from its /sys, fsys being the root of the file system: one per DRM card on the PCI bus, with its driver, the driver's version, and the memory of its own when the driver gives it (amdgpu). nvidiaSMI, called only when a card is NVIDIA's or when /sys shows none (WSL), runs nvidia-smi; what it gives replaces the NVIDIA cards of /sys. A /sys that cannot be read gives no GPU.
type Group ¶
type Group struct {
// Processes running.
Processes int
// CPU time, user and system, of the processes running and of the children they waited for.
CPU time.Duration
// Resident memory, summed over the processes: a page they share counts once per process. Read from a cgroup,
// what the kernel charges it (ReadCgroup).
Memory uint64
// Peak is the most memory the worker's cgroup held since it started; 0 without a cgroup.
Peak uint64
}
Group is what a worker uses at one time: its process group, and every process it started, even one that left the group (a tool an agent starts in a session of its own).
func ParsePS ¶
ParsePS reads, from the output of ps with PSArgs, what the worker whose process leads group pid uses.
func ReadCgroup ¶
ReadCgroup reads, from a cgroup v2 folder dir (Scope.Cgroup) of the file system fsys, what the processes in it use: cgroup.procs, cpu.stat (usage_usec, every process the cgroup held, ended ones too), memory.current (what the kernel charges the cgroup: resident memory and the page cache it filled) and memory.peak (since Linux 5.19; 0 before). Without the memory controller, it fails: memory.current does not exist.
func ReadGroup ¶
ReadGroup reads, from a Linux /proc, what the worker whose process leads group pid uses; fsys is the root of the file system. No process left: a zero Group.
func ReadSelf ¶ added in v0.1.1
ReadSelf reads what Djinn's own process uses, without any process it started (its window, leads, workers, gate holders): its CPU time, from getrusage, and its resident memory.
func ReadWorker ¶
ReadWorker reads what the worker whose process leads group pid uses: from its cgroup when it runs in one (Scope.Cgroup, ReadCgroup), else from its processes, listed at most once a second for every worker. Where workers are not measured (NotMeasured), it fails. A worker not listed yet, or listed at its exec, before it touched a page, reads as a zero Group: no reading.
type HandlerOption ¶ added in v0.1.1
type HandlerOption func(*service)
HandlerOption configures the machine service handler.
func WithHistory ¶ added in v0.1.1
func WithHistory(h *History) HandlerOption
WithHistory reads the series from the store's history, which outlives a restart, rather than from memory.
func WithSeriesIntervals ¶ added in v0.1.1
func WithSeriesIntervals(fn func(cutoff time.Time) []*machinev1.GateInterval) HandlerOption
WithSeriesIntervals sets the function returning gate intervals.
func WithSeriesRecorder ¶ added in v0.1.1
func WithSeriesRecorder(rec *SeriesRecorder) HandlerOption
WithSeriesRecorder sets the machine series recorder.
func WithSeriesWorkers ¶ added in v0.1.1
func WithSeriesWorkers(fn func(cutoff time.Time, gateIntervals []*machinev1.GateInterval) []*machinev1.WorkerSeries) HandlerOption
WithSeriesWorkers sets the function returning series of running workers.
type History ¶ added in v0.1.1
type History struct {
// contains filtered or unexported fields
}
History keeps the series of the machine and of each worker in the store, so that they outlive a restart of Djinn: the readings wait in memory, then Flush writes them, every 30 s in djinn up; reading merges both.
func NewHistory ¶ added in v0.1.1
NewHistory keeps the series in db.
func (*History) Flush ¶ added in v0.1.1
Flush writes the readings waiting, and rolls up and prunes the store's samples every 10 minutes (HistoryRetention). Readings it could not write wait for the next flush, up to an hour of them.
func (*History) Machine ¶ added in v0.1.1
func (h *History) Machine(p *machinev1.MachinePoint)
Machine records a reading of the machine.
func (*History) MachinePoints ¶ added in v0.1.1
MachinePoints is the machine's series after from, until to.
func (*History) Worker ¶ added in v0.1.1
func (h *History) Worker(taskID string, p *machinev1.WorkerPoint)
Worker records a reading of the worker of a task.
func (*History) WorkerPoints ¶ added in v0.1.1
func (h *History) WorkerPoints(ctx context.Context, taskID string, from, to time.Time) []*machinev1.WorkerPoint
WorkerPoints is the series of a task's worker after from, until to.
type IdleSource ¶ added in v0.1.1
IdleSource returns the duration of user inactivity (time since last keyboard or mouse input) and whether idle time could be determined on the current platform/session. When ok is false, idle time is unavailable (headless, SSH, or unsupported desktop), and auto mode falls back to host CPU and memory load alone.
func DefaultIdleSource ¶ added in v0.1.1
func DefaultIdleSource() IdleSource
DefaultIdleSource returns the default Linux idle source.
func LinuxSessionIdleSource ¶ added in v0.1.1
func LinuxSessionIdleSource() IdleSource
LinuxSessionIdleSource returns an IdleSource for Linux desktop sessions over D-Bus. It queries GNOME Mutter IdleMonitor on the session bus, falling back to org.freedesktop.ScreenSaver.GetSessionIdleTime if available.
Note on KDE Plasma: On KDE Plasma (Wayland), KWin does not expose an unprivileged synchronous D-Bus polling method for session idle time (org.freedesktop.ScreenSaver only supports inhibition, and KIdleTime uses the Wayland client protocol ext-idle-notify-v1 / org_kde_kwin_idle). When running under KDE, GetIdletime is not found, and LinuxSessionIdleSource returns (0, false), causing Auto mode to gracefully fall back to host CPU and memory load alone.
type LoadOption ¶ added in v0.1.1
type LoadOption func(*loadService)
LoadOption configures loadService.
func WithLoadAutoController ¶ added in v0.1.1
func WithLoadAutoController(ac *AutoController) LoadOption
WithLoadAutoController sets a custom AutoController on the load service.
func WithLoadClock ¶ added in v0.1.1
func WithLoadClock(clock func() time.Time) LoadOption
WithLoadClock sets the clock function used for auto mode.
func WithLoadForcedWorkers ¶ added in v0.1.2
func WithLoadForcedWorkers(forced func() int) LoadOption
WithLoadForcedWorkers sets a function returning how many running workers were started or resumed by hand.
func WithLoadIdleSource ¶ added in v0.1.1
func WithLoadIdleSource(source IdleSource) LoadOption
WithLoadIdleSource sets the idle source used for auto mode.
func WithLoadLowerPauses ¶ added in v0.1.2
func WithLoadLowerPauses(pauses func() bool) LoadOption
WithLoadLowerPauses sets a function telling whether lowering the notch pauses the workers above it.
func WithLoadPausedWorkers ¶ added in v0.1.1
func WithLoadPausedWorkers(paused func() int) LoadOption
WithLoadPausedWorkers sets a function returning the count of currently paused workers.
func WithLoadRunningWorkers ¶ added in v0.1.1
func WithLoadRunningWorkers(running func() int) LoadOption
WithLoadRunningWorkers sets a function returning the count of currently running workers.
func WithLoadSignal ¶ added in v0.1.1
func WithLoadSignal(signal ActivitySignal) LoadOption
WithLoadSignal sets the activity signal function used for auto mode.
func WithLoadStepDuration ¶ added in v0.1.1
func WithLoadStepDuration(d time.Duration) LoadOption
WithLoadStepDuration sets the hysteresis minimum interval for auto mode.
func WithLoadStreamer ¶ added in v0.1.1
func WithLoadStreamer(attach func(func(ctx context.Context, send func(*djinnv1.LoadServiceWatchResponse) error) error)) LoadOption
WithLoadStreamer provides a function that can be called to stream load changes.
func WithLoadTickInterval ¶ added in v0.1.1
func WithLoadTickInterval(d time.Duration) LoadOption
WithLoadTickInterval sets the auto ticker interval (<= 0 disables background ticker).
func WithLoadWorkerForecast ¶ added in v0.1.1
func WithLoadWorkerForecast(forecast func() uint64) LoadOption
WithLoadWorkerForecast sets a function returning the measured forecast per worker in bytes.
type Monitor ¶
type Monitor struct {
// contains filtered or unexported fields
}
Monitor reads the machine at most once a second, for the scheduler and the gates.
func NewMonitor ¶
NewMonitor is a monitor of this machine with the policy p. read, when not nil, replaces reading the machine: the tests simulate it.
func (*Monitor) Available ¶
Available is the memory available to new programs now, in bytes; 0 when unknown.
func (*Monitor) BarSlots ¶ added in v0.1.2
BarSlots is the most workers the notch n itself lets run now (Policy.BarSlots), djinn up --workers holding.
func (*Monitor) Capacity ¶
Capacity is the most workers the machine runs at once and its rule, and why it is under pressure ("" when it is not).
func (*Monitor) NotchSlots ¶ added in v0.1.2
func (m *Monitor) NotchSlots() []NotchSlots
NotchSlots is the most workers each manual notch lets run now, as the scheduler weighs them (Capacity): the load bar shows these, so that what it says a notch runs is what the scheduler lets run there (W577). djinn up --workers holds for every notch.
func (*Monitor) SetWorkerMemory ¶ added in v0.1.1
SetWorkerMemory gives the resident memory of Djinn's running workers, in bytes, which each snapshot carries (Snapshot.WorkersResident): djinn up gives the harness's (harness.Harness.Resident). It must not call the monitor.
type NotchSlots ¶ added in v0.1.2
NotchSlots is the most workers a notch lets run on the machine as it is now.
type Peaks ¶
type Peaks struct {
// contains filtered or unexported fields
}
Peaks reads the highest peak memory measured of each command, for the gates.
type Policy ¶
type Policy struct {
// Notch is the operating load slider notch that controls how much of the machine Djinn uses.
Notch djinnv1.LoadNotch
// Workers, when above 0, is the number of workers, whatever the machine (djinn up --workers).
Workers int
// One worker per CoresPerWorker cores, and per MemoryPerWorker bytes beyond MemoryReserve; the smaller wins,
// between 1 and MaxWorkers.
CoresPerWorker int
MemoryPerWorker uint64
MemoryReserve uint64
MaxWorkers int
// WorkerMemory, when above 0, is the most memory a worker may hold, in bytes, where it runs in a systemd scope
// of its own (Scopes, djinn up --worker-memory): past it, the kernel reclaims, then kills a process of the worker.
// 0, the default: no ceiling. An expert setting, never tied to operating load notches.
WorkerMemory uint64
// WorkerMemoryGuard, when above 0, is an optional guardrail factor (typically 2 to 3) applied to the provider's
// observed typical peak (median of latest WorkerPeaks finished workers) to set a dynamic MemoryMax ceiling for
// each worker, at least its forecast (peak + WorkerMargin). 0, the default: disabled.
// Without measurements (measured == 0), no ceiling is set. Never tied to operating load notches.
WorkerMemoryGuard float64
// The machine is under pressure when, over the last 10 seconds, tasks waited for the CPU at least CPUPressure
// percent of the time, or for memory at least MemoryPressure percent (PSI "some").
CPUPressure float64
MemoryPressure float64
// Without PSI: when the load average per core reaches LoadPerCore, or the memory available falls below
// MemoryFree of the total. On macOS, instead of MemoryFree, the system's own memory pressure level at MemoryLevel
// or above: warning (MemoryWarning) at Minimal only, since warning is frequent and passing on a busy Mac;
// critical (MemoryCritical, also what 0 means) from Medium up.
LoadPerCore float64
MemoryFree float64
MemoryLevel int
// A gate goes to a command measured in its project only when the memory available, less the peaks of the
// commands holding a gate, holds its highest peak plus CommandMargin; a command never measured goes as it comes.
// Djinn's recommendation: the developer may change it.
CommandMargin uint64
// Another worker starts only when the memory available, less what the workers running may still take, holds the
// typical peak of a worker of its provider plus WorkerMargin. The typical peak is the median of the peaks of the
// latest WorkerPeaks finished workers of that provider; WorkerPeak while none is measured. A running worker may
// still take the typical peak of its provider less what it uses now; one not read yet, all of it.
WorkerPeak uint64
WorkerPeaks int
WorkerMargin uint64
// Percentile is the percentile of a worker's memory series it is engaged at (95, 80, 70, 60 or 50): a running
// worker at that percentile of its own readings, a new one at the median of the latest WorkerPeaks finished
// workers' value at it. The higher the notch, the lower: builds and tests spike a worker's memory, and the gates
// already serialize them. 0 is 95.
Percentile int
Share float64
// On max (1.0), all RAM except WorkerMargin may be committed; overclock (1.50) may exceed what the rule engages.
MemoryShare float64
// Auto is whether the operating load is currently managed by auto mode.
Auto bool
// A local model runs on an NVIDIA or AMD GPU, its driver loaded, with ModelGPUMemory of its own; on Apple
// Silicon with ModelMemory of unified memory; else on the CPU, slowly, with ModelMemory. Its weights need
// ModelDisk free on the disk of the data folder.
ModelGPUMemory uint64
ModelMemory uint64
ModelDisk uint64
}
Policy turns a snapshot into a number of workers and a pressure verdict. Every threshold is a field: the defaults are DefaultPolicy.
func DefaultPolicy ¶
func DefaultPolicy() Policy
DefaultPolicy is the policy Djinn runs with: medium operating load. A worker is mostly an agent waiting for its model; the heavy commands it runs (builds, tests, code generation) go through gates. Two cores and 2 GiB a worker leaves room for them.
func NotchPolicy ¶ added in v0.1.1
NotchPolicy returns the policy of the operating load notch. Medium is the default policy Djinn runs with.
func (Policy) AvailableMemory ¶ added in v0.1.1
AvailableMemory returns the memory available to new programs: s.MemoryAvailable, or s.MemoryTotal when available is unknown.
func (Policy) BarSlots ¶ added in v0.1.2
BarSlots is the most workers the notch itself lets run, before the memory's share of Slots: its share of the CPU rule's slots, at least 1; djinn up --workers when set. It changes only with the notch: lowering the notch pauses the workers above it, never a dip of the memory available, which pausing would not free.
func (Policy) BaseSlots ¶ added in v0.1.1
BaseSlots is the number of worker slots the machine allows today under the standard rule: min of what CPU allows and what memory allows, up to 16, at least 1.
func (Policy) BindingResource ¶ added in v0.1.1
BindingResource reports which resource limits worker capacity: "memory" or "cpu".
func (Policy) CPUSlots ¶ added in v0.1.1
CPUSlots returns the worker slots allowed by the CPU rule before notch scaling: one worker per 2 cores, at least 1, up to MaxWorkers.
func (Policy) CommitMemory ¶ added in v0.1.1
CommitMemory returns the memory Djinn could use with no worker running: the memory available plus what its running workers hold (s.WorkersResident), which the memory available already leaves out; at most the total. Counting the workers' own memory both out of what is available and into what they engage would count it twice.
func (Policy) CommittableLimit ¶ added in v0.1.1
CommittableLimit is the maximum memory Djinn commits to peak forecasts, available being the memory Djinn could use with no worker running (CommitMemory: free + reclaimable + its running workers' own). Djinn's engaged memory never exceeds the notch's share of it beyond the reserve, with Overclock included only up to the reserve (at most available). It returns 0 when available is 0 or unknown.
func (Policy) EngagedAt ¶ added in v0.1.1
EngagedAt says at which percentile of its memory a worker is engaged, and why: "engaged at p50 (overclock)".
func (Policy) LocalModel ¶
LocalModel says whether a local open-weight model can run on the machine, and why: dispatch asks one only where it can (T07). The first usable GPU decides; without one, the memory.
func (Policy) LowPriority ¶ added in v0.1.1
LowPriority reports whether the policy runs workers with low CPU priority.
func (Policy) MemoryPercentile ¶ added in v0.1.1
MemoryPercentile is the percentile a worker is engaged at (Percentile): 95 when unset.
func (Policy) MemorySlots ¶ added in v0.1.1
MemorySlots returns the worker slots allowed by memory at 100% (usable memory / worker forecast) before notch scaling: usable memory is available plus the running workers' own, minus reserve (UsableMemory); forecast is measured peak per worker or default; at least 1, up to MaxWorkers. A machine whose memory is unknown returns MaxWorkers.
func (Policy) NotchTitle ¶ added in v0.1.1
NotchTitle returns the title-case name of the policy's load notch.
func (Policy) Pressure ¶
Pressure says why the machine is under pressure, or "" when it is not. Under pressure, no worker starts and no gate is granted; what runs goes on.
func (Policy) Room ¶
Room says why the machine cannot hold the command yet, its highest measured peak memory being peak, or "" when it can: the memory available, less held (the peaks of the commands holding a gate, which may not have reached them yet), holds the peak plus CommandMargin. A command never measured (peak 0), or a machine whose memory is unknown, has room.
func (Policy) RuleMemory ¶ added in v0.1.1
RuleMemory returns the memory the rule would engage on a machine with total RAM.
func (Policy) Slots ¶
Slots is the most workers the machine runs at once, and the rule that gave it. Workers allowed = the notch's share of min(what the CPU rule allows, what the memory allows), where memory allows (memory Djinn may engage at that notch) / (the measured peak forecast per worker); the memory Djinn may engage counts its running workers' own back in (CommitMemory), so a worker's memory does not take a slot from the others.
func (Policy) Typical ¶
Typical is the typical peak memory of a worker, and how many measured peaks gave it: the median of the first WorkerPeaks of peaks, the latest first; WorkerPeak and 0 when none is measured. With an even count, the mean of the two in the middle.
func (Policy) UsableMemory ¶ added in v0.1.1
UsableMemory returns the memory Djinn could use beyond the reserve, its running workers' included: max(0, CommitMemory - MemoryReserve).
func (Policy) WorkerForecast ¶ added in v0.1.1
WorkerForecast returns the forecast peak memory per worker (typical peak plus WorkerMargin). Without measurements, it returns WorkerPeak + WorkerMargin (1.5 GiB by default).
func (Policy) WorkerMemoryCeiling ¶ added in v0.1.1
WorkerMemoryCeiling returns the memory ceiling in bytes for a worker of a provider, evaluating the guardrail (if WorkerMemoryGuard > 0) against the hard ceiling WorkerMemory. Returns 0 when no ceiling applies.
func (Policy) WorkerMemoryMax ¶ added in v0.1.1
WorkerMemoryMax calculates the dynamic memory ceiling (MemoryMax in bytes) for a worker of a provider with observed peak and measured count, using the guardrail factor. When factor <= 0 or measured == 0, the guardrail sets no ceiling (returns 0). When measured > 0, it returns at least the current forecast (peak + WorkerMargin), and factor * peak if larger.
func (Policy) WorkerRoom ¶
func (p Policy) WorkerRoom(total, available, resident, held, engaged uint64, provider string, peak uint64, measured int) string
WorkerRoom says why the machine cannot hold another worker of provider yet, or "" when it can. Two checks:
- engaged (what the workers running are engaged at, their resident memory included) plus the new worker's forecast stays within CommittableLimit of the memory Djinn could use with no worker running: available plus resident, the running workers' resident memory, which available already leaves out;
- the memory available, less held (what the workers running may still take beyond what they hold), holds peak, the typical memory of a worker of provider measured over measured workers (Typical), plus WorkerMargin.
A machine whose memory is unknown (available 0) has room.
type Pressure ¶
Pressure is how much of the last 10 seconds tasks waited for a resource, in percent: Linux's pressure stall information.
type Scope ¶
type Scope struct {
// Unit names it: djinn-<task code>-<uuid8>.scope.
Unit string
// Prefix runs a command in it, the command appended. The scope keeps the process: same PID, same process group,
// same streams.
Prefix []string
// Cgroup is its folder, under /sys/fs/cgroup; it exists from the time systemd-run makes the scope until its last
// process ends. Empty when unknown.
Cgroup string
}
Scope is the scope of one process a worker starts: its unit, the command it runs under, its cgroup.
type Scopes ¶
type Scopes struct {
// CPU caps each worker at this percent of one core (CPUQuota, djinn up --worker-cpu); 0: uncapped.
CPU int
// Memory caps each worker's memory at this many bytes (MemoryMax, Policy.WorkerMemory); 0: no ceiling.
Memory uint64
// MemoryController is true when systemd gives the memory controller to the user's scopes.
MemoryController bool
// contains filtered or unexported fields
}
Scopes start each worker in a systemd user scope of its own, without root: a cgroup that holds every process the worker starts, even one that leaves its process group, so that stopping, pausing and measuring it take the whole tree. ProbeScopes makes them.
func ProbeScopes ¶
ProbeScopes returns the scopes that run each worker in a systemd user scope of its own, its CPU capped at cpu percent of one core (150 is a core and a half) and its memory at memory bytes, 0 capping nothing. It starts one such scope first and reads its cgroup. An error wrapping ErrNoScope says why there is none: Djinn runs workers as they are. A cap that would not hold is set to 0, and a note says why.
type SeriesRecorder ¶ added in v0.1.1
type SeriesRecorder struct {
// contains filtered or unexported fields
}
SeriesRecorder records machine and Djinn process consumption samples over time.
func NewSeriesRecorder ¶ added in v0.1.1
func NewSeriesRecorder(m *Monitor, readWorker func(pid int, cgroup string) (Group, error)) *SeriesRecorder
NewSeriesRecorder returns a recorder for machine metrics.
func (*SeriesRecorder) AddPoint ¶ added in v0.1.1
func (r *SeriesRecorder) AddPoint(p *machinev1.MachinePoint)
AddPoint appends a pre-built machine point (used in tests).
func (*SeriesRecorder) Keep ¶ added in v0.1.1
func (r *SeriesRecorder) Keep(h *History)
Keep keeps each sample in h too, the store's series that outlive a restart.
func (*SeriesRecorder) Points ¶ added in v0.1.1
func (r *SeriesRecorder) Points(cutoff time.Time) []*machinev1.MachinePoint
Points returns all recorded machine points since cutoff.
func (*SeriesRecorder) ReadSelf ¶ added in v0.1.1
func (r *SeriesRecorder) ReadSelf(read func() (Group, error))
ReadSelf reads Djinn's own process alone with read: ReadSelf in djinn up.
func (*SeriesRecorder) Sample ¶ added in v0.1.1
func (r *SeriesRecorder) Sample()
Sample collects one measurement point from the machine and Djinn process.
func (*SeriesRecorder) SetFS ¶ added in v0.1.1
func (r *SeriesRecorder) SetFS(fsys fs.FS)
SetFS overrides the filesystem for testing /proc.
type Snapshot ¶
type Snapshot struct {
OS, Arch string
Cores int
MemoryTotal uint64 // bytes; 0 when unknown
MemoryAvailable uint64 // bytes available to new programs
Load1 float64
LoadKnown bool
CPU, Memory *Pressure // nil without PSI
// MemoryLevel is macOS's memory pressure level (kern.memorystatus_vm_pressure_level): 1 normal, 2 warning,
// 4 critical; 0 when unknown.
MemoryLevel int
Disk *Disk // the data folder's; nil when unknown
GPUs []GPU
Time time.Time
// WorkersResident is the resident memory of Djinn's running workers, in bytes (Monitor.SetWorkerMemory): memory
// available already leaves it out, so what Djinn may commit counts it back in (CommitMemory); 0 when unknown.
WorkersResident uint64
}
Snapshot is the machine as read at one time. What the system does not give stays unknown.