diff --git a/Assets/Scripts/ServerShared/HaulRun.cs b/Assets/Scripts/ServerShared/HaulRun.cs index 764e6376a..7e13267a6 100644 --- a/Assets/Scripts/ServerShared/HaulRun.cs +++ b/Assets/Scripts/ServerShared/HaulRun.cs @@ -43,23 +43,15 @@ public static class HaulRun return refused; } - // How many units of the good the hauler loads: up to ProbeFactor times what To took of it on its last visit while that sight is fresh (a - // carrier that brings only what was taken last time never finds a door that has grown hungrier), none of a good it saw refused - // outright, and the whole hold of a good it has no fresh sight of (it learns by trying). The hold and what From has cap it further. - public const int ProbeFactor = 2; - - private static int LoadLimit(Ship ship, CultRecordKey good) + // A sight is fresh or stale by Fresh alone. Prune drops the stale ones the hold does not carry, before a call at From loads: a stale sight + // of a good is no sight of it, so the good loads whole and the hauler learns it again at the door. Refused counts a stale sight only + // while the good is aboard, so the two never read one sight two ways (a load of a stale-sighted good was returned at the next dock, + // for ever, every 660 s: Soul s4). + private static void Prune(Ship ship, HaulOrderData order) { - var sight = ship.HaulSeen?.Sights.FirstOrDefault(candidate => candidate.Good.Key.Equals(good)); - if (sight == null || !Fresh(ship, sight)) return int.MaxValue; - return sight.Took > 0 ? Math.Max(1, ProbeFactor * sight.Took) : sight.Left > 0 ? 0 : int.MaxValue; - } - - // The units of the good the hold may still take at From: its load limit less what it carries. - private static int Allowance(Ship ship, CultRecordKey good) - { - var limit = LoadLimit(ship, good); - return limit == int.MaxValue ? int.MaxValue : Math.Max(0, limit - Held(ship, good)); + if (ship.HaulSeen == null) return; + var carried = Carried(ship, order).Select(stack => ((ItemInstance) stack).Data.Key).ToHashSet(); + ship.HaulSeen.Sights.RemoveAll(sight => !Fresh(ship, sight) && !carried.Contains(sight.Good.Key)); } private static int Held(Ship ship, CultRecordKey good) => ship.CargoBays.Sum(bay => bay.Count(good)); @@ -95,7 +87,7 @@ public static class HaulRun if (orbit.Equals(order.From.Key)) return Carried(ship, order).Any(stack => refused.Contains(((ItemInstance) stack).Data.Key) && StationWants.OutputBays(station, ((ItemInstance) stack).Data.Key).Any(bay => bay.TryFindSpace(stack.Split(1)))) - || Goods(order).Where(good => Held(ship, good) < LoadLimit(ship, good)).Any(good => StationWants.OutputBays(station, good).SelectMany(bay => bay.Cargo.Keys).OfType() + || Goods(order).Where(good => !refused.Contains(good)).Any(good => StationWants.OutputBays(station, good).SelectMany(bay => bay.Cargo.Keys).OfType() .Any(stack => ((ItemInstance) stack).Data.Key.Equals(good) && ship.CargoBays.Any(bay => bay.TryFindSpace(stack.Split(1))))); if (orbit.Equals(order.To.Key)) { @@ -118,40 +110,34 @@ public static class HaulRun var now = ship.Zone?.ExactTime ?? 0; if (depot.OrbitData.Equals(order.From.Key)) { + Prune(ship, order); var refused = Refused(ship, order); StationServices.Return(depot, Goods(order).Where(refused.Contains).ToArray(), ship); // The sight's clock starts at the unload: a refusal governs the next load, not the trip home. foreach (var sight in ship.HaulSeen?.Sights.Where(sight => refused.Contains(sight.Good.Key)) ?? Enumerable.Empty()) - { sight.At = now; - if (sight.Took > 0) sight.Left = 0; - } - StationServices.Load(depot, Goods(order), ship, good => Allowance(ship, good)); + StationServices.Load(depot, Goods(order).Where(good => !refused.Contains(good)).ToArray(), ship); } else { var carried = Carried(ship, order).Select(stack => ((ItemInstance) stack).Data.Key).Distinct().ToArray(); var takes = taken; - var delivered = carried.ToDictionary(good => good, good => 0); foreach (var bay in ship.CargoBays.ToArray()) foreach (var stack in bay.Cargo.Keys.OfType().Where(stack => takes.Contains(((ItemInstance) stack).Data.Key)).ToArray()) - delivered[((ItemInstance) stack).Data.Key] += StationServices.TryStorePart(bay, depot, stack).Sold; - Saw(ship, now, carried.Select(good => (good, delivered[good], Held(ship, good)))); + StationServices.TryStorePart(bay, depot, stack); + Saw(ship, now, carried, carried.Where(good => Held(ship, good) > 0)); } depot.TryUndock(ship, piloted: true); return true; } - // Writes down at the To door, for each good the hold carried there: now, the units taken, the units refused. A good is one sight. - private static void Saw(Ship ship, double now, IEnumerable<(CultRecordKey Good, int Took, int Left)> goods) + // Writes down at the To door, for each good the hold carried there (`visited`), whether it was refused (`refused`: still in the hold after + // the delivery) and when. A good is one sight; a good delivered whole has none. + private static void Saw(Ship ship, double now, IReadOnlyCollection visited, IEnumerable refused) { var seen = ship.HaulSeen ?? (ship.HaulSeen = new HaulSeen()); - seen.Sights.RemoveAll(sight => now - sight.At > SightLife); - foreach (var (good, took, left) in goods) - { - seen.Sights.RemoveAll(sight => sight.Good.Key.Equals(good)); - seen.Sights.Add(new HaulSight { Good = new CultRecordRef(good), At = now, Took = took, Left = left }); - } + seen.Sights.RemoveAll(sight => now - sight.At > SightLife || visited.Contains(sight.Good.Key)); + foreach (var good in refused) seen.Sights.Add(new HaulSight { Good = new CultRecordRef(good), At = now, Left = 1 }); } // The GalaxyZone whose live contents hold the orbit; null when none does. diff --git a/Assets/Scripts/ServerShared/StationServices.cs b/Assets/Scripts/ServerShared/StationServices.cs index deeb46ebf..624189bba 100644 --- a/Assets/Scripts/ServerShared/StationServices.cs +++ b/Assets/Scripts/ServerShared/StationServices.cs @@ -144,22 +144,14 @@ public static class StationServices // The bays where the station's outputs land (StationWants.OutputBays: its silo, or every bay with no silo) giving the ship the units of // `goods` they hold, as far as the ship's bays take them. The one writer of a station-to-hauler move; a hauler docks to call it (ruling // docking-is-enclosed-bays). Returns the units moved. - public static int Load(Entity station, IReadOnlyCollection goods, Entity ship, Func allowance = null) + public static int Load(Entity station, IReadOnlyCollection goods, Entity ship) { var into = ship.CargoBays.ToArray(); var loaded = 0; foreach (var good in goods) - { - var left = allowance?.Invoke(good) ?? int.MaxValue; foreach (var bay in StationWants.OutputBays(station, good).ToArray()) foreach (var stack in bay.Cargo.Keys.OfType().Where(stack => ((ItemInstance) stack).Data.Key.Equals(good)).ToArray()) - { - if (left <= 0) break; - var moved = MoveParts(bay, into, stack, null, left); - loaded += moved; - left -= moved; - } - } + loaded += MoveParts(bay, into, stack, null); return loaded; } diff --git a/Assets/Scripts/ServerShared/StationWants.cs b/Assets/Scripts/ServerShared/StationWants.cs index fffebfee2..d1ea24ec6 100644 --- a/Assets/Scripts/ServerShared/StationWants.cs +++ b/Assets/Scripts/ServerShared/StationWants.cs @@ -142,7 +142,7 @@ public class HaulOrderData } // What a hauler last saw at its To station's door (ruling hauler-remembers-what-it-saw): for each good of its order that it carried there, -// when (zone time of the visit), how many units the station took (Took) and how many it refused (Left). The hauler's own knowledge, set +// whether the station refused it (Left, units refused) and when (zone time of the visit). The hauler's own knowledge, set // at the door and read to choose its leg and its load; saved with it (EntityPack Key 25). A sight lives HaulRun.SightLife seconds. [MessagePackObject, JsonObject(MemberSerialization.OptIn)] public class HaulSeen @@ -150,7 +150,7 @@ public class HaulSeen [JsonProperty("sights"), Key(0)] public List Sights = new List(); // A copy no later visit changes: what a pack holds and what the ship holds are never one list. - public HaulSeen Copy() => new HaulSeen { Sights = Sights.Select(sight => new HaulSight { Good = sight.Good, At = sight.At, Took = sight.Took, Left = sight.Left }).ToList() }; + public HaulSeen Copy() => new HaulSeen { Sights = Sights.Select(sight => new HaulSight { Good = sight.Good, At = sight.At, Left = sight.Left }).ToList() }; } [MessagePackObject, JsonObject(MemberSerialization.OptIn)] @@ -158,8 +158,7 @@ public class HaulSight { [JsonProperty("good"), Key(0)] public CultRecordRef Good; [JsonProperty("at"), Key(1)] public double At; - [JsonProperty("took"), Key(3)] public int Took; - [JsonProperty("left"), Key(4)] public int Left; + [JsonProperty("left"), Key(3)] public int Left; // Element identity: minted by the cache on write; "" means unset. [Key(2)] [CultElementId] public string Id = ""; } diff --git a/tests/Aetheria.Shared.Tests/RegionLegsMemoryTests.cs b/tests/Aetheria.Shared.Tests/RegionLegsMemoryTests.cs index 4fdc779f9..2491d9c74 100644 --- a/tests/Aetheria.Shared.Tests/RegionLegsMemoryTests.cs +++ b/tests/Aetheria.Shared.Tests/RegionLegsMemoryTests.cs @@ -33,6 +33,7 @@ public sealed partial class RunStartTests { var (galaxy, _, legs) = SeededRegion(1, quiet: true); var leg = legs.First(candidate => candidate.Path.Length >= 2); + RegionClock.Advance(galaxy, null, 1000); Stock(leg.From, leg.Good, 10); var before = Held(new[] { leg.From }, leg.Good); Assert.True(HaulRun.Call(leg.Hauler, leg.From)); @@ -46,7 +47,8 @@ public sealed partial class RunStartTests Assert.Equal(1, visits); Assert.Equal(0, Held(new[] { leg.To }, leg.Good)); Assert.NotNull(leg.Hauler.HaulSeen); - Assert.Contains(leg.Hauler.HaulSeen.Sights, refusal => refusal.Good.Key.Equals(leg.Good)); + var written = Assert.Single(leg.Hauler.HaulSeen.Sights, refusal => refusal.Good.Key.Equals(leg.Good)); + Assert.Equal(leg.ToZone.Contents.ExactTime, written.At); Assert.Equal(0, Held(new[] { leg.Hauler }, leg.Good)); Assert.Equal(before, Held(new[] { leg.From }, leg.Good)); Assert.Same(leg.FromZone.Contents, leg.Hauler.Zone); @@ -101,6 +103,7 @@ public sealed partial class RunStartTests Assert.Equal(0, Held(new[] { leg.Hauler }, a)); Assert.Equal(zone.ExactTime, leg.Hauler.HaulSeen.Sights[0].At); Assert.Contains(a, HaulRun.Refused(leg.Hauler, leg.Order)); + Assert.Equal(1, leg.Hauler.HaulSeen.Sights[0].Left); // the sight keeps what was refused: it governs the next load leg.Hauler.HaulSeen.Sights[0].At = zone.ExactTime - 601; Assert.DoesNotContain(a, HaulRun.Refused(leg.Hauler, leg.Order)); } @@ -155,19 +158,19 @@ public sealed partial class RunStartTests { var (_, _, legs) = SeededRegion(1, quiet: true); var leg = legs.First(); - leg.Hauler.HaulSeen = new HaulSeen { Sights = { new HaulSight { Good = new CultRecordRef(leg.Good), At = 123.5, Took = 4, Left = 2 } } }; + leg.Hauler.HaulSeen = new HaulSeen { Sights = { new HaulSight { Good = new CultRecordRef(leg.Good), At = 123.5, Left = 2 } } }; var pack = EntitySerializer.Pack(leg.Hauler); leg.Hauler.HaulSeen.Sights[0].At = 999; var restored = (Ship) EntitySerializer.Unpack(_items, leg.FromZone.Contents, pack); var refusal = Assert.Single(restored.HaulSeen.Sights); - Assert.Equal((leg.Good, 123.5, 4, 2), (refusal.Good.Key, refusal.At, refusal.Took, refusal.Left)); + Assert.Equal((leg.Good, 123.5, 2), (refusal.Good.Key, refusal.At, refusal.Left)); Assert.NotSame(pack.HaulSeen, restored.HaulSeen); } - // The visit writes down what the door took and refused, and when: with the To bays free the hauler delivers, the sight reads the units it - // gave and none refused, dated by the To zone's clock, and a delivered good is no refusal. + // A visit that delivers writes no sight: with the To bays free the hauler delivers the load whole, the good has no refusal, and what it + // gave is in the station. [Fact] - public void AVisitWritesWhatTheDoorTookAndWhen() + public void AVisitThatDeliversWritesNoSight() { var (galaxy, _, legs) = SeededRegion(1, quiet: true); var leg = legs.First(candidate => candidate.Path.Length >= 2); @@ -179,33 +182,76 @@ public sealed partial class RunStartTests HaulRun.Fly(leg.Hauler, 6000, null, AllZones(galaxy)); var delivered = Held(new[] { leg.To }, leg.Good) - before; Assert.True(delivered > 0); - var sight = leg.Hauler.HaulSeen.Sights.First(candidate => candidate.Good.Key.Equals(leg.Good)); - Assert.Equal((delivered, 0), (sight.Took, sight.Left)); - Assert.Equal(leg.ToZone.Contents.ExactTime, sight.At); Assert.Equal(carried, delivered + Held(new[] { leg.Hauler }, leg.Good)); + Assert.DoesNotContain(leg.Hauler.HaulSeen?.Sights ?? new List(), sight => sight.Good.Key.Equals(leg.Good)); Assert.DoesNotContain(leg.Good, HaulRun.Refused(leg.Hauler, leg.Order)); } - // A hauler loads toward what the door took on its last visit, not a whole hold: with a fresh sight of 3 units taken, a call at a From that - // holds twenty loads six, twice what was taken (it probes upward). + // One rule for a sight, read by Load and Return alike: a stale sight of a good the hold does not carry is dropped before the load, so the + // good loads and is not returned at the next dock (Soul's w1; the hauler used to load it and give it back every 660 s for ever); a fresh + // refusal loads none of the good. [Fact] - public void ALoadFollowsWhatTheDoorTook() + public void AStaleSightIsDroppedBeforeTheLoad() { var (_, _, legs) = SeededRegion(1, quiet: true); var leg = legs.First(candidate => candidate.Path.Length >= 2); + var zone = leg.FromZone.Contents; Stock(leg.From, leg.Good, 20); - leg.Hauler.HaulSeen = new HaulSeen { Sights = { new HaulSight { Good = new CultRecordRef(leg.Good), At = leg.FromZone.Contents.ExactTime, Took = 3 } } }; + leg.Hauler.HaulSeen = new HaulSeen { Sights = { new HaulSight { Good = new CultRecordRef(leg.Good), At = zone.ExactTime - 700, Left = 1 } } }; Assert.True(HaulRun.Call(leg.Hauler, leg.From)); - Assert.Equal(6, Held(new[] { leg.Hauler }, leg.Good)); - Assert.Equal(2, HaulRun.ProbeFactor); - Assert.False(HaulRun.CanCall(leg.Hauler, leg.From, leg.Order) && Held(new[] { leg.Hauler }, leg.Good) >= 6 && HaulRun.Leg(leg.Hauler, leg.Order).Equals(leg.From.OrbitData)); + Assert.True(Held(new[] { leg.Hauler }, leg.Good) > 0); + Assert.Empty(leg.Hauler.HaulSeen.Sights); + Assert.Equal(leg.To.OrbitData, HaulRun.Leg(leg.Hauler, leg.Order)); + Assert.False(HaulRun.CanCall(leg.Hauler, leg.From, leg.Order) && HaulRun.Refused(leg.Hauler, leg.Order).Contains(leg.Good)); + + var (_, _, again) = SeededRegion(1, quiet: true); + var fresh = again.First(candidate => candidate.Path.Length >= 2); + Stock(fresh.From, fresh.Good, 20); + fresh.Hauler.HaulSeen = new HaulSeen { Sights = { new HaulSight { Good = new CultRecordRef(fresh.Good), At = fresh.FromZone.Contents.ExactTime - 100, Left = 1 } } }; + Assert.False(HaulRun.CanCall(fresh.Hauler, fresh.From, fresh.Order)); + Assert.Equal(0, Held(new[] { fresh.Hauler }, fresh.Good)); + } + + // No hauler loads at From and gives the load back at its next dock at From without a visit to To between: over 24 sim h on seed 2 and + // seed 1. That was the livelock of a stale sight that loaded a whole hold and returned it every 660 s, which ate 38 to 49 percent of + // hauler-seconds (Soul s4). Counted per hauler from its docks and the units it leaves a dock with. + [Fact] + public void NoHaulerLoadsAtFromAndReturnsItAtFrom() + { + foreach (var seed in new uint[] { 1, 2 }) + { + var (galaxy, _, legs) = SeededRegion(seed); + int Units(Ship ship, HaulOrderData order) => order.Goods.Sum(good => Held(new[] { (Entity) ship }, good.Key)); + var loadedAtFrom = legs.ToDictionary(leg => leg.Hauler, leg => false); + var atFromBefore = new Dictionary(); + var loops = 0; + foreach (var leg in legs) + { + var l = leg; + l.Hauler.Docked.Subscribe(station => + { + if (ReferenceEquals(station, l.To)) { loadedAtFrom[l.Hauler] = false; return; } + if (!ReferenceEquals(station, l.From)) return; + var carried = Units(l.Hauler, l.Order); + if (loadedAtFrom[l.Hauler] && carried > 0) loops++; + atFromBefore[l.Hauler] = carried; + }); + } + foreach (var zone in galaxy.Zones.Select(candidate => candidate.Contents)) + zone.Entities.ObserveAdd().Subscribe(add => + { + if (add.Value is Ship ship && atFromBefore.Remove(ship, out var before) && Units(ship, legs.First(l => l.Hauler == ship).Order) > before) loadedAtFrom[ship] = true; + }); + AdvanceBy(galaxy, null, 0, 24 * 3600); + Assert.True(loops == 0, $"seed {seed}: {loops} loads returned at From"); + } } // No ping-pong: over 24 sim h on seed 2 a hauler never turns straight back through the wormhole it came by without a call between (the // refusal expiring under its own cargo made it do so 238 times). Counted per hauler from the admissions into zones and its docks. - // Bound (margin rule): 1518 wormhole transfers shipped on seed 2 over 24 sim h; the refusal expiring under its cargo gave 4262. - // sqrt(1518 * 4262) = 2543, 1.7 from each. - private const int TransferBound = 2543; + // Bound (margin rule): 2683 wormhole transfers shipped on seed 2 over 24 sim h (empty learning visits are about half the door calls); the + // refusal expiring under its cargo gave 4262. sqrt(2683 * 4262) = 3382, 1.26 from each. + private const int TransferBound = 3382; [Fact] public void NoHaulerTurnsBackWithoutACall()