ModernUO/Projects/Server/Serialization/GenericPersistence.cs
Kamron Batman 5570537aa0
fix: anchored times shift only while still running at save start (#2730)
Follow-up to #2729.

## Problem

At load, `ReadAnchoredTime` shifted **every** anchored value forward by the downtime, including values that were already in the past when the save started. That caused two problems.

**An expired deadline came back.** A deadline that passed 5 minutes before a 30-minute outage loaded 25 minutes in the future. For example:
- `Sheep.NextWoolTime`: a sheep that was ready to shear stopped being ready.
- `PlayerVendor.NextPayTime`: an overdue payment was pushed back.
- `BaseCreature.SummonEnd`, the spell fields' `End`, `TransientItem.Expiration`, and the ChampionSpawn times could move the same way.

**Records were rewritten for nothing.** The first save after every restart rewrote:
- stamps of things that had already happened: VirtueContext's `LastHonorUse`, `LastSacrificeGain`, the four `Last*Loss` stamps, and `Corpse.TimeOfDeath`
- every deadline that had expired long ago.

## Change

- **`IGenericReader.AnchoredTimeOrigin`** is the loaded save's start time.
  - `GenericEntityPersistence` and `GenericPersistence` set it from `World.LoadedSaveStartTime`.
  - `BufferReader`, `UnmanagedDataReader` and `BinaryFileReader` expose it.
- **`ReadAnchoredTime` returns any value at or before the origin exactly as saved.**
  - A deadline still running at save start is shifted as before and keeps its remaining time.
  - Readers without an origin keep the old behaviour.
- **This covers every anchored field, including generated ones.** Generated `[AnchoredDateTime]` fields call `reader.ReadAnchoredTime()`, so the one change covers all 26 generated fields as well as the manual reads. `[DeserializeTimer]` only restores timers that were running at save time, so it is unaffected.
- **The `[AnchoredDateTime]` section of `dev-docs/serialization.md` and the `WriteAnchoredTime` doc comment describe the new rule.**

## Behaviour change

Downtime now counts toward windows measured from a past stamp:

| Window | Length |
|---|---|
| Honor use | 5 minutes |
| Sacrifice gain | 1 day |
| Virtue atrophy | 7 days |
| Instanced corpse looting | 3 minutes |

A 30-minute outage makes a 7-day atrophy fire about 0.3% sooner. No format change.

## Tests

New tests in `AnchoredTimeTests`:
- A deadline running at save start keeps its remaining time.
- A deadline that passed before save start stays passed.
- A past stamp is not shifted.
- A value exactly at save start is not shifted.

`Server.Tests`: 845 passed. `UOContent.Tests`: 1140 passed.
2026-10-25 16:44:33 -07:00

139 lines
5.1 KiB
C#

/*************************************************************************
* ModernUO *
* Copyright 2019-2026 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: GenericPersistence.cs *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.MemoryMappedFiles;
namespace Server;
public abstract class GenericPersistence : Persistence, IGenericSerializable
{
public string Name { get; }
public string SaveFilePath { get; protected set; } // "<Folder>/<System>.bin"
// Placement of the self-payload in the worker heaps for the most recent save. Only
// persistences carry placement state — entities are located through the per-worker
// segment logs instead.
private protected byte _selfThread;
private protected int _selfPosition;
private protected int _selfLength;
internal void SetSelfPlacement(byte thread, int position, int length)
{
_selfThread = thread;
_selfPosition = position;
_selfLength = length;
}
private long _loadedFileLength;
// Scheduling estimate only: previous save's payload size, or the loaded file size before the first save.
internal long EstimatedSize => _selfLength > 0 ? _selfLength : _loadedFileLength;
public GenericPersistence(string name, int priority) : base(priority)
{
Name = name;
SaveFilePath = Path.Combine(Name, $"{Name}.bin");
}
public override void Serialize()
{
// Always a dedicated chunk: self-payloads can be arbitrarily large and must not
// ride inside a shared chunk where one worker would serialize them plus the chunk.
World.PushSingleToCache(this);
}
public override void WriteSnapshot(string savePath)
{
if (_selfLength == 0)
{
return;
}
var file = Path.Combine(savePath, SaveFilePath);
var dir = Path.GetDirectoryName(file);
PathUtility.EnsureDirectory(dir);
var threads = World._threadWorkers;
using var binFs = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None);
binFs.Write(threads[_selfThread].GetHeap(_selfPosition, _selfLength));
}
public override unsafe void Deserialize(string savePath, Dictionary<ulong, string> typesDb)
{
// Assume savePath has the Core.BaseDirectory already prepended
var dataPath = Path.GetFullPath(SaveFilePath, savePath);
var file = new FileInfo(dataPath);
if (!file.Exists || file.Length <= 0)
{
return;
}
var fileLength = file.Length;
_loadedFileLength = fileLength;
string error;
try
{
using var mmf = MemoryMappedFile.CreateFromFile(dataPath, FileMode.Open);
using var accessor = mmf.CreateViewStream();
byte* ptr = null;
accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref ptr);
var dataReader = new UnmanagedDataReader(ptr, accessor.Length, typesDb)
{
// These payloads carry no anchor of their own; they inherit the save-wide
// shift stamped while the entity indexes were read (indexes always load
// before persistence payloads — see Persistence.Load).
AnchoredTimeShift = World.LoadTimeShift,
AnchoredTimeOrigin = World.LoadedSaveStartTime
};
Deserialize(dataReader);
error = dataReader.Position != fileLength
? $"Serialized {fileLength} bytes, but {dataReader.Position} bytes deserialized"
: null;
accessor.SafeMemoryMappedViewHandle.ReleasePointer();
}
catch (Exception e)
{
error = e.ToString();
}
if (error != null)
{
Console.WriteLine($"***** Bad deserialize of {file.FullName} *****");
Console.WriteLine(error);
Console.Write("Skip this file and continue? (y/n): ");
var y = ConsoleInputHandler.ReadLine();
if (!y.InsensitiveEquals("y"))
{
throw new Exception("Deserialization failed.");
}
}
}
public abstract void Serialize(IGenericWriter writer);
public abstract void Deserialize(IGenericReader reader);
}