diff --git a/OpenSim/Framework/OglBudgetedLruCache.cs b/OpenSim/Framework/OglBudgetedLruCache.cs index bd8cf90f..7a0d8efb 100644 --- a/OpenSim/Framework/OglBudgetedLruCache.cs +++ b/OpenSim/Framework/OglBudgetedLruCache.cs @@ -142,6 +142,45 @@ namespace OpenSim.Framework return RemoveCore(key); } + /// + /// Releases only disposable LRU entries down to the requested byte target. + /// Does not force a GC, alter authoritative assets, or block on I/O. + /// + public int TrimToBytes(long targetBytes) + { + if (targetBytes < 0) throw new ArgumentOutOfRangeException(nameof(targetBytes)); + lock (m_Sync) + { + if (m_Disposed) return 0; + int removed = 0; + while (m_Bytes > targetBytes && m_Lru.Last != null) + { + if (RemoveCore(m_Lru.Last.Value)) + removed++; + } + return removed; + } + } + + /// + /// Low-frequency optional high-memory-pressure relief. MemoryLoadBytes + /// and TotalAvailableMemoryBytes come from GC.GetGCMemoryInfo. + /// This is deliberately hysteresis-free on allocation: no background + /// repopulation, no GC. Refill uses normal bounded cache behavior. + /// + public int TrimForMemoryPressure(long memoryLoadBytes, long totalAvailableBytes, + int thresholdPercent = 85, int targetCachePercent = 50) + { + if (totalAvailableBytes <= 0 || memoryLoadBytes < 0 || + thresholdPercent < 1 || thresholdPercent > 100 || + targetCachePercent < 0 || targetCachePercent > 100) + return 0; + + if (100.0 * memoryLoadBytes / totalAvailableBytes < thresholdPercent) + return 0; + return TrimToBytes(m_MaxBytes * targetCachePercent / 100); + } + public void Clear() { lock (m_Sync) diff --git a/OpenSim/Region/CoreModules/Asset/FlotsamAssetCache.cs b/OpenSim/Region/CoreModules/Asset/FlotsamAssetCache.cs index c9b8f70f..9527a632 100644 --- a/OpenSim/Region/CoreModules/Asset/FlotsamAssetCache.cs +++ b/OpenSim/Region/CoreModules/Asset/FlotsamAssetCache.cs @@ -110,6 +110,12 @@ namespace OpenSim.Region.CoreModules.Asset private OglBudgetedLruCache m_BudgetedMemoryCache; private int m_MemoryCacheMaxMiB = 0; private int m_MemoryCacheMaxEntries = 8192; + // Optional RAM relief under high .NET GC memory load, disabled by default. + private bool m_MemoryPressureTrimEnabled; + private int m_MemoryPressureTrimThresholdPercent = 85; + private int m_MemoryPressureTrimTargetPercent = 50; + private System.Threading.Timer m_MemoryPressureTrimTimer; + private long m_MemoryPressureTrimmed; private ExpiringKey m_negativeCache; private bool m_negativeCacheEnabled = true; @@ -214,6 +220,14 @@ namespace OpenSim.Region.CoreModules.Asset assetConfig.GetInt("MemoryCacheMaxMiB", m_MemoryCacheMaxMiB), 0, 16384); m_MemoryCacheMaxEntries = Math.Clamp( assetConfig.GetInt("MemoryCacheMaxEntries", m_MemoryCacheMaxEntries), 1, 65536); + m_MemoryPressureTrimEnabled = assetConfig.GetBoolean( + "MemoryPressureTrimEnabled", m_MemoryPressureTrimEnabled); + m_MemoryPressureTrimThresholdPercent = Math.Clamp( + assetConfig.GetInt("MemoryPressureTrimThresholdPercent", + m_MemoryPressureTrimThresholdPercent), 70, 99); + m_MemoryPressureTrimTargetPercent = Math.Clamp( + assetConfig.GetInt("MemoryPressureTrimTargetPercent", + m_MemoryPressureTrimTargetPercent), 10, 90); m_MemoryExpiration = assetConfig.GetDouble("MemoryCacheTimeout", m_MemoryExpiration); m_MemoryExpiration *= 3600.0; // config in hours to seconds @@ -323,6 +337,8 @@ namespace OpenSim.Region.CoreModules.Asset m_AdaptiveFileWriteGate?.Dispose(); m_WeakReferencePruneTimer?.Dispose(); m_WeakReferencePruneTimer = null; + m_MemoryPressureTrimTimer?.Dispose(); + m_MemoryPressureTrimTimer = null; m_BudgetedMemoryCache?.Dispose(); } } @@ -366,6 +382,8 @@ namespace OpenSim.Region.CoreModules.Asset // No active scenes: release the opt-in RAM cache now // instead of pinning stale assets until the next TTL. m_BudgetedMemoryCache?.Clear(); + m_MemoryPressureTrimTimer?.Dispose(); + m_MemoryPressureTrimTimer = null; m_WeakReferencePruneTimer?.Dispose(); m_WeakReferencePruneTimer = null; m_AdaptiveFileWriteTimer?.Dispose(); @@ -427,6 +445,16 @@ namespace OpenSim.Region.CoreModules.Asset SampleAdaptiveFileWritePressure, null, interval, interval); } + if (m_MemoryPressureTrimEnabled && + m_BudgetedMemoryCache != null && + m_MemoryPressureTrimTimer == null) + { + // Slow, independent of scene heartbeat and asset hot paths. + TimeSpan memoryInterval = TimeSpan.FromSeconds(30); + m_MemoryPressureTrimTimer = new System.Threading.Timer( + SampleMemoryPressure, null, memoryInterval, memoryInterval); + } + if (m_WeakReferencePruneSeconds > 0 && m_WeakReferencePruneTimer == null) { @@ -483,6 +511,30 @@ namespace OpenSim.Region.CoreModules.Asset } } + private void SampleMemoryPressure(object unused) + { + OglBudgetedLruCache cache = m_BudgetedMemoryCache; + if (!m_MemoryPressureTrimEnabled || cache == null) + return; + + try + { + // No forced GC and no authority over the real asset store. + GCMemoryInfo memory = GC.GetGCMemoryInfo(); + int trimmed = cache.TrimForMemoryPressure( + memory.MemoryLoadBytes, memory.TotalAvailableMemoryBytes, + m_MemoryPressureTrimThresholdPercent, + m_MemoryPressureTrimTargetPercent); + if (trimmed > 0) + Interlocked.Add(ref m_MemoryPressureTrimmed, trimmed); + } + catch (Exception error) + { + m_log.Warn("[FLOTSAM ASSET CACHE]: Optional RAM-pressure sample skipped: " + + error.GetType().Name); + } + } + private void SampleAdaptiveFileWritePressure(object unused) { if (m_AdaptiveFileWriteGate == null) @@ -1637,9 +1689,15 @@ namespace OpenSim.Region.CoreModules.Asset m_BudgetedMemoryCache.Count, m_BudgetedMemoryCache.EstimatedBytes / (1024 * 1024), m_MemoryCacheMaxMiB); - else if (m_MemoryCacheEnabled) + if (m_MemoryPressureTrimEnabled && m_BudgetedMemoryCache != null) + con.Output( + "[FLOTSAM ASSET CACHE] RAM pressure trim: enabled at {0}% GC load, LRU target {1}% of budget; {2} assets evicted", + m_MemoryPressureTrimThresholdPercent, + m_MemoryPressureTrimTargetPercent, + Interlocked.Read(ref m_MemoryPressureTrimmed)); + if (m_MemoryCacheEnabled && m_BudgetedMemoryCache == null) con.Output("[FLOTSAM ASSET CACHE] Memory Cache: {0} assets", m_MemoryCache.Count); - else + else if (!m_MemoryCacheEnabled) con.Output("[FLOTSAM ASSET CACHE] Memory cache disabled"); if (m_FileCacheEnabled) diff --git a/bin/config-include/FlotsamCache.ini.example b/bin/config-include/FlotsamCache.ini.example index 5dbc15c0..0d435e43 100644 --- a/bin/config-include/FlotsamCache.ini.example +++ b/bin/config-include/FlotsamCache.ini.example @@ -32,6 +32,16 @@ MemoryCacheMaxMiB = 0 MemoryCacheMaxEntries = 8192 + ; Optional G1.1 high-memory-pressure relief for the byte-budgeted LRU. + ; Effective only when MemoryCacheEnabled=true and MemoryCacheMaxMiB>0. + ; Every 30 seconds, check .NET GC memory load; if >=85% trim only + ; disposable RAM-cache entries down to 50% of the configured cache budget. + ; Does not force GC, modify authoritative asset storage, or cap whole-process RSS. + ; Remains OFF unless explicitly activated in the loaded [AssetCache] section. + MemoryPressureTrimEnabled = false + MemoryPressureTrimThresholdPercent = 85 + MemoryPressureTrimTargetPercent = 50 + ; Optional dead weak-reference key reclamation for long-lived regions. ; Weak asset targets already allow GC, but UUID string keys in the ; reference dictionary otherwise persist until cache clear/deep scan. diff --git a/doc/OpenGenesisLINK/OGL_PERFORMANCE_ENGINE_1_1_RAM_PRESSURE.md b/doc/OpenGenesisLINK/OGL_PERFORMANCE_ENGINE_1_1_RAM_PRESSURE.md new file mode 100644 index 00000000..385e2716 --- /dev/null +++ b/doc/OpenGenesisLINK/OGL_PERFORMANCE_ENGINE_1_1_RAM_PRESSURE.md @@ -0,0 +1,62 @@ +# OpenGenesisLINK Generation 1 – OGL Performance Engine: RAM-Pressure Trim + +**Status:** opt-in, konservativer RAM-Entlastungsblock. Keine Aenderung an +Physics, 55-FPS-Normalisierung, Region-Scheduling oder Runtime-GC. + +## Problem und Umsetzung + +Der mit PR #416 eingefuehrte Flotsam-LRU haelt zwischengespeicherte Assets +innerhalb des konfigurierten RAM-Budgets bis zum Ablauf ihrer TTL oder +bis zur LRU-Verdraengung. Bei hoher System-Speicherlast +kann dieser optionale Cache entbehrliche Payloads vorzeitig freigeben. + +Mit `MemoryPressureTrimEnabled=true` ueberprueft ein Timer alle 30 Sekunden +die von .NET ueber `GC.GetGCMemoryInfo()` gemeldete GC-Speicherlast. +Ab `MemoryPressureTrimThresholdPercent` (Default 85 %) werden ausschliesslich +die am laengsten nicht verwendeten Eintraege aus dem **optional aktivierten, +byte-begrenzten Flotsam-RAM-LRU** entfernt, bis maximal +`MemoryPressureTrimTargetPercent` (Default 50 %) des konfigurierten +`MemoryCacheMaxMiB`-Budgets belegt ist. + +- Die Quelle ist die GC-MemoryLoad-Schaetzung, **nicht** eine Messung des + gesamten Linux-RAM-Verbrauchs oder der RSS dieser Node. +- Kein `GC.Collect()`, keine Aenderung des GC-Modus und kein Zugriff auf + die autoritativen Assets, den Disk-Cache oder die laufende Physik. +- Der Timer ist nur bei aktivem byte-begrenzten RAM-Cache vorhanden. + Beim Entfernen der letzten Region wird er entsorgt; beim Neustart einer + Region kann er erneut gestartet werden. +- Ohne ausdrueckliches Opt-in bleibt das bisherige Cache-Verhalten + unveraendert. Die Cache-Abfragen bleiben synchronisiert und die + LRU-Entfernung greift nur auf kurz gesperrte interne Metadaten zu. +- Der Status `fcache status` meldet bei aktivierter Funktion + Schwelle, Zielbudget und die Zahl der aus dem Cache entfernten Assets. + +## Beispiel fuer eine Test-Node + +In **der geladenen** `[AssetCache]`-Sektion (nicht nur in einer +`.ini.example`-Datei): + +```ini +[AssetCache] + MemoryCacheEnabled = true + MemoryCacheMaxMiB = 256 + MemoryCacheMaxEntries = 8192 + MemoryPressureTrimEnabled = true + MemoryPressureTrimThresholdPercent = 85 + MemoryPressureTrimTargetPercent = 50 +``` + +Die Schwelle wird auf 70..99 % und das Ziel auf 10..90 % begrenzt. +Ein hoher Schwellenwert fuehrt nicht automatisch zu geringerer +Gesamtprozess-RSS: Im Cache koennen nur eigene starke Referenzen geloest +werden; andere Referenzen und die .NET-GC-Freigabe bleiben separat. + +## Abnahme + +Die `OglPerformanceEngineRegression` prueft die Schwelle, ungueltige +Drucksamples, LRU-Verdrängungsreihenfolge und fehlende Uebertrimmung. +Vor produktiver Aktivierung bitte in einem isolierten Simulator die +Speicher-/GC-Metriken, Cache-Hit-Rate und Asset-Ladezeit unter gleicher +Mesh-/Texturlast mit und ohne Trim vergleichen. Entlastung gegen hoehere +Cache-Miss-Rate abwaegen. Das ist kein automatisches Optimieren +aller Prozessspeicher und keine CPU-Kern-Parallelisierung. diff --git a/tools/ci/OglPerformanceEngineRegression/Program.cs b/tools/ci/OglPerformanceEngineRegression/Program.cs index bc1120bb..40558a53 100644 --- a/tools/ci/OglPerformanceEngineRegression/Program.cs +++ b/tools/ci/OglPerformanceEngineRegression/Program.cs @@ -98,6 +98,35 @@ static class Program "zero TTL must preserve non-expiring legacy semantics"); } + // High GC memory load must release only least-recently-used disposable + // RAM entries; normal pressure and invalid samples leave cache intact. + using (var cache = new OglBudgetedLruCache( + 1000, 5, value => value.LongLength)) + { + Require(cache.AddOrUpdate("a", new byte[300], TimeSpan.FromMinutes(5)), + "pressure fixture a"); + Require(cache.AddOrUpdate("b", new byte[300], TimeSpan.FromMinutes(5)), + "pressure fixture b"); + Require(cache.AddOrUpdate("c", new byte[300], TimeSpan.FromMinutes(5)), + "pressure fixture c"); + Require(cache.TryGetValue("a", out _), "pressure fixture must update LRU order"); + Require(cache.TrimForMemoryPressure(84, 100, 85, 50) == 0 && + cache.EstimatedBytes == 900, + "normal pressure should not trim the RAM cache"); + Require(cache.TrimForMemoryPressure(100, 0) == 0 && + cache.TrimForMemoryPressure(-1, 100) == 0, + "unavailable/invalid GC pressure must not evict assets"); + Require(cache.TrimForMemoryPressure(90, 100, 85, 50) == 2 && + cache.Count == 1 && cache.EstimatedBytes == 300 && + cache.Contains("a") && !cache.Contains("b") && !cache.Contains("c"), + "high pressure must evict oldest RAM assets to half budget"); + Require(cache.TrimForMemoryPressure(90, 100, 85, 50) == 0, + "repeated pressure sampling must not overtrim below target"); + Require(cache.TrimToBytes(0) == 1 && cache.Count == 0 && + cache.EstimatedBytes == 0, + "explicit zero target must release all disposable entries"); + } + using (var cache = new OglBudgetedLruCache( 4096, 8, value => value.LongLength)) {