Add fractal surface page residency policy

This commit is contained in:
Meta Vens 2026-05-19 20:28:13 +01:00
commit d07a24a522
11 changed files with 306 additions and 3 deletions

View file

@ -516,8 +516,10 @@ Current state: `AquariumFractalSurfacePageKey` and
2D signed-distance, material, and confidence pages. `FractalSurfacePagePlanner`
turns a selected IFS cut into stable page metadata, and the Zyphos render plan
now exposes height, 2D signed-distance, material, and confidence pages beside
its structural probe reservoir. The page store, eviction policy, atlas, and
D3D12 lowering remain open.
its structural probe reservoir. `FractalSurfacePageResidencyPlanner` adds a
mockable page-store boundary with byte-budgeted resident, missing, requested,
and evicted page decisions. The real page store, atlas, and D3D12 lowering
remain open.
### Phase F: 3D SDF Splat Backend

View file

@ -404,6 +404,8 @@ Tasks:
2D signed-distance, material, and confidence pages.
- [x] Add CPU surface page planner that lowers selected IFS cuts into stable
page metadata.
- [x] Add mockable surface page store boundary with resident/request/evict
decisions under a byte budget.
- [x] Add fake payload store with resident/missing states.
- [x] Add child request queue.
- [x] Add score/cost eviction policy.

View file

@ -0,0 +1,28 @@
namespace Aquarium.Engine.Fractal.Lod;
public sealed class FractalSurfacePageResidencyPlan
{
public FractalSurfacePageResidencyPlan(
IReadOnlyList<AquariumFractalSurfacePage> residentPages,
IReadOnlyList<AquariumFractalSurfacePage> missingPages,
IReadOnlyList<AquariumFractalSurfacePage> requestedPages,
IReadOnlyList<AquariumFractalSurfacePage> evictedPages,
long residentBytes)
{
ResidentPages = residentPages;
MissingPages = missingPages;
RequestedPages = requestedPages;
EvictedPages = evictedPages;
ResidentBytes = residentBytes;
}
public IReadOnlyList<AquariumFractalSurfacePage> ResidentPages { get; }
public IReadOnlyList<AquariumFractalSurfacePage> MissingPages { get; }
public IReadOnlyList<AquariumFractalSurfacePage> RequestedPages { get; }
public IReadOnlyList<AquariumFractalSurfacePage> EvictedPages { get; }
public long ResidentBytes { get; }
}

View file

