Skip to content
Draft
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
6 changes: 4 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
- **The router hosts a bridge to the older client's invalidation channel.** `RouterBuilder.UseChannelBridge(IChannelBridge)` takes the application's adapter. Every key write, delete and create the router commits, and every clear, is published on it as a `BridgeMessage` (`Key`, `Clear`) carrying the router's identity, on either path and in `BypassLibrary`, since the bridge needs no started library. A received `Key` message evicts that key's local copy, a `Clear` drops the cache's local copies and a `Tag` drops every cache's, since the router keeps no tags; a message carrying the router's own identity is ignored, and nothing received is published again, so no echo can start. A publish runs off the caller's thread and is cancelled at the source timeout, at most 16 run at once by default (more are dropped; `PublishAsync` must not block), a throwing `Subscribe` is retried in the background, and every failure is counted (`bridge`), never thrown; the local cap bounds how long a peer serves its copy. The adapter for a real older client is the application's. See [Router](docs/how-to/router.md).
- **A router group can be pinned to the library path, and a switch is durable.** `RouterBuilder.UsePinWhen` pins groups (polled about once a second): a pinned group ignores bypass and the group predicate and never falls to the source, answering unavailable instead. A node advertises `pin=<group>` only after calls that started on the old path have ended, with an `ap` token naming its application so applications sharing one node hash do not count each other. The switch state of a group is a durable Redis key, `{prefix}mg:{app:group}:sw`, recorded by a script when a format write needs it and only while every live node's acknowledgement record is unchanged, and a withdrawal is recorded in the same step as the read that confirms it (the pin needs scripts); a switched group stays on the library or unavailable through a restart, a failed library start, a throwing predicate and bypass, which changes the router's rule that a throwing predicate means the source. State is read before the first call and refreshed; an unknown state fails a group that is not pinned closed. `IFormatWriteGate` is a new seam: a registered gate holds non-JSON value writes while it returns a reason, as part of the existing hold, including on a custom serializer proxy, and a gate that closes, even briefly, restarts the hold. The router's gate opens only when every group is pinned. Counter path reasons `pin` and `pin_state_unknown`. See [Router](docs/how-to/router.md).
- **The stream maintainer removes the consumer groups of departed nodes.** A group is named for its node, so the maintainer checks the node list once per pass (only when a stream has a group with consumers) and quarantines, then deletes, a group whose node left (`left=1`), whose entry is older than the gone window, or, on Redis 7.2 and later in a fleet that advertises, whose entry was pruned and whose consumers have all been idle past the gone window and the quarantine. Everything else is kept, as is every group while the node list cannot be read. Metric `Caching.Stats.DepartedGroupDeleted` by reason. Before this, groups of crashed nodes stayed on quiet streams for good. See [Broadcast](docs/how-to/broadcast.md).
- **An inventory by reason and a bounded sweep of stored values.** `RedisCacheProvider.CountFormatsByReasonAsync(keyPattern, token)` (or `(keyPattern, group, token)`, which sets the `group` tag) returns a `FormatInventoryReport` (`ByFormat`, `ByReason`, `Scanned`) whose reasons are `format_json`, `format_<name>`, `format_unknown`, `empty`, `oversize`, `no_ttl` and `hash_sampled`; each string costs a `PTTL` and a headerless one a `STRLEN`, so it is for an operator and not for a request. `SweepFormatsAsync<T>(keyPattern, options, token)` rewrites strings stored in another format into the default policy's write format in place, with the conversion of `MigrateOnRead`: lossless check, compare-and-set that keeps the exact TTL, transaction when scripts are refused, no origin call and no event, so a writer or a delete that comes meanwhile wins and no key is created. It takes its own `FormatSweepOptions.RatePerSecond`, shares the one-minute claim window and byte budget of `MigrateOnRead`, asks the node list again for each key (the first refusal ends the pass), and a `Budget` and a `Cursor` make it resumable (`FormatSweepReport.NextCursor`, `Completed`). It leaves the empty, `default(T)`, oversize and lossy values and reports each under its reason; hashes are never swept (only the inventory reports them, as `hash_sampled`). Metrics `cache.format.sweep{outcome,group}` and `cache.format.inventory{reason,group}`. `CountFormatsAsync` and `CountFormatsByKeyAsync` are unchanged. See [concepts](docs/concepts.md#counting-by-reason-and-sweeping-what-reads-do-not-reach).
- **An inventory by reason and a bounded sweep of stored values.** `RedisCacheProvider.CountFormatsByReasonAsync(keyPattern, token)` (or `(keyPattern, group, token)`, which sets the `group` tag) returns a `FormatInventoryReport` (`ByFormat`, `ByReason`, `Scanned`) whose reasons are `format_json`, `format_<name>`, `format_unknown`, `empty`, `oversize`, `no_ttl` and `hash_sampled`; each string costs a `PTTL` and a headerless one a `STRLEN`, so it is for an operator and not for a request. `SweepFormatsAsync<T>(keyPattern, options, token)` rewrites strings stored in another format into the default policy's write format in place, with the conversion of `MigrateOnRead`: lossless check, compare-and-set that keeps the exact TTL, transaction when scripts are refused, no origin call and no event, so a writer or a delete that comes meanwhile wins and no key is created. It takes its own `FormatSweepOptions.RatePerSecond`, shares the one-minute claim window and byte budget of `MigrateOnRead`, asks the node list again for each key (the first refusal ends the pass), and a `Budget` and a `Cursor` make it resumable (`FormatSweepReport.NextCursor`, `Completed`). It leaves the empty, `default(T)`, oversize and lossy values and reports each under its reason; hashes are never swept (only the inventory reports them, as `hash_sampled`). Metrics `cache.format.sweep{outcome,group}` and `cache.format.inventory{reason,group}`. `CountFormatsAsync` and `CountFormatsByKeyAsync` are unchanged. Every inventory counts an entry frame as `frame`, and one with a stale window as `frame_windowed` too; the sweep leaves frames as they are and counts them in `FormatSweepReport.Framed`. See [concepts](docs/concepts.md#counting-by-reason-and-sweeping-what-reads-do-not-reach).
- **`IHeaderFreeSerializerProxy`** marks a custom byte serializer proxy whose values never start with a format header byte. Such a proxy is treated as the default JSON proxy is: reads tell its values from a registered format by the first byte under every policy, the node advertises the formats it reads instead of `nosniff`, a write the format negotiation holds back falls back to the proxy's bytes, and `MigrateOnRead` converts its values when the proxy writes the value back byte for byte. The router marks its envelope this way, and an envelope write whose first byte would read as a header fails with `InvalidOperationException`.
- **A router group can write MessagePack while the others keep the envelope.** `RouterBuilder.UseValueSerializers` registers value serializers in the router's stack and `UseWriteFormatWhen(group => "messagepack" | "json" | null)` is a live setting read on every library write; both need `UsePinWhen`. A group writes MessagePack only while it is pinned, acknowledged and switched and the gate is open, and the envelope otherwise, including when the setting throws or names an unknown format. The gate now covers the groups that ask for MessagePack, so a group that does not ask holds nothing and is never recorded as switched; with no `UseWriteFormatWhen`, the gate is over every group as before. With `UseWriteFormatWhen`, the stack's format negotiation takes `Redis:FormatNegotiation` from the router's configuration section, as the pin already validated it; a router without it keeps the stack's own defaults, so a malformed section still only skips the advertisement. A setting that throws clears the group's wanted bit, so the group holds the gate no longer, and a read of a group that is not switched and durable carries the envelope policy, so a default `MigrateOnRead` never rewrites it. See [Router](docs/how-to/router.md).
- **`CacheKey.Verbatim(name)`** builds a key whose name is exactly the text given: no trim, no casing change, whatever `CacheKey.DefaultCasing` is. It reports the new `CacheKeyCasing.Verbatim` value (code that treats "not `Sensitive`" as insensitive must handle it), which `WithName` and the library's key strategies carry over, so the Redis key, local key and event key hold the given name. A key prefix is still lowercased by `PrefixCacheKeyStrategy` and `PrefixRedisKeyStrategy`, so the guarantee covers the name only. A custom `ICacheKeyStrategy` must build its result with `WithName` to keep it. A null, empty or whitespace-only name throws `ArgumentException`; `WithName` with whitespace on a verbatim key throws too, where other modes return an empty key. `Verbatim` is not a valid `CacheOptions.KeyCasing`. Peer events now match a key by ordinal comparison, so keys that differ only in case no longer share invalidations. `RedisCacheProvider.CountFormatsByKeyAsync(CacheKey)` counts a verbatim pattern. `CacheKeyComparer.Insensitive` folds verbatim keys too. A strategy that returns verbatim keys must decline the span path (`ISpanCacheKeyStrategy.TryGetCacheKey` returns false), and the `IDistributedCache` adapter trims the caller's key before its strategy runs.
Expand Down Expand Up @@ -81,7 +81,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)

