Skip to content
33 changes: 30 additions & 3 deletions src/Dapr.Actors/Runtime/ActorStateManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,29 @@ internal ActorStateManager(Actor actor)
this.defaultTracker = new Dictionary<string, StateMetadata>();
}

public Task UnloadStateAsync(string stateName, UnloadStateOptions options = null, CancellationToken cancellationToken = default)
{
ArgumentVerifier.ThrowIfNull(stateName, nameof(stateName));
EnsureStateProviderInitialized();

var stateChangeTracker = GetContextualStateTracker();
if (!stateChangeTracker.ContainsKey(stateName))
{
// Nothing to unload from memory
return Task.CompletedTask;
}

var stateMetadata = stateChangeTracker[stateName];
bool isModified = stateMetadata.ChangeKind == StateChangeKind.Add || stateMetadata.ChangeKind == StateChangeKind.Update || stateMetadata.ChangeKind == StateChangeKind.Remove;
if (isModified && (options == null || !options.AllowUnloadingWhenStateModified))
{
throw new InvalidOperationException($"Cannot unload state '{stateName}' because it has been modified and not yet persisted. Set AllowUnloadingWhenStateModified to true to override.");
}

stateChangeTracker.Remove(stateName);
return Task.CompletedTask;
}

public async Task AddStateAsync<T>(string stateName, T value, CancellationToken cancellationToken)
{
EnsureStateProviderInitialized();
Expand Down Expand Up @@ -543,12 +566,16 @@ private StateMetadata(object value, Type type, StateChangeKind changeKind, DateT
this.Type = type;
this.ChangeKind = changeKind;

if (ttlExpireTime.HasValue && ttl.HasValue) {
if (ttlExpireTime.HasValue && ttl.HasValue)
{
throw new ArgumentException("Cannot specify both TTLExpireTime and TTL");
}
if (ttl.HasValue) {
if (ttl.HasValue)
{
this.TTLExpireTime = DateTimeOffset.UtcNow.Add(ttl.Value);
} else {
}
else
{
this.TTLExpireTime = ttlExpireTime;
}
}
Expand Down
9 changes: 9 additions & 0 deletions src/Dapr.Actors/Runtime/IActorStateManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,15 @@ namespace Dapr.Actors.Runtime;
/// </summary>
public interface IActorStateManager
{
/// <summary>
/// Unloads the specified state from the in-memory cache/tracker, but does not remove it from the underlying store.
/// </summary>
/// <param name="stateName">Name of the actor state to unload.</param>
/// <param name="options">Options for unloading state (e.g., allow unloading modified state).</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>A task that represents the asynchronous unload operation.</returns>
/// <exception cref="InvalidOperationException">Thrown if the state is modified and not yet persisted, unless allowed by options.</exception>
Task UnloadStateAsync(string stateName, UnloadStateOptions options = null, CancellationToken cancellationToken = default);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

consider adding as a default interface method with a NotImplementedException / virtual behavior.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why?

@WhitWaldo WhitWaldo Apr 9, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In this scenario, adding a default interface method to throw NotSupportedException isn't a meaningful inclusion because we already provide the concrete type implementing this interface ourselves, and this will ship with same-day support.

Especially as this project doesn't support dependency injection, I would not expect that developers have implemented their own types on this interface, modified the library to use them instead, update the package and see this new method on the interface and call it in their applications just to see a TypeLoadException because they didn't implement the method themselves - I just don't think that's likely. I wouldn't have expected them to wrap every actor invocation in a try/catch block either, so this would just shift throwing a TypeLoadException to an NotSupportedException - not a meaningful change here.

/// <summary>
/// Adds an actor state with given state name.
/// </summary>
Expand Down
14 changes: 14 additions & 0 deletions src/Dapr.Actors/Runtime/UnloadStateOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Options for UnloadStateAsync operation
Comment thread
olitomlinson marked this conversation as resolved.
Outdated
namespace Dapr.Actors.Runtime
{
/// <summary>
/// Options for the UnloadStateAsync operation on ActorStateManager.
/// </summary>
public class UnloadStateOptions
{
/// <summary>
/// If true, allows unloading state even if it is modified and not yet persisted.
/// </summary>
public bool AllowUnloadingWhenStateModified { get; set; } = false;
}
}
85 changes: 85 additions & 0 deletions test/Dapr.Actors.Test/ActorStateManagerUnloadStateTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// ------------------------------------------------------------------------
// Copyright 2023 The Dapr Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ------------------------------------------------------------------------

using System;
using System.Threading;
using System.Threading.Tasks;
using Dapr.Actors.Runtime;
using Dapr.Actors.Communication;
using Moq;
using Xunit;

namespace Dapr.Actors.Test
{
public class ActorStateManagerUnloadStateTest
{
[Fact]
public async Task UnloadState_RemovesFromMemoryButNotStore()
{
var interactor = new Moq.Mock<TestDaprInteractor>();
// Simulate state existence only after SaveStateAsync
bool stateSaved = false;
interactor.Setup(d => d.GetStateAsync(
Moq.It.IsAny<string>(),
Moq.It.IsAny<string>(),
Moq.It.Is<string>(key => key == "big-data"),
Moq.It.IsAny<CancellationToken>()))
.ReturnsAsync(() =>
stateSaved
? new Dapr.Actors.Communication.ActorStateResponse<string>("\"payload\"", null)
: new Dapr.Actors.Communication.ActorStateResponse<string>("", null));
var host = ActorHost.CreateForTest<TestActor>();
host.StateProvider = new DaprStateProvider(interactor.Object, new System.Text.Json.JsonSerializerOptions());
var mngr = new ActorStateManager(new TestActor(host));
var token = TestContext.Current.CancellationToken;

// Add and save state
await mngr.AddStateAsync("big-data", "payload", token);
await mngr.SaveStateAsync(token);
stateSaved = true;
Assert.Equal("payload", await mngr.GetStateAsync<string>("big-data", token));

// Unload from memory
await mngr.UnloadStateAsync("big-data", cancellationToken: token);

// Should reload from store
interactor.Setup(d => d.GetStateAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new Dapr.Actors.Communication.ActorStateResponse<string>("\"payload\"", null));
Assert.Equal("payload", await mngr.GetStateAsync<string>("big-data", token));
}

[Fact]
public async Task UnloadState_ThrowsIfModifiedUnlessAllowed()
{
var interactor = new Moq.Mock<TestDaprInteractor>();
// Default: state does not exist
interactor.Setup(d => d.GetStateAsync(
Moq.It.IsAny<string>(),
Moq.It.IsAny<string>(),
Moq.It.IsAny<string>(),
Moq.It.IsAny<CancellationToken>()))
.ReturnsAsync(new Dapr.Actors.Communication.ActorStateResponse<string>("", null));
var host = ActorHost.CreateForTest<TestActor>();
host.StateProvider = new DaprStateProvider(interactor.Object, new System.Text.Json.JsonSerializerOptions());
var mngr = new ActorStateManager(new TestActor(host));
var token = TestContext.Current.CancellationToken;

await mngr.AddStateAsync("key", "value", token);
// Not yet saved, so is modified
await Assert.ThrowsAsync<InvalidOperationException>(() => mngr.UnloadStateAsync("key", cancellationToken: token));

// Should not throw if allowed
await mngr.UnloadStateAsync("key", new UnloadStateOptions { AllowUnloadingWhenStateModified = true }, token);
}
}
}
Loading