@ -0,0 +1,120 @@
namespace Aquarium.Engine.Fractal.Lod;
public static class FractalSurfacePageResidencyPlanner
{
public static FractalSurfacePageResidencyPlan Plan(
IReadOnlyList<AquariumFractalSurfacePage> pages,
IFractalSurfacePageStore store,
long maxResidentBytes,
int maxRequests)
{
ArgumentNullException.ThrowIfNull(pages);
ArgumentNullException.ThrowIfNull(store);
if (maxResidentBytes < 0)
{
throw new ArgumentOutOfRangeException(nameof(maxResidentBytes), maxResidentBytes, "Resident byte budget must not be negative.");
}
if (maxRequests < 0)
{
throw new ArgumentOutOfRangeException(nameof(maxRequests), maxRequests, "Request budget must not be negative.");
}
var rows = pages
.Select((page, index) => new PageCandidate(page, index, EstimatedBytes(page), store.IsResident(page.Key)))
.ToArray();
var retainedIndexes = new HashSet<int>();
var retainedBytes = 0L;
foreach (var candidate in rows
.Where(candidate => candidate.IsResident)
.OrderByDescending(PageValue)
.ThenByDescending(candidate => candidate.Page.MaxError)
.ThenBy(candidate => candidate.Page.Key.Value, StringComparer.Ordinal))
{
if (retainedBytes + candidate.EstimatedBytes > maxResidentBytes)
{
continue;
}
retainedIndexes.Add(candidate.Index);
retainedBytes += candidate.EstimatedBytes;
}
var resident = new List<AquariumFractalSurfacePage>();
var missing = new List<AquariumFractalSurfacePage>();
var evicted = new List<AquariumFractalSurfacePage>();
foreach (var candidate in rows)
{
if (candidate.IsResident && retainedIndexes.Contains(candidate.Index))
{
resident.Add(candidate.Page);
continue;
}
missing.Add(candidate.Page);
if (candidate.IsResident)
{
evicted.Add(candidate.Page);
store.Evict(candidate.Page.Key);
}
}
var requested = rows
.Where(candidate => !candidate.IsResident)
.Select(candidate => candidate.Page)
.OrderByDescending(PageValue)
.ThenByDescending(page => page.MaxError)
.ThenBy(page => page.Key.Value, StringComparer.Ordinal)
.Take(maxRequests)
.ToArray();
foreach (var page in requested)
{
store.Request(page);
}
return new FractalSurfacePageResidencyPlan(resident, missing, requested, evicted, retainedBytes);
}
public static long EstimatedBytes(AquariumFractalSurfacePage page)
{
if (page.Width <= 0 || page.Height <= 0)
{
return 0;
}
return (long)page.Width * page.Height * BytesPerPixel(page.Key.Kind);
}
private static float PageValue(PageCandidate candidate)
{
return PageValue(candidate.Page, candidate.EstimatedBytes);
}
private static float PageValue(AquariumFractalSurfacePage page)
{
return PageValue(page, EstimatedBytes(page));
}
private static float PageValue(AquariumFractalSurfacePage page, long estimatedBytes)
{
return MathF.Max(page.MaxError, 0.000001f) / Math.Max(estimatedBytes, 1L);
}
private static int BytesPerPixel(AquariumFractalSurfacePageKind kind)
{
return kind switch
{
AquariumFractalSurfacePageKind.Material => 4,
AquariumFractalSurfacePageKind.Height => 2,
AquariumFractalSurfacePageKind.SignedDistance2D => 2,
AquariumFractalSurfacePageKind.Confidence => 2,
_ => 4,
};
}
private readonly record struct PageCandidate(
AquariumFractalSurfacePage Page,
int Index,
long EstimatedBytes,
bool IsResident);
}

View file

@ -0,0 +1,10 @@
namespace Aquarium.Engine.Fractal.Lod;
public interface IFractalSurfacePageStore
{
bool IsResident(AquariumFractalSurfacePageKey key);
void Request(AquariumFractalSurfacePage page);
void Evict(AquariumFractalSurfacePageKey key);
}

View file

