diff --git a/benchmarks/UiPath.Caching.Benchmarks/FakeRedisConnector.cs b/benchmarks/UiPath.Caching.Benchmarks/FakeRedisConnector.cs
index 0c3f98feb..8da88aec0 100644
--- a/benchmarks/UiPath.Caching.Benchmarks/FakeRedisConnector.cs
+++ b/benchmarks/UiPath.Caching.Benchmarks/FakeRedisConnector.cs
@@ -46,6 +46,9 @@ public event EventHandler? OnReconnected
/// GETs sent so far.
public long Gets => Volatile.Read(ref _store.GetCount);
+ /// The key of the last write, so a benchmark can check that its measured calls sent none.
+ public RedisKey? LastSet => _store.LastSet;
+
/// Stores a hash for HGETALL to answer.
public void SeedHash(RedisKey key, HashEntry[] entries) => _store.Hashes[key] = entries;
diff --git a/benchmarks/UiPath.Caching.Benchmarks/RedisPlainHitGateBenchmark.cs b/benchmarks/UiPath.Caching.Benchmarks/RedisPlainHitGateBenchmark.cs
new file mode 100644
index 000000000..7a53734b7
--- /dev/null
+++ b/benchmarks/UiPath.Caching.Benchmarks/RedisPlainHitGateBenchmark.cs
@@ -0,0 +1,73 @@
+using BenchmarkDotNet.Attributes;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.DependencyInjection.Extensions;
+using Microsoft.Extensions.Hosting;
+using UiPath.Caching.Redis;
+
+namespace UiPath.Caching.Benchmarks;
+
+///
+/// The local hit of a get-or-add with an explicit expiration on a layered cache over Redis on the fake connector, with entry metadata off (RB1) and on (RB2).
+/// Public members only, so the same file runs on a build without the write anchor. Each measured call is a local hit: the fake sees no command.
+///
+[MemoryDiagnoser]
+public class RedisPlainHitGateBenchmark
+{
+ private static readonly CacheKey Key = "rb:hit";
+
+ private readonly FakeRedisConnector _redis = new();
+ private IHost _host = default!;
+ private ICache _cache = default!;
+ private DateTimeOffset _expiration;
+ private (long Gets, StackExchange.Redis.RedisKey? LastSet) _commands;
+
+ [Params(false, true)]
+ public bool EntryMetadataEnabled { get; set; }
+
+ [GlobalSetup]
+ public async Task Setup()
+ {
+ var extra = new Dictionary
+ {
+ { "Caching:Connections:Redis:ConnectionString", "fake:6379,abortConnect=false" },
+ { "Caching:Redis:EntryMetadataEnabled", EntryMetadataEnabled ? "true" : "false" },
+ };
+ _host = HostHelper.GetHost(0, cache: KnownCacheProviderNames.InMemoryRedis, extra: extra, configure: b => b.Services.Replace(ServiceDescriptor.Singleton(_redis)));
+ await _host.StartAsync();
+ _cache = _host.Services.GetRequiredService().CreateCache(KnownCacheProviderNames.InMemoryRedis);
+ _expiration = DateTimeOffset.UtcNow.AddDays(1);
+ await _cache.SetAsync(Key, "value", _expiration, policy: null);
+ for (var i = 0; i < 16; i++)
+ {
+ if (await Hit() != "value")
+ {
+ throw new InvalidOperationException("The warm-up call was not a hit");
+ }
+ }
+
+ _commands = Commands();
+ await Hit();
+ if (Commands() != _commands)
+ {
+ throw new InvalidOperationException("A measured call reached the fake connector, so it is no local hit");
+ }
+ }
+
+ [GlobalCleanup]
+ public async Task Cleanup()
+ {
+ var after = Commands();
+ await _host.StopAsync();
+ _host.Dispose();
+ _redis.Dispose();
+ if (after != _commands)
+ {
+ throw new InvalidOperationException("A measured call reached the fake connector, so it is no local hit");
+ }
+ }
+
+ [Benchmark]
+ public ValueTask Hit() => _cache.GetOrAddAsync(Key, static _ => Task.FromResult("generated"), _expiration, policy: null);
+
+ private (long Gets, StackExchange.Redis.RedisKey? LastSet) Commands() => (_redis.Gets, _redis.LastSet);
+}
diff --git a/samples/UiPath.Caching.Sample/appsettings.all.json b/samples/UiPath.Caching.Sample/appsettings.all.json
index 559e01596..672bd63ba 100644
--- a/samples/UiPath.Caching.Sample/appsettings.all.json
+++ b/samples/UiPath.Caching.Sample/appsettings.all.json
@@ -382,6 +382,8 @@
"RemoveUnreadable": true,
// RemoveTombstone: null = off; when set, a remove leaves a tombstone that lives this long, so a fill whose generator started before the remove does not put the value back. Set it to the longest generator time, the same on every node
"RemoveTombstone": null,
+ // EntryMetadataEnabled: write entry frames when format negotiation allows them
+ "EntryMetadataEnabled": false,
// ReadFrom: Master reads from the master, which is faster and never stale after an invalidation; Replica reads from a replica when one exists, except for keys just written or invalidated
"ReadFrom": "Master",
// MasterReadWindow: with ReadFrom Replica, how long a just-written or invalidated key keeps reading from the master; must exceed the replica lag
@@ -542,6 +544,10 @@
"FailSafeCooldown": "0:00:30",
// FailSafeTimeout: generator time after which fail-safe returns the last value and lets the generator finish in the background; null = wait (default)
"FailSafeTimeout": null,
+ // FailSafeDistributedEnabled: retain expired values in the shared tier when fail-safe and entry metadata are enabled
+ "FailSafeDistributedEnabled": false,
+ // FailSafeDistributedMaxStaleAge: how long the shared tier retains an expired value
+ "FailSafeDistributedMaxStaleAge": "0:15:00",
// Lock: per-cache lock overrides; field-level merged against default policy (UiPath.Caching.LockProfile)
"Lock": {
// LocalSingleFlightEnabled: null = inherit from provider options or default policy
diff --git a/src/UiPath.Caching.Abstractions/Config/CachePolicy.cs b/src/UiPath.Caching.Abstractions/Config/CachePolicy.cs
index 27ccac134..c05fe25e0 100644
--- a/src/UiPath.Caching.Abstractions/Config/CachePolicy.cs
+++ b/src/UiPath.Caching.Abstractions/Config/CachePolicy.cs
@@ -95,6 +95,12 @@ public sealed class CachePolicy
/// With fail-safe and a value to fall back to, how long the generator runs before that value is returned; the generator then finishes in the background and its value is stored. still cancels it. null or zero waits for the generator (default).
public TimeSpan? FailSafeTimeout { get; init; }
+ /// With , writes keep an expired copy in Redis for . Needs RedisCacheOptions.EntryMetadataEnabled. null inherits (default off).
+ public bool? FailSafeDistributedEnabled { get; init; }
+
+ /// How long past its logical expiration a value stays in Redis, in whole seconds from 1 second to seconds. null inherits, then takes , then 1 day.
+ public TimeSpan? FailSafeDistributedMaxStaleAge { get; init; }
+
///
/// Lock settings. Merged field-level against the default policy's —
/// a named policy can override individual fields (e.g. )
diff --git a/src/UiPath.Caching.Abstractions/PublicAPI.Unshipped.txt b/src/UiPath.Caching.Abstractions/PublicAPI.Unshipped.txt
index 1aec25c60..5b8741ea8 100644
--- a/src/UiPath.Caching.Abstractions/PublicAPI.Unshipped.txt
+++ b/src/UiPath.Caching.Abstractions/PublicAPI.Unshipped.txt
@@ -22,6 +22,10 @@ UiPath.Caching.SerializerPolicy.Write.get -> string?
UiPath.Caching.SerializerPolicy.Write.init -> void
UiPath.Caching.CachePolicy.FailSafeCooldown.get -> System.TimeSpan?
UiPath.Caching.CachePolicy.FailSafeCooldown.init -> void
+UiPath.Caching.CachePolicy.FailSafeDistributedEnabled.get -> bool?
+UiPath.Caching.CachePolicy.FailSafeDistributedEnabled.init -> void
+UiPath.Caching.CachePolicy.FailSafeDistributedMaxStaleAge.get -> System.TimeSpan?
+UiPath.Caching.CachePolicy.FailSafeDistributedMaxStaleAge.init -> void
UiPath.Caching.CachePolicy.FailSafeEnabled.get -> bool?
UiPath.Caching.CachePolicy.FailSafeEnabled.init -> void
UiPath.Caching.CachePolicy.FailSafeMaxStaleAge.get -> System.TimeSpan?
diff --git a/src/UiPath.Caching.Migration/RegistrationValidator.cs b/src/UiPath.Caching.Migration/RegistrationValidator.cs
index 4f28bc68e..6261a356b 100644
--- a/src/UiPath.Caching.Migration/RegistrationValidator.cs
+++ b/src/UiPath.Caching.Migration/RegistrationValidator.cs
@@ -34,6 +34,11 @@ public static IReadOnlyList Violations(CacheOptions cacheOptions, RedisC
violations.Add($"Redis.{nameof(RedisCacheOptions.EntryFactory)} is set: the entry must be the value the source writes.");
}
+ if (redisOptions.EntryMetadataEnabled)
+ {
+ violations.Add($"Redis.{nameof(RedisCacheOptions.EntryMetadataEnabled)} is on: the source must receive values in its own format.");
+ }
+
if (redisOptions.RemoveUnreadable)
{
violations.Add($"Redis.{nameof(RedisCacheOptions.RemoveUnreadable)} is on: a value only the source can read would be deleted.");
diff --git a/src/UiPath.Caching/AnchoredOptions.cs b/src/UiPath.Caching/AnchoredOptions.cs
new file mode 100644
index 000000000..0d78efd61
--- /dev/null
+++ b/src/UiPath.Caching/AnchoredOptions.cs
@@ -0,0 +1,37 @@
+namespace UiPath.Caching;
+
+/// The options of a layered entry with the anchor of its deadline beside them, so the layered entry flow of an anchored write carries both and does not grow (WA6, C7).
+internal struct AnchoredOptions(CacheEntryOptions options, WriteAnchor anchor) : ILayeredOptions
+{
+ private CacheEntryOptions _options = options;
+
+ public readonly CacheEntryOptions Options => _options;
+
+ public readonly WriteAnchor Anchor => anchor;
+
+ public readonly CacheKey CacheKey => _options.CacheKey;
+
+ public readonly CacheKey CallerKey => _options.CallerKey;
+
+ public readonly TopicKey TopicKey => _options.TopicKey;
+
+ public readonly CancellationToken Token => _options.Token;
+
+ public readonly DateTimeOffset Expiration => _options.Expiration;
+
+ public IDictionary? Metadata
+ {
+ readonly get => _options.Metadata;
+ set => _options.Metadata = value;
+ }
+
+ public readonly AnchoredOptions WithToken(CancellationToken token) => new(_options.WithToken(token), anchor);
+
+ /// The same entry under another deadline, with the anchor of that deadline.
+ public readonly AnchoredOptions WithExpiration(DateTimeOffset expiration)
+ {
+ var changed = _options;
+ changed.Expiration = expiration;
+ return new(changed, anchor);
+ }
+}
diff --git a/src/UiPath.Caching/CacheEntryBuilder.cs b/src/UiPath.Caching/CacheEntryBuilder.cs
index b1796f012..061691bfb 100644
--- a/src/UiPath.Caching/CacheEntryBuilder.cs
+++ b/src/UiPath.Caching/CacheEntryBuilder.cs
@@ -41,4 +41,8 @@ public CacheEntryOptions BuildEntryOptions(CacheKey cacheKey, DateTimeOffset?
Expiration = _clock.ToDateTimeOffset(expiration),
};
}
+
+ /// for a deadline that already has its anchor: the options and that anchor, unchanged. It takes no anchor and reads no clock (WA4 (b)).
+ public (CacheEntryOptions Options, WriteAnchor Anchor) BuildEntryOptions(CacheKey cacheKey, DateTimeOffset expiration, WriteAnchor anchor, CancellationToken token) =>
+ (BuildEntryOptions(cacheKey, expiration, token), anchor);
}
diff --git a/src/UiPath.Caching/Config/CachePolicyFactoryValidator.cs b/src/UiPath.Caching/Config/CachePolicyFactoryValidator.cs
index 93f641243..6eda56bc8 100644
--- a/src/UiPath.Caching/Config/CachePolicyFactoryValidator.cs
+++ b/src/UiPath.Caching/Config/CachePolicyFactoryValidator.cs
@@ -72,6 +72,28 @@ public static void ValidateAgainstEffectiveDefault(
}
}
+ /// Refuses a default or named policy with on a Redis tier without entry metadata, which cannot write the window.
+ internal static void ValidateDistributedFailSafe(ICachePolicyFactory factory, bool entryMetadataEnabled)
+ {
+ if (entryMetadataEnabled)
+ {
+ return;
+ }
+
+ if (factory.Default?.FailSafeDistributedEnabled == true)
+ {
+ Throw(DistributedNeedsMetadata("DefaultCachePolicy"));
+ }
+
+ foreach (var name in factory.Keys)
+ {
+ if (factory.Resolve(name)?.FailSafeDistributedEnabled == true)
+ {
+ Throw(DistributedNeedsMetadata($"Policies['{name}']"));
+ }
+ }
+ }
+
private static void ValidatePolicy(string scope, CachePolicy policy, TimeSpan pollInterval)
{
if (policy.LocalExpiration is { } local
@@ -101,6 +123,11 @@ private static void ValidatePolicy(string scope, CachePolicy policy, TimeSpan po
ValidateNonNegative(scope, nameof(CachePolicy.FailSafeMaxStaleAge), policy.FailSafeMaxStaleAge);
ValidateNonNegative(scope, nameof(CachePolicy.FailSafeCooldown), policy.FailSafeCooldown);
ValidateNonNegative(scope, nameof(CachePolicy.FailSafeTimeout), policy.FailSafeTimeout);
+ ValidateNonNegative(scope, nameof(CachePolicy.FailSafeDistributedMaxStaleAge), policy.FailSafeDistributedMaxStaleAge);
+ if (policy.FailSafeDistributedEnabled == true && policy.FailSafeEnabled != true)
+ {
+ Throw(ValidateOptionsResult.Fail($"{scope}.{nameof(CachePolicy.FailSafeDistributedEnabled)} needs {nameof(CachePolicy.FailSafeEnabled)}."));
+ }
}
private static void ValidateNonNegative(string scope, string field, TimeSpan? value)
@@ -142,4 +169,7 @@ private static void Throw(ValidateOptionsResult result)
throw new OptionsValidationException(nameof(CacheOptions), typeof(CacheOptions), result.Failures);
}
}
+
+ private static ValidateOptionsResult DistributedNeedsMetadata(string scope) =>
+ ValidateOptionsResult.Fail($"{scope}.{nameof(CachePolicy.FailSafeDistributedEnabled)} needs RedisCacheOptions.EntryMetadataEnabled.");
}
diff --git a/src/UiPath.Caching/Config/CachePolicyMerger.cs b/src/UiPath.Caching/Config/CachePolicyMerger.cs
index 30a4864fa..b41956b8e 100644
--- a/src/UiPath.Caching/Config/CachePolicyMerger.cs
+++ b/src/UiPath.Caching/Config/CachePolicyMerger.cs
@@ -83,6 +83,8 @@ private static CachePolicy Combine(CachePolicy primary, CachePolicy fallback, IC
FailSafeMaxStaleAge = primary.FailSafeMaxStaleAge ?? fallback.FailSafeMaxStaleAge,
FailSafeCooldown = primary.FailSafeCooldown ?? fallback.FailSafeCooldown,
FailSafeTimeout = primary.FailSafeTimeout ?? fallback.FailSafeTimeout,
+ FailSafeDistributedEnabled = primary.FailSafeDistributedEnabled ?? fallback.FailSafeDistributedEnabled,
+ FailSafeDistributedMaxStaleAge = primary.FailSafeDistributedMaxStaleAge ?? fallback.FailSafeDistributedMaxStaleAge,
Serializer = MergeSerializer(primary.Serializer, fallback.Serializer),
WriteSerializer = writeSerializer
?? (primary.Serializer?.Write is not null
diff --git a/src/UiPath.Caching/Config/CachingBuilder.cs b/src/UiPath.Caching/Config/CachingBuilder.cs
index bf7d06969..c7ec41ccf 100644
--- a/src/UiPath.Caching/Config/CachingBuilder.cs
+++ b/src/UiPath.Caching/Config/CachingBuilder.cs
@@ -58,13 +58,18 @@ internal void Complete()
ServiceDescriptor.Singleton, CacheKeyCasingSeeder>());
Services.TryAddSingleton>(sp => new SystemJsonByteSerializerProxy(sp.GetService()));
Services.TryAddSingleton(ValueSerializerRegistration.BuildRegistry);
- if (Services.Any(d => d.ServiceType == typeof(ValueSerializerRegistration) || d.ServiceType == typeof(EventFormatRegistry)))
+ var hasRegisteredFormats = Services.Any(d => d.ServiceType == typeof(ValueSerializerRegistration) || d.ServiceType == typeof(EventFormatRegistry));
+ if (hasRegisteredFormats || Services.Any(d => d.ServiceType == typeof(IEntryFrameWrites)))
{
Services.TryAddSingleton(FormatNegotiation.Create);
- Services.TryAddSingleton(sp => ValueMigration.Create(sp)!);
Services.TryAddEnumerable(ServiceDescriptor.Singleton());
}
+ if (hasRegisteredFormats)
+ {
+ Services.TryAddSingleton(sp => ValueMigration.Create(sp)!);
+ }
+
Services.TryAddSingleton(EmptyResiliencePipelineProvider.Instance);
Services.TryAddSingleton(NullChangeTokenFactory.Instance);
Services.TryAddSingleton(NullTopicFactory.Instance);
diff --git a/src/UiPath.Caching/Config/RedisCollectionExtensions.cs b/src/UiPath.Caching/Config/RedisCollectionExtensions.cs
index 3427bd804..df924db58 100644
--- a/src/UiPath.Caching/Config/RedisCollectionExtensions.cs
+++ b/src/UiPath.Caching/Config/RedisCollectionExtensions.cs
@@ -1,4 +1,5 @@
using Microsoft.Extensions.Hosting;
+using UiPath.Caching.Negotiation;
using UiPath.Caching.Telemetry;
namespace UiPath.Caching.Config;
@@ -22,6 +23,8 @@ public static ICachingBuilder AddRedis(this ICachingBuilder builder, Action(sp =>
+ sp.GetRequiredService().FrameWrites(sp.GetRequiredService>().Value));
builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton(RedisCacheProvider.Create));
return builder;
}
diff --git a/src/UiPath.Caching/FailSafeLifetimeWarning.cs b/src/UiPath.Caching/FailSafeLifetimeWarning.cs
index dde3698bc..ec3b922f6 100644
--- a/src/UiPath.Caching/FailSafeLifetimeWarning.cs
+++ b/src/UiPath.Caching/FailSafeLifetimeWarning.cs
@@ -2,7 +2,7 @@
namespace UiPath.Caching;
-/// Warns once per policy that enables fail-safe on a cache with no size limit, where nothing caps how many values are kept.
+/// Warns once per policy that enables fail-safe on a cache with no size limit, where nothing caps how many values are kept, and once per policy that keeps a stale window in Redis.
internal static partial class FailSafeLifetimeWarning
{
internal const string DefaultPolicyName = "(default)";
@@ -23,6 +23,28 @@ public static void Log(ILogger logger, string provider, ICachePolicyFactory poli
}
}
+ /// Logs one warning for the default policy and each named policy that keeps a stale window in Redis, naming the window.
+ public static void LogRedisWindows(ILogger logger, ICachePolicyFactory policies)
+ {
+ CheckWindow(logger, DefaultPolicyName, policies.Default);
+ foreach (var name in policies.Keys)
+ {
+ CheckWindow(logger, name, policies.Resolve(name));
+ }
+ }
+
+ /// The stale window a policy keeps in Redis: the distributed age, then the local one, then the default, in whole seconds from 1 to ; zero without both switches.
+ internal static TimeSpan RedisWindow(CachePolicy policy)
+ {
+ if (policy.FailSafeEnabled != true || policy.FailSafeDistributedEnabled != true)
+ {
+ return TimeSpan.Zero;
+ }
+
+ var age = policy.FailSafeDistributedMaxStaleAge ?? policy.FailSafeMaxStaleAge ?? StaleValues.DefaultMaxStaleAge;
+ return TimeSpan.FromSeconds(Math.Clamp(age.Ticks / TimeSpan.TicksPerSecond, 1L, uint.MaxValue));
+ }
+
private static void Check(ILogger logger, string provider, string name, CachePolicy? policy)
{
if (policy?.FailSafeEnabled == true)
@@ -31,6 +53,17 @@ private static void Check(ILogger logger, string provider, string name, CachePol
}
}
+ private static void CheckWindow(ILogger logger, string name, CachePolicy? policy)
+ {
+ if (policy is not null && RedisWindow(policy) is { Ticks: > 0 } window)
+ {
+ LogRedisWindow(logger, name, window);
+ }
+ }
+
+ [LoggerMessage(Level = LogLevel.Warning, Message = "Policy {Policy} keeps every value it writes in Redis for {Window} after its logical expiration, so Redis holds each key for its lifetime plus that window. Set a shorter FailSafeDistributedMaxStaleAge to use less Redis memory.")]
+ private static partial void LogRedisWindow(ILogger logger, string policy, TimeSpan window);
+
[LoggerMessage(Level = LogLevel.Warning, Message = "Policy {Policy} enables fail-safe while {Provider} SizeLimit is unset: every key written under it keeps its value in memory until FailSafeMaxStaleAge ({MaxStaleAge}) after its local copy expires, whatever LocalMaxExpiration or LocalExpiration is, and nothing caps how many are kept. Set SizeLimit, which then bounds the local entries and the kept values together, or a shorter FailSafeMaxStaleAge.")]
private static partial void LogUnlimited(ILogger logger, string policy, string provider, TimeSpan maxStaleAge);
}
diff --git a/src/UiPath.Caching/IAnchoredTier.cs b/src/UiPath.Caching/IAnchoredTier.cs
new file mode 100644
index 000000000..371346ae4
--- /dev/null
+++ b/src/UiPath.Caching/IAnchoredTier.cs
@@ -0,0 +1,24 @@
+namespace UiPath.Caching;
+
+/// A tier that takes the write anchor of a deadline the layered cache made, so the send counts that deadline's life on both clocks and takes no anchor of its own (WA6).
+internal interface IAnchoredTier
+{
+ /// Whether the tier frames its writes and so takes the anchor; asked once per layered call, before the call makes or validates its first deadline.
+ bool TakesAnchor { get; }
+
+ ValueTask SetAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token);
+
+ ValueTask SetAsync(KeyValuePair[] keyValues, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token);
+
+ ValueTask TryAddAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token);
+
+ ValueTask> TryFillAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token);
+
+ ValueTask> TryFillAfterAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor anchor, TimeSpan generatorElapsed, CachePolicy? policy, CancellationToken token);
+
+ ValueTask[]> TryFillManyAsync(KeyValuePair[] entries, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token, TimeSpan? generatorElapsed);
+
+ ValueTask> SetIfChangedAsync(CacheKey cacheKey, T? value, IEqualityComparer comparer, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token);
+
+ ValueTask WriteIfStampAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, object? stamp, CancellationToken token);
+}
diff --git a/src/UiPath.Caching/ILayeredShape.cs b/src/UiPath.Caching/ILayeredShape.cs
index 45ee4eb55..db4c96931 100644
--- a/src/UiPath.Caching/ILayeredShape.cs
+++ b/src/UiPath.Caching/ILayeredShape.cs
@@ -30,6 +30,15 @@ internal interface ILayeredShape
TOptions BuildOptions(CacheKey cacheKey, DateTimeOffset expiration, CancellationToken token);
+ /// The options under a deadline made here from and the jitter, as a rehydrate makes its fresh deadline; a shape that anchors its writes takes the anchor there.
+ TOptions BuildJittered(CacheKey cacheKey, TimeSpan duration, TimeSpan? jitter, CancellationToken token);
+
+ /// The options under an instant the generator named, which the library first validates here; a shape that anchors its writes takes the anchor of that reading.
+ TOptions BuildOwn(CacheKey cacheKey, DateTimeOffset expiration, CancellationToken token);
+
+ /// The rehydrate run under the shape that takes the anchor of its fresh deadline, when the inner tier takes one; null when this shape's own flow runs it.
+ ValueTask? RehydrateAnchored(CacheKey originalCacheKey, DateTimeOffset entryExpiration, Func> generator, CachePolicy policy, TimeSpan duration, TimeSpan? jitter, RehydrateRun run, CancellationToken ct, RehydrateOverride? shaped);
+
ValueTask> ReadInnerAsync(TOptions options, CachePolicy policy);
/// The read that decides an adoption: an atomic snapshot of value and lifetime, and a failure thrown rather than answered as a miss; what it saw goes in when the shape can compare against it.
diff --git a/src/UiPath.Caching/MultilayerCache.Anchored.cs b/src/UiPath.Caching/MultilayerCache.Anchored.cs
new file mode 100644
index 000000000..8bb2e6323
--- /dev/null
+++ b/src/UiPath.Caching/MultilayerCache.Anchored.cs
@@ -0,0 +1,43 @@
+namespace UiPath.Caching;
+
+/// A layered cache over a tier that takes the anchor takes the anchor too, and a layered cache above it hands its own on (WA6).
+internal sealed partial class MultilayerCache : IAnchoredTier
+{
+ /// Whether the shared tier takes the anchor of a write; asked once per call, right before the call makes or validates its first deadline. A layered tier answers by asking its own.
+ public bool TakesAnchor => _anchoredInner?.TakesAnchor == true;
+
+ ValueTask IAnchoredTier.SetAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token)
+ where T : default =>
+ SetCoreAnchoredAsync(cacheKey, value, GetExpirationHanded(expiration), anchor, policy ?? _defaultPolicy, token);
+
+ ValueTask IAnchoredTier.SetAsync(KeyValuePair[] keyValues, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token)
+ where T : default =>
+ SetCoreAnchoredAsync(keyValues, GetExpirationHanded(expiration), anchor, policy ?? _defaultPolicy, token);
+
+ ValueTask IAnchoredTier.TryAddAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token)
+ where T : default =>
+ TryAddCoreAnchoredAsync(cacheKey, value, GetExpirationHanded(expiration), anchor, policy ?? _defaultPolicy, token);
+
+ ValueTask> IAnchoredTier.TryFillAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token)
+ where T : default =>
+ TryFillCoreAnchoredAsync(cacheKey, value, GetExpirationHanded(expiration), anchor, policy ?? _defaultPolicy, token);
+
+ ValueTask> IAnchoredTier.TryFillAfterAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor anchor, TimeSpan generatorElapsed, CachePolicy? policy, CancellationToken token)
+ where T : default =>
+ TryFillCoreAnchoredAsync(cacheKey, value, GetExpirationHanded(expiration), anchor, policy ?? _defaultPolicy, token);
+
+ ValueTask[]> IAnchoredTier.TryFillManyAsync(KeyValuePair[] entries, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token, TimeSpan? generatorElapsed)
+ where T : default =>
+ throw new NotSupportedException("A layered cache fills the keys of a batch itself and does not take a fill of many keys.");
+
+ ValueTask> IAnchoredTier.SetIfChangedAsync(CacheKey cacheKey, T? value, IEqualityComparer comparer, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, CancellationToken token)
+ where T : default =>
+ SetIfChangedCoreAnchoredAsync(cacheKey, value, comparer, GetExpirationHanded(expiration), anchor, policy ?? _defaultPolicy, token);
+
+ ValueTask IAnchoredTier.WriteIfStampAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor anchor, CachePolicy? policy, object? stamp, CancellationToken token)
+ where T : default =>
+ throw new NotSupportedException("A layered cache does not compare against a stamp.");
+
+ /// The instant an outer layered cache hands on is validated as the public overload validates it, with no timestamp and no anchor of its own (WA6).
+ private DateTimeOffset GetExpirationHanded(DateTimeOffset expiration) => GetExpiration(expiration);
+}
diff --git a/src/UiPath.Caching/MultilayerCache.AnchoredBatch.cs b/src/UiPath.Caching/MultilayerCache.AnchoredBatch.cs
new file mode 100644
index 000000000..9a163b591
--- /dev/null
+++ b/src/UiPath.Caching/MultilayerCache.AnchoredBatch.cs
@@ -0,0 +1,447 @@
+namespace UiPath.Caching;
+
+/// The batch get-or-add of a layered cache whose shared tier takes the anchor (WA4 (b), WA6): twins of the miss path of the batch that carry the anchor of the batch's one deadline, and hand it to the tier at the fill. The twins are the paths of today with the anchor beside the policy.
+internal sealed partial class MultilayerCache
+{
+ private async ValueTask[]> GetOrAddBatchInternalAnchoredAsync(
+ KeyValuePair[] entries,
+ TArg argument,
+ Func[]>> generator,
+ DateTimeOffset expiration,
+ WriteAnchor anchor,
+ TimeSpan effectiveDuration,
+ TimeSpan? rehydrateJitter,
+ CachePolicy policy,
+ CancellationToken token)
+ where TState : notnull
+ {
+ NotCacheableException.ThrowIfNotCacheable();
+ ArgumentNullException.ThrowIfNull(entries);
+
+ if (TryGetAllLocal(entries, policy, token, out var local))
+ {
+ return local;
+ }
+
+ var (states, keyIndexOfState, callerKeys, options, firstStateOfKey) = DistinctEntries(entries, expiration, token);
+ if (states.Length == 0)
+ {
+ return [];
+ }
+
+ var seen = _localMemorySetter.Writes;
+ var probe = await GetCacheEntriesInnerAsync(options, policy, token).ConfigureAwait(false);
+
+ var values = new T?[options.Length];
+ var missIndices = new List();
+ var hits = new List<(CacheKey CallerKey, TState State, CacheEntryOptions Options, DateTimeOffset Expiration, T? Value)>();
+ for (var i = 0; i < probe.Length; i++)
+ {
+ var entry = probe[i].Value;
+ if (entry.Found)
+ {
+ values[i] = entry.Value;
+ hits.Add((callerKeys[i], states[firstStateOfKey[i]], options[i], entry.Expiration, entry.Value));
+ continue;
+ }
+ missIndices.Add(i);
+ }
+
+ if (hits.Count > 0 && policy.RehydrateEnabled == true && policy.Rehydrate is not null)
+ {
+ TryRehydrateBatch(hits, BindBatch(argument, generator), policy, effectiveDuration, rehydrateJitter);
+ }
+
+ if (missIndices.Count == 0)
+ {
+ return Project(states, keyIndexOfState, values);
+ }
+
+ var missOptions = new CacheEntryOptions[missIndices.Count];
+ var missStates = new TState[missIndices.Count];
+ var missProbe = new KeyValuePair>[missIndices.Count];
+ for (var i = 0; i < missIndices.Count; i++)
+ {
+ var index = missIndices[i];
+ missOptions[i] = options[index];
+ missStates[i] = states[firstStateOfKey[index]];
+ missProbe[i] = probe[index];
+ }
+
+ var bound = BindBatch(argument, generator);
+ var resolved = SharesRuns(policy.Lock)
+ ? await RunBatchSharedAnchoredAsync(missOptions, missStates, missProbe, bound, anchor, policy, seen, token).ConfigureAwait(false)
+ : await RunBatchGuardedAnchoredAsync(missOptions, missStates, missProbe, bound, anchor, policy, token).ConfigureAwait(false);
+
+ for (var i = 0; i < missIndices.Count; i++)
+ {
+ values[missIndices[i]] = resolved[i].Value.Value;
+ }
+
+ return Project(states, keyIndexOfState, values);
+ }
+
+ private async ValueTask>[]> RunBatchGuardedAnchoredAsync(
+ CacheEntryOptions[] options,
+ TState[] states,
+ KeyValuePair>[] probe,
+ Func[]>> generator,
+ WriteAnchor anchor,
+ CachePolicy policy,
+ CancellationToken token)
+ where TState : notnull
+ {
+ if (!DistributedLockOn(policy.Lock))
+ {
+ return await RunBatchGeneratorAndStoreAnchoredAsync(options, states, probe, generator, anchor, policy, token).ConfigureAwait(false);
+ }
+
+ await using var lease = await AcquireDistributedLockAsync(CompositeCacheKey.For(Array.ConvertAll(options, o => o.CacheKey)), policy.Lock, token).ConfigureAwait(false);
+ var latest = await GetCacheEntriesInnerAsync(options, policy, token).ConfigureAwait(false);
+ return await RunBatchGeneratorAndStoreAnchoredAsync(options, states, latest, generator, anchor, policy, token).ConfigureAwait(false);
+ }
+
+ private async ValueTask>[]> RunBatchSharedAnchoredAsync(
+ CacheEntryOptions[] missOptions,
+ TState[] missStates,
+ KeyValuePair>[] probe,
+ Func[]>> generator,
+ WriteAnchor anchor,
+ CachePolicy policy,
+ long seen,
+ CancellationToken token)
+ where TState : notnull
+ {
+ var result = (KeyValuePair>[])probe.Clone();
+ var owned = new List();
+ var joined = new List>();
+ try
+ {
+ ReserveBatchKeys(missOptions, probe, owned, joined, token);
+ if (owned.Count > 0)
+ {
+ await RunOwnedAnchoredAsync(owned, missOptions, missStates, probe, generator, anchor, policy, seen, result, token).ConfigureAwait(false);
+ }
+ }
+ catch (OperationCanceledException) when (token.IsCancellationRequested)
+ {
+ EndOwned(owned, new InFlightAbandonedException());
+ WithdrawAll(joined);
+ throw;
+ }
+ catch (Exception ex)
+ {
+ EndOwned(owned, ex);
+ WithdrawAll(joined);
+ throw;
+ }
+
+ var abandoned = await AwaitJoinedAsync(joined, missOptions, result).ConfigureAwait(false);
+ if (abandoned.Count > 0)
+ {
+ await RetryAbandonedAnchoredAsync(abandoned, missOptions, missStates, generator, anchor, policy, result, token).ConfigureAwait(false);
+ }
+
+ return result;
+ }
+
+ private async ValueTask RunOwnedAnchoredAsync(
+ List owned,
+ CacheEntryOptions[] missOptions,
+ TState[] missStates,
+ KeyValuePair>[] probe,
+ Func[]>> generator,
+ WriteAnchor anchor,
+ CachePolicy policy,
+ long seen,
+ KeyValuePair>[] result,
+ CancellationToken token)
+ where TState : notnull
+ {
+ // A write in this process since the caller probed may have left values in the local tier, which a run writes before it leaves the table.
+ var rewritten = _localMemorySetter.Writes != seen;
+
+ // Every key is ours, none joined, so the arrays already are the owned set and need no copy.
+ var all = owned.Count == missOptions.Length;
+ var ownedOptions = all ? missOptions : owned.Select(o => missOptions[o.Index]).ToArray();
+ var ownedStates = all ? missStates : owned.Select(o => missStates[o.Index]).ToArray();
+ var current = all && !rewritten
+ ? probe
+ : owned.Select(o => rewritten && TryGetLocalEntry(missOptions[o.Index], out var local) ? new KeyValuePair>(missOptions[o.Index].CacheKey, local) : probe[o.Index]).ToArray();
+ var produced = await RunBatchGuardedAnchoredAsync(ownedOptions, ownedStates, current, generator, anchor, policy, token).ConfigureAwait(false);
+ for (var i = 0; i < owned.Count; i++)
+ {
+ result[owned[i].Index] = produced[i];
+ owned[i].Run.Complete(produced[i].Value);
+ }
+ }
+
+ private async ValueTask RetryAbandonedAnchoredAsync(
+ List abandoned,
+ CacheEntryOptions[] missOptions,
+ TState[] missStates,
+ Func[]>> generator,
+ WriteAnchor anchor,
+ CachePolicy policy,
+ KeyValuePair>[] result,
+ CancellationToken token)
+ where TState : notnull
+ {
+ var retryOptions = abandoned.Select(i => missOptions[i]).ToArray();
+ var freshSeen = _localMemorySetter.Writes;
+ var fresh = await GetCacheEntriesInnerAsync(retryOptions, policy, token).ConfigureAwait(false);
+ var again = await RunBatchSharedAnchoredAsync(retryOptions, abandoned.Select(i => missStates[i]).ToArray(), fresh, generator, anchor, policy, freshSeen, token).ConfigureAwait(false);
+ for (var i = 0; i < abandoned.Count; i++)
+ {
+ result[abandoned[i]] = again[i];
+ }
+ }
+
+ private async ValueTask>[]> RunBatchGeneratorAndStoreAnchoredAsync(
+ CacheEntryOptions[] missOptions,
+ TState[] missStates,
+ KeyValuePair>[] probe,
+ Func[]>> generator,
+ WriteAnchor anchor,
+ CachePolicy policy,
+ CancellationToken token)
+ where TState : notnull
+ {
+ var stillMissing = new List();
+ for (var i = 0; i < missOptions.Length; i++)
+ {
+ if (!probe[i].Value.Found)
+ {
+ stillMissing.Add(i);
+ }
+ }
+ if (stillMissing.Count == 0)
+ {
+ return probe;
+ }
+
+ var requestStates = new TState[stillMissing.Count];
+ var mappedKeys = new CacheKey[stillMissing.Count];
+ // Log-only, so it is not built for a disabled level.
+ var missedOptions = _logger.IsEnabled(LogLevel.Debug) ? new CacheEntryOptions[stillMissing.Count] : null;
+ for (var i = 0; i < stillMissing.Count; i++)
+ {
+ requestStates[i] = missStates[stillMissing[i]];
+ mappedKeys[i] = missOptions[stillMissing[i]].CacheKey;
+ if (missedOptions is not null)
+ {
+ missedOptions[i] = missOptions[stillMissing[i]];
+ }
+ }
+
+ var telemetryKey = CompositeCacheKey.For(mappedKeys);
+ if (missedOptions is not null)
+ {
+ LogBatchCacheMissed(Logged(missedOptions, typeof(T)), stillMissing.Count);
+ }
+
+ var watched = BeginBatchFill(missOptions, stillMissing);
+ try
+ {
+ var produced = await InvokeFactoryAsync(telemetryKey, ct => generator(requestStates, ct), policy.FactoryTimeout, token).ConfigureAwait(false);
+ var producedByState = SelectRequestedProduced(produced, requestStates);
+
+ var toStore = SelectEntriesToStore(missOptions, missStates, stillMissing, producedByState);
+ Dictionary>? adopted = null;
+ if (toStore.Count > 0)
+ {
+ var innerCacheDisconnected = GetInnerCacheDisconnected();
+ if (innerCacheDisconnected)
+ {
+ await InternalSetAsync(toStore.ToArray(), innerCacheDisconnected, policy, keepRefused: true, token).ConfigureAwait(false);
+ }
+ else
+ {
+ adopted = await FillBatchAnchoredAsync(toStore.ToArray(), watched, anchor, policy, token).ConfigureAwait(false);
+ }
+ }
+
+ return BuildBatchEntries(missOptions, missStates, probe, producedByState, adopted);
+ }
+ finally
+ {
+ EndBatchFill(watched);
+ }
+ }
+
+ private async ValueTask>?> FillBatchAnchoredAsync(CacheEntryValue[] entries, Dictionary watched, WriteAnchor anchor, CachePolicy policy, CancellationToken token)
+ {
+ if (entries.Length == 0)
+ {
+ return null;
+ }
+
+ try
+ {
+ return await _background.FillAsync(
+ entries.Select(static e => e.CacheEntry.CacheKey.Name),
+ (Cache: this, Entries: entries, Watched: watched, Anchor: anchor, Policy: policy, Token: token),
+ static (s, _) => s.Cache.TryFillEachAnchoredAsync(s.Entries, s.Watched, s.Anchor, s.Policy, s.Token),
+ static (s, results, keeper) => s.Cache.KeepFilledBatch(s.Entries, s.Watched, s.Policy, results, keeper),
+ token).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException) when (token.IsCancellationRequested)
+ {
+ return null;
+ }
+ catch (Exception ex)
+ {
+ LogBatchSetError(ex, entries);
+ return null;
+ }
+ }
+
+ private async ValueTask[]> TryFillEachAnchoredAsync(CacheEntryValue[] entries, Dictionary watched, WriteAnchor anchor, CachePolicy policy, CancellationToken token)
+ {
+ if (_innerCache is not IFillManyTier || _innerCache is not IAnchoredTier many)
+ {
+ var fills = new Task>[entries.Length];
+ for (var i = 0; i < entries.Length; i++)
+ {
+ fills[i] = TryFillOrReplaceAnchoredAsync(entries[i].CacheEntry, anchor, entries[i].Value, policy, BatchToken(watched, entries[i].CacheEntry.CacheKey.Name)).AsTask();
+ }
+
+ return await Task.WhenAll(fills).ConfigureAwait(false);
+ }
+
+ var results = new FillResult[entries.Length];
+ var open = new List(entries.Length);
+ for (var i = 0; i < entries.Length; i++)
+ {
+ var name = entries[i].CacheEntry.CacheKey.Name;
+ // In the key's turn, just before the command, as for a single fill.
+ if (LateStillCurrent(entries[i].CacheEntry) && _background.FillIntact(name, BatchToken(watched, name)))
+ {
+ open.Add(i);
+ }
+ }
+
+ if (open.Count == 0)
+ {
+ return results;
+ }
+
+ try
+ {
+ var pairs = open.Select(i => new KeyValuePair(entries[i].CacheEntry.CacheKey, entries[i].Value)).ToArray();
+ // One deadline for the batch, as a batch write has: every entry is built from the same resolved expiration.
+ var filled = await many.TryFillManyAsync(pairs, entries[open[0]].CacheEntry.Expiration, anchor, policy, token, OldestGenerator(entries, watched, open)).ConfigureAwait(false);
+ for (var k = 0; k < open.Count; k++)
+ {
+ var entry = entries[open[k]];
+ results[open[k]] = filled[k].Outcome == FillOutcome.Unreadable
+ ? await HealUnreadableAnchoredAsync(entry.CacheEntry, anchor, entry.Value, policy, BatchToken(watched, entry.CacheEntry.CacheKey.Name)).ConfigureAwait(false)
+ : filled[k];
+ }
+ }
+ catch (Exception ex) when (!(ex is OperationCanceledException && token.IsCancellationRequested))
+ {
+ LogBatchSetError(ex, entries);
+ }
+
+ return results;
+ }
+
+ /// As , for a tier that takes the anchor: the fresh deadline of the run takes its anchor where it is made, after the generator.
+ private async ValueTask RehydrateReservedAnchoredAsync(
+ CacheKey[] reservedKeys,
+ Dictionary stateByCallerKey,
+ Dictionary byState,
+ Func[]>> generator,
+ CachePolicy policy,
+ TimeSpan duration,
+ TimeSpan? rehydrateJitter,
+ RehydrateRun run,
+ CancellationToken token)
+ where TState : notnull
+ {
+ var rehydrateStates = MapReservedKeysToStates(reservedKeys, stateByCallerKey);
+ rehydrateStates = await AdoptFreshInnerAsync(rehydrateStates, byState, policy, duration, run, token).ConfigureAwait(false);
+ if (rehydrateStates.Length == 0)
+ {
+ return;
+ }
+
+ var produced = await generator(rehydrateStates, token).ConfigureAwait(false);
+
+ var (freshExpiration, anchor) = JitteredAnchored(duration, rehydrateJitter);
+ var groups = GroupRehydratedAt(produced, rehydrateStates, byState, freshExpiration);
+ if (groups.Count == 0)
+ {
+ return;
+ }
+
+ await WriteRehydrateGroupsAnchoredAsync(groups, freshExpiration, anchor, policy, token).ConfigureAwait(false);
+ }
+
+ /// Writes then announces one expiration group at a time, handing the anchor to the group that holds the fresh deadline.
+ private async ValueTask WriteRehydrateGroupsAnchoredAsync(
+ Dictionary Entry, CacheKey CallerKey)>> groups,
+ DateTimeOffset freshExpiration,
+ WriteAnchor anchor,
+ CachePolicy policy,
+ CancellationToken token)
+ {
+ var failed = new List();
+ var innerCacheDisconnected = GetInnerCacheDisconnected();
+ foreach (var (expiration, group) in groups)
+ {
+ var entries = group.ConvertAll(e => e.Entry);
+ var (written, kept) = await SetInnerAnchoredAsync(entries.ToArray(), expiration == freshExpiration ? anchor : default, innerCacheDisconnected, policy, keepRefused: false, token).ConfigureAwait(false);
+
+ // Written before the events, so a node they wake reads the new value; announced even when the write reports
+ // failure, since across Redis Cluster slots it can have written some keys.
+ var published = innerCacheDisconnected || await PublishSetsAsync(entries).ConfigureAwait(false);
+ if (!kept || !published || (!innerCacheDisconnected && !written))
+ {
+ failed.AddRange(group.Select(e => e.CallerKey.Name));
+ }
+ }
+
+ if (failed.Count > 0)
+ {
+ // A run timeout that ended the write is the coordinator's to report, not a write failure.
+ token.ThrowIfCancellationRequested();
+ throw new RehydrateWriteFailedException(string.Join(",", failed));
+ }
+ }
+
+ /// Groups the produced pairs by target expiration, the fresh one made by the caller of this method; a null value keeps its original deadline.
+ private Dictionary Entry, CacheKey CallerKey)>> GroupRehydratedAt(
+ KeyValuePair[]? produced,
+ TState[] rehydrateStates,
+ Dictionary byState,
+ DateTimeOffset freshExpiration)
+ where TState : notnull
+ {
+ var requested = new HashSet(rehydrateStates);
+ var seen = new HashSet(rehydrateStates.Length);
+ var groups = new Dictionary Entry, CacheKey CallerKey)>>();
+ foreach (var pair in produced ?? [])
+ {
+ if (!requested.Contains(pair.Key) || !seen.Add(pair.Key))
+ {
+ continue;
+ }
+ if (pair.Value is null && !_multiLayerCacheOptions.CacheNullValues)
+ {
+ continue;
+ }
+ var (options, originalExpiration, callerKey) = byState[pair.Key];
+ var target = pair.Value is null ? originalExpiration : freshExpiration;
+ options.Expiration = target;
+ if (!groups.TryGetValue(target, out var group))
+ {
+ group = [];
+ groups[target] = group;
+ }
+ group.Add((new CacheEntryValue(options, pair.Value), callerKey));
+ }
+ return groups;
+ }
+}
diff --git a/src/UiPath.Caching/MultilayerCache.AnchoredFill.cs b/src/UiPath.Caching/MultilayerCache.AnchoredFill.cs
new file mode 100644
index 000000000..2e2040c4e
--- /dev/null
+++ b/src/UiPath.Caching/MultilayerCache.AnchoredFill.cs
@@ -0,0 +1,279 @@
+namespace UiPath.Caching;
+
+/// The fills and the compare-and-set of a layered cache whose shared tier takes the anchor (WA6): twins of TryFillCoreAsync and SetIfChangedCoreAsync that hand the anchor to the tier.
+internal sealed partial class MultilayerCache
+{
+ private async ValueTask> TryFillCoreAnchoredAsync(CacheKey cacheKey, T? value, DateTimeOffset expiration, WriteAnchor handed, CachePolicy policy, CancellationToken token)
+ {
+ NotCacheableException.ThrowIfNotCacheable();
+ token.ThrowIfCancellationRequested();
+ var (options, anchor) = _entryBuilder.BuildEntryOptions(cacheKey, expiration, handed, token);
+ if (!CanFill(options, value, policy))
+ {
+ return default;
+ }
+
+ // Counting orders a fill against competing writes, so it is on before the first mark or local commit.
+ _background.Track();
+ if (!_sharedInner)
+ {
+ return FillLocally(options, value, policy);
+ }
+
+ if (GetInnerCacheDisconnected())
+ {
+ KeepUnfilled(options, null, value, policy);
+ return default;
+ }
+
+ var name = options.CacheKey.Name;
+ var mark = MarkInnerRead(name, options.TopicKey);
+ FillResult filled;
+ try
+ {
+ filled = await ((IAnchoredTier)_innerCache).TryFillAsync(options.CacheKey, value, options.Expiration, anchor, policy, token).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (!(ex is OperationCanceledException && token.IsCancellationRequested))
+ {
+ LogInnerCacheFillError(ex, Logged(options, typeof(T)));
+ filled = default;
+ }
+
+ return AfterFill(filled, options, mark, value, policy);
+ }
+
+ private async ValueTask> SetIfChangedCoreAnchoredAsync(CacheKey cacheKey, T? value, IEqualityComparer comparer, DateTimeOffset expiration, WriteAnchor handed, CachePolicy policy, CancellationToken token)
+ {
+ NotCacheableException.ThrowIfNotCacheable();
+ ArgumentNullException.ThrowIfNull(comparer);
+ token.ThrowIfCancellationRequested();
+ var (options, anchor) = _entryBuilder.BuildEntryOptions(cacheKey, expiration, handed, token);
+ if (!CanFill(options, value, policy))
+ {
+ return default;
+ }
+
+ _background.Track();
+ _background.NoteChange(options.CacheKey.Name);
+ if (!_sharedInner)
+ {
+ return await ChangeLocallyAsync(options, value, comparer, policy).ConfigureAwait(false);
+ }
+
+ if (GetInnerCacheDisconnected())
+ {
+ KeepUnfilled(options, null, value, policy);
+ return default;
+ }
+
+ var name = options.CacheKey.Name;
+ var mark = MarkInnerRead(name, options.TopicKey);
+ ChangeResult changed;
+ var guarded = new ThrowRecordingComparer(comparer);
+ try
+ {
+ changed = await ((IAnchoredTier)_innerCache).SetIfChangedAsync(options.CacheKey, value, guarded, options.Expiration, anchor, policy, token).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (guarded.Thrown is null && !(ex is OperationCanceledException && token.IsCancellationRequested))
+ {
+ LogInnerCacheFillError(ex, Logged(options, typeof(T)));
+ changed = default;
+ }
+
+ return await AfterChangeAsync(changed, options, mark, value, policy).ConfigureAwait(false);
+ }
+
+ /// What the layered cache keeps locally of an inner compare-and-set's answer.
+ private async ValueTask> AfterChangeAsync(ChangeResult changed, CacheEntryOptions options, long mark, T? value, CachePolicy policy)
+ {
+ switch (changed.Outcome)
+ {
+ case ChangeOutcome.Filled:
+ Layered().FillFromInnerRead(options, mark, value, policy);
+ break;
+ case ChangeOutcome.Unchanged when changed.Expiration is { } deadline && deadline > _clock.GetUtcNow() && !_innerTier.MayHaveMetWindowedFrame:
+ Layered().FillFromInnerRead(options with { Expiration = deadline }, mark, changed.Current, policy);
+ break;
+ case ChangeOutcome.Replaced:
+ await KeepAndAnnounceAsync(options, mark, value, policy).ConfigureAwait(false);
+ break;
+ case ChangeOutcome.Unchanged:
+ break;
+ default:
+ if (options.Expiration > _clock.GetUtcNow())
+ {
+ KeepUnfilled(options, mark, value, policy);
+ }
+
+ break;
+ }
+
+ return changed with { Expiration = null };
+ }
+
+ /// As , with the anchor of the deadline handed to the tier.
+ private async ValueTask> FillInnerAnchoredAsync(CacheEntryOptions options, WriteAnchor anchor, T? value, CachePolicy policy, ICacheEntry entry, long fill)
+ {
+ try
+ {
+ return await _background.FillAsync(
+ options.CacheKey.Name,
+ (Args: new FillArgs(this, options, value, policy, entry, fill), Anchor: anchor),
+ static (s, _) => s.Args.Cache.TryFillOrReplaceAnchoredAsync(s.Args.Options, s.Anchor, s.Args.Value, s.Args.Policy, s.Args.Fill),
+ static (s, filled, keeper) => s.Args.Cache.KeepFilled(s.Args, filled, keeper),
+ options.Token).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException) when (options.Token.IsCancellationRequested)
+ {
+ return default;
+ }
+ catch (Exception ex)
+ {
+ LogInnerCacheSetError(ex, Logged(options, typeof(T)));
+ return default;
+ }
+ }
+
+ [AsyncMethodBuilder(typeof(Pooled<>))]
+ private async ValueTask> TryFillOrReplaceAnchoredAsync(CacheEntryOptions options, WriteAnchor anchor, T? value, CachePolicy policy, long fill = BackgroundWrites.Untracked)
+ {
+ try
+ {
+ // A late fail-safe value checks in the key's turn that nothing removed or replaced the key since its generator started.
+ if (!LateStillCurrent(options))
+ {
+ return default;
+ }
+
+ // Just before the command: a write or removal since the generator started leaves the key to it, and the keep that follows counts the refusal.
+ if (!_background.FillIntact(options.CacheKey.Name, fill))
+ {
+ return default;
+ }
+
+ var filled = await TryInnerFillAnchoredAsync(options, anchor, value, policy, fill).ConfigureAwait(false);
+ if (filled.Outcome != FillOutcome.Unreadable)
+ {
+ return filled;
+ }
+
+ return await HealUnreadableAnchoredAsync(options, anchor, value, policy, fill).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (!(ex is OperationCanceledException && options.Token.IsCancellationRequested))
+ {
+ LogInnerCacheSetError(ex, Logged(options, typeof(T)));
+ return default;
+ }
+ }
+
+ private async ValueTask> HealUnreadableAnchoredAsync(CacheEntryOptions options, WriteAnchor anchor, T? value, CachePolicy policy, long fill)
+ {
+ if (_innerCache is not IStampedTier tier)
+ {
+ return default;
+ }
+
+ var (snapshot, stamp) = await tier.ReadStampedAsync(options.CacheKey, policy, options.Token).ConfigureAwait(false);
+ switch (snapshot.Outcome)
+ {
+ case SnapshotOutcome.Found:
+ return new FillResult(FillOutcome.Existed, snapshot.Entry!.Value, snapshot.Entry.Expiration);
+ case SnapshotOutcome.Unreadable or SnapshotOutcome.Absent when _background.FillIntact(options.CacheKey.Name, fill):
+ var written = await ((IAnchoredTier)_innerCache).WriteIfStampAsync(options.CacheKey, value, options.Expiration, anchor, policy, stamp, options.Token).ConfigureAwait(false);
+ if (written == StampedWrite.Won)
+ {
+ return new FillResult(FillOutcome.Added, default);
+ }
+
+ // Changed again since the read: the key is the winner's, or gone.
+ return written == StampedWrite.Lost ? await AfterLostHealAnchoredAsync(options, anchor, value, policy, fill).ConfigureAwait(false) : default;
+ default:
+ return default;
+ }
+ }
+
+ private async ValueTask> AfterLostHealAnchoredAsync(CacheEntryOptions options, WriteAnchor anchor, T? value, CachePolicy policy, long fill)
+ {
+ // A removal that arrived while the compare was in flight leaves the key to it.
+ if (!_background.FillIntact(options.CacheKey.Name, fill))
+ {
+ return default;
+ }
+
+ var filled = await TryInnerFillAnchoredAsync(options, anchor, value, policy, fill).ConfigureAwait(false);
+ return filled.Outcome == FillOutcome.Unreadable ? default : filled;
+ }
+
+ /// The inner fill with the anchor, told how long the key's generator has run when the inner tier leaves tombstones.
+ private ValueTask> TryInnerFillAnchoredAsync(CacheEntryOptions options, WriteAnchor anchor, T? value, CachePolicy policy, long fill) =>
+ _fencedInner && (_background.FillElapsed(options.CacheKey.Name, fill) ?? LateGeneratorElapsed()) is { } elapsed
+ ? ((IAnchoredTier)_innerCache).TryFillAfterAsync(options.CacheKey, value, options.Expiration, anchor, elapsed, policy, options.Token)
+ : ((IAnchoredTier)_innerCache).TryFillAsync(options.CacheKey, value, options.Expiration, anchor, policy, options.Token);
+
+ /// As , with the anchor handed to the tier.
+ private bool FillInBackgroundAnchored(CacheEntryOptions options, WriteAnchor anchor, T? value, CachePolicy policy, ICacheEntry entry, long fill)
+ {
+ var name = options.CacheKey.Name;
+ var watched = fill != BackgroundWrites.Untracked;
+ if (watched)
+ {
+ _background.RetainFill(name);
+ }
+
+ var queued = _background.RunWithoutEvent(
+ name,
+ (Cache: this, Options: options, Anchor: anchor, Value: value, Policy: policy, Entry: entry, Fill: fill),
+ static s => s.Cache.MemorySet(s.Options, s.Value, s.Cache.DisconnectedLifetime(s.Policy), s.Entry, s.Policy),
+ static (s, token) => s.Cache.DetachedWriteAsync(s, static (s, token) => s.Cache.FillDetachedAnchoredAsync(s.Options, s.Anchor, s.Value, s.Policy, s.Entry, s.Fill, token), static s => s.Cache.PromoteDetached(s.Options, s.Value, s.Policy, s.Entry), publish: null, token),
+ static s => s.Cache.EndFill(s.Options.CacheKey.Name, s.Fill)) is not null;
+ if (!queued && watched)
+ {
+ EndFill(name, fill);
+ }
+
+ return queued;
+ }
+
+ private async ValueTask FillDetachedAnchoredAsync(CacheEntryOptions options, WriteAnchor anchor, T? value, CachePolicy policy, ICacheEntry entry, long fill, CancellationToken token)
+ {
+ try
+ {
+ // The key may have changed while the write waited in the queue.
+ if (!_background.FillIntact(options.CacheKey.Name, fill))
+ {
+ _background.FillSuperseded();
+ return false;
+ }
+
+ var filled = await TryFillOrReplaceAnchoredAsync(options, anchor, value, policy, fill).ConfigureAwait(false);
+ switch (filled.Outcome)
+ {
+ case FillOutcome.Added:
+ return true;
+ case FillOutcome.Existed:
+ SwapForStored(options, policy, entry, filled);
+ return true;
+ case FillOutcome.Removed:
+ // The generator ran across a removal: the value this node kept ahead of the write goes too.
+ _background.FillSuperseded();
+ ApplyLocal(options.CacheKey.Name, (Cache: this, options.CacheKey.Name, Kept: entry), static s => s.Cache.IsLocalEntry(s.Name, s.Kept) && s.Cache.RemoveHeld(s.Name));
+ return false;
+ default:
+ return false;
+ }
+ }
+ catch (OperationCanceledException) when (token.IsCancellationRequested)
+ {
+ throw;
+ }
+ catch (Exception ex)
+ {
+ LogInnerCacheSetError(ex, Logged(options, typeof(T)));
+ return false;
+ }
+ finally
+ {
+ EndFill(options.CacheKey.Name, fill);
+ }
+ }
+}
diff --git a/src/UiPath.Caching/MultilayerCache.AnchoredGetOrAdd.cs b/src/UiPath.Caching/MultilayerCache.AnchoredGetOrAdd.cs
new file mode 100644
index 000000000..666bd567e
--- /dev/null
+++ b/src/UiPath.Caching/MultilayerCache.AnchoredGetOrAdd.cs
@@ -0,0 +1,332 @@
+namespace UiPath.Caching;
+
+///
+/// The get-or-add and result calls of a layered cache whose shared tier takes the anchor (WA4 (b), WA6): twins of the miss path that carry the anchor of the call's deadline beside its options, in the type of
+/// the generator where the run's frames take it, and hand it to the tier at the store. A hit takes the path of today, and a rehydrate takes its own anchor where it makes its fresh deadline.
+///
+internal sealed partial class MultilayerCache
+{
+ private ValueTask GetOrAddInternalAnchoredAsync(CacheKey cacheKey, Func> generator, DateTimeOffset expiration, WriteAnchor anchor, TimeSpan effectiveDuration, CachePolicy policy, long seen, bool localMissed, CancellationToken token)
+ {
+ // Not async, as the path of today: the miss path's delegates capture these parameters, and an async method would build that closure on a hit too.
+ NotCacheableException.ThrowIfNotCacheable();
+ if (!localMissed && !token.IsCancellationRequested)
+ {
+ var probe = ProbeLocal(cacheKey, token, out var local);
+ if (probe == LocalProbe.Hit && local!.Found)
+ {
+ Layered().TryRehydrate(cacheKey, local.Expiration, local.Value, generator, policy, effectiveDuration, null);
+ return new ValueTask(local.Value);
+ }
+
+ localMissed = probe == LocalProbe.Miss;
+ }
+
+ return GetOrAddCoreAnchoredAsync(cacheKey, generator, expiration, anchor, effectiveDuration, null, policy, seen, localMissed, token);
+ }
+
+ private ValueTask GetOrAddInternalAnchoredAsync(CacheKey cacheKey, TState state, Func> generator, DateTimeOffset expiration, WriteAnchor anchor, TimeSpan effectiveDuration, CachePolicy policy, long seen, bool localMissed, CancellationToken token)
+ {
+ // Binds the state to a delegate only where one is needed, so a hit builds no closure.
+ NotCacheableException.ThrowIfNotCacheable();
+ if (!localMissed && !token.IsCancellationRequested)
+ {
+ var probe = ProbeLocal(cacheKey, token, out var local);
+ if (probe == LocalProbe.Hit && local!.Found)
+ {
+ var layered = Layered();
+ if (layered.ShouldRehydrate(local.Value, policy, effectiveDuration))
+ {
+ layered.TriggerRehydrate(cacheKey, local.Expiration, Bind(state, generator), policy, effectiveDuration, null);
+ }
+
+ return new ValueTask(local.Value);
+ }
+
+ localMissed = probe == LocalProbe.Miss;
+ }
+
+ return GetOrAddCoreAnchoredAsync(cacheKey, Bind(state, generator), expiration, anchor, effectiveDuration, null, policy, seen, localMissed, token);
+ }
+
+ /// The miss of a get-or-add whose deadline has an anchor; a miss of a policy call (no ) makes its jittered deadline and its anchor here (WA4 (b)).
+ private ValueTask GetOrAddCoreAnchoredAsync(CacheKey cacheKey, Func> generator, DateTimeOffset? expiration, WriteAnchor handed, TimeSpan effectiveDuration, TimeSpan? rehydrateJitter, CachePolicy policy, long seen, bool localMissed, CancellationToken token)
+ {
+ try
+ {
+ var deadline = expiration ?? JitteredFor(effectiveDuration, rehydrateJitter, ref handed);
+ var (options, anchor) = _entryBuilder.BuildEntryOptions(cacheKey, deadline, handed, token);
+ if (TryGetCooling(options.CacheKey.Name, policy, out var cooling))
+ {
+ return new ValueTask(cooling.Value);
+ }
+
+ var fetch = localMissed ? Layered().FetchInnerAsync(options, policy) : GetCacheEntryInnerAsync(options, policy);
+ var miss = new Miss(cacheKey, options, generator, effectiveDuration, rehydrateJitter, policy, seen, localMissed);
+ if (fetch.IsCompletedSuccessfully)
+ {
+ return GenerateOnMissAnchoredAsync(miss, anchor, fetch.Result, token);
+ }
+
+ return AwaitFetchAnchoredAsync(miss, anchor, fetch, token);
+ }
+ catch (Exception ex)
+ {
+ return FailedAsync(ex);
+ }
+ }
+
+ private DateTimeOffset JitteredFor(TimeSpan duration, TimeSpan? jitter, ref WriteAnchor anchor)
+ {
+ var (deadline, taken) = JitteredAnchored(duration, jitter);
+ anchor = taken;
+ return deadline;
+ }
+
+ private ValueTask GenerateOnMissAnchoredAsync(Miss miss, WriteAnchor anchor, ICacheEntry entry, CancellationToken token)
+ {
+ if (entry.Found)
+ {
+ Layered().TryRehydrate(miss.Key, entry.Expiration, entry.Value, miss.Generator, miss.Policy, miss.Duration, miss.RehydrateJitter);
+ return new ValueTask(entry.Value);
+ }
+
+ var generated = GetOrGenerateEntryAsync> Generator, WriteAnchor Anchor)>(miss.Options, (miss.Generator, anchor), miss.Policy, static (cache, options, g, p, scope) => cache.RunGeneratorAndStoreEntryAnchoredAsync(options, g.Anchor, g.Generator, p, scope), miss.Seen, miss.InnerMissed, token);
+ if (generated.IsCompletedSuccessfully)
+ {
+ return new ValueTask(((ICacheEntry)generated.Result!).Value);
+ }
+
+ return ValueOfAsync(generated);
+ }
+
+ private async ValueTask AwaitFetchAnchoredAsync(Miss miss, WriteAnchor anchor, ValueTask> fetch, CancellationToken token)
+ {
+ var entry = await fetch.ConfigureAwait(false);
+ return await GenerateOnMissAnchoredAsync(miss, anchor, entry, token).ConfigureAwait(false);
+ }
+
+ private ValueTask> GetOrAddResultInternalAnchoredAsync(CacheKey cacheKey, Func> generator, DateTimeOffset expiration, WriteAnchor anchor, TimeSpan effectiveDuration, CachePolicy policy, long seen, bool localMissed, CancellationToken token)
+ {
+ NotCacheableException.ThrowIfNotCacheable();
+ if (!localMissed && !token.IsCancellationRequested)
+ {
+ var probe = ProbeLocal(cacheKey, token, out var local);
+ if (probe == LocalProbe.Hit && local!.Found)
+ {
+ Layered().TryRehydrate(cacheKey, local.Expiration, local.Value, generator, policy, effectiveDuration, null);
+ return new ValueTask>(ResultOf(local, generated: false));
+ }
+
+ localMissed = probe == LocalProbe.Miss;
+ }
+
+ return GetOrAddResultCoreAnchoredAsync(cacheKey, generator, expiration, anchor, effectiveDuration, null, policy, seen, localMissed, token);
+ }
+
+ private ValueTask> GetOrAddResultInternalAnchoredAsync(CacheKey cacheKey, TState state, Func> generator, DateTimeOffset expiration, WriteAnchor anchor, TimeSpan effectiveDuration, CachePolicy policy, long seen, bool localMissed, CancellationToken token)
+ {
+ NotCacheableException.ThrowIfNotCacheable();
+ if (!localMissed && !token.IsCancellationRequested)
+ {
+ var probe = ProbeLocal(cacheKey, token, out var local);
+ if (probe == LocalProbe.Hit && local!.Found)
+ {
+ var layered = Layered();
+ if (layered.ShouldRehydrate(local.Value, policy, effectiveDuration))
+ {
+ layered.TriggerRehydrate(cacheKey, local.Expiration, Bind(state, generator), policy, effectiveDuration, null);
+ }
+
+ return new ValueTask>(ResultOf(local, generated: false));
+ }
+
+ localMissed = probe == LocalProbe.Miss;
+ }
+
+ return GetOrAddResultCoreAnchoredAsync(cacheKey, Bind(state, generator), expiration, anchor, effectiveDuration, null, policy, seen, localMissed, token);
+ }
+
+ /// The miss of a result call whose deadline has an anchor, as for a call that reports what it ran.
+ private async ValueTask> GetOrAddResultCoreAnchoredAsync(CacheKey cacheKey, Func> generator, DateTimeOffset? expiration, WriteAnchor handed, TimeSpan effectiveDuration, TimeSpan? rehydrateJitter, CachePolicy policy, long seen, bool localMissed, CancellationToken token)
+ {
+ var deadline = expiration ?? JitteredFor(effectiveDuration, rehydrateJitter, ref handed);
+ var (options, anchor) = _entryBuilder.BuildEntryOptions(cacheKey, deadline, handed, token);
+ if (TryGetCooling(options.CacheKey.Name, policy, out var cooling))
+ {
+ return ResultOf(cooling, generated: false);
+ }
+
+ var entry = localMissed ? await Layered().FetchInnerAsync(options, policy).ConfigureAwait(false) : await GetCacheEntryInnerAsync(options, policy).ConfigureAwait(false);
+ if (entry.Found)
+ {
+ Layered().TryRehydrate(cacheKey, entry.Expiration, entry.Value, generator, policy, effectiveDuration, rehydrateJitter);
+ return ResultOf(entry, generated: false);
+ }
+
+ var recorder = GeneratorRecorder.For(generator);
+ var generated = (ICacheEntry)(await GetOrGenerateEntryAsync> Generator, WriteAnchor Anchor)>(
+ options,
+ (recorder.Generator, anchor),
+ policy,
+ static (cache, o, g, p, scope) => cache.RunGeneratorAndStoreEntryAnchoredAsync(o, g.Anchor, g.Generator, p, scope),
+ seen,
+ localMissed,
+ token).ConfigureAwait(false))!;
+ return ResultOf(generated, recorder.Ran);
+ }
+
+ private async ValueTask GetOrAddGeneratedAnchoredAsync(CacheKey cacheKey, Func>> generator, CachePolicy policy, long seen, bool localMissed, CancellationToken token)
+ {
+ NotCacheableException.ThrowIfNotCacheable();
+ var (deadline, anchor) = GetExpirationAnchored(policy);
+ var (cacheEntryOptions, _) = _entryBuilder.BuildEntryOptions(cacheKey, deadline, anchor, token);
+ if (TryGetCooling(cacheEntryOptions.CacheKey.Name, policy, out var cooling))
+ {
+ return cooling.Value;
+ }
+
+ var entry = localMissed
+ ? await Layered().FetchInnerAsync(cacheEntryOptions, policy).ConfigureAwait(false)
+ : await GetCacheEntryInnerAsync(cacheEntryOptions, policy).ConfigureAwait(false);
+ if (entry.Found)
+ {
+ return entry.Value;
+ }
+
+ var result = (ICacheEntry)(await GetOrGenerateEntryAsync>> Generator, WriteAnchor Anchor)>(cacheEntryOptions, (generator, anchor), policy, static (cache, options, g, p, scope) => cache.RunGeneratedAndStoreEntryAnchoredAsync(options, g.Anchor, g.Generator, p, scope), seen, localMissed, token).ConfigureAwait(false))!;
+ return result.Value;
+ }
+
+ private async ValueTask