< Summary

Information
Class: Gravitas.RetainedPartitionLifecycle
Assembly: Gravitas
File(s): /home/runner/work/Gravitas/Gravitas/src/Gravitas/Partitions/RetainedPartitionLifecycle.cs
Line coverage
100%
Covered lines: 108
Uncovered lines: 0
Coverable lines: 108
Total lines: 280
Line coverage: 100%
Branch coverage
100%
Covered branches: 84
Total branches: 84
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
DetachAll(...)100%1212100%
Track(...)100%22100%
Untrack(...)100%1010100%
RetireExpired(...)100%1212100%
TryRetireEmptyForReuse(...)100%1212100%
RefreshEmptyEligibility(...)100%1212100%
UntrackEmpty(...)100%44100%
RemoveEmptyAt(...)100%22100%
FindIndex(...)100%44100%
ShouldRetire(...)100%88100%
Retire(...)100%66100%

File(s)

/home/runner/work/Gravitas/Gravitas/src/Gravitas/Partitions/RetainedPartitionLifecycle.cs

#LineLine coverage
 1//=======================================================================
 2// RetainedPartitionLifecycle.cs
 3//=======================================================================
 4// MIT License, Copyright (c) 2026-present David Oravsky (mrdav30)
 5// See LICENSE file in the project root for full license information.
 6//=======================================================================
 7
 8using System;
 9using GridForge.Grids;
 10using SwiftCollections;
 11
 12namespace Gravitas;
 13
 14/// <summary>
 15/// Tracks retained partitions and releases empty payloads through expiry, reuse, or context teardown.
 16/// </summary>
 17internal static class RetainedPartitionLifecycle
 18{
 19    internal static void DetachAll<TPartition, TOwner>(
 20        SwiftList<TPartition> retainedPartitions,
 21        SwiftList<TPartition> emptyPartitions,
 22        GridWorld world,
 23        TOwner owner,
 24        Action<TPartition> releasePartition,
 25        string partitionName,
 26        string detachError)
 27        where TPartition : class, IRetainedPhysicsPartition<TOwner>
 28    {
 29        // Reset is a context boundary; retained GridForge payloads are a runtime cache, not replay state.
 1348230        while (retainedPartitions.Count > 0)
 31        {
 1309332            TPartition partition = retainedPartitions[retainedPartitions.Count - 1];
 1309333            if (!partition.IsOwnedBy(owner))
 34            {
 135                int disabledCursor = -1;
 136                Untrack(retainedPartitions, emptyPartitions, owner, partition, ref disabledCursor);
 137                continue;
 38            }
 39
 1309240            if (world.TryGetVoxel(partition.WorldIndex, out Voxel? voxel)
 1309241                && voxel!.TryGetPartition(out TPartition? attachedPartition)
 1309242                && ReferenceEquals(attachedPartition, partition))
 43            {
 1309144                bool removed = voxel.TryRemovePartition<TPartition>();
 1309145                ChronicleGuard.ThrowIfTrue(!removed, partitionName, detachError);
 46
 1309147                if (partition.IsOwnedBy(owner))
 148                    releasePartition(partition);
 49
 150                continue;
 51            }
 52
 153            releasePartition(partition);
 54        }
 38955    }
 56
 57    internal static void Track<TPartition, TOwner>(
 58        SwiftList<TPartition> retainedPartitions,
 59        SwiftList<TPartition> emptyPartitions,
 60        TOwner owner,
 61        TPartition partition,
 62        string partitionName)
 63        where TPartition : class, IRetainedPhysicsPartition<TOwner>
 64    {
 171802565        ChronicleGuard.ThrowIfNull(partition, nameof(partition));
 66        // Tracking runs once per newly occupied voxel. Format validation details
 67        // only on failure, rather than allocating a message for every payload.
 171802568        if (partition.RetainedIndex >= 0)
 169            throw new ArgumentException($"{partitionName} is already tracked as retained.", nameof(partition));
 70
 171802471        partition.SetRetainedIndex(retainedPartitions.Count);
 171802472        retainedPartitions.Add(partition);
 73        // Every retained payload can become empty later. Reserve those slots
 74        // during registration so ordinary membership removal cannot allocate.
 171802475        emptyPartitions.EnsureCapacity(retainedPartitions.Count);
 171802476        RefreshEmptyEligibility(emptyPartitions, owner, partition);
 171802477    }
 78
 79    internal static void Untrack<TPartition, TOwner>(
 80        SwiftList<TPartition> retainedPartitions,
 81        SwiftList<TPartition> emptyPartitions,
 82        TOwner owner,
 83        TPartition partition,
 84        ref int retirementCursor)
 85        where TPartition : class, IRetainedPhysicsPartition<TOwner>
 86    {
 171796587        UntrackEmpty<TPartition, TOwner>(emptyPartitions, partition);
 171796588        int index = FindIndex(retainedPartitions, owner, partition);
 171796589        if (index < 0)
 90        {
 2291            partition.ClearRetainedIndex();
 2292            return;
 93        }
 94
 171794395        int lastIndex = retainedPartitions.Count - 1;
 171794396        if (index != lastIndex)
 97        {
 118175698            TPartition movedPartition = retainedPartitions[lastIndex];
 118175699            retainedPartitions[index] = movedPartition;
 1181756100            movedPartition.SetRetainedIndex(index);
 101        }
 102
 1717943103        retainedPartitions.RemoveAt(lastIndex);
 1717943104        partition.ClearRetainedIndex();
 105
 1717943106        if (retirementCursor < 0)
 2107            return;
 108
 1717941109        if (retirementCursor > index)
 155998110            retirementCursor--;
 1717941111        if (retirementCursor >= retainedPartitions.Count)
 15735112            retirementCursor = 0;
 1717941113    }
 114
 115    internal static void RetireExpired<TPartition, TOwner>(
 116        SwiftList<TPartition> retainedPartitions,
 117        GridWorld world,
 118        TOwner owner,
 119        int budget,
 120        long currentFrame,
 121        int timeToKillFrames,
 122        Action<TPartition> releasePartition,
 123        ref int retirementCursor)
 124        where TPartition : class, IRetainedPhysicsPartition<TOwner>
 125    {
 103361126        if (budget <= 0 || retainedPartitions.Count == 0)
 2886127            return;
 128
 100475129        int inspected = 0;
 6555442130        while (inspected < budget && retainedPartitions.Count > 0)
 131        {
 6454967132            if (retirementCursor >= retainedPartitions.Count)
 131854133                retirementCursor = 0;
 134
 6454967135            TPartition partition = retainedPartitions[retirementCursor];
 6454967136            inspected++;
 137
 6454967138            if (!ShouldRetire(partition, owner, currentFrame, timeToKillFrames))
 139            {
 6454081140                retirementCursor++;
 6454081141                continue;
 142            }
 143
 886144            Retire(world, owner, partition, releasePartition);
 145        }
 100475146    }
 147
 148    internal static bool TryRetireEmptyForReuse<TPartition, TOwner>(
 149        SwiftList<TPartition> emptyPartitions,
 150        SwiftStack<TPartition> inactivePartitionPool,
 151        GridWorld world,
 152        TOwner owner,
 153        Action<TPartition> releasePartition)
 154        where TPartition : class, IRetainedPhysicsPartition<TOwner>
 155    {
 156        // Membership transitions maintain this dense list. Occupied cold rentals
 157        // never scan retained payloads; reuse takes the last dense eligible entry.
 1717694158        while (emptyPartitions.Count > 0)
 159        {
 87609160            int lastIndex = emptyPartitions.Count - 1;
 87609161            TPartition partition = emptyPartitions[lastIndex];
 87609162            RemoveEmptyAt<TPartition, TOwner>(emptyPartitions, lastIndex);
 163
 164            // Recheck ownership and eligibility before detaching a selected payload,
 165            // without rediscovering occupied payloads or trusting stale cache entries.
 87609166            if (partition.RetainedIndex < 0 || !partition.IsOwnedBy(owner) || !partition.IsEmpty || partition.IsAllocate
 167                continue;
 168
 87605169            int poolCount = inactivePartitionPool.Count;
 87605170            Retire(world, owner, partition, releasePartition);
 87605171            if (inactivePartitionPool.Count > poolCount)
 87604172                return true;
 173        }
 174
 1630085175        return false;
 176    }
 177
 178    internal static void RefreshEmptyEligibility<TPartition, TOwner>(
 179        SwiftList<TPartition> emptyPartitions,
 180        TOwner owner,
 181        TPartition partition)
 182        where TPartition : class, IRetainedPhysicsPartition<TOwner>
 183    {
 4240070184        bool eligible = partition.RetainedIndex >= 0 && partition.IsOwnedBy(owner)
 4240070185            && partition.IsEmpty && !partition.IsAllocated;
 4240070186        if (!eligible)
 187        {
 2253631188            UntrackEmpty<TPartition, TOwner>(emptyPartitions, partition);
 2253631189            return;
 190        }
 191
 1986439192        if ((uint)partition.EmptyIndex < (uint)emptyPartitions.Count
 1986439193            && ReferenceEquals(emptyPartitions[partition.EmptyIndex], partition))
 4194            return;
 195
 1986435196        partition.EmptyIndex = emptyPartitions.Count;
 1986435197        emptyPartitions.Add(partition);
 1986435198    }
 199
 200    private static void UntrackEmpty<TPartition, TOwner>(
 201        SwiftList<TPartition> emptyPartitions,
 202        TPartition partition)
 203        where TPartition : class, IRetainedPhysicsPartition<TOwner>
 204    {
 3971596205        int index = partition.EmptyIndex;
 3971596206        if ((uint)index < (uint)emptyPartitions.Count && ReferenceEquals(emptyPartitions[index], partition))
 1898784207            RemoveEmptyAt<TPartition, TOwner>(emptyPartitions, index);
 208        else
 2072812209            partition.EmptyIndex = -1;
 2072812210    }
 211
 212    private static void RemoveEmptyAt<TPartition, TOwner>(SwiftList<TPartition> emptyPartitions, int index)
 213        where TPartition : class, IRetainedPhysicsPartition<TOwner>
 214    {
 215        // Swap-back keeps transitions constant-time; update the moved payload's
 216        // slot so a later reoccupation removes it without searching the list.
 1986393217        TPartition partition = emptyPartitions[index];
 1986393218        int lastIndex = emptyPartitions.Count - 1;
 1986393219        if (index != lastIndex)
 220        {
 98561221            TPartition movedPartition = emptyPartitions[lastIndex];
 98561222            emptyPartitions[index] = movedPartition;
 98561223            movedPartition.EmptyIndex = index;
 224        }
 225
 1986393226        emptyPartitions.RemoveAt(lastIndex);
 1986393227        partition.EmptyIndex = -1;
 1986393228    }
 229
 230    private static int FindIndex<TPartition, TOwner>(
 231        SwiftList<TPartition> retainedPartitions,
 232        TOwner owner,
 233        TPartition partition)
 234        where TPartition : class, IRetainedPhysicsPartition<TOwner>
 235    {
 236        _ = owner;
 1717965237        int index = partition.RetainedIndex;
 1717965238        return (uint)index < (uint)retainedPartitions.Count && ReferenceEquals(retainedPartitions[index], partition)
 1717965239            ? index
 1717965240            : -1;
 241    }
 242
 243    private static bool ShouldRetire<TPartition, TOwner>(
 244        TPartition partition,
 245        TOwner owner,
 246        long currentFrame,
 247        int timeToKillFrames)
 248        where TPartition : class, IRetainedPhysicsPartition<TOwner>
 249    {
 6454967250        if (!partition.IsOwnedBy(owner) || !partition.IsEmpty || partition.IsAllocated || partition.EmptySinceFrame < 0)
 6182000251            return false;
 252
 272967253        long idleFrames = currentFrame - partition.EmptySinceFrame;
 272967254        return idleFrames >= timeToKillFrames;
 255    }
 256
 257    private static void Retire<TPartition, TOwner>(
 258        GridWorld world,
 259        TOwner owner,
 260        TPartition partition,
 261        Action<TPartition> releasePartition)
 262        where TPartition : class, IRetainedPhysicsPartition<TOwner>
 263    {
 264        _ = owner;
 88491265        if (!world.TryGetVoxel(partition.WorldIndex, out Voxel? voxel))
 266        {
 4267            releasePartition(partition);
 4268            return;
 269        }
 270
 88487271        if (!voxel!.TryGetPartition(out TPartition? attachedPartition)
 88487272            || !ReferenceEquals(attachedPartition, partition))
 273        {
 2274            releasePartition(partition);
 2275            return;
 276        }
 277
 88485278        _ = voxel.TryRemovePartition<TPartition>();
 88485279    }
 280}