Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Docs/ImportActivateSlices.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,11 @@ hierarchy, game logic, update unregistration, render, `OnEntityDelete`, id table
someone else queued for delete before this frame's `DeleteRememberedEntities`. Read them as the `add*`
fields.

When the source slices a release, it closes the partition members first. The `release_descendants`
phase then reports how many child IDs the source captured (`capturedDescendants`) and how many
survived grid teardown as live world entities (`entities`). Those survivors, including detached
pilots, close under the same per-frame limit.

### Node-age tags (T-0401, same knob)

The bench put the first import on a fresh node at 3.70 ms/entity, the second at 1.45, warm 0.86 (live 1.8 p50).
Expand Down
82 changes: 50 additions & 32 deletions Shared/Cluster/ClusterControlServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5411,9 +5411,9 @@ internal static int AdoptClientView(ulong client, string state, bool ownBindings
}

/// <summary>
/// Handler-thread driver. release.closePerFrame=0 (default): one game-thread Invoke as before.
/// N>0: the released roots are closed N per frame (hierarchy children go with their root), then
/// the bookkeeping runs in a final frame - the close stall of a large grid becomes short frames.
/// The handler closes the whole transfer in one game-thread call when release.closePerFrame is zero.
/// With a positive limit, each frame closes at most that many roots. A grid and its attached
/// blocks close together. Detached children are collected after the members close.
/// </summary>
private static int Release(Guid transferId, ulong partitionId, uint generation)
{
Expand Down Expand Up @@ -5451,26 +5451,49 @@ private static int Release(Guid transferId, ulong partitionId, uint generation)
try
{
int closed = 0;
// Roots first, then the descendants vanilla may have re-topped (see ReleaseFinish's caller
// history): a seated pilot closes with its grid, a detached one in its own slice.
long[][] slices = chunked
.Members.Concat(chunked.Descendants)
.Distinct()
.Chunk(perFrame)
.ToArray();
foreach (long[] slice in slices)
closed += InvokePhase(
"release_close",
void CloseSlices(IEnumerable<long> ids)
{
foreach (long[] slice in ids.Chunk(perFrame))
closed += InvokePhase(
"release_close",
transferId,
partitionId,
() =>
{
ImportAddSlice timed = ReleaseTimers();
int count = CloseEntities(slice, timed);
AppendReleaseFields(timed, chunkedIndex);
return count;
}
);
}

CloseSlices(chunked.Members);
if (chunked.Descendants.Count > 0)
{
// Grid teardown closes its fat blocks. Only children that survived as world
// entities (such as a detached pilot) still need their own release slice.
long[] survivors = InvokePhase(
"release_descendants",
transferId,
partitionId,
() =>
{
ImportAddSlice timed = ReleaseTimers();
int count = CloseEntities(slice, timed);
AppendReleaseFields(timed, chunkedIndex);
return count;
long[] live = LiveCloseTargets(
chunked.Descendants.Where(id => !chunked.Members.Contains(id))
)
.Select(entity => entity.EntityId)
.ToArray();
if (HandoverPhaseTimer.Current is HandoverPhaseTimer timer)
{
timer.Entities = live.Length;
timer.Fields = $" capturedDescendants={chunked.Descendants.Count}";
}
return live;
}
);
CloseSlices(survivors);
}
return InvokePhase(
"release_finish",
transferId,
Expand Down Expand Up @@ -6155,26 +6178,21 @@ private static void AppendReleaseFields(ImportAddSlice timed, int releaseIndex)
timer.Fields += timed.ReleaseFields() + NodeAgeCounter.Releases.Fields(releaseIndex);
}

private static IEnumerable<MyEntity> LiveCloseTargets(IEnumerable<long> ids)
{
// An id can identify a dormant incarnation outside the world entity set. Only a live
// world entity can be closed here. The direct lookups avoid scanning the world per slice.
var world = MyEntities.GetEntities();
return ids.Select(id => MyEntities.GetEntityByIdOrDefault(id))
.Where(entity => entity != null && !entity.MarkedForClose && world.Contains(entity));
}

/// <param name="release">T-0401: when set (a source release with diag.importAddTimers), the close sequence below
/// runs unchanged inside ImportAddDiag.RunRelease, which times it; null runs it exactly as before.</param>
private static int CloseEntities(IEnumerable<long> ids, ImportAddSlice release = null)
{
HashSet<long> selected = ids.ToHashSet();
int count = 0;
// Was MyEntities.GetEntities().Where(e => selected.Contains(e.EntityId) ...), a full
// world scan per call - and release.closePerFrame calls this ONCE PER SLICE, so a chunked release
// re-scanned the whole world for every chunk. Looking each id up directly is O(ids) instead of
// O(world x chunks), and it stops enumerating MyConcurrentHashSet, which was 678.6 ms of contended
// lock wait in the one 30 s trace that happened to span a handover (n4b, 2026-08-22).
// The predicate is preserved EXACTLY, including the membership test: GetEntityByIdOrDefault consults
// MyEntityIdentifier, which can hold ids that are not in the world entity set, and closing one of
// those is precisely the stray-incarnation class of bug this method exists to avoid. Contains on a
// MyConcurrentHashSet is O(1), so keeping the test costs nothing.
var world = MyEntities.GetEntities();
MyEntity[] targets = selected
.Select(id => MyEntities.GetEntityByIdOrDefault(id))
.Where(entity => entity != null && !entity.MarkedForClose && world.Contains(entity))
.ToArray();
MyEntity[] targets = LiveCloseTargets(ids.ToHashSet()).ToArray();
// Closing a grid ejects its seated pilot (grid close -> RemovePilot) into a live top-level
// entity that outlives this sweep and gets adopted as a stray duplicate (partition 28,
// 2026-08-10). Hierarchy children go down with the entity they are attached to.
Expand Down
44 changes: 44 additions & 0 deletions Test/scenarios_ext.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import json
import os
import re
import subprocess
import sys
import time
Expand Down Expand Up @@ -843,6 +844,48 @@ def _verified_round_trip(bench, grid: int, partition: int, home: str, client: in
f"blocks {before.get('blocks')} -> {state.get('blocks')}")


def p3_hnd_release_slices(bench) -> None:
"""SE-1908: closing a grid with many fat blocks spends slices only on live roots."""
from scenarios import _force_handover

bench.start_cluster()
bench.cluster.post("/automatic/pause")
try:
bench.cluster.handover_config({"release.closePerFrame": "1", "diag.importAddTimers": "true"})
wait_until(
lambda: bench.cluster.node("node-1", "/config")["values"]["release.closePerFrame"] == "1",
30,
"source to apply release slicing",
)
started = bench.cluster.node("node-1", "/rich-test-spawn?kind=rich&x=900000&y=0&z=0", "POST")["grids"][0]
grid = started["grid"]
partition = _wait_partition(bench, "node-1", grid)
_force_handover(bench, "node-1", "node-2", partition)
_wait_arrival(bench, partition, "node-2")
after = _settled_state(bench, "node-2", grid)
bench.check(
"the transfer preserves the rich grid",
started["blocks"] >= 45 and after["blocks"] == started["blocks"],
f"{started['blocks']} -> {after['blocks']} blocks",
)
game_log = next((bench.run_root / "node-1-data").glob("SpaceEngineersDedicated_*.log"))
finish = f"partition={partition} phase=release_finish "
wait_until(lambda: finish in game_log.read_text(errors="replace"), 15, "source release to be logged")
close = re.compile(rf"partition={partition} phase=release_close .*? relN=(\d+).*? relFatBlocksSum=(\d+)")
frames = [(int(roots), int(blocks)) for roots, blocks in close.findall(game_log.read_text(errors="replace"))]
bench.record("release-slices", frames)
bench.check(
"the source closed the grid and its fat blocks", sum(blocks for _, blocks in frames) >= 10, str(frames)
)
bench.check(
"every close frame closed one live root",
bool(frames) and all(roots == 1 for roots, _ in frames),
f"close frames={len(frames)}, roots closed={sum(roots for roots, _ in frames)}",
)
finally:
bench.cluster.post("/automatic/resume")


def _assert_normalizer_committed(bench) -> None:
"""The normalizer the PACKAGE was built from: its source at the manifest's commit, read from
the checkout the suite runs in (the package ships binaries only)."""
Expand Down Expand Up @@ -1934,6 +1977,7 @@ def p1_char_noident(bench) -> None:
"T0266-HVK-02": (t0266_hvk_02, "T-0266 harness: real release paths under the Havok body audit", "1"),
"T0266-HVK-03": (t0266_hvk_03, "T-0266 harness: cluster release/offline paths in a procedural world", "1"),
"T0266-HVK-01": (t0266_hvk_01, "closing an entity with an already-destroyed native body does not crash", "1"),
"P3-HND-RELEASE-SLICES": (p3_hnd_release_slices, "SE-1908: chunked release only schedules surviving world entities", "3"),
"P3-HND-01": (p3_hnd_01, "round-trip fidelity on rich content, both directions, both modes", "3"),
"P3-HND-02": (p3_hnd_02, "transient interaction-state matrix", "3"),
"P3-HND-DUMMY": (p3_hnd_dummy, "SE1-0225: a target dummy round-trips the gate, intact and destroyed", "3"),
Expand Down