ModernUO/Projects/UOContent/Engines/Advanced Search/AdvancedSearchUtilities.cs
Kamron Batman a7e65aab01
perf(login): run password hashing on a parked worker thread (#2566)
## Why

An Argon2 verify is **~8.9 ms of frozen world per login attempt** — more than half a 16 ms frame. Failed attempts cost exactly the same as successful ones, by design, so a credential-stuffing flood is a full-cost stall per packet without needing valid credentials. `SetPassword` derives a hash too, so `[password`, the admin gump and account creation each pay the same.

## What the measurement says

Off-loading does not delete the cost, it relocates it. Three things stay on the loop:

| Component | Measured |
|---|---:|
| Inline verify (today) | **8.92 ms** |
| Dispatch to the worker | 210 ns |
| Drain the continuation off `LoopContext` | 13 ns |
| Loop's own work slowed by shared-L3 eviction | **0.05 – 5.44 ms** |

Net gain **3.5 – 8.9 ms** of on-loop time per login. Harness in `ModernUO-Benchmarks` (`Benchmarks/Argon2OffLoop/`): it models the loop as a dependent-load pointer chase swept across working-set sizes, which is an upper bound on cache-latency sensitivity, and copies `EventLoopContext` so the hand-off cost is the real one.

Two results shaped the design:

- **The contention tax peaks in the middle of the working-set range**, not at the top — 5.44 ms at 8 MiB (a quarter of this chip's L3), but 0.76 ms at 30 MiB and 0.10 ms at 256 KiB. A tiny hot set has nothing in L3 to lose; a huge one is already DRAM-bound.
- **Per-login tax falls as concurrency rises** (5.44 → 2.56 → 1.60 ms at 1/2/4 hashers) while *total* loop damage rises. Contention is shared, not additive, so a login rush is not the disaster case — a single login is.

## Why exactly one worker

It is load-bearing three times over, which is also why it must not quietly become a pool:

- **Cost bound.** Off-loop loses to inline only if a hash steals ~82% of the loop's throughput. One hasher contending for one core leaves the loop ~50%. **A single background hasher cannot cost the loop more than the inline verify under any scheduling regime**, which is what lets the measurement hold on hardware we cannot inspect — AMD, VPS, oversubscribed VM. Four hashers drop the loop to ~20% and break it.
- **Memory.** Exactly one hashing arena is live at a time whatever the login volume.
- **Ordering.** Writes apply in dispatch order *only* because a single thread drains FIFO. A second worker would need ordering reintroduced; `WritesApplyInDispatchOrder` fails if that happens.

Throughput is ~110 verifies/sec. Only loop time matters, not login latency, so head-of-line blocking during a rush costs nothing.

## Making every protection safe off-thread

The worker was initially Argon2-only. That was the right call for the wrong reason — it was blamed on Argon2's salt RNG, which is a stateless syscall wrapper and was never a problem. The real blockers were elsewhere, and both are fixed at the source:

| Protection | Was | Now |
|---|---|---|
| MD5/SHA1/SHA2 | shared `HashAlgorithm.ComputeHash`, which carries the running digest across `HashCore`/`HashFinal` through process-wide singletons | static `HashData` into a `stackalloc` span — no state, no allocation, identical bytes |
| PBKDF2 | `Utility.RandomMinMax` → shared `System.Random`, thread-unsafe *and* game state | `RandomNumberGenerator.GetInt32`, matching the salt beside it |
| Argon2 | already safe (`Verify` is static + stackalloc) | unchanged, singleton reused |

Literal digests are pinned in a test **before** the change and still pass after it. These are compared as strings against every account database, so any casing or encoding drift would lock out every SHA and MD5 account at once.

With all three safe, the worker no longer knows which algorithm it runs and the dispatch conditions collapse to "is off-loop available".

## Correctness

- **Phrase derivation** moves to `AccountSecurity.DerivePhrase`, so verification (stored algorithm's rule) and rehash (target algorithm's rule) cannot disagree. Deriving with the wrong one is the shape of the lockout fixed in #2562.
- **Liveness** is checked at dequeue *and* at apply — a connection can drop while queued or while the result sits in the loop queue. A job with no connection attached, such as an admin password change, runs regardless.
- **Queue overflow rejects** a login rather than verifying inline; steering work back onto the loop is what a flood wants. A password change instead falls back to hashing inline, because unlike a login it must not be dropped.
- **Shutdown and crash** both just stop the thread, and pending jobs are dropped. No save is initiated once shutdown begins — saving is the operator's choice up front, via the admin gump's save/no-save variants, and `WaitForWriteCompletion` honours one already in flight — so a write applied during teardown would reach no disk. The crash path needs its own subscription because `HandleClosed` skips `InvokeShutdown` when crashed.

## Bounding

`MaxPending` is 4096 — a backstop, not a flood defense. `SentFirstPacket` holds a connection to one pending verify and the engine caps connections at 4096, so the queue is already bounded by construction and this can only trip if that invariant breaks. A cap low enough to blunt an attack would reject real players first; during a mass reconnect they *are* the queue. Flood defense belongs at the connection layer.

The real DoS improvement is elsewhere: today every attempt stalls the world, and after this a flood occupies one core while the loop keeps ticking.

## Gate

Release builds on 4+ cores. Below that there is no spare core to move work to, so off-loading buys nothing by construction; `DEBUG` is excluded because dev boxes and test shards have few logins. Both modes call the same code — the gate only chooses where it runs.

## Engine change

One property, `AccountLoginEventArgs.Deferred`, so a subscriber can say "no verdict yet". `EventSink.AccountLogin` is `Action<...>` with no continuation, and the packet handler replies in the same call. Approved separately since it touches `Projects/Server/`.

## Docs

`dev-docs/threading-model.md` and the threading skill gain a vetted-workers section. The forbidden-patterns table bans `new Thread`, `ConcurrentQueue<T>`, `Interlocked` and `volatile` in `UOContent`, and its exceptions covered only `Projects/Server/` — the existing Advanced Search fan-out already sat outside it. The new section leads with proving the need (measure on-loop time, not wall-clock; gate on core count; record the measurement), keeps game logic on the loop via chunking, and documents the hand-off protocol in both directions.

## Testing

698 UOContent tests, 810 Server tests, Release build clean.

Covered: verify and rehash outcomes, phrase rules for SHA1/SHA2 vs Argon2, stored-format stability for MD5/SHA1/SHA2, jobs with no connection attached, and dispatch ordering through the real queue. The liveness and ordering guards are mutation-verified.
2026-08-09 00:13:34 -07:00

437 lines
16 KiB
C#

using System;
using System.Buffers;
using System.Globalization;
using System.Numerics;
using System.Runtime.CompilerServices;
namespace Server.Engines.AdvancedSearch;
public static class AdvancedSearchUtilities
{
private static readonly SearchValues<char> _operators = SearchValues.Create(['=', '!', '>', '<', '~']);
public static ReadOnlySpan<char> FindOperatorIndex(ReadOnlySpan<char> expression, out int index)
{
index = expression.IndexOfAny(_operators);
if (index == -1)
{
return ReadOnlySpan<char>.Empty;
}
// We are at the end
if (index + 1 == expression.Length)
{
return expression.Slice(index, 1);
}
// Look for double character
// <=, >=, ~<, ~>, ~~, ~=, ~!
var op = expression[index];
var next = expression[index + 1];
if (next is '=' && op is '=' or '<' or '>' or '~' or '!' || op is '~' && next is '<' or '>' or '~' or '!')
{
return expression.Slice(index, 2);
}
return expression.Slice(index, 1);
}
public static bool CompareValues(Type propertyType, object propertyValue, ReadOnlySpan<char> valuePart, ReadOnlySpan<char> operatorSpan)
{
// TODO: Add support for implicit conversion types like Serial -> uint
if (propertyType == typeof(long))
{
return TryParseValue<long>(valuePart, out var parsedValue) &&
CompareNumeric((long)propertyValue!, parsedValue, operatorSpan);
}
if (propertyType == typeof(ulong))
{
return TryParseValue<ulong>(valuePart, out var parsedValue) &&
CompareNumeric((ulong)propertyValue!, parsedValue, operatorSpan);
}
if (propertyType == typeof(int))
{
return TryParseValue<int>(valuePart, out var parsedValue) &&
CompareNumeric((int)propertyValue!, parsedValue, operatorSpan);
}
if (propertyType == typeof(uint))
{
return TryParseValue<uint>(valuePart, out var parsedValue) &&
CompareNumeric((uint)propertyValue!, parsedValue, operatorSpan);
}
if (propertyType == typeof(short))
{
return TryParseValue<short>(valuePart, out var parsedValue) &&
CompareNumeric((short)propertyValue!, parsedValue, operatorSpan);
}
if (propertyType == typeof(ushort))
{
return TryParseValue<ushort>(valuePart, out var parsedValue) &&
CompareNumeric((ushort)propertyValue!, parsedValue, operatorSpan);
}
if (propertyType == typeof(sbyte))
{
return TryParseValue<sbyte>(valuePart, out var parsedValue) &&
CompareNumeric((sbyte)propertyValue!, parsedValue, operatorSpan);
}
if (propertyType == typeof(byte))
{
return TryParseValue<byte>(valuePart, out var parsedValue) &&
CompareNumeric((byte)propertyValue!, parsedValue, operatorSpan);
}
if (propertyType == typeof(float))
{
return TryParseValue<float>(valuePart, out var parsedValue) &&
Compare((float)propertyValue!, parsedValue, valuePart, operatorSpan);
}
if (propertyType == typeof(double))
{
return TryParseValue<double>(valuePart, out var parsedValue) &&
Compare((double)propertyValue!, parsedValue, valuePart, operatorSpan);
}
if (propertyType == typeof(string))
{
return TryParseValue<string>(valuePart, out var parsedValue) &&
Compare((string)propertyValue!, parsedValue, operatorSpan);
}
if (propertyType == typeof(TimeSpan))
{
return TryParseValue<TimeSpan>(valuePart, out var parsedValue) &&
Compare((TimeSpan)propertyValue!, parsedValue, operatorSpan);
}
if (propertyType == typeof(DateTime))
{
return TryParseValue<DateTime>(valuePart, out var parsedValue) &&
Compare((DateTime)propertyValue!, parsedValue, operatorSpan);
}
if (propertyType == typeof(bool))
{
return TryParseValue<bool>(valuePart, out var parsedValue) &&
Compare((bool)propertyValue!, parsedValue, operatorSpan);
}
if (propertyType.IsEnum)
{
if (!Enum.TryParse(propertyType, valuePart.ToString(), true, out var valueEnum) || valueEnum == null)
{
return false;
}
return GetEnumSize(propertyType) switch
{
1 => CompareNumeric((byte)propertyValue!, (byte)valueEnum, operatorSpan),
2 => CompareNumeric((short)propertyValue!, (short)valueEnum, operatorSpan),
4 => CompareNumeric((int)propertyValue!, (int)valueEnum, operatorSpan),
8 => CompareNumeric((long)propertyValue!, (long)valueEnum, operatorSpan),
_ => false
};
}
// Anything the hot typed paths above didn't handle — reference types (Poison, Map, entity
// properties resolved by serial), IParsable value types (Guid, decimal, ...), and legacy
// RunUO types with a static Parse(string) (Faction, Town, ...). Delegate to the shared,
// thread-safe Types converter so the target is parsed into the property's real type, then
// compare by value. A string is allocated here, but this is the uncommon path; the common
// types never reach it. Types returns a non-null message when it can't parse -> no match.
return Types.TryParse(propertyType, valuePart.ToString(), out var parsed) == null &&
CompareReference(propertyValue!, parsed, operatorSpan);
}
public static bool CompareNumeric<T>(T propertyValue, T parsedValue, ReadOnlySpan<char> operatorSpan) where T : INumber<T> =>
operatorSpan switch
{
"=" or "==" => propertyValue == parsedValue,
"!" or "!=" => propertyValue != parsedValue,
">" => propertyValue > parsedValue,
"<" => propertyValue < parsedValue,
">=" => propertyValue >= parsedValue,
"<=" => propertyValue <= parsedValue,
_ => false
};
public static bool Compare(
double propertyValue,
double parsedValue,
ReadOnlySpan<char> originalValue,
ReadOnlySpan<char> operatorSpan
)
{
var epsilon = CalculateEpsilon(originalValue);
return operatorSpan switch
{
"=" or "==" => Math.Abs(propertyValue - parsedValue) < epsilon,
"!" or "!=" => Math.Abs(propertyValue - parsedValue) >= epsilon,
">" => propertyValue > parsedValue + epsilon,
"<" => propertyValue < parsedValue - epsilon,
">=" => propertyValue >= parsedValue - epsilon,
"<=" => propertyValue <= parsedValue + epsilon,
_ => throw new ArgumentException("Invalid operator")
};
}
public static double CalculateEpsilon(ReadOnlySpan<char> value)
{
var decimalPlace = value.IndexOf('.');
if (decimalPlace == -1)
{
// No decimal point, so use a default small epsilon
return 1E-10;
}
// Convert decimal places to a negative power of 10
return (value.Length - decimalPlace - 1) switch
{
< 10 => 1E-10,
10 => 1E-11,
11 => 1E-12,
12 => 1E-13,
13 => 1E-14,
14 => 1E-15,
_ => 1E-16
};
}
public static bool Compare(string propertyValue, string parsedValue, ReadOnlySpan<char> operatorSpan) =>
operatorSpan switch
{
"=" or "==" => propertyValue.EqualsOrdinal(parsedValue),
"!" or "!=" => !propertyValue.EqualsOrdinal(parsedValue),
">" => propertyValue.StartsWithOrdinal(parsedValue),
"<" => propertyValue.EndsWithOrdinal(parsedValue),
"~" => propertyValue.Contains(parsedValue),
"~<" => propertyValue.InsensitiveEndsWith(parsedValue),
"~>" => propertyValue.InsensitiveStartsWith(parsedValue),
"~~" => propertyValue.InsensitiveContains(parsedValue),
"~=" => propertyValue.InsensitiveEquals(parsedValue),
"~!" => !propertyValue.InsensitiveEquals(parsedValue),
_ => false
};
public static bool Compare(TimeSpan propertyValue, TimeSpan parsedValue, ReadOnlySpan<char> operatorSpan) =>
operatorSpan switch
{
"=" or "==" => propertyValue == parsedValue,
"!" or "!=" => propertyValue != parsedValue,
">" => propertyValue > parsedValue,
"<" => propertyValue < parsedValue,
">=" => propertyValue >= parsedValue,
"<=" => propertyValue <= parsedValue,
_ => false
};
public static bool Compare(DateTime propertyValue, DateTime parsedValue, ReadOnlySpan<char> operatorSpan) =>
operatorSpan switch
{
"=" or "==" => propertyValue == parsedValue,
"!" or "!=" => propertyValue != parsedValue,
">" => propertyValue > parsedValue,
"<" => propertyValue < parsedValue,
">=" => propertyValue >= parsedValue,
"<=" => propertyValue <= parsedValue,
_ => false
};
public static bool Compare(bool propertyValue, bool parsedValue, ReadOnlySpan<char> operatorSpan) =>
operatorSpan switch
{
"=" or "==" => propertyValue == parsedValue,
"!" or "!=" => propertyValue != parsedValue,
_ => false
};
public static bool CompareReference<T>(T propertyValue, T parsedValue, ReadOnlySpan<char> operatorSpan)
{
switch (operatorSpan)
{
case "=":
case "==": return Equals(propertyValue, parsedValue);
case "!":
case "!=": return !Equals(propertyValue, parsedValue);
}
if (propertyValue is IComparable cmp && parsedValue != null)
{
try
{
var c = cmp.CompareTo(parsedValue);
return operatorSpan switch
{
">" => c > 0,
"<" => c < 0,
">=" => c >= 0,
"<=" => c <= 0,
_ => false
};
}
catch
{
return false;
}
}
return false;
}
internal static bool TryParseValue<T>(ReadOnlySpan<char> valuePart, out T value)
{
// Special handling for boolean and hexadecimal values
if (typeof(T) == typeof(bool))
{
var val = valuePart.ToString().ToLower();
if (val is "true" or "1" or "enabled" or "on")
{
value = (T)(object)true;
return true;
}
if (val is "false" or "0" or "disabled" or "off")
{
value = (T)(object)false;
return true;
}
value = default;
return false;
}
if (typeof(T) == typeof(long))
{
return TryParseNumericValue<long, T>(valuePart, out value);
}
if (typeof(T) == typeof(ulong))
{
return TryParseNumericValue<ulong, T>(valuePart, out value);
}
if (typeof(T) == typeof(int))
{
return TryParseNumericValue<int, T>(valuePart, out value);
}
if (typeof(T) == typeof(uint))
{
return TryParseNumericValue<uint, T>(valuePart, out value);
}
if (typeof(T) == typeof(short))
{
return TryParseNumericValue<short, T>(valuePart, out value);
}
if (typeof(T) == typeof(ushort))
{
return TryParseNumericValue<ushort, T>(valuePart, out value);
}
if (typeof(T) == typeof(sbyte))
{
return TryParseNumericValue<sbyte, T>(valuePart, out value);
}
if (typeof(T) == typeof(byte))
{
return TryParseNumericValue<byte, T>(valuePart, out value);
}
if (typeof(T) == typeof(float))
{
return TryParseNumericValue<float, T>(valuePart, out value);
}
if (typeof(T) == typeof(double))
{
return TryParseNumericValue<double, T>(valuePart, out value);
}
// string needs no parsing — the span itself is the value.
if (typeof(T) == typeof(string))
{
value = (T)(object)valuePart.ToString();
return true;
}
// Remaining supported types (TimeSpan, DateTime) parse straight from the span via
// ISpanParsable<T> — no allocation, no reflection, and unlike Convert.ChangeType it handles
// TimeSpan, which is not IConvertible and previously failed silently.
if (typeof(T) == typeof(TimeSpan))
{
return TryParseSpanParsable<TimeSpan, T>(valuePart, out value);
}
if (typeof(T) == typeof(DateTime))
{
return TryParseSpanParsable<DateTime, T>(valuePart, out value);
}
value = default;
return false;
}
// Parses U (a value type exposing ISpanParsable<U>) from the span and reinterprets it as T. The
// two type params mirror TryParseNumericValue: the caller dispatches on typeof(T), so U == T at
// every call site and the (T)(object) cast is always valid.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool TryParseSpanParsable<U, T>(ReadOnlySpan<char> valuePart, out T value) where U : ISpanParsable<U>
{
if (U.TryParse(valuePart, null, out var parsed))
{
value = (T)(object)parsed;
return true;
}
value = default;
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool TryParseNumericValue<T, R>(ReadOnlySpan<char> valuePart, out R value) where T : INumber<T>
{
var ok = valuePart.StartsWith("0x")
? T.TryParse(valuePart[2..], NumberStyles.HexNumber, null, out var parsed)
: T.TryParse(valuePart, null, out parsed);
if (ok)
{
value = (R)(object)parsed;
return true;
}
value = default;
return false;
}
// Evaluates one trimmed leaf atom against caller-supplied state. A custom delegate is required
// because ReadOnlySpan<char> cannot be a Func<> type argument; passing state avoids a per-call
// capturing closure, so the recursion allocates neither a string nor a closure.
internal delegate bool LeafEvaluator<in TState>(TState state, ReadOnlySpan<char> leaf);
// OR ('|') binds looser than AND ('@'); split on the outermost OR first, then AND.
internal static bool EvaluateBoolean<TState>(ReadOnlySpan<char> expr, TState state, LeafEvaluator<TState> evalLeaf)
{
var orIndex = expr.IndexOf('|');
if (orIndex != -1)
{
return EvaluateBoolean(expr[..orIndex], state, evalLeaf) || EvaluateBoolean(expr[(orIndex + 1)..], state, evalLeaf);
}
var andIndex = expr.IndexOf('@');
if (andIndex != -1)
{
return EvaluateBoolean(expr[..andIndex], state, evalLeaf) && EvaluateBoolean(expr[(andIndex + 1)..], state, evalLeaf);
}
return evalLeaf(state, expr.Trim());
}
private static int GetEnumSize(Type enumType) =>
Type.GetTypeCode(Enum.GetUnderlyingType(enumType)) switch
{
TypeCode.Byte or TypeCode.SByte => sizeof(byte),
TypeCode.Int16 or TypeCode.UInt16 => sizeof(ushort),
TypeCode.Int32 or TypeCode.UInt32 => sizeof(uint),
TypeCode.Int64 or TypeCode.UInt64 => sizeof(ulong),
_ => 4
};
}