- **`GeneratedValue<T>` equality and `ToString` include `SkipFailSafe`.** Two values that differ only in it are no longer equal.

- **A value serializer declares its format ids when it is registered.** `AddValueSerializer(name, formatIds, factory)` checks the ids at the call: `0x01`-`0x0F` (except `0x09`, `0x0A`, `0x0D`), `0x10`-`0x1E` or `0x100`-`0x1FF`, one header length, none claimed twice, and a failing call registers nothing. The serializer's `FormatIds` must then equal them as a set, with no id repeated, or the registry build throws an `InvalidOperationException` that names both lists. The ids `0x01`-`0x0F` are allocated by the table in [docs/reference/format-ids.md](docs/reference/format-ids.md) and open to any serializer, not only this repository's own. The core names no serializer package: `MessagePackFormats` in `UiPath.Caching.MessagePack` holds `Value` (`0x02`), `ValueLz4` (`0x03`), `Event` (`0x02`) and `ValueIds`. A body that starts with any format header byte, not only `0x02`, `0x03` and the consumer ids, counts as a format this node cannot read: a Pub/Sub or stream event with such a first byte is a topic loss instead of being skipped. `ICacheValueSerializer` documents that `Serialize` must be deterministic.
- **A value serializer declares its format ids when it is registered.** `AddValueSerializer(name, formatIds, factory)` checks the ids at the call: `0x01`-`0x0C` (except `0x09` and `0x0A`), `0x10`-`0x1E` or `0x100`-`0x1FF`, one header length, none claimed twice, and a failing call registers nothing. The serializer's `FormatIds` must then equal them as a set, with no id repeated, or the registry build throws an `InvalidOperationException` that names both lists. Any serializer can claim an allocated id listed in the [format id table](docs/reference/format-ids.md). The library reserves `0x0E` for the entry frame and `0x0F` for a remove tombstone. The core names no serializer package: `MessagePackFormats` in `UiPath.Caching.MessagePack` holds `Value` (`0x02`), `ValueLz4` (`0x03`), `Event` (`0x02`) and `ValueIds`. A body that starts with any format header byte, not only `0x02`, `0x03` and the consumer ids, counts as a format this node cannot read: a Pub/Sub or stream event with such a first byte is a topic loss instead of being skipped. `ICacheValueSerializer` documents that `Serialize` must be deterministic.

- **A peer drops its local copy on a refresh event.** On an `InMemoryRedis` cache, a node that receives another node's refresh or metadata update for a key it holds no longer renews its local copy with the expiration the event carries, which Redis may not have accepted. It drops the copy, and its next read of the key takes the value and its expiration from Redis. That costs one Redis read per node that held the key and reads it again, and the dropped copy takes its `ETag` and `LastModified` validators with it. The `InMemory` provider and the hash caches renew the copy as before.

### Added

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using UiPath.Caching.Config;

namespace UiPath.Caching.Benchmarks;
#if NET9_0_OR_GREATER

[MemoryDiagnoser]
[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)]
Expand Down Expand Up @@ -67,3 +68,4 @@ public ValueTask<bool> TryGet()
[Benchmark, BenchmarkCategory("Write")]
public ValueTask SetSequence() => _buffered.SetAsync(Key, _sequence, _options);
}
#endif
25 changes: 25 additions & 0 deletions benchmarks/UiPath.Caching.Benchmarks/FakeRedisConnector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,15 @@ public void ForgetLastWrite()
}
}

/// <summary>Wraps the value most recently SET in a windowed frame and gives its key a TTL, for the anchored read.</summary>
public void FrameLastWrite(DateTimeOffset expiration, TimeSpan window, TimeSpan timeToLive)
{
var key = _store.LastSet!.Value;
var inner = (byte[])_store.Values[key]!;
_store.Values[key] = EntryFrame.Write(inner, expiration, window, validators: null);
_store.TimeToLives[key] = timeToLive;
}

public void ForceReconnect()
{
}
Expand All @@ -72,6 +81,7 @@ internal sealed class FakeRedisStore : IDisposable
{
public readonly ConcurrentDictionary<RedisKey, RedisValue> Values = new();
public readonly ConcurrentDictionary<RedisKey, HashEntry[]> Hashes = new();
public readonly ConcurrentDictionary<RedisKey, TimeSpan> TimeToLives = new();
public long GetCount;
public RedisKey? LastSet;
private readonly BlockingCollection<(TaskCompletionSource<RedisValue> Reply, RedisValue Value)> _replies = [];
Expand Down Expand Up @@ -125,6 +135,21 @@ public static T Create(FakeRedisStore store)
return _store.Get(key);
}

if (method.Name == "KeyTimeToLiveAsync" && args is [RedisKey ttlKey, ..])
{
return Task.FromResult(_store.TimeToLives.TryGetValue(ttlKey, out var ttl) ? (TimeSpan?)ttl : null);
}

if (method.Name == "CreateTransaction")
{
return FakeProxy<ITransaction>.Create(_store);
}

if (method.Name == "ExecuteAsync" && typeof(T) == typeof(ITransaction))
{
return Task.FromResult(true);
}

if (method.Name == "HashGetAllAsync" && args is [RedisKey hashKey, ..])
{
return Task.FromResult(_store.Hashes.TryGetValue(hashKey, out var entries) ? entries : []);
Expand Down
91 changes: 91 additions & 0 deletions benchmarks/UiPath.Caching.Benchmarks/ObservedHitBenchmark.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
using BenchmarkDotNet.Attributes;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using UiPath.Caching.Config;
using UiPath.Caching.Redis;

namespace UiPath.Caching.Benchmarks;

/// <summary>A local hit on an observed entry: the layered cache adopted a windowed frame with a TTL of one day, by key and by the span form.</summary>
[MemoryDiagnoser]
[MarkdownExporterAttribute.GitHub]
public class ObservedHitBenchmark
{
private const string KeyText = "observed:42";
private static readonly CacheKey Key = KeyText;

private readonly FakeRedisConnector _redis = new();
private IHost _writerHost = default!;
private IHost _host = default!;
private ICache<string> _cache = default!;

[GlobalSetup]
public async Task Setup()
{
_writerHost = await StartAsync(KnownCacheProviderNames.Redis);
_host = await StartAsync(KnownCacheProviderNames.InMemoryRedis);
var writer = _writerHost.Services.GetRequiredService<ICacheFactory>().CreateCache(KnownCacheProviderNames.Redis);
await writer.SetAsync(Key, "value", TimeSpan.FromDays(1), policy: null);
_redis.FrameLastWrite(DateTimeOffset.UtcNow.AddDays(1), TimeSpan.FromHours(1), TimeSpan.FromDays(1));
_cache = _host.Services.GetRequiredService<ICache<string>>();

// The first read goes to the fake and adopts the frame; the next ones are local.
if (await ByKey() != "value" || _redis.Gets == 0)
{
throw new InvalidOperationException("The fake connector did not serve the framed value");
}

var gets = _redis.Gets;
if (await ByKey() != "value" || await BySpan() != "value" || _redis.Gets != gets)
{
throw new InvalidOperationException("A measured call was not a local hit");
}

if (!await IsObservedAsync())
{
throw new InvalidOperationException("The local entry is not an observed one");
}
}

[GlobalCleanup]
public async Task Cleanup()
{
var gets = _redis.Gets;
await ByKey();
await _host.StopAsync();
await _writerHost.StopAsync();
_host.Dispose();
_writerHost.Dispose();
_redis.Dispose();
if (_redis.Gets != gets)
{
throw new InvalidOperationException("A measured call reached the fake connector");
}
}

[Benchmark]
public ValueTask<string?> ByKey() => _cache.GetAsync(Key);

[Benchmark]
public ValueTask<string?> BySpan()
{
Span<char> buffer = stackalloc char[KeyText.Length];
KeyText.CopyTo(buffer);
return ((ISpanKeyCache<string>)_cache).GetAsync(buffer);
}

private async Task<bool> IsObservedAsync()
{
var layered = _host.Services.GetRequiredService<ICacheFactory>().CreateCache(KnownCacheProviderNames.InMemoryRedis);
return await layered.GetCacheEntryAsync<string>(Key, policy: null) is ObservedEntry;
}

private async Task<IHost> StartAsync(string cache)
{
var extra = new Dictionary<string, string?> { { "Caching:Connections:Redis:ConnectionString", "fake:6379,abortConnect=false" }, { "Caching:BroadcastEnabled", "false" } };
var host = HostHelper.GetHost(0, cache: cache, topic: "RedisPubSub", extra: extra, configure: b => b.Services.Replace(ServiceDescriptor.Singleton<IRedisConnector>(_redis)));
await host.StartAsync();
return host;
}
}
Loading