Documentation
¶
Overview ¶
Package memory owns opt-in application memory admission. It consumes cached physical usage samples; callers reserve forecast growth before allocating and release it when the owned work ends. This is a soft limit, not an allocator or kernel OOM boundary.
Author: #1683 implementation lane (Codex), 2026-11-01.
Index ¶
- Variables
- func HTTPHeaderWireBytes(header http.Header) int64
- func HTTPRequestWireBytes(r *http.Request) int64
- func HandleHTTPRequest(policy *Policy, w http.ResponseWriter, r *http.Request, ...)
- func ReleaseRetainedCaches(policy *Policy, forecast int64)
- func RuntimeLiveHeapHeadroom() int64
- func WireSize(parts ...int64) int64
- type Budget
- type HTTPWireOptions
- type Lease
- type Policy
- type PolicyOption
- type RetainedCache
- type Sample
- type WireRequest
- func (w *WireRequest) Close()
- func (w *WireRequest) Context(ctx context.Context) context.Context
- func (w *WireRequest) Grow(parts ...int64) error
- func (w *WireRequest) Move() *WireRequest
- func (w *WireRequest) Reset()
- func (w *WireRequest) RetainHandler(next http.Handler) http.Handler
- func (w *WireRequest) Run(consume func() error) error
- func (w *WireRequest) WireLimit() (int64, error)
Constants ¶
This section is empty.
Variables ¶
var ( // ErrStaleSample means an enabled policy has no fresh physical reading. ErrStaleSample = errors.New("memory usage reading unavailable or stale") // ErrLimitExceeded means the requested reservation exceeds soft capacity. ErrLimitExceeded = errors.New("application memory soft limit exceeded") )
Functions ¶
func HTTPHeaderWireBytes ¶
HTTPHeaderWireBytes counts decoded header fields. Request trailers may only be inspected after Body.Read returns EOF, when net/http has published them.
func HTTPRequestWireBytes ¶
HTTPRequestWireBytes counts the request line, host, headers and query string. A body-size cap is independent of these bytes and must not clamp them.
func HandleHTTPRequest ¶
func HandleHTTPRequest(policy *Policy, w http.ResponseWriter, r *http.Request, options HTTPWireOptions, reject func(http.ResponseWriter, *http.Request, error), next http.Handler)
HandleHTTPRequest owns admission until the consumer actually returns, even after cancellation or upgrade. Delegated consumers borrow the context owner instead of creating another reservation. reject writes the caller's existing transient memory response, including failures discovered during body reads.
func ReleaseRetainedCaches ¶
ReleaseRetainedCaches runs before the existing application admission decision and from the runtime observer. It never collects, waits for a query lease, or changes a policy's sample/reservation arithmetic.
func RuntimeLiveHeapHeadroom ¶
func RuntimeLiveHeapHeadroom() int64
RuntimeLiveHeapHeadroom preserves the search build queue's existing post-collection live-heap reservation contract. Both consumers observe the same applied runtime limit; this projection is not a pressure measurement.
Types ¶
type Budget ¶
type Budget struct {
Source string
Used int64
Limit int64
Headroom int64
Available int64
Fresh bool
}
Budget describes an existing memory boundary, not a separately configured cache limit. Runtime usage includes Go's heap, stacks and runtime metadata. Application usage retains Policy's physical sample/ancestor semantics.
func RuntimeBudget ¶
func RuntimeBudget() Budget
RuntimeBudget observes the limit already installed by configuration (including NORNICDB_MEMORY_LIMIT and GOMEMLIMIT). No limit is installed or changed here.
type HTTPWireOptions ¶
type HTTPWireOptions struct {
MaxBodyBytes int64
LimitBody bool
// MetadataOnly runs before middleware; body guards belong to the actual
// decoder worker, which can outlive a timeout response.
MetadataOnly bool
}
HTTPWireOptions preserves a caller's existing body cap independently of admission. Without LimitBody, streamed bytes are bounded only by the policy.
type Lease ¶
type Lease struct {
// contains filtered or unexported fields
}
Lease owns one atomic forecast reservation. Release is idempotent because failure, cancellation and normal cleanup can converge at a session owner.
func (*Lease) GrowWireRequest ¶
GrowWireRequest extends a ReserveWireRequest lease to cover the accumulated wire size, before a transport grows its input buffer. It charges only the increase and rechecks fresh physical capacity even within the minimum forecast. The caller keeps this lease through decode/setup and releases it on success, rejection, disconnect or cancellation.
func (*Lease) Release ¶
func (l *Lease) Release()
Release returns a forecast when its owner has completed cleanup.
func (*Lease) WireLimit ¶
WireLimit returns the largest accumulated wire size this lease can currently cover, including its existing charge. Streaming transports use this as a read-limit snapshot and still grow/recheck the lease before accumulating bytes. Zero means the application policy is disabled.
type Policy ¶
type Policy struct {
// contains filtered or unexported fields
}
Policy is the single application admission owner. It does not poll from execution loops; an external periodic worker calls Refresh.
func NewPolicy ¶
func NewPolicy(limit, headroom int64, freshness time.Duration, sampler func() (Sample, error), now func() time.Time, options ...PolicyOption) *Policy
NewPolicy constructs an opt-in application policy. A nonpositive limit disables sampling and admission. Headroom is held below both the operator limit and a known container ceiling.
func (*Policy) Refresh ¶
Refresh publishes a reading after the sampler succeeds. Quiescent readings update the persistent baseline; active reservations are never learned into it as though they were persistent resources. After physical pressure rejects work, the sampler may reclaim idle heap pages and remeasure, subject to the recovery cooldowns for completed admitted work and unleased allocations.
func (*Policy) Reserve ¶
Reserve atomically checks cached physical pressure and all outstanding forecasts. Adding both is conservative while an allocation may already appear in the physical sample, but prevents unrelated growth during active work from silently spending the same headroom twice.
func (*Policy) ReserveWireRequest ¶
ReserveWireRequest forecasts decode and parser expansion for an incoming message. Unknown-size streams grow this same reservation before accumulating bytes. A transport may also impose its own size bound. This forecast is not a precise bound on allocations made by a decoder.
type PolicyOption ¶
type PolicyOption func(*Policy)
PolicyOption configures one policy at construction, before its sampler starts.
func WithRecoveryTimings ¶
func WithRecoveryTimings(interval, rearm time.Duration) PolicyOption
WithRecoveryTimings sets the minimum reclamation spacing and unleased rearm. Timings must be at least one millisecond, with rearm >= interval; invalid programmatic options panic. Startup configuration is validated before use.
type RetainedCache ¶
type RetainedCache struct {
// contains filtered or unexported fields
}
RetainedCache is a lifecycle registration for optional, reconstructible data. Its release callback detaches installed ownership; active request data may finish its admitted work but cannot be republished by that generation.
func RegisterRetainedCache ¶
func RegisterRetainedCache(policy *Policy, release func(Budget)) *RetainedCache
RegisterRetainedCache binds an optional copy to the existing admission owner. The process observer exists only while live registrations exist. Weak entries cannot extend a database/service lifetime, including callers that omit Close.
func (*RetainedCache) Admission ¶
func (c *RetainedCache) Admission(growth int64, refill bool) (Budget, bool)
Admission returns the strictest existing budget for this cache. growth is a forecast for the optional data only; it never reserves or denies query work. The caller selects refill hysteresis when recovering from an earlier release.
func (*RetainedCache) Close ¶
func (c *RetainedCache) Close()
Close unregisters this cache. Its owner releases its own data at shutdown.
type Sample ¶
type Sample struct {
Used int64
Ceiling int64
// Headroom is the tightest limit-minus-usage across the cgroup hierarchy.
Headroom int64
HasHeadroom bool
}
Sample is one physical observation. Used includes all members and file cache of a shared cgroup; Ceiling is its effective hard limit, if known.
func CgroupSample ¶
CgroupSample obtains one Linux cgroup observation. A missing usage file is an unavailable reading rather than a permissive zero. The effective hard limit is included when the cgroup exposes one.
type WireRequest ¶
type WireRequest struct {
// contains filtered or unexported fields
}
WireRequest owns a pre-decode reservation across reads, setup and cleanup. Run defers cleanup on return or panic; retained workers finish their credit. Move explicitly transfers ownership to a queue; Reset ends one message in a longer-lived transport.
func NewWireRequest ¶
func NewWireRequest(policy *Policy) *WireRequest
NewWireRequest starts an empty, lazily reserved request. Disabled admission uses a nil owner so the existing fast path requires no allocation.
func WireRequestFromContext ¶
func WireRequestFromContext(ctx context.Context) *WireRequest
WireRequestFromContext borrows an enclosing request's reservation owner.
func (*WireRequest) Close ¶
func (w *WireRequest) Close()
Close ends the outer scope; any retained decoder worker must also finish before the reservation is returned. Cleanup is safe to repeat concurrently.
func (*WireRequest) Context ¶
func (w *WireRequest) Context(ctx context.Context) context.Context
Context passes the same owner to delegated consumers without transferring cleanup. Only the enclosing Run releases the request's reservation.
func (*WireRequest) Grow ¶
func (w *WireRequest) Grow(parts ...int64) error
Grow reserves the full known wire size before it is decoded or accumulated.
func (*WireRequest) Move ¶
func (w *WireRequest) Move() *WireRequest
Move transfers the reservation once, leaving the caller's deferred Close safe.
func (*WireRequest) Reset ¶
func (w *WireRequest) Reset()
Reset releases a completed frame before waiting for another one.
func (*WireRequest) RetainHandler ¶
func (w *WireRequest) RetainHandler(next http.Handler) http.Handler
RetainHandler pins this owner before an asynchronous HTTP worker is started. Its credit remains available for body reads after a timeout response returns, and is released only after both the outer request and worker have ended.
func (*WireRequest) Run ¶
func (w *WireRequest) Run(consume func() error) error
Run keeps the reservation through the complete consumer callback.
func (*WireRequest) WireLimit ¶
func (w *WireRequest) WireLimit() (int64, error)
WireLimit is the current capacity for all wire components in this request.