@ -11,6 +11,8 @@ public static class ZyphosFractalTerrain
{
private const string PatchRelativePath = "Worlds/zyphos-first-fractal-terrain.aquageo";
private const int SurfacePageDimension = 128;
private const long MaxResidentSurfacePageBytes = 2L * 1024L * 1024L;
private const int MaxSurfacePageRequests = 8;
private static readonly Lazy<string> PatchSource = new(() => File.ReadAllText(PatchPath));
private static readonly Lazy<FractalOwnershipTree> Tree = new(() => FractalDslCompiler.Compile(PatchSource.Value));
@ -69,6 +71,11 @@ public static class ZyphosFractalTerrain
bucketPixelsPerWorld,
new FractalXorShiftRandom(((uint)bucket ^ 0xC2B2AE35u) + (uint)selectedCut.Length));
var surfacePages = PlanSurfacePages(selectedCut);
var surfacePageResidency = FractalSurfacePageResidencyPlanner.Plan(
surfacePages,
ResidentSurfacePageStore.Instance,
MaxResidentSurfacePageBytes,
MaxSurfacePageRequests);
var cutKey = CutCacheKey(selectedCut);
AquariumHeightFieldBrush[] brushes;
lock (PlanCacheLock)
@ -86,8 +93,9 @@ public static class ZyphosFractalTerrain
resourcePlan,
structuralProbeReservoir,
surfacePages,
surfacePageResidency,
bucketPixelsPerWorld,
$"{selectedCut.Length}/{Summaries.Value.Length} cuts / {brushes.Length}/{OwnershipTree.Claims.Count} brushes / {resourcePlan.UpdateNodes.Length}/{DefaultBudget.MaxCpuUpdates} cpu updates / {resourcePlan.GpuEstimatedCost:0.0}/{DefaultBudget.MaxGpuEstimatedCost:0.0} gpu cost / {resourcePlan.Residency.ResidentNodes.Count}/{DefaultBudget.MaxResidentPayloads} resident / {resourcePlan.Residency.RequestedNodes.Count}/{DefaultBudget.MaxSsdRequests} ssd requests / {(structuralProbeReservoir.HasSample ? structuralProbeReservoir.CandidateCount : 0)} probe candidates / {surfacePages.Length} surface pages / {bucketPixelsPerWorld:0.00} px-wu");
$"{selectedCut.Length}/{Summaries.Value.Length} cuts / {brushes.Length}/{OwnershipTree.Claims.Count} brushes / {resourcePlan.UpdateNodes.Length}/{DefaultBudget.MaxCpuUpdates} cpu updates / {resourcePlan.GpuEstimatedCost:0.0}/{DefaultBudget.MaxGpuEstimatedCost:0.0} gpu cost / {resourcePlan.Residency.ResidentNodes.Count}/{DefaultBudget.MaxResidentPayloads} resident / {resourcePlan.Residency.RequestedNodes.Count}/{DefaultBudget.MaxSsdRequests} ssd requests / {(structuralProbeReservoir.HasSample ? structuralProbeReservoir.CandidateCount : 0)} probe candidates / {surfacePageResidency.ResidentPages.Count}/{surfacePages.Length} surface pages / {bucketPixelsPerWorld:0.00} px-wu");
}
private static AquariumFractalSurfacePage[] PlanSurfacePages(IReadOnlyList<AquariumSelectedCut> selectedCut)
@ -139,6 +147,9 @@ public static class ZyphosFractalTerrain
$" 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}",
$" surfacePageResident: {plan.SurfacePageResidency.ResidentPages.Count}/{plan.SurfacePages.Length} bytes={plan.SurfacePageResidency.ResidentBytes}/{MaxResidentSurfacePageBytes}",
$" surfacePageRequests: {plan.SurfacePageResidency.RequestedPages.Count}/{MaxSurfacePageRequests}",
$" surfacePageEvictions: {plan.SurfacePageResidency.EvictedPages.Count}",
"selected:",
};
@ -172,6 +183,24 @@ public static class ZyphosFractalTerrain
{
}
}
private sealed class ResidentSurfacePageStore : IFractalSurfacePageStore
{
public static ResidentSurfacePageStore Instance { get; } = new();
public bool IsResident(AquariumFractalSurfacePageKey key)
{
return true;
}
public void Request(AquariumFractalSurfacePage page)
{
}
public void Evict(AquariumFractalSurfacePageKey key)
{
}
}
}
public readonly record struct ZyphosFractalRenderPlan(
@ -180,5 +209,6 @@ public readonly record struct ZyphosFractalRenderPlan(
FractalResourcePlan ResourcePlan,
FractalProbeReservoirSnapshot StructuralProbeReservoir,
AquariumFractalSurfacePage[] SurfacePages,
FractalSurfacePageResidencyPlan SurfacePageResidency,
float PixelsPerWorld,
string Summary);

View file

@ -171,3 +171,4 @@
{"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"}
{"timestamp":"2026-05-19T23:10:00+01:00","topic":"fractal-surface-page-residency","lesson":"Surface page residency now has a separate mockable boundary from node payload residency. `IFractalSurfacePageStore` owns page-key resident/request/evict calls, and `FractalSurfacePageResidencyPlanner` turns planned pages into resident, missing, requested, evicted, and resident-byte rows using a max-error-per-byte heuristic. Zyphos carries this page residency plan for inspection before any real atlas or SSD-backed page store exists.","files":["src/Aquarium.Engine.Fractal/Lod/IFractalSurfacePageStore.cs","src/Aquarium.Engine.Fractal/Lod/FractalSurfacePageResidencyPlan.cs","src/Aquarium.Engine.Fractal/Lod/FractalSurfacePageResidencyPlanner.cs","tests/Aquarium.Engine.Fractal.Tests/FractalSurfacePageResidencyPlannerTests.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 E page-store boundary slice"}

View file

@ -138,6 +138,7 @@ renderer_state:
- 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.
- Surface page residency has its own mockable store boundary: IFractalSurfacePageStore plus FractalSurfacePageResidencyPlanner produce resident, missing, requested, evicted, and byte-budget rows for planned pages without collapsing page cache policy into node payload residency.
- The actionable fractal brush implementation roadmap lives in research/rendering/fractal-brush-implementation-roadmap.md and is the execution authority for the first pass.
- Bundled blue-noise texture assets are retained for future dithering/noise work even though the removed medium path no longer samples them.
- D3D11 scene renderer, runtime volumetrics, cloud/fog research, medium/froxel render targets, and the SDF-field renderer plan are shelved and removed from live repo state.

View file

@ -102,6 +102,7 @@
"The Perfect Machine waterfall architecture lives in docs/perfect-machine-architecture.md. Treat it as the design authority before expanding SDF splat backends, sensor-fusion candidate adapters, reservoir guide buffers, occupancy graph state, resource-tier residency, or stochastic learned priority. Its core split is domains -> evidence candidates -> target evaluation -> ReSTIR/GRIS reservoirs -> occupancy graph -> residency -> 2D/3D/projected SDF splat packets -> TAA guide buffers.",
"AquariumFractalSurfacePageKey and AquariumFractalSurfacePage are the renderer-agnostic page contracts for Phase E: height, SignedDistance2D, material, and confidence surface pages carry stable domain/node/kind/mip keys, bounds, dimensions, payload handles, and max error before any D3D12 page store exists.",
"FractalSurfacePagePlanner lowers selected IFS cuts into stable surface page metadata without renderer dependencies. ZyphosFractalRenderPlan now exposes height, SignedDistance2D, material, and confidence pages beside brushes, resource plans, and structural probe reservoirs; the actual page store, eviction, atlas, and D3D12 lowering are still open.",
"FractalSurfacePageResidencyPlanner is the renderer-agnostic page-store policy boundary: it asks IFractalSurfacePageStore about page-key residency, keeps best max-error-per-byte resident pages under a byte budget, requests highest-value missing pages, and reports evictions. Zyphos carries this page residency plan, but real storage and D3D12 atlas mutation remain future work.",
"The actionable fractal brush roadmap lives in research/rendering/fractal-brush-implementation-roadmap.md. Start with the first work packet: add Aquarium.Engine.Fractal and tests, cube-face/tile key types, identity and tangent projection candidates, an area distortion sampler, face-edge tests, and a projection report before touching recursive detail."
],
"text_and_ui": [

View file

@ -0,0 +1,102 @@
using System.Numerics;
using Aquarium.Engine.Fractal;
using Aquarium.Engine.Fractal.Lod;
namespace Aquarium.Engine.Fractal.Tests;
public sealed class FractalSurfacePageResidencyPlannerTests
{
[Fact]
public void SurfacePageResidencyRetainsBestErrorPerByteUnderBudget()
{
var expensive = Page("domain/a", "node/a", AquariumFractalSurfacePageKind.Material, width: 256, height: 256, maxError: 1.0f);
var cheap = Page("domain/a", "node/b", AquariumFractalSurfacePageKind.Height, width: 64, height: 64, maxError: 0.5f);
var store = new TestSurfacePageStore([expensive.Key, cheap.Key]);
var plan = FractalSurfacePageResidencyPlanner.Plan(
[expensive, cheap],
store,
maxResidentBytes: FractalSurfacePageResidencyPlanner.EstimatedBytes(cheap),
maxRequests: 0);
Assert.Equal([cheap.Key], plan.ResidentPages.Select(page => page.Key));
Assert.Equal([expensive.Key], plan.EvictedPages.Select(page => page.Key));
Assert.Equal([expensive.Key], store.Evictions);
Assert.Equal(FractalSurfacePageResidencyPlanner.EstimatedBytes(cheap), plan.ResidentBytes);
Assert.Empty(plan.RequestedPages);
}
[Fact]
public void SurfacePageResidencyRequestsHighestValueMissingPages()
{
var low = Page("domain/a", "node/low", AquariumFractalSurfacePageKind.Material, width: 256, height: 256, maxError: 0.1f);
var high = Page("domain/a", "node/high", AquariumFractalSurfacePageKind.Height, width: 64, height: 64, maxError: 0.5f);
var store = new TestSurfacePageStore();
var plan = FractalSurfacePageResidencyPlanner.Plan([low, high], store, maxResidentBytes: 0, maxRequests: 1);
Assert.Equal([high.Key], plan.RequestedPages.Select(page => page.Key));
Assert.Equal([high.Key], store.Requests.Select(page => page.Key));
Assert.Equal([low.Key, high.Key], plan.MissingPages.Select(page => page.Key));
}
[Fact]
public void SurfacePageResidencyRejectsNegativeBudgets()
{
var store = new TestSurfacePageStore();
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => FractalSurfacePageResidencyPlanner.Plan(
[],
store,
maxResidentBytes: -1,
maxRequests: 0));
Assert.Equal("maxResidentBytes", ex.ParamName);
}
private static AquariumFractalSurfacePage Page(
string domainKey,
string nodeKey,
AquariumFractalSurfacePageKind kind,
int width,
int height,
float maxError)
{
return new AquariumFractalSurfacePage(
new AquariumFractalSurfacePageKey(
new AquariumFractalKey(domainKey),
new AquariumFractalKey(nodeKey),
kind,
mipLevel: 0),
Vector4.Zero,
width,
height,
PayloadHandle: 0,
maxError);
}
private sealed class TestSurfacePageStore(IEnumerable<AquariumFractalSurfacePageKey>? resident = null) : IFractalSurfacePageStore
{
private readonly HashSet<string> residentKeys = resident?.Select(key => key.Value).ToHashSet(StringComparer.Ordinal) ?? [];
public List<AquariumFractalSurfacePage> Requests { get; } = [];
public List<AquariumFractalSurfacePageKey> Evictions { get; } = [];
public bool IsResident(AquariumFractalSurfacePageKey key)
{
return residentKeys.Contains(key.Value);
}
public void Request(AquariumFractalSurfacePage page)
{
Requests.Add(page);
}
public void Evict(AquariumFractalSurfacePageKey key)
{
Evictions.Add(key);
residentKeys.Remove(key.Value);
}
}
}

View file

@ -59,6 +59,9 @@ public sealed class ZyphosFractalTerrainTests
Assert.True(near.StructuralProbeReservoir.WeightSum > 0.0f);
Assert.Equal(near.SelectedCuts.Length * 4, near.SurfacePages.Length);
Assert.Contains(near.SurfacePages, page => page.Key.Kind == AquariumFractalSurfacePageKind.SignedDistance2D);
Assert.True(near.SurfacePageResidency.ResidentPages.Count <= near.SurfacePages.Length);
Assert.True(near.SurfacePageResidency.ResidentBytes <= 2L * 1024L * 1024L);
Assert.True(near.SurfacePageResidency.RequestedPages.Count <= 8);
Assert.All(near.SurfacePages, page =>
{
Assert.Equal(128, page.Width);
@ -85,6 +88,9 @@ public sealed class ZyphosFractalTerrainTests
Assert.Contains("structuralProbe:", dump, StringComparison.Ordinal);
Assert.Contains("structuralProbeWeight:", dump, StringComparison.Ordinal);
Assert.Contains("surfacePages:", dump, StringComparison.Ordinal);
Assert.Contains("surfacePageResident:", dump, StringComparison.Ordinal);
Assert.Contains("surfacePageRequests:", dump, StringComparison.Ordinal);
Assert.Contains("surfacePageEvictions:", dump, StringComparison.Ordinal);
Assert.Contains("selected:", dump, StringComparison.Ordinal);
}
}