Merge pull request #460 from opengenesislink/fix/hg-foreign-presence-20261118

fix(gen1): Hypergrid visitor online ghosts, UUI normalization and pending presence cleanup
This commit is contained in:
OpenGenesis (MPL 2.0) authored and GitHub committed 2026-11-18 08:30:19 +01:00
commit 62cc44447c
10 files changed
+232 -78

No files matched your search

+7
View File
@@ -993,6 +993,13 @@ jobs:
python3 tools/ci/verify_gen1_approved_viewer_access.py
dotnet run --project tools/ci/OglApprovedViewerRegression/OglApprovedViewerRegression.csproj --configuration Release
- name: Verify Hypergrid foreign presence and GridUser canonicalization
shell: bash
run: |
set -euo pipefail
python3 tools/ci/verify_hg_foreign_presence.py
dotnet run --project tools/ci/HGForeignPresenceRegression/HGForeignPresenceRegression.csproj --configuration Release
- name: Verify NexBus shutdown race and Wolfvoice integration
shell: bash
run: |
@@ -917,9 +917,19 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
if (aCircuit != null && aCircuit.ServiceURLs != null && aCircuit.ServiceURLs.ContainsKey("HomeURI"))
{
string url = aCircuit.ServiceURLs["HomeURI"].ToString();
IUserAgentService security = new UserAgentServiceConnector(url);
security.LogoutAgent(obj.AgentId, obj.SessionId);
//m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Sent logout call to UserAgentService @ {0}", url);
// A foreign home grid may be offline during logout. Do not
// throw from the OnConnectionClosed multicast event: other
// listeners must still clear local GridUser and Presence.
try
{
IUserAgentService security = new UserAgentServiceConnector(url);
security.LogoutAgent(obj.AgentId, obj.SessionId);
}
catch (Exception error)
{
m_log.WarnFormat("[HG ENTITY TRANSFER MODULE]: Foreign home logout unavailable ({0}); continuing local disconnect cleanup",
error.GetType().Name);
}
}
else
{
@@ -507,6 +507,7 @@ namespace OpenSim.Services.HypergridService
m_log.DebugFormat("[GATEKEEPER SERVICE]: User {0} is ok", aCircuit.Name);
bool isFirstLogin = false;
bool createdPresence = false;
//
// Login the presence, if it's not there yet (by the login service)
//
@@ -523,90 +524,114 @@ namespace OpenSim.Services.HypergridService
aCircuit.firstname, aCircuit.lastname);
return false;
}
createdPresence = true;
}
//
// Get the region
//
destination = m_GridService.GetRegionByUUID(m_ScopeID, destination.RegionID);
if (destination is null)
// The gatekeeper creates a provisional Presence before QueryAccess
// and CreateAgent. On any rejected/failed arrival it must remove
// ONLY the session it created (never an existing login session).
bool regionAccepted = false;
try
{
reason = "Destination region not found";
return false;
}
m_log.DebugFormat(
"[GATEKEEPER SERVICE]: Destination {0} is ok for {1}", destination.RegionName, aCircuit.Name);
//
// Adjust the visible name
//
if (account is not null)
{
aCircuit.firstname = account.FirstName;
aCircuit.lastname = account.LastName;
}
if (account is null)
{
if (!aCircuit.lastname.StartsWith("@"))
aCircuit.firstname = aCircuit.firstname + "." + aCircuit.lastname;
try
destination = m_GridService.GetRegionByUUID(m_ScopeID, destination.RegionID);
if (destination is null)
{
Uri uri = new(aCircuit.ServiceURLs["HomeURI"].ToString());
aCircuit.lastname = "@" + uri.Authority;
reason = "Destination region not found";
return false;
}
catch
m_log.DebugFormat(
"[GATEKEEPER SERVICE]: Destination {0} is ok for {1}", destination.RegionName, aCircuit.Name);
//
// Adjust the visible name
//
if (account is not null)
{
m_log.WarnFormat("[GATEKEEPER SERVICE]: Malformed HomeURI (this should never happen): {0}", aCircuit.ServiceURLs["HomeURI"]);
aCircuit.lastname = "@" + aCircuit.ServiceURLs["HomeURI"].ToString();
aCircuit.firstname = account.FirstName;
aCircuit.lastname = account.LastName;
}
}
//
// Finally launch the agent at the destination
//
Constants.TeleportFlags loginFlag = isFirstLogin ? Constants.TeleportFlags.ViaLogin : Constants.TeleportFlags.ViaHGLogin;
// Preserve our TeleportFlags we have gathered so-far
loginFlag |= (Constants.TeleportFlags) aCircuit.teleportFlags;
m_log.DebugFormat("[GATEKEEPER SERVICE]: Launching {0}, Teleport Flags: {1}", aCircuit.Name, loginFlag);
EntityTransferContext ctx = new();
if (!m_SimulationService.QueryAccess(
destination, aCircuit.AgentID, aCircuit.ServiceURLs["HomeURI"].ToString(),
true, aCircuit.startpos, new List<UUID>(), ctx, out reason))
return false;
bool didit = m_SimulationService.CreateAgent(source, destination, aCircuit, (uint)loginFlag, ctx, out reason);
if(didit)
{
m_log.DebugFormat("[GATEKEEPER SERVICE]: Login presence {0} is ok", aCircuit.Name);
if(!isFirstLogin && m_GridUserService is not null && account is null)
if (account is null)
{
// Also login foreigners with GridUser service
string userId = aCircuit.AgentID.ToString();
string first = aCircuit.firstname, last = aCircuit.lastname;
if (last.StartsWith("@"))
if (!aCircuit.lastname.StartsWith("@"))
aCircuit.firstname = aCircuit.firstname + "." + aCircuit.lastname;
try
{
string[] parts = aCircuit.firstname.Split('.');
if (parts.Length >= 2)
{
first = parts[0];
last = parts[1];
}
Uri uri = new(aCircuit.ServiceURLs["HomeURI"].ToString());
aCircuit.lastname = "@" + uri.Authority;
}
catch
{
m_log.WarnFormat("[GATEKEEPER SERVICE]: Malformed HomeURI (this should never happen): {0}", aCircuit.ServiceURLs["HomeURI"]);
aCircuit.lastname = "@" + aCircuit.ServiceURLs["HomeURI"].ToString();
}
}
userId += ";" + aCircuit.ServiceURLs["HomeURI"] + ";" + first + " " + last;
m_GridUserService.LoggedIn(userId);
//
// Finally launch the agent at the destination
//
Constants.TeleportFlags loginFlag = isFirstLogin ? Constants.TeleportFlags.ViaLogin : Constants.TeleportFlags.ViaHGLogin;
// Preserve our TeleportFlags we have gathered so-far
loginFlag |= (Constants.TeleportFlags) aCircuit.teleportFlags;
m_log.DebugFormat("[GATEKEEPER SERVICE]: Launching {0}, Teleport Flags: {1}", aCircuit.Name, loginFlag);
EntityTransferContext ctx = new();
if (!m_SimulationService.QueryAccess(
destination, aCircuit.AgentID, aCircuit.ServiceURLs["HomeURI"].ToString(),
true, aCircuit.startpos, new List<UUID>(), ctx, out reason))
return false;
bool didit = m_SimulationService.CreateAgent(source, destination, aCircuit, (uint)loginFlag, ctx, out reason);
regionAccepted = didit;
if(didit)
{
m_log.DebugFormat("[GATEKEEPER SERVICE]: Login presence {0} is ok", aCircuit.Name);
if(!isFirstLogin && m_GridUserService is not null && account is null)
{
// Also login foreigners with GridUser service
string userId = aCircuit.AgentID.ToString();
string first = aCircuit.firstname, last = aCircuit.lastname;
if (last.StartsWith("@"))
{
string[] parts = aCircuit.firstname.Split('.');
if (parts.Length >= 2)
{
first = parts[0];
last = parts[1];
}
}
userId += ";" + aCircuit.ServiceURLs["HomeURI"] + ";" + first + " " + last;
m_GridUserService.LoggedIn(userId);
}
}
return didit;
}
finally
{
if (createdPresence && !regionAccepted)
{
try
{
m_PresenceService.LogoutAgent(aCircuit.SessionID);
}
catch (Exception e)
{
m_log.WarnFormat("[GATEKEEPER SERVICE]: Failed to release a rejected provisional presence: {0}",
e.GetType().Name);
}
}
}
return didit;
}
protected bool Authenticate(AgentCircuitData aCircuit)
@@ -212,6 +212,9 @@ namespace OpenSim.Services.PresenceService
{
if(ByUserCache.TryGetValue(userIDStr, out PresenceData pd))
{
// A pending login with no region is not an online avatar.
if (pd.RegionID.IsZero())
continue;
ByUserCache.Add(pd.UserID, pd, EXPIREMS);
BySessionCache.Add(pd.SessionID, pd, EXPIREMS);
ret = new PresenceInfo()
@@ -227,6 +230,8 @@ namespace OpenSim.Services.PresenceService
if(data.Length == 0)
continue;
PresenceData d = data[0];
if (d.RegionID.IsZero())
continue;
ByUserCache.Add(d.UserID, d, EXPIREMS);
BySessionCache.Add(d.SessionID, d, EXPIREMS);
ret = new PresenceInfo()
@@ -131,10 +131,28 @@ namespace OpenSim.Services.UserAccountService
// A foreign visitor is identified by UUID;HomeURI;display-name,
// not the bare 36-character UUID. Separate cache entries are
// essential: UUID collisions can exist across distinct home grids.
// LoginAgent may receive a HomeURI ending in '/', while the region's
// UserManagementModule can return the same HomeURI without that slash.
// Normalize both before consulting the cache AND before database writes,
// otherwise a foreign avatar's logout creates a separate offline row
// and leaves the original row permanently online.
private static string CanonicalHGUserID(string userID)
{
if (String.IsNullOrEmpty(userID) || userID.Length <= 36 || userID[36] != ';')
return userID;
int homeEnd = userID.IndexOf(';', 37);
if (homeEnd <= 37)
return userID;
string home = userID.Substring(37, homeEnd - 37);
return userID.Substring(0, 37) + home.TrimEnd('/') + "/" + userID.Substring(homeEnd);
}
private static string GridUserCacheKey(string userID)
{
if (userID.Length > 36 && userID[36] == ';')
return userID;
return CanonicalHGUserID(userID);
return userID.Length > 36 ? userID.Substring(0, 36) : userID;
}
@@ -155,8 +173,8 @@ namespace OpenSim.Services.UserAccountService
// UserID lookup.
if (userID.Length > 36 && userID[36] == ';')
{
GridUserData exact = m_Database.Get(userID);
CacheGridUser(userID, exact);
GridUserData exact = m_Database.Get(cacheKey);
CacheGridUser(cacheKey, exact);
return exact;
}
@@ -269,6 +287,7 @@ namespace OpenSim.Services.UserAccountService
public GridUserInfo LoggedIn(string userID)
{
userID = GridUserCacheKey(userID);
m_log.DebugFormat("[GRID USER SERVICE]: User {0} is online", userID);
GridUserData d = GetGridUserData(userID);
@@ -290,6 +309,7 @@ namespace OpenSim.Services.UserAccountService
public bool LoggedOut(string userID, UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt)
{
userID = GridUserCacheKey(userID);
m_log.DebugFormat("[GRID USER SERVICE]: User {0} is offline", userID);
GridUserData d = GetGridUserData(userID);
@@ -316,6 +336,7 @@ namespace OpenSim.Services.UserAccountService
public bool SetHome(string userID, UUID homeID, Vector3 homePosition, Vector3 homeLookAt)
{
userID = GridUserCacheKey(userID);
GridUserData d = GetGridUserData(userID);
if (d == null)
@@ -338,6 +359,7 @@ namespace OpenSim.Services.UserAccountService
public bool SetLastPosition(string userID, UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt)
{
userID = GridUserCacheKey(userID);
// m_log.DebugFormat("[GRID USER SERVICE]: SetLastPosition for {0}", userID);
GridUserData d = GetGridUserData(userID);
@@ -0,0 +1,19 @@
# Generation 1 – Hypergrid presence and GridUser online ghosts
**Evidence (production, November 18, 2026; read-only):** `Presence` contained four old sessions with `RegionID=00000000-0000-0000-0000-000000000000`; all lacked local UserAccounts. `GridUser` had 483 foreign UUIs with `Online=True` and 485 foreign UUIs with `Online=False`. Across 467 avatar UUIDs, both statuses existed under different UUIs but the **same normalized HomeURI**; for 461, the display name was also unchanged. All 483 online UUIs carried a terminal `/` on HomeURI; most offline records omitted it. Of the 483 online foreign rows, 458 had login timestamps older than one day, 347 older than seven days, and 479 had no matching `Presence` row. No UUIDs, HomeURIs or personal data were collected in this report.
## Root cause and code correction
`GatekeeperService.LoginAgent` creates the foreign `GridUser` identity using a HomeURI that commonly ends with `/`. On disconnect, `ActivityDetector` asks `UserManagementModule.GetUserUUI`; the region-normalized HomeURI can omit that slash. `GridUserService` previously treated these as two different exact database keys and cache entries. Thus logout created a new **offline** record while leaving the original **online** record untouched. `GridUserService` now canonicalizes a fully-qualified foreign UUI to exactly one terminal `/` on the HomeURI for cache lookup, database lookup and all write operations; bare local UUIDs and different home grids remain separate. The separate foreign display name remains part of the UUI and is not collapsed across avatars.
`GatekeeperService` now removes only its own temporary Presence when destination lookup, `QueryAccess`, or `CreateAgent` fails (including exceptions). It never clears a session already created by the login service. `PresenceService.GetAgents` no longer considers a `RegionID=UUID.Zero` preliminary login as an online arrival. `HGEntityTransferModule` catches a foreign-home-grid logout communication failure, allowing remaining local disconnect event handlers to execute.
## Testing and deployment
- Functional normalization regression: `dotnet run --project tools/ci/HGForeignPresenceRegression/HGForeignPresenceRegression.csproj -c Release`. This test was first run against the original code and failed specifically on the HomeURI slash mismatch, then passed with the fix.
- Static lifetime regressions: `python3 tools/ci/verify_hg_foreign_presence.py`.
- Full Generation 1 .NET 10 solution build and normal NexVerse CI, especially HomeAgent/Gatekeeper login and standard local login, must remain green.
- **No production data cleanup is included in this PR.** It is not safe to blanket-delete `Presence` or to clear all `GridUser.Online` rows. Before one-time reconciliation of existing historical duplicates, export a backup, compare canonical identity plus `Login`/`Logout` timestamps and region session state, and update only proven stale rows with optimistic compare-and-swap conditions. Never modify a currently logged-in avatar. No direct SQL writes were made during the diagnostic investigation.
- Optional future maintenance: age-bound invalid `RegionID=UUID.Zero` presences and stale foreign GridUser entries, but only with durable region/session liveness checks, idempotence and fail-closed race protection.
Tracking: [Issue #459](https://github.com/opengenesislink/opengenesislinkserver/issues/459).
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Reference Include="OpenSim.Services.UserAccountService">
<HintPath>../../../bin/OpenSim.Services.UserAccountService.dll</HintPath>
</Reference>
</ItemGroup>
</Project>
@@ -0,0 +1,31 @@
// SPDX-License-Identifier: MPL-2.0
using System;
using System.Reflection;
using OpenSim.Services.UserAccountService;
static string Identity(string value)
{
MethodInfo? cacheKey = typeof(GridUserService).GetMethod(
"GridUserCacheKey", BindingFlags.Static | BindingFlags.NonPublic);
if (cacheKey is null)
throw new Exception("GridUserCacheKey not available");
return (string)cacheKey.Invoke(null, new object[] { value })!;
}
static void Check(bool condition, string reason)
{
if (!condition) throw new Exception(reason);
}
const string id = "d1844e28-095c-4f9c-8e05-9412b5996336";
string bare = id;
string original = id + ";https://home.example.test:8002/;Visitor Example";
string missingSlash = id + ";https://home.example.test:8002;Visitor Example";
string extraSlash = id + ";https://home.example.test:8002///;Visitor Example";
string differentGrid = id + ";https://another.example.test:8002/;Visitor Example";
string differentName = id + ";https://home.example.test:8002/;Visitor Changed";
Check(Identity(bare) == bare, "Local UUID must remain unchanged");
Check(Identity(original) == Identity(missingSlash), "HG login and logout UUI slash mismatch");
Check(Identity(original) == Identity(extraSlash), "HG home URI slash normalization failed");
Check(Identity(original) != Identity(differentGrid), "Distinct home grids must not share cache keys");
Check(Identity(original) != Identity(differentName), "Different UUI display identities must not be collapsed");
Check(Identity(original).EndsWith("/;Visitor Example"), "Expected canonical trailing slash");
Console.WriteLine("HG foreign GridUser canonical UUI and cross-grid isolation: PASS");
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env python3
"""Generation 1 HG foreign presence regression invariants."""
from pathlib import Path
r=Path(__file__).resolve().parents[2]
grid=(r/'OpenSim/Services/UserAccountService/GridUserService.cs').read_text()
assert 'private static string CanonicalHGUserID(string userID)' in grid
assert 'return CanonicalHGUserID(userID);' in grid
assert 'GridUserData exact = m_Database.Get(cacheKey);' in grid
assert grid.count('userID = GridUserCacheKey(userID);')>=4
assert "home.TrimEnd(" in grid and ' + "/"' in grid
presence=(r/'OpenSim/Services/PresenceService/PresenceService.cs').read_text()
assert presence.count('RegionID.IsZero()')>=2
check=(r/'OpenSim/Services/HypergridService/GatekeeperService.cs').read_text()
for marker in ('bool createdPresence = false;', 'createdPresence = true;', 'bool regionAccepted = false;', 'regionAccepted = didit;', 'if (createdPresence && !regionAccepted)', 'm_PresenceService.LogoutAgent(aCircuit.SessionID);'):
assert marker in check, marker
transfer=(r/'OpenSim/Region/CoreModules/Framework/EntityTransfer/HGEntityTransferModule.cs').read_text()
assert 'Foreign home logout unavailable' in transfer
assert 'catch (Exception error)' in transfer
print('HG foreign login/logout canonical identity, provisional presence and callback cleanup: PASS')
+8 -5
View File
@@ -38,15 +38,18 @@ assert 'NexNodeRegistry nodes = null' in stats
assert 'nodeRegistry);' in routes
assert "m_UserAccounts == null || m_GridUsers == null" not in stats
# Full OpenSim HG UUIs must be looked up exactly. Prefixing all lookups
# with the bare 36-character UUID merges different HG homes and can erase
# the GridUser origin rows expected by statistics:read.
# Fully qualified HG UUIs must retain their HomeURI and display identity;
# only the nonsemantic terminal HomeURI slash is normalized before an exact
# lookup. Prefixing with the bare UUID merges different HG homes and can
# erase provenance rows published by statistics:read.
griduser = (root / "OpenSim/Services/UserAccountService/GridUserService.cs").read_text(encoding="utf-8")
for marker in (
"private static string GridUserCacheKey(string userID)",
"userID.Length > 36 && userID[36] == ';'",
"GridUserData exact = m_Database.Get(userID);",
"CacheGridUser(userID, exact);",
"private static string CanonicalHGUserID(string userID)",
"return CanonicalHGUserID(userID);",
"GridUserData exact = m_Database.Get(cacheKey);",
"CacheGridUser(cacheKey, exact);",
"GridUserData local = m_Database.Get(bareId);",
"CacheGridUser(userID, d);",
):