From db06ec4a8d9f6e3cf2dd7ce443bd17cab3390ef1 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 19 May 2026 20:23:45 +0100 Subject: [PATCH] Add score-cost fractal residency eviction --- docs/perfect-machine-architecture.md | 6 ++- .../fractal-brush-implementation-roadmap.md | 4 +- .../Lod/FractalResidencyPlan.cs | 6 ++- .../Lod/FractalResidencyPlanner.cs | 49 +++++++++++++++++-- .../Lod/FractalResourceBudgetPlanner.cs | 2 +- src/Aquarium.Zyphos/ZyphosFractalTerrain.cs | 1 + state/evidence.jsonl | 1 + state/map.yaml | 1 + state/memory.json | 1 + .../FractalResidencyPlannerTests.cs | 37 ++++++++++++++ .../ZyphosFractalTerrainTests.cs | 1 + 11 files changed, 99 insertions(+), 10 deletions(-) diff --git a/docs/perfect-machine-architecture.md b/docs/perfect-machine-architecture.md index 21bbc05..41b6c85 100644 --- a/docs/perfect-machine-architecture.md +++ b/docs/perfect-machine-architecture.md @@ -501,8 +501,10 @@ confidence decay, stale uncertainty growth, and convergence telemetry. Current state: `FractalOccupancyGraph` now owns per-node contribution state, last visible frame, last observed score, and update probability. The contribution cache routes through this graph, and unobserved nodes decay -confidence while stale uncertainty grows. Convergence telemetry and richer -resource-tier residency fields remain open. +confidence while stale uncertainty grows. Residency planning now keeps resident +payloads by score-per-cost and emits eviction decisions for low-value expensive +payloads. Convergence telemetry and richer resource-tier residency fields remain +open. ### Phase E: 2D SDF Tile Backend diff --git a/research/rendering/fractal-brush-implementation-roadmap.md b/research/rendering/fractal-brush-implementation-roadmap.md index 125721f..01477e9 100644 --- a/research/rendering/fractal-brush-implementation-roadmap.md +++ b/research/rendering/fractal-brush-implementation-roadmap.md @@ -406,7 +406,7 @@ Tasks: page metadata. - [x] Add fake payload store with resident/missing states. - [x] Add child request queue. -- [ ] Add score/cost eviction policy. +- [x] Add score/cost eviction policy. - [x] Add parent-summary fallback path. - [x] Clamp simulated RAM residency and SSD requests through the resource plan. - [x] Add debug channels: residency, requests, evictions. @@ -415,7 +415,7 @@ Tests: - [x] missing child renders parent summary; - [x] high-score missing child enqueues request; -- low-score high-cost payload evicts first; +- [x] low-score high-cost payload evicts first; - [x] frame path never blocks on fake store. Exit gate: diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalResidencyPlan.cs b/src/Aquarium.Engine.Fractal/Lod/FractalResidencyPlan.cs index 3f6bcd8..68aff73 100644 --- a/src/Aquarium.Engine.Fractal/Lod/FractalResidencyPlan.cs +++ b/src/Aquarium.Engine.Fractal/Lod/FractalResidencyPlan.cs @@ -7,11 +7,13 @@ public sealed class FractalResidencyPlan public FractalResidencyPlan( IReadOnlyList residentNodes, IReadOnlyList summaryFallbackNodes, - IReadOnlyList requestedNodes) + IReadOnlyList requestedNodes, + IReadOnlyList? evictedNodes = null) { ResidentNodes = residentNodes; SummaryFallbackNodes = summaryFallbackNodes; RequestedNodes = requestedNodes; + EvictedNodes = evictedNodes ?? []; } public IReadOnlyList ResidentNodes { get; } @@ -19,4 +21,6 @@ public sealed class FractalResidencyPlan public IReadOnlyList SummaryFallbackNodes { get; } public IReadOnlyList RequestedNodes { get; } + + public IReadOnlyList EvictedNodes { get; } } diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalResidencyPlanner.cs b/src/Aquarium.Engine.Fractal/Lod/FractalResidencyPlanner.cs index 46c2e1b..6469a2d 100644 --- a/src/Aquarium.Engine.Fractal/Lod/FractalResidencyPlanner.cs +++ b/src/Aquarium.Engine.Fractal/Lod/FractalResidencyPlanner.cs @@ -14,8 +14,19 @@ public static class FractalResidencyPlanner IFractalPayloadStore payloadStore, int maxRequests, int maxResidentNodes) + { + return Plan(selectedCut, [], payloadStore, maxRequests, maxResidentNodes); + } + + public static FractalResidencyPlan Plan( + IReadOnlyList selectedCut, + IReadOnlyList summaries, + IFractalPayloadStore payloadStore, + int maxRequests, + int maxResidentNodes) { ArgumentNullException.ThrowIfNull(selectedCut); + ArgumentNullException.ThrowIfNull(summaries); ArgumentNullException.ThrowIfNull(payloadStore); if (maxRequests < 0) @@ -28,21 +39,40 @@ public static class FractalResidencyPlanner throw new ArgumentOutOfRangeException(nameof(maxResidentNodes), maxResidentNodes, "Resident budget must not be negative."); } + var costsByKey = summaries.ToDictionary(summary => summary.NodeKey.Value, summary => MathF.Max(summary.EstimatedCost, 1.0f), StringComparer.Ordinal); + var candidates = selectedCut + .Select((cut, index) => new ResidencyCandidate( + cut, + index, + payloadStore.IsResident(cut.NodeKey), + costsByKey.TryGetValue(cut.NodeKey.Value, out var cost) ? cost : 1.0f)) + .ToArray(); + var retainedResidentIndexes = candidates + .Where(candidate => candidate.IsResident) + .OrderByDescending(candidate => ResidencyValue(candidate)) + .ThenByDescending(candidate => candidate.Cut.Score) + .ThenBy(candidate => candidate.Index) + .Take(maxResidentNodes) + .Select(candidate => candidate.Index) + .ToHashSet(); var resident = new List(); var fallback = new List(); var requested = new List(); + var evicted = new List(); - foreach (var cut in selectedCut) + foreach (var candidate in candidates) { - if (payloadStore.IsResident(cut.NodeKey)) + var cut = candidate.Cut; + if (candidate.IsResident) { - if (resident.Count < maxResidentNodes) + if (retainedResidentIndexes.Contains(candidate.Index)) { resident.Add(cut.NodeKey); } else { fallback.Add(cut.NodeKey); + evicted.Add(cut.NodeKey); } continue; @@ -56,6 +86,17 @@ public static class FractalResidencyPlanner } } - return new FractalResidencyPlan(resident, fallback, requested); + return new FractalResidencyPlan(resident, fallback, requested, evicted); } + + private static float ResidencyValue(ResidencyCandidate candidate) + { + return MathF.Max(candidate.Cut.Score, 0.0f) / MathF.Max(candidate.EstimatedCost, 1.0f); + } + + private readonly record struct ResidencyCandidate( + AquariumSelectedCut Cut, + int Index, + bool IsResident, + float EstimatedCost); } diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalResourceBudgetPlanner.cs b/src/Aquarium.Engine.Fractal/Lod/FractalResourceBudgetPlanner.cs index a693c01..9984b6c 100644 --- a/src/Aquarium.Engine.Fractal/Lod/FractalResourceBudgetPlanner.cs +++ b/src/Aquarium.Engine.Fractal/Lod/FractalResourceBudgetPlanner.cs @@ -24,7 +24,7 @@ public static class FractalResourceBudgetPlanner var selectedCut = FractalSelectedCutBuilder.Build(summaries, projectedPixelsPerWorldUnit, budget.MaxGpuEstimatedCost); var updateNodes = FractalStochasticUpdateScheduler.SelectUpdates(states, currentScore, budget.MaxCpuUpdates, random, frameIndex); - var residency = FractalResidencyPlanner.Plan(selectedCut, payloadStore, budget.MaxSsdRequests, budget.MaxResidentPayloads); + var residency = FractalResidencyPlanner.Plan(selectedCut, summaries, payloadStore, budget.MaxSsdRequests, budget.MaxResidentPayloads); return new FractalResourcePlan( selectedCut, diff --git a/src/Aquarium.Zyphos/ZyphosFractalTerrain.cs b/src/Aquarium.Zyphos/ZyphosFractalTerrain.cs index e3cfc83..c9727e4 100644 --- a/src/Aquarium.Zyphos/ZyphosFractalTerrain.cs +++ b/src/Aquarium.Zyphos/ZyphosFractalTerrain.cs @@ -135,6 +135,7 @@ public static class ZyphosFractalTerrain $" gpuEstimatedCost: {plan.ResourcePlan.GpuEstimatedCost:0.000}/{budget.MaxGpuEstimatedCost:0.000}", $" ramResident: {plan.ResourcePlan.Residency.ResidentNodes.Count}/{budget.MaxResidentPayloads}", $" ssdRequests: {plan.ResourcePlan.Residency.RequestedNodes.Count}/{budget.MaxSsdRequests}", + $" evictions: {plan.ResourcePlan.Residency.EvictedNodes.Count}", $" structuralProbe: {(plan.StructuralProbeReservoir.HasSample ? plan.StructuralProbeReservoir.NodeKey.Value : "none")}", $" structuralProbeWeight: {plan.StructuralProbeReservoir.WeightSum:0.000} candidates={plan.StructuralProbeReservoir.CandidateCount} contributionWeight={plan.StructuralProbeReservoir.ContributionWeight:0.000}", $" surfacePages: {plan.SurfacePages.Length} {SurfacePageDimension}x{SurfacePageDimension}", diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 5c8f6c3..f95d1c3 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -170,3 +170,4 @@ {"timestamp":"2026-05-19T21:42:00+01:00","topic":"fractal-probe-temporal-validation","lesson":"Fractal probe reuse now has a CPU temporal validation contract before GPU reuse exists. `FractalProbeReuseValidator.ValidateTemporal` composes domain/local-shift validation with renderer-facing gates for camera motion, disocclusion confidence, material delta, and visibility confidence, returning explicit rejection reasons. This keeps future ReSTIR/GRIS probe reuse from becoming private shader folklore.","files":["src/Aquarium.Engine.Fractal/Lod/FractalProbeSample.cs","tests/Aquarium.Engine.Fractal.Tests/FractalProbeSampleTests.cs","docs/perfect-machine-architecture.md","research/rendering/fractal-brush-implementation-roadmap.md","state/memory.json"],"source":"Perfect Machine Phase C validation contract work"} {"timestamp":"2026-05-19T22:03:00+01:00","topic":"fractal-surface-page-contract","lesson":"Phase E has a portable page contract before renderer lowering. `AquariumFractalSurfacePageKey` gives height, 2D signed-distance, material, and confidence pages stable domain/node/kind/mip identity; `AquariumFractalSurfacePage` carries bounds, dimensions, payload handle, and max error without D3D12 types. This lets the residency/page store evolve without treating current height brushes as the page model.","files":["src/Aquarium.Engine.Contracts/Fractal/AquariumFractalContracts.cs","tests/Aquarium.Engine.Fractal.Tests/FractalSurfacePageContractTests.cs","docs/perfect-machine-architecture.md","research/rendering/fractal-brush-implementation-roadmap.md","state/memory.json"],"source":"Perfect Machine Phase E groundwork after fractal probe validation"} {"timestamp":"2026-05-19T22:31:00+01:00","topic":"fractal-surface-page-planner","lesson":"Phase E now has a CPU page-planning boundary. `FractalSurfacePagePlanner` lowers selected IFS cuts into stable height, 2D signed-distance, material, and confidence page metadata; `ZyphosFractalRenderPlan` carries those pages beside brushes, resource planning, and structural probe reservoirs. This proves page identity and inspection before adding a page store, eviction policy, D3D12 atlas, or GPU lowering.","files":["src/Aquarium.Engine.Fractal/Lod/FractalSurfacePagePlanner.cs","src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","tests/Aquarium.Engine.Fractal.Tests/FractalSurfacePagePlannerTests.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs","docs/perfect-machine-architecture.md","research/rendering/fractal-brush-implementation-roadmap.md","state/memory.json","state/map.yaml"],"source":"Perfect Machine Phase E CPU page planning"} +{"timestamp":"2026-05-19T22:48:00+01:00","topic":"fractal-residency-eviction-policy","lesson":"Residency planning now has an explicit score-per-cost eviction decision. `FractalResidencyPlanner` can receive node summaries, retain resident payloads with the best contribution per estimated cost under RAM budget, place evicted residents on summary fallback, and report evicted node keys without mutating a real store. This keeps eviction testable until a page/payload store owns storage changes.","files":["src/Aquarium.Engine.Fractal/Lod/FractalResidencyPlanner.cs","src/Aquarium.Engine.Fractal/Lod/FractalResidencyPlan.cs","src/Aquarium.Engine.Fractal/Lod/FractalResourceBudgetPlanner.cs","tests/Aquarium.Engine.Fractal.Tests/FractalResidencyPlannerTests.cs","src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs","docs/perfect-machine-architecture.md","research/rendering/fractal-brush-implementation-roadmap.md","state/memory.json","state/map.yaml"],"source":"Perfect Machine Phase D/E residency pressure slice"} diff --git a/state/map.yaml b/state/map.yaml index 3cb11b0..8aecf69 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -134,6 +134,7 @@ renderer_state: - IFS LOD should be driven by cached node contribution summaries: each node carries bounds, projected error/material delta, coverage, cost, estimator state, residency, and summary/child payload handles so traversal can choose a stable hierarchy cut and render parent summaries while child details stream or fade in. - Contribution weights cannot all be refreshed every frame; the cache needs a probabilistic online estimator that samples nodes under budget, updates mean/uncertainty/sample age/confidence, preserves nonzero exploration for visible or near-threshold nodes, and can later become a learned predictor without replacing conservative SDF bounds. - Fractal resource planning is explicit: one plan coordinates CPU contribution updates, GPU selected-cut estimated cost, RAM resident payload budget, and SSD request pressure before backend packet compilation. This same budget language should generalize to Mimir-style sensor fusion because both fractal SDF probes and camera/microphone feature detections accumulate confidence-weighted spatial samples into temporal reservoirs. + - Fractal residency uses score-per-cost retention under RAM pressure and emits evicted node keys as planner output; real storage mutation waits for a page/payload store boundary. - The consolidated fractal brush architecture plan defines the intended pipeline: client intent -> domain roots -> semantic IFS brush grammar -> ownership tree -> node summaries -> contribution cache/residency scheduler -> backend packets -> renderer passes -> debug/evidence, with explicit module boundaries and mockable unit-test seams. - The Perfect Machine architecture lives in docs/perfect-machine-architecture.md. It is the current waterfall design authority for fast 2D SDF splats, 3D SDF splats, 2D-projected-to-3D surface splats, IFS `.aquageo` structural probes, Mimir-style camera/audio evidence candidates, ReSTIR/GRIS reservoir reuse, heuristic occupancy graph updates, resource-tier residency, and TAA guide-buffer integration. - Fractal surface page planning now has a CPU boundary: FractalSurfacePagePlanner lowers selected IFS cuts into stable height, 2D signed-distance, material, and confidence page metadata; ZyphosFractalRenderPlan exposes these pages, while the live D3D12 page store and atlas remain future work. diff --git a/state/memory.json b/state/memory.json index 7f4a2ef..f1845d3 100644 --- a/state/memory.json +++ b/state/memory.json @@ -92,6 +92,7 @@ "Temporal resolve now has explicit reservoir guide targets. SDF and temporal Gaussian passes write a current scene reservoir guide MRT and D3D12Post reads/writes ping-ponged history reservoir guide targets with x=confidence, y=sample age, z=domain validity, w=invalidation code. History-control.w still owns pixel history age; do not pack reservoir history back into scene-control folklore.", "FractalContributionCache is the live cache loop: each frame builds a resource plan from current summaries and cached states, stochastically observes only budgeted update nodes, stores mean/variance/confidence/sample age through FractalContributionEstimator, frames scheduled updates as weighted ResampledImportanceReservoir candidates, and lets backend packet compilation stay cached by selected-cut key. It is a candidate source, not the whole temporal/spatial reuse pass. Do not replace this with a static plan cache that stops learning after the first camera bucket.", "FractalOccupancyGraph is now the live memory behind FractalContributionCache. It owns per-node contribution state, last visible frame, last observed score, and update probability; unobserved nodes decay confidence and grow stale uncertainty. Keep richer residency/resource fields here rather than adding another cache beside it.", + "FractalResidencyPlanner keeps resident payloads by score-per-cost when RAM budget is capped and reports evicted node keys explicitly. Eviction is a planner decision row until a real payload/page store owns mutation; selected nodes still render through summary fallback when evicted or missing.", "FractalProbeSample is the typed reservoir sample shape for fractal SDF/detail reuse: domain key, node key, local center, bound radius, target contribution, source PDF, material delta, and payload handle. Reuse must pass domain lineage and local-shift validation now, and later camera motion, disocclusion, material compatibility, and visibility validation before it is allowed into temporal/spatial reuse.", "FractalProbeReuseValidator.ValidateTemporal is the CPU contract for future GPU temporal reuse. It rejects excessive camera motion, disocclusion, material mismatch, low visibility, bad domain lineage, excessive local shift, and invalid bounds with explicit reasons; shader reuse should mirror this contract instead of inventing private validation rules.", "FractalStructuralProbeGenerator lowers AquariumFractalSummary rows into FractalProbeSample reservoir candidates with local support, projected target contribution, clamped source PDF, material delta, and payload handle. This is the structural IFS probe producer; renderer-facing temporal validation still needs camera/disocclusion/material/visibility inputs.", diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalResidencyPlannerTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalResidencyPlannerTests.cs index 3e69bb1..bd94fa2 100644 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalResidencyPlannerTests.cs +++ b/tests/Aquarium.Engine.Fractal.Tests/FractalResidencyPlannerTests.cs @@ -1,3 +1,4 @@ +using System.Numerics; using Aquarium.Engine.Fractal; using Aquarium.Engine.Fractal.Lod; @@ -59,6 +60,42 @@ public sealed class FractalResidencyPlannerTests Assert.Equal([missingA], store.Requests); } + [Fact] + public void ResidencyPlannerEvictsLowScoreHighCostPayloadsFirst() + { + var expensive = new AquariumFractalKey("node/expensive"); + var cheap = new AquariumFractalKey("node/cheap"); + var store = new TestPayloadStore([expensive, cheap]); + var cuts = new[] + { + new AquariumSelectedCut(expensive, Score: 5.0f, Fade: 1.0f, UsesSummary: true, RequestedChildren: false), + new AquariumSelectedCut(cheap, Score: 4.0f, Fade: 1.0f, UsesSummary: true, RequestedChildren: false), + }; + var summaries = new[] + { + Summary(expensive, estimatedCost: 100.0f), + Summary(cheap, estimatedCost: 1.0f), + }; + + var plan = FractalResidencyPlanner.Plan(cuts, summaries, store, maxRequests: 0, maxResidentNodes: 1); + + Assert.Equal([cheap], plan.ResidentNodes); + Assert.Equal([expensive], plan.SummaryFallbackNodes); + Assert.Equal([expensive], plan.EvictedNodes); + Assert.Empty(plan.RequestedNodes); + } + + private static AquariumFractalSummary Summary(AquariumFractalKey key, float estimatedCost) + { + return new AquariumFractalSummary( + key, + Vector4.Zero, + MaxHeightError: 1.0f, + MaxMaterialDelta: 0.0f, + estimatedCost, + DescendantCount: 0); + } + private sealed class TestPayloadStore(IEnumerable? resident = null) : IFractalPayloadStore { private readonly HashSet residentKeys = resident?.Select(key => key.Value).ToHashSet(StringComparer.Ordinal) ?? []; diff --git a/tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs b/tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs index 471fb35..e56eb32 100644 --- a/tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs +++ b/tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs @@ -81,6 +81,7 @@ public sealed class ZyphosFractalTerrainTests Assert.Contains("gpuEstimatedCost:", dump, StringComparison.Ordinal); Assert.Contains("ramResident:", dump, StringComparison.Ordinal); Assert.Contains("ssdRequests:", dump, StringComparison.Ordinal); + Assert.Contains("evictions:", dump, StringComparison.Ordinal); Assert.Contains("structuralProbe:", dump, StringComparison.Ordinal); Assert.Contains("structuralProbeWeight:", dump, StringComparison.Ordinal); Assert.Contains("surfacePages:", dump, StringComparison.Ordinal);