mempressure

package
v0.6.20 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 10 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

Rendered for darwin/amd64

Overview

Package mempressure provides Darwin process memory accounting, live memory-pressure notifications, and coordinated memory shedding without cgo.

Snapshot reads the current task's kernel VM accounting from task_info(TASK_VM_INFO) alongside getrusage(RUSAGE_SELF), reporting the same physical footprint metric that macOS jetsam and Activity Monitor use.

Watcher wraps a live DISPATCH_SOURCE_TYPE_MEMORYPRESSURE source on a dedicated serial dispatch queue, translating Darwin pressure flags into Level values (Normal, Warn, Critical). Watcher.Notify delivers synthetic events through the same serialized path for deterministic testing.

Controller coordinates memory shedding across a Level transition by invoking registered eviction callbacks, tightening or restoring runtime/debug.SetMemoryLimit, and calling runtime/debug.FreeOSMemory on elevated pressure.

Basic usage:

ctrl := mempressure.NewController(mempressure.Config{
	BaseLimit: 512 << 20,
})
defer ctrl.Close()
ctrl.Register(func(level mempressure.Level) uint64 {
	return cache.Evict(level)
})

w := mempressure.NewWatcher(func(level mempressure.Level) {
	ctrl.Handle(level)
})
defer w.Close()
Example
package main

import (
	"fmt"

	"github.com/tmc/apple/x/mempressure"
)

func main() {
	ctrl := mempressure.NewController(mempressure.Config{
		BaseLimit:           512 << 20,
		DisableFreeOSMemory: true,
		OnReport: func(rep mempressure.Report) {
			fmt.Printf("level=%s freed=%dMiB limit=%dMiB\n",
				rep.Level, rep.FreedBytes>>20, rep.NewMemoryLimit>>20)
		},
	})
	defer ctrl.Close()

	ctrl.Register(func(level mempressure.Level) uint64 {
		switch level {
		case mempressure.Warn:
			return 64 << 20
		case mempressure.Critical:
			return 128 << 20
		default:
			return 0
		}
	})

	w := mempressure.NewWatcher(func(level mempressure.Level) {
		ctrl.Handle(level)
	})
	defer w.Close()

	w.Notify(mempressure.Warn)
	w.Notify(mempressure.Critical)
	w.Notify(mempressure.Normal)

}
Output:
level=warn freed=64MiB limit=384MiB
level=critical freed=128MiB limit=256MiB
level=normal freed=0MiB limit=512MiB

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// BaseLimit is the Go heap soft memory limit (bytes) applied via
	// debug.SetMemoryLimit on creation and restored on Normal and Close.
	// If <= 0, the controller does not modify debug.SetMemoryLimit unless
	// WarnLimit or CriticalLimit is explicitly set.
	BaseLimit int64

	// WarnLimit is the Go memory limit applied on Warn.
	// If <= 0 and BaseLimit > 0, it defaults to 75% of BaseLimit.
	WarnLimit int64

	// CriticalLimit is the Go memory limit applied on Critical.
	// If <= 0 and BaseLimit > 0, it defaults to 50% of BaseLimit.
	CriticalLimit int64

	// DisableFreeOSMemory suppresses calling debug.FreeOSMemory on Warn and
	// Critical transitions.
	DisableFreeOSMemory bool

	// OnReport, if non-nil, is called after each Handle completes.
	OnReport func(Report)
}

Config configures a Controller.

type Controller

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

Controller coordinates eviction callbacks, runtime/debug.SetMemoryLimit, and runtime/debug.FreeOSMemory in response to memory-pressure transitions.

The zero value is not usable; construct a Controller with NewController and call Controller.Close to restore the prior Go memory limit.

func NewController

func NewController(cfg Config) *Controller

NewController creates a Controller configured by cfg. If cfg.BaseLimit > 0, debug.SetMemoryLimit is set immediately and the prior limit is restored by Controller.Close.

func (*Controller) Close

func (c *Controller) Close() error

Close restores the Go memory limit that was active before NewController was called. It is safe to call more than once.

func (*Controller) Handle

func (c *Controller) Handle(level Level) Report

Handle executes the configured shedding policy for level:

  1. Captures the process physical footprint via Snapshot.
  2. Invokes all registered eviction callbacks in registration order.
  3. Adjusts runtime/debug.SetMemoryLimit according to Config.
  4. Calls runtime/debug.FreeOSMemory on Warn and Critical (unless disabled).
  5. Captures the updated physical footprint and notifies Config.OnReport.
Example
package main

import (
	"fmt"

	"github.com/tmc/apple/x/mempressure"
)

func main() {
	ctrl := mempressure.NewController(mempressure.Config{
		BaseLimit:           256 << 20,
		DisableFreeOSMemory: true,
	})
	defer ctrl.Close()

	unregister := ctrl.Register(func(level mempressure.Level) uint64 {
		if level == mempressure.Warn {
			return 32 << 20
		}
		return 0
	})

	rep := ctrl.Handle(mempressure.Warn)
	fmt.Printf("%s: freed=%dMiB limit=%dMiB\n", rep.Level, rep.FreedBytes>>20, rep.NewMemoryLimit>>20)

	unregister()
	rep = ctrl.Handle(mempressure.Normal)
	fmt.Printf("%s: freed=%dMiB limit=%dMiB\n", rep.Level, rep.FreedBytes>>20, rep.NewMemoryLimit>>20)

}
Output:
warn: freed=32MiB limit=192MiB
normal: freed=0MiB limit=256MiB

func (*Controller) MemoryLimit

func (c *Controller) MemoryLimit() int64

MemoryLimit returns the current Go memory limit tracked by the controller, or the runtime's current limit if limit management is disabled.

func (*Controller) Register

func (c *Controller) Register(fn func(Level) uint64) (unregister func())

Register adds an eviction callback invoked on pressure transitions. The callback should return the number of bytes freed (or 0 if unknown). The returned function unregisters the callback and is safe to call more than once.

type Level

type Level uint8

Level represents a Darwin memory-pressure state.

const (
	// Normal indicates system memory pressure has returned to normal.
	Normal Level = iota
	// Warn indicates elevated memory pressure; caches should shed non-essential memory.
	Warn
	// Critical indicates severe memory pressure; jetsam termination is imminent
	// unless the process drops memory promptly.
	Critical
)

func (Level) String

func (l Level) String() string

String returns the lowercase name of l.

type Report

type Report struct {
	Level           Level
	FreedBytes      uint64
	FootprintBefore uint64
	FootprintAfter  uint64
	OldMemoryLimit  int64
	NewMemoryLimit  int64
}

Report summarizes one memory-pressure response executed by a Controller.

type Stats

type Stats struct {
	PhysFootprint uint64 // task_info(TASK_VM_INFO).phys_footprint (jetsam ledger)
	ResidentSize  uint64 // task_info(TASK_VM_INFO).resident_size
	VirtualSize   uint64 // task_info(TASK_VM_INFO).virtual_size
	MaxRSS        uint64 // getrusage(RUSAGE_SELF).ru_maxrss (bytes on macOS)
}

Stats holds kernel-reported memory accounting for the current process.

func Snapshot

func Snapshot() (Stats, error)

Snapshot reads the current process's Mach VM accounting and rusage max RSS.

Example
package main

import (
	"fmt"

	"github.com/tmc/apple/x/mempressure"
)

func main() {
	st, err := mempressure.Snapshot()
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println(st.PhysFootprint > 0, st.ResidentSize > 0, st.VirtualSize > 0, st.MaxRSS > 0)

}
Output:
true true true true

type Watcher

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

Watcher receives live Darwin memory-pressure notifications from a DISPATCH_SOURCE_TYPE_MEMORYPRESSURE source.

The zero value is not usable; construct a Watcher with NewWatcher and call Watcher.Close when done.

func NewWatcher

func NewWatcher(handler func(Level)) *Watcher

NewWatcher creates an active Watcher that invokes handler on Darwin memory-pressure transitions (Normal, Warn, Critical).

Callbacks are serialized on a dedicated dispatch queue and with calls to Watcher.Notify. A nil handler is allowed and still updates Watcher.Level.

func (*Watcher) Close

func (w *Watcher) Close() error

Close cancels the underlying dispatch memory-pressure source and prevents further handler invocations. It is safe to call more than once.

func (*Watcher) Level

func (w *Watcher) Level() Level

Level returns the most recently observed or simulated pressure level.

func (*Watcher) Notify

func (w *Watcher) Notify(level Level)

Notify synchronously delivers a synthetic pressure event to the watcher's handler. It is a no-op if the watcher has been closed.

Example
package main

import (
	"fmt"

	"github.com/tmc/apple/x/mempressure"
)

func main() {
	w := mempressure.NewWatcher(func(level mempressure.Level) {
		fmt.Println("pressure:", level)
	})
	defer w.Close()

	w.Notify(mempressure.Warn)
	w.Notify(mempressure.Normal)
	fmt.Println("current:", w.Level())

}
Output:
pressure: warn
pressure: normal
current: normal

Jump to

Keyboard shortcuts

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