MemoryPressureHandler class

Handles memory pressure by clearing caches.

Usage:

// Register caches to be cleared under pressure
MemoryPressureHandler.registerCache('fileMetrics', FileMetricsCache.clearCache);

// Check periodically (e.g., every 100 files)
MemoryPressureHandler.checkAndRelieve();

// Or set up automatic threshold-based clearing
MemoryPressureHandler.enableAutoRelief(thresholdMb: 500);

Properties

hashCode → int
The hash code for this object.
no setterinherited
runtimeType → Type
A representation of the runtime type of the object.
no setterinherited

Methods

noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
toString() → String
A string representation of this object.
inherited

Operators

operator ==(Object other) → bool
The equality operator.
inherited

Static Properties

consecutiveTripsForTesting → int
Test-only read of the consecutive-trip counter. See _consecutiveTrips.
no setter
currentRecheckIntervalForTesting → Duration
Test-only read of the current backoff-widened recheck interval. See _currentRecheckInterval.
no setter
estimateCallCountForTesting → int
Test-only read of the cache-walk counter. See _estimateCallCount.
no setter
hardRssLimitMb → int
The configured hard RSS cap in MB, or 0 if disabled. Used by FileBudgetTracker to compute its file-skipping threshold.
no setter
isOverHardLimit → bool
Whether the process RSS is currently over the hard cap, meaning rule execution should pause. Self-samples the real RSS on a throttle so callers can invoke it on the hot per-node path without a syscall every time.
no setter
onShedLevelChanged ↔ void Function(int shedLevel, int rssMb)?
Callback invoked when the shed level changes. Set by the plugin at startup to write the memory state file for the VS Code extension. Nullable so the core library has no hard dependency on IO/extension code.
getter/setter pair
physicalMemoryProbeCountForTesting → int
How many times the physical-RAM probe has actually been attempted.
no setter
shedLevel → int
Public getter for the current shed level. Read by SaropaContext's _wrapCallback on the hot per-node path — must be a simple field read.
no setter
shedRuleCount → int
Count of rules currently shed. Cheaper than copying the set.
no setter
shedRuleNames → Set<String>
Snapshot of shed rule names for diagnostics and extension communication.
no setter

Static Methods

adaptiveRssCapForTesting(int fallbackMb, int ramMb) → int
Test-only bridge to the adaptive-cap computation, so the caching fix can be pinned at the real call site rather than only at the probe.
checkAndRelieve() → bool
Check memory pressure and relieve if needed.
clearAll() → void
Force clear all registered caches.
disableAutoRelief() → void
Disable automatic memory relief.
enableAutoRelief({int thresholdMb = 512, int checkIntervalFiles = 50}) → void
Enable automatic memory relief.
enableShedding() → void
Arm graduated rule shedding. Called from the native plugin's config loader (shed_rules: true in analysis_options_custom.yaml, or the legacy SAROPA_LINTS_SHED_RULES=true env var) once the user opts in.
getShedDetails() → Map<String, dynamic>
Detailed breakdown of currently shed rules for extension telemetry. Groups shed rules by category (typeResolving, highCost, infoSeverity, warningSeverity) so the user can see exactly what coverage was lost. Only called on shed-level transitions — not on the hot path.
getStats() → Map<String, dynamic>
Get statistics including process RSS and cache breakdown.
isRuleShed(String ruleName) → bool
Whether ruleName is currently shed due to memory pressure. Called from SaropaContext._wrapCallback on the hot per-node path — the Set lookup is O(1) and the _shedLevel short-circuit avoids the lookup when no shedding is active.
recordFileProcessed() → void
Record that a file was processed (for auto-relief timing).
refreshForTesting() → void
Runs the real RSS refresh (including the periodic memory-log write) on demand. Test-only — production code reaches _refreshHardLimit only via isOverHardLimit's call-count throttle, which a test would otherwise have to drive 200+ times just to exercise the log line.
registerCache(String name, void clearFunction(), {int priority = 50}) → void
Register a cache to be cleared under memory pressure.
registerEstimator(String name, int estimator()) → void
Register a named callback that returns estimated bytes for memory not directly visible to this library (cross-library trackers). The estimate is included in _estimateMemoryUsageMb and therefore influences soft auto-relief decisions.
registerRuleCosts({required Set<String> typeResolving, required Set<String> highCost}) → void
Register cost metadata for cost-aware shedding. typeResolving lists rules that declare usesTypeResolution => true; highCost lists rules with RuleCost.high or RuleCost.extreme. Called once at startup alongside registerRuleSeverities.
registerRuleSeverities(Map<String, int> severities) → void
Register the severity of each active rule so the shed mechanism can filter by severity without instantiating rules at shedding time. Called once at plugin startup after rule registration.
relieve({bool clearAll = false}) → void
Clear caches to relieve memory pressure.
resetEstimateCallCountForTesting() → void
Test-only reset of the cache-walk counter. See _estimateCallCount.
resetMemoryLogCooldownForTesting() → void
Resets the periodic memory-log cooldown so the next refreshForTesting or isOverHardLimit refresh is guaranteed to log. Test-only.
resetPhysicalMemoryProbeForTesting({bool forceFailure = false}) → void
Clear the memoized RAM value and probe counter. forceFailure makes the probe report "unavailable" without touching the platform, so the cached- failure path is testable on a machine where detection would succeed. Tests MUST reset this in tearDown — a leaked true would make every later cap computation fall back to the fixed default.
resetShedStateForTesting() → void
Reset all soft-limit, shedding, and attribution state. Test-only — clears the soft flag, shed level, shed rule names, attribution tracking, and cost metadata so tests start clean.
setHardLimitTrippedForTest(bool value) → void
Force the hard-limit-tripped flag for testing. Production code should never call this — use setHardRssLimitMb to arm the real valve instead. This exists because tests can't control the real process RSS, so the end-to-end eviction path needs a way to simulate the trip.
setHardRssLimitMb(int mb) → void
Set the hard RSS cap (MB). 0 or negative disables the valve.
setPanicRssLimitMbForTest(int mb) → void
Test-only override of the OOM panic threshold (MB); 0 disables it. Production derives this from system RAM in initializeCacheManagement. Tests cannot control real process RSS, so this is the only way to pin that panic still bypasses attribution on both the trip and release paths.
setShedLevelForTest(int level) → void
Force the shed level for testing. Allows end-to-end shedding tests without real RSS pressure. Levels: 0=none, 1=expensive, 2=+INFO, 3=+WARNING.
setSoftLimitTrippedForTest(bool value) → void
Force the soft-limit-tripped flag for testing. Allows tests to simulate memory pressure without controlling real process RSS.
totalPhysicalMemoryMbForTesting() → int
Test-only bridge to the memoized physical-RAM probe. The probe and its cache are library-private top-level members, which a test outside this library cannot name; this static on a public class is the only handle.
unregisterCache(String name) → void
Unregister a cache.

Constants

maxShedLevel → const int
Highest supported shed level. Single source of truth for clamp bounds, escalation branches, and test helpers.