.NET Agents That Survive Restarts: Temporal, Typed Tool Outcomes, and the Call You Pay for Twice
From the publisher’s feed, collected in the ZeroLabs newsroom.
A few weeks ago I wrote about killing a Microsoft Agent Framework workflow with kill -9 and watching what came back (Durable Agents in .NET: Kill the Process and See What Survives). The workflow survived. The step that was in flight ran again, and the only thing between me and a duplicate side effect was an idempotency key I had added myself.This is the follow-up I promised myself: the same question on Temporal, plus the other half of the problem that I glossed over last time. When a tool comes back, how does the loop know whether to continue, retry, ask a human, or stop?My position after reading this week’s material: durability is not about whether your run survives a restart. It is about which side effects are allowed to happen twice. And typed tool outcomes are how the loop decides what happens next without guessing. The two ideas need each other. A durable loop that cannot tell a denial from a network blip will retry the denial forever, and it will do so very reliably.What Petrusheuski’s Temporal tests actually showMikhail Petrusheuski published a .NET sample that pairs Microsoft.Extensions.AI with Temporal, written after Cecil Phillip's .NET Conf session on production AI workflows. The idea is simple. The workflow is the deterministic coordinator. Every model call and every tool call is an activity, which gets retries and timeouts from the platform.His repository has four tests that run the workflow against a local Temporal server with a scripted chat client that counts its calls. These are his tests, on his setup, with a fake client. I have not reproduced them, and they are small. But they are precise about the thing that matters:Scenario (Petrusheuski's tests) Model calls What it means------------------------------------------------------- ----------- --------------------------------------Worker stopped after the model call completed 1 Completed activities are not repeatedWorker stopped while the model call was in flight 2 Activities are at-least-once: paid twicePrompt rejected with a non-retryable error type 1 NonRetryableErrorTypes stops the loopTwo transient HttpRequestExceptions, then success 3 Normal retry, each attempt countsThe second row is the one I would print and pin above the desk. Temporal makes completed steps durable. It does not make interrupted ones free. An attempt that dies mid-call is retried after the attempt timeout, and on a real provider that is two charges.He also lists a few things Temporal does not do, and I agree with every one of them:Temporal caps attempts and time, not tokens. MaximumAttempts, StartToCloseTimeout and ScheduleToCloseTimeout will stop an unavailable provider from becoming an open-ended bill, but they know nothing about cost.SDK retries multiply with activity retries. If your model client retries three times internally and the activity retries four times, the worst case is twelve requests. He turns the SDK’s retries off and lets Temporal own the policy. So would I.There are no exactly-once side effects. You get a stable place to keep an operation ID. Making the effect idempotent is your job.One small detail from his post that saved me a confused afternoon in advance: NonRetryableErrorTypes matches the exception's class name without the namespace.A note on packages: I am deliberately not listing Temporal package ids or versions here. Take them from the Temporal .NET SDK documentation when you set this up, because anything I paste will be stale by the time you read it.Where each failure landsBefore writing any code, I sat down and walked through the four places a run can die between “ask the model” and “change the world”. This table is the design. Everything after it is just wiring.Failure point What Temporal does Cost impact Your guard------------------------ --------------------------------------- ---------------------------------- -----------------------------------------Before the model call Attempt times out (StartToClose), None. No request left the worker. Nothing extra. The token reservation activity retried on a live worker is released when the call settles.During the model call Attempt is lost and retried after the Paid twice (Petrusheuski: 2 calls). Reserve estimate x MaxAttempts before attempt timeout (at-least-once) SDK retries multiply on top. the call; charge unreported attempts; turn SDK retries off.After the call, Model result is already in history and No extra tokens (Petrusheuski: Keep the model call and the write inbefore the write is not repeated. The write activity is 1 call), but only if the call and separate activities. Build the operation scheduled again. the write are separate activities. id in the workflow, not the activity.During the write Write activity retried from the top Rarely tokens. The risk is a Operation table + downstream duplicate side effect. Idempotency-Key + read-back before reporting success.Two of those guards are things I did not appreciate until I wrote the table out.The third row only holds if the model call and the write live in separate activities. If one activity calls the model and then writes, a crash between the two repeats both, and you pay for the call again to redo work you already had. It sounds obvious written down. It is very easy to get wrong when an “agent step” feels like one thing.The fourth row has a subtlety the operation table alone does not fix. When an attempt times out, Temporal schedules a retry, but it cannot reach into a partitioned or frozen worker and stop the old attempt. For a short window, two attempts can be talking to your downstream system at once. A row in your own database does not serialize that. A key the downstream system honors does.(a) The workflow and the activitiesThe example is a triage agent: for each bug report, ask the model for a ticket draft, then create the ticket in a tracker. Small enough to read, real enough to have every failure mode in the table.First, the job, the kill criteria and the messages. I pass the kill criteria in with the job on purpose. Temporal records workflow input in history, so after a run you can see exactly which thresholds the gate was using. That is the “write the kill criteria before the run” idea from Jaroslaw Wasowski’s piece on deterministic gates, more on that below.namespace DurableToolRuns;public sealed record KillCriteria( long TokenCeiling, long EstimatedTokensPerCall, // keep this honest: prompt size + MaxOutputTokens int MaxRetryableInARow, TimeSpan ApprovalWait);public sealed record TriageJob( string Repository, IReadOnlyList Reports, KillCriteria Kill);public sealed record TicketDraft(string Title, string Body);public sealed record ModelReply( TicketDraft Draft, long? InputTokens, long? OutputTokens, int Attempt);public sealed record RunSummary( string Status, string Reason, long TokensCharged, IReadOnlyList Evidence){ public static RunSummary Completed(long tokens, IEnumerable evidence) => new("completed", "", tokens, [.. evidence]); public static RunSummary Stopped(string reason, long tokens, IEnumerable evidence) => new("stopped", reason, tokens, [.. evidence]); public static RunSummary Killed(string reason, long tokens, IEnumerable evidence) => new("killed", reason, tokens, [.. evidence]);}The workflow. No I/O, no clocks, no Task.Run, no IChatClient. It only decides.using Temporalio.Common;using Temporalio.Exceptions;using Temporalio.Workflows;namespace DurableToolRuns;[Workflow]public sealed class TriageWorkflow{ static readonly RetryPolicy ModelRetry = new() { InitialInterval = TimeSpan.FromSeconds(2), BackoffCoefficient = 2, MaximumInterval = TimeSpan.FromSeconds(30), MaximumAttempts = 3, NonRetryableErrorTypes = ["PromptRejectedException"], // class name, no namespace }; static readonly ActivityOptions ModelOptions = new() { StartToCloseTimeout = TimeSpan.FromMinutes(2), // one attempt ScheduleToCloseTimeout = TimeSpan.FromMinutes(8), // all attempts together RetryPolicy = ModelRetry, }; static readonly ActivityOptions WriteOptions = new() { StartToCloseTimeout = TimeSpan.FromSeconds(30), RetryPolicy = new() { MaximumAttempts = 5 }, }; TokenBudget _budget = new(0); readonly List _evidence = []; bool _approved; [WorkflowQuery] public long TokensCharged => _budget.Charged; [WorkflowSignal] public Task ApproveAsync() { _approved = true; return Task.CompletedTask; } [WorkflowRun] public async Task RunAsync(TriageJob job) { _budget = new TokenBudget(job.Kill.TokenCeiling); long reservation = job.Kill.EstimatedTokensPerCall * ModelRetry.MaximumAttempts!.Value; for (int i = 0; i { // (d) The guard Temporal does not give you: checked before every model activity. if (!_budget.TryReserve(reservation)) { return RunSummary.Killed( $"token ceiling {job.Kill.TokenCeiling} would be crossed before report {i}", _budget.Charged, _evidence); } ModelReply reply; try { string report = job.Reports[i]; reply = await Workflow.ExecuteActivityAsync( (AgentActivities a) => a.DraftTicketAsync(job.Repository, report), ModelOptions); } catch (ActivityFailureException e) { // We do not know what the failed attempts cost. Charge the whole reservation. _budget.ChargeReservation(reservation); return RunSummary.Stopped($"model step failed: {e.InnerException?.Message}", _budget.Charged, _evidence); } _budget.Settle(reservation, reply, job.Kill.EstimatedTokensPerCall); // Built here, from workflow state, so every replay and every retry sees the same id. string operationId = $"{Workflow.Info.WorkflowId}/report-{i}"; ToolOutcome outcome = await ApplyWithPolicyAsync(operationId, reply.Draft, job.Kill); // A switch *expression*, so the compiler checks it. More on that in (b). RunSummary? stop = outcome switch { ToolSucceeded s => Record(s), ToolDenied d => RunSummary.Stopped($"denied: {d.Reason}", _budget.Charged, _evidence), ToolRetryableFailure r => RunSummary.Killed( $"{job.Kill.MaxRetryableInARow} retryable failures in a row ({r.Code})", _budget.Charged, _evidence), ToolPermanentFailure p => RunSummary.Stopped($"permanent failure: {p.Code}", _budget.Charged, _evidence), }; if (stop is not null) return stop; } return RunSummary.Completed(_budget.Charged, _evidence); } RunSummary? Record(ToolSucceeded s) { _evidence.Add(s.EvidenceId); return null; } async Task ApplyWithPolicyAsync(string operationId, TicketDraft draft, KillCriteria kill) { int retryableInARow = 0; bool approvalUsed = false; while (true) { bool approved = approvalUsed; ToolOutcome outcome = await Workflow.ExecuteActivityAsync( (AgentActivities a) => a.CreateTicketOnceAsync(operationId, draft, approved), WriteOptions); if (outcome is ToolRetryableFailure r && ++retryableInARow { // A durable timer: survives a worker restart, costs nothing, same operation id. await Workflow.DelayAsync(TimeSpan.FromSeconds(r.RetryAfterSeconds)); continue; } if (outcome is ToolDenied && !approvalUsed) { approvalUsed = true; _approved = false; bool gotApproval = await Workflow.WaitConditionAsync(() => _approved, kill.ApprovalWait); if (!gotApproval) return outcome; continue; // same operation id, so an approval can never create a second ticket } return outcome; } }}A design decision worth calling out: typed outcomes and Temporal retries have different jobs. Temporal’s activity retry handles “the worker died” and “something threw that I did not expect”. The tool’s typed outcome handles “the tracker answered, and here is what it said”. So the write activity returns ToolRetryableFailure as a value instead of throwing, and the workflow decides to wait with a durable timer. If I threw instead, Temporal would retry blindly with its own backoff and ignore the RetryAfterSeconds the tracker gave me.The activities are thin. The real logic lives in a TicketTool class so the same code can sit behind the HTTP endpoint in (c).using Microsoft.Extensions.AI;using Temporalio.Activities;namespace DurableToolRuns;public sealed class PromptRejectedException(string message) : Exception(message);public sealed class AgentActivities(IChatClient chat, TicketTool tickets){ [Activity] public async Task DraftTicketAsync(string repository, string report) { ActivityExecutionContext ctx = ActivityExecutionContext.Current; ChatResponse response = await chat.GetResponseAsync( $""" Repository: {repository} Turn this bug report into a tracker ticket with a short title and a body. {report} """, new ChatOptions { MaxOutputTokens = 800 }, // makes the token estimate a real ceiling cancellationToken: ctx.CancellationToken); // Retrying the same prompt on a model that cannot produce the shape is a paid coin flip. if (!response.TryGetResult(out TicketDraft? draft) || draft is null) throw new PromptRejectedException("model did not return a ticket draft"); return new ModelReply( draft, response.Usage?.InputTokenCount, response.Usage?.OutputTokenCount, ctx.Info.Attempt); // the workflow needs this to charge attempts it never saw } [Activity] public Task CreateTicketOnceAsync(string operationId, TicketDraft draft, bool approved) => tickets.CreateOnceAsync(operationId, draft, approved, ActivityExecutionContext.Current.CancellationToken);}The operation table and the read-backPetrusheuski’s sample keys writes on an operation ID in a ConcurrentDictionary, which is the right shape and the wrong storage for anything past a demo. A dictionary dies with the worker. The table has to outlive it.CREATE TABLE IF NOT EXISTS operations ( op_id TEXT PRIMARY KEY, status TEXT NOT NULL CHECK (status IN ('open', 'done')), outcome_json TEXT, attempts INTEGER NOT NULL, updated_at TEXT NOT NULL);using System.Text.Json;using Microsoft.Data.Sqlite;namespace DurableToolRuns;public sealed class OperationStore(string connectionString){ // Returns the stored outcome if the operation already finished, otherwise null. public async Task ClaimAsync(string opId, CancellationToken ct) { await using var conn = new SqliteConnection(connectionString); await conn.OpenAsync(ct); await using var cmd = conn.CreateCommand(); cmd.CommandText = """ INSERT INTO operations(op_id, status, attempts, updated_at) VALUES ($id, 'open', 1, $now) ON CONFLICT(op_id) DO UPDATE SET attempts = attempts + 1, updated_at = $now RETURNING status, outcome_json; """; cmd.Parameters.AddWithValue("$id", opId); cmd.Parameters.AddWithValue("$now", DateTime.UtcNow.ToString("O")); await using var reader = await cmd.ExecuteReaderAsync(ct); await reader.ReadAsync(ct); return reader.GetString(0) == "done" ? JsonSerializer.Deserialize(reader.GetString(1)) : null; } // Only terminal outcomes are stored. Denied and retryable stay 'open' so a later attempt can proceed. public async Task FinishAsync(string opId, ToolOutcome outcome, CancellationToken ct) { await using var conn = new SqliteConnection(connectionString); await conn.OpenAsync(ct); await using var cmd = conn.CreateCommand(); cmd.CommandText = """ UPDATE operations SET status = 'done', outcome_json = $json, updated_at = $now WHERE op_id = $id; """; cmd.Parameters.AddWithValue("$id", opId); cmd.Parameters.AddWithValue("$json", JsonSerializer.Serialize(outcome)); cmd.Parameters.AddWithValue("$now", DateTime.UtcNow.ToString("O")); await cmd.ExecuteNonQueryAsync(ct); return outcome; }}SQLite keeps the sample self-contained. With more than one worker I would move this to Postgres; the ON CONFLICT ... RETURNING statement carries over unchanged.Now the tool. The tracker is behind an interface because yours is not mine. What matters is the contract: it accepts an external reference it deduplicates on, and it can look a ticket up by that reference. If your tracker cannot do the second thing, you cannot do read-back, and no framework fixes that.using Microsoft.Extensions.Logging;namespace DurableToolRuns;public interface ITicketApi{ // The tracker must deduplicate on externalRef (an Idempotency-Key header or a custom field). Task CreateAsync(TicketDraft draft, string externalRef, CancellationToken ct); Task FindByExternalRefAsync(string externalRef, CancellationToken ct);}public sealed record TicketRecord(string Id, string Title);public sealed class TicketApiException(int statusCode, string code, int? retryAfterSeconds = null) : Exception(code){ public int StatusCode { get; } = statusCode; public string Code { get; } = code; public int? RetryAfterSeconds { get; } = retryAfterSeconds;}public sealed class TicketTool(OperationStore ops, ITicketApi api, ILogger log){ public async Task CreateOnceAsync( string operationId, TicketDraft draft, bool approved, CancellationToken ct) { // 1. A finished operation is answered from the table, never by calling the tracker again. if (await ops.ClaimAsync(operationId, ct) is { } finished) return finished; // My rule for this example: anything mentioning security needs a human first. if (!approved && draft.Title.Contains("security", StringComparison.OrdinalIgnoreCase)) return new ToolDenied("tickets:create-security", "security tickets need human approval"); try { await api.CreateAsync(draft, operationId, ct); } catch (TicketApiException e) when (e.StatusCode == 403) { return new ToolDenied("tickets:create", e.Code); } catch (TicketApiException e) when (e.StatusCode is 429 or 503) { return new ToolRetryableFailure(e.Code, e.Message, e.RetryAfterSeconds ?? 30); } catch (TicketApiException e) when (e.StatusCode is >= 400 and { return await ops.FinishAsync(operationId, new ToolPermanentFailure(e.Code, e.Message), ct); } catch (Exception e) when ((e is HttpRequestException or TaskCanceledException) && !ct.IsCancellationRequested) { // The request may or may not have landed. We stopped waiting; that proves nothing. log.LogWarning(e, "create for {OperationId} has an unknown outcome, reading back", operationId); } // 2. Read-back: success is what the tracker says it has, not what the create call returned. TicketRecord? stored = await api.FindByExternalRefAsync(operationId, ct); if (stored is null) return new ToolRetryableFailure("not-confirmed", "create was not confirmed by read-back", 10); if (stored.Title != draft.Title) return await ops.FinishAsync( operationId, new ToolPermanentFailure("readback-mismatch", $"tracker holds '{stored.Title}'"), ct); return await ops.FinishAsync(operationId, new ToolSucceeded($"created {stored.Id}", stored.Id), ct); }}If the read-back call itself throws, I let it throw. Temporal retries the whole activity with the same operation ID, which is safe precisely because of steps 1 and 2.(b) One outcome type, two waysPetrusheuski’s second post makes the argument I wanted to make before I had a good way to make it. A ToolResult(bool Success, string Message) record lets a tool return Success: true with the message "Permission denied". Then the model guesses what to do, and it will not guess the same way twice.His fix is a C# 15 union with four cases: succeeded, denied, retryable failure, permanent failure. He reports that .NET 11 shipped on November 10 with C# 15 unions, and he built against the released SDK. I am still marking the syntax and the JSON attribute below as “check against the current .NET 11 docs”, because both are new, I have only seen them in his post, and new language features tend to move between the announcement and the first real project..NET 11: a C# 15 union// .NET 11 / C# 15. Verify the union syntax and JsonUnion against the current .NET 11 docs.using System.Text.Json.Serialization;namespace DurableToolRuns;public sealed record ToolSucceeded(string Summary, string EvidenceId);public sealed record ToolDenied(string RequiredPermission, string Reason);public sealed record ToolRetryableFailure( string Code, string Message, [property: JsonRequired] int RetryAfterSeconds);public sealed record ToolPermanentFailure(string Code, string Message);// Every case is a JSON object, so reading one back needs a structural classifier.[JsonUnion(TypeClassifier = typeof(JsonUnionTypeStructuralClassifier))]public union ToolOutcome( ToolSucceeded, ToolDenied, ToolRetryableFailure, ToolPermanentFailure);The two attributes look like noise. They are not. Per his post, ASP.NET Core 11 writes a union as the active case’s plain object with no type field, and reading it back failed with an “ambiguous” JsonException because every case is an object. The structural classifier picks a case by property names, which created a second problem: a permanent failure and a retryable failure both have code and message. Marking RetryAfterSeconds as required is what separates them. That is a fragile thing to depend on. Add a field to one case and you can reintroduce the overlap without noticing.This matters twice in my sample: once in the operation table, which stores outcome_json, and once at the Temporal boundary, because activity results go through Temporal's payload converter. I would not trust either until a round-trip test covers all four cases..NET 10: an abstract record hierarchyIf you are on .NET 10, or you control both ends of the wire, the hierarchy is the boring and stable choice. Petrusheuski points out that Microsoft’s own serialization guidance leans this way when you own both sides, because a $type discriminator does not depend on property names.// .NET 10. Same case names, so call sites read the same.using System.Diagnostics;using System.Text.Json.Serialization;namespace DurableToolRuns;[JsonPolymorphic][JsonDerivedType(typeof(ToolSucceeded), "succeeded")][JsonDerivedType(typeof(ToolDenied), "denied")][JsonDerivedType(typeof(ToolRetryableFailure), "retryable")][JsonDerivedType(typeof(ToolPermanentFailure), "permanent")]public abstract record ToolOutcome{ // Keeps other assemblies from casually adding cases. private protected ToolOutcome() { } // The compiler-checked switch on .NET 10: every caller must pass every handler. public T Match( Func succeeded, Func denied, Func retryable, Func permanent) => this switch { ToolSucceeded s => succeeded(s), ToolDenied d => denied(d), ToolRetryableFailure r => retryable(r), ToolPermanentFailure p => permanent(p), _ => throw new UnreachableException($"unhandled outcome {GetType().Name}"), };}public sealed record ToolSucceeded(string Summary, string EvidenceId) : ToolOutcome;public sealed record ToolDenied(string RequiredPermission, string Reason) : ToolOutcome;public sealed record ToolRetryableFailure(string Code, string Message, int RetryAfterSeconds) : ToolOutcome;public sealed record ToolPermanentFailure(string Code, string Message) : ToolOutcome;Here is the part I had to think through, and that I think trips people up. On .NET 10, a switch expression over an abstract record is never provably exhaustive. The compiler does not know the hierarchy is closed, so it raises CS8509 even when you list all four cases. Promote CS8509 to an error and you are forced to add a discard arm, and once the discard is there, adding a fifth case compiles silently. You end up exactly where you started.That is why the hierarchy version has Match. The discard lives in one place, and every caller has to pass one handler per case. Add a case, add a parameter, and every call site stops compiling. It is uglier than a switch. It is also the only version of "the compiler checks it" I trust on .NET 10.With the union on .NET 11 you get the real thing: the switch in the workflow above has no discard, and the compiler knows the set is closed.The csproj line that makes it countPetrusheuski tested the claim that a new union case breaks the build. It does not. It produces warning CS8509, the build succeeds, and the warning scrolls past in a busy log. So: net11.0 enable enable $(WarningsAsErrors);CS8509 I would put it in Directory.Build.props so every project that consumes outcomes gets it. I use $(WarningsAsErrors);CS8509 rather than a bare CS8509 so the line adds to whatever is already there instead of replacing it.One gotcha that is easy to miss: CS8509 is about switch expressions. A switch statement with missing cases compiles without a word. That is why the workflow’s decision point is written as an expression that returns RunSummary?, and the retry loop, which deliberately handles only two cases, is written with if statements so nobody mistakes it for an exhaustive check.The case I would add nextWasowski’s typed tool states are a superset of Petrusheuski’s: SUCCESS, RETRYABLE_FAILURE, NON_RETRYABLE_FAILURE, PARTIAL_SUCCESS and UNKNOWN. I went back and forth on whether my outcome type should carry the last two.PartialSuccess I would leave out of a single-write tool. If a tool can partially succeed, I would rather split it into several operations, each with its own ID, so each one is binary. Partial success inside one operation ID is a reconciliation job hiding in a return value.Unknown is harder. In this design, read-back converts most unknowns into a definite answer: found means succeeded, not found means retryable. The case that remains is "read-back itself failed", and today that throws and becomes Temporal's problem. When Temporal gives up, the workflow sees an ActivityFailureException, which is an unknown outcome wearing an exception's clothes. I am leaning toward catching that in the workflow and turning it into an explicit ToolOutcomeUnknown(OperationId) case that parks the run for a human. With the union and CS8509 as an error, adding it means the build tells me every place that has to decide what unknown means. That is exactly the conversation I want to be forced into.© Mapping outcomes to HTTPPetrusheuski’s other finding: return the union straight from a minimal API endpoint and every outcome comes back as HTTP 200, the denial included. The type says what happened. It does not choose a status code.using Microsoft.AspNetCore.Mvc;using DurableToolRuns;app.MapPost("/agent-tools/tickets", async ( [FromHeader(Name = "Idempotency-Key")] string? idempotencyKey, TicketDraft draft, TicketTool tool, HttpResponse response, CancellationToken ct) =>{ if (string.IsNullOrWhiteSpace(idempotencyKey)) return Results.Problem("Idempotency-Key header is required", statusCode: StatusCodes.Status400BadRequest); ToolOutcome outcome = await tool.CreateOnceAsync($"http/{idempotencyKey}", draft, approved: false, ct); int statusCode = outcome switch { ToolSucceeded => StatusCodes.Status200OK, ToolDenied => StatusCodes.Status403Forbidden, ToolRetryableFailure => StatusCodes.Status503ServiceUnavailable, ToolPermanentFailure => StatusCodes.Status422UnprocessableEntity, }; if (outcome is ToolRetryableFailure retry) response.Headers.RetryAfter = retry.RetryAfterSeconds.ToString(); // Serialize as the declared type, so polymorphic or union metadata is applied. return Results.Json(outcome, statusCode: statusCode);}).Produces(StatusCodes.Status200OK).Produces(StatusCodes.Status403Forbidden).Produces(StatusCodes.Status422UnprocessableEntity).Produces(StatusCodes.Status503ServiceUnavailable);A few deliberate choices in there:The caller’s Idempotency-Key becomes the operation ID, prefixed so HTTP calls and workflow calls cannot collide in the same table. An endpoint that creates things without a key is a duplicate waiting for a flaky client.RetryAfterSeconds goes into a real Retry-After header. Clients that know nothing about my types still back off correctly.Nothing about the outcome is in the route. Per Petrusheuski, unions are not supported for route values, query strings, headers or form fields, and in SignalR they work only with the JSON hub protocol, not MessagePack. If you were planning to push outcomes to a dashboard over a MessagePack hub, map them to a plain DTO first.He also makes a point I want to repeat because it is the one teams skip: a union makes the contract precise, not true. A buggy tool can still return ToolSucceeded. That is why mine only returns it after read-back, with the tracker's own ID as evidence.(d) The token budget Temporal does not give youPetrusheuski’s rule is that a token or cost ceiling “still has to live in your activity or your provider settings.” I put mine in the workflow, and I want to explain why, because it is the decision in this article I am least sure is universally right.An activity cannot hold a counter across workers without a store of its own. The workflow can, for free: its fields are rebuilt from history on every replay, so the counter survives a restart exactly like everything else. It is also the only place that sees every model call in the run, in order, deterministically.namespace DurableToolRuns;// Pure and deterministic, so it is safe inside a workflow.public sealed class TokenBudget(long ceiling){ long _held; public long Charged { get; private set; } public bool TryReserve(long amount) { if (Charged + _held + amount > ceiling) return false; _held += amount; return true; } public void Settle(long reservation, ModelReply reply, long estimatePerAttempt) { _held -= reservation; // Attempts before the successful one never reported usage. They may have been billed. long unseenAttempts = (reply.Attempt - 1) * estimatePerAttempt; // No usage block from the provider is not zero. Charge the whole reservation. long reported = reply.InputTokens is long input && reply.OutputTokens is long output ? input + output : reservation; Charged += reported + unseenAttempts; } public void ChargeReservation(long reservation) { _held -= reservation; Charged += reservation; }}The design has three properties I care about:It is checked before the call, not after. The reservation is the estimate times MaximumAttempts, because that is the real worst case for one activity. If the ceiling cannot absorb the worst case, the call does not start.It charges the attempts Temporal hid from me. ActivityExecutionContext.Current.Info.Attempt tells the workflow how many attempts it took. The in-flight call that died in Petrusheuski's second test shows up here as one unseen attempt, charged at the estimate.Missing usage is not zero. Same rule as my previous post. A budget a missing JSON field can fool is not a budget.The weak spot is the estimate. It is only an upper bound if you cap output with MaxOutputTokens and keep the prompt size predictable. If your prompts grow with history, compute the estimate per call instead of passing a constant. The [WorkflowQuery] on TokensCharged lets you watch the counter on a running workflow without guessing.This is where Wasowski’s framing fits. As I read the public part of his post (the rest is member-only), the point is that an agent honestly reporting “I am at risk” is just a better-documented failure unless something already has the authority to act on it. Thresholds written before the run, checked by code that is not the model, are that authority. The token ceiling and MaxRetryableInARow are my kill criteria. His deterministic gate with read-back after each write is the same shape as TicketTool: the write is not done until a second read agrees.(e) Running it all locally with OllamaNothing here needs a cloud key. Temporal’s dev server and Ollama both run locally.# Temporal dev server (install the Temporal CLI first, per Temporal's docs)temporal server start-dev# Ollama in Dockerdocker run -d --name ollama -p 11434:11434 -v ollama:/root/.ollama ollama/ollamadocker exec -it ollama ollama pull llama3.2appsettings.json:{ "Temporal": { "Target": "localhost:7233", "Namespace": "default", "TaskQueue": "agent-runs" }, "Chat": { "Provider": "ollama", "Endpoint": "http://localhost:11434", "Model": "llama3.2" }, "Operations": { "ConnectionString": "Data Source=operations.db" }}The registration in Program.cs. OllamaSharp's OllamaApiClient implements IChatClient, so the activities never know which provider they got:using Microsoft.Extensions.AI;using OllamaSharp;using Temporalio.Extensions.Hosting;using DurableToolRuns;var builder = WebApplication.CreateBuilder(args);IConfigurationSection chat = builder.Configuration.GetSection("Chat");builder.Services.AddChatClient(_ => chat["Provider"] switch{ "ollama" => new OllamaApiClient(new Uri(chat["Endpoint"]!), chat["Model"]!), // For a hosted provider, turn the SDK's own retries off so Temporal's limits are the real limits: // "openai" => new OpenAI.OpenAIClient( // new System.ClientModel.ApiKeyCredential(chat["ApiKey"]!), // new OpenAI.OpenAIClientOptions { RetryPolicy = new System.ClientModel.Primitives.ClientRetryPolicy(maxRetries: 0) }) // .GetChatClient(chat["Model"]!).AsIChatClient(), _ => throw new InvalidOperationException($"unknown chat provider '{chat["Provider"]}'"),});builder.Services.AddSingleton(new OperationStore(builder.Configuration["Operations:ConnectionString"]!));builder.Services.AddScoped();// builder.Services.AddHttpClient(); // your tracker adapter goes hereIConfigurationSection temporal = builder.Configuration.GetSection("Temporal");builder.Services .AddHostedTemporalWorker(temporal["Target"]!, temporal["Namespace"]!, temporal["TaskQueue"]!) .AddScopedActivities() .AddWorkflow();var app = builder.Build();// app.MapPost("/agent-tools/tickets", ...) from section (c)app.Run();Starting a run from anywhere that has a Temporal client:using Temporalio.Client;using DurableToolRuns;var client = await TemporalClient.ConnectAsync(new("localhost:7233"));var job = new TriageJob( Repository: "my-org/my-service", Reports: ["Login page returns 500 when the session cookie is expired"], Kill: new KillCriteria( TokenCeiling: 20_000, EstimatedTokensPerCall: 1_500, MaxRetryableInARow: 3, ApprovalWait: TimeSpan.FromHours(24)));var handle = await client.StartWorkflowAsync( (TriageWorkflow wf) => wf.RunAsync(job), new(id: $"triage-{Guid.NewGuid():N}", taskQueue: "agent-runs"));Two honest caveats about the local path. Small local models are worse at structured output, so expect more PromptRejectedException stops with llama3.2 than with a large hosted model. And Ollama's tokens cost nothing in money, which makes the budget look pointless locally. It is not. The guard is about behavior: the same code stops the same way when the tokens are billed.What I am still unsure aboutBudget in the workflow or at the provider. My counter only sees calls that go through this workflow. A provider-side spend limit sees everything, including calls I forgot to route through here. I think you want both, and I have not settled which one should be authoritative.Union serialization at the Temporal boundary. I have reasoned that JsonUnion should apply because Temporal's default converter is System.Text.Json based. I have not seen anyone confirm it. Write the round-trip test before you trust it.Read-back and eventual consistency. If the tracker’s search index lags behind its writes, “not found” right after a create is a lie, and my tool returns retryable. The operation ID makes the retry safe, but a tracker with slow search will burn retries. A short delay before read-back may be the pragmatic fix.Whether Temporal is worth it. Petrusheuski says it plainly: you are adding a server, workers, task queues and workflow versioning. For a request-response agent that finishes in ten seconds, that is a lot. It earns its cost when a run is long, waits on a human, or touches things that must not happen twice. David R Oliver’s software factory piece, of which I could only read the public opening, makes the same bet from the other direction: a plan, build, test, review line that stops for a human yes and keeps going after you pull the plug.What I am taking awayDurability gives you a place to stand after the crash. It does not tell you what is safe to do from there. That answer comes from two things you write yourself.The first is the failure table: for every point where a run can die, which side effect can happen twice, what it costs, and what guard stops it. In my sample that is separate activities, an operation ID built in the workflow, a downstream key, read-back, and a token reservation that assumes the worst.The second is a closed set of outcomes the loop can act on without interpretation. Succeeded continues. Denied waits for a human. Retryable waits on a durable timer. Permanent stops. And the build fails the day someone adds a fifth answer without deciding what it means.Sources:Mikhail Petrusheuski, “Temporal Makes .NET Agent Runs Survive Process Restarts” (Medium, November 2026). Test results are his, run against a local Temporal server with a counting fake client. https://medium.com/@mikhail.petrusheuski/temporal-makes-net-agent-runs-survive-process-restarts-880fa1acdb64Mikhail Petrusheuski, “.NET 11 Makes Agent Tool Outcomes Compiler-Checked” (Medium, November 2026). Union, JsonUnion, CS8509, status code and SignalR findings are his. https://medium.com/@mikhail.petrusheuski/net-11-makes-agent-tool-outcomes-compiler-checked-6bbdd48b4995Jaroslaw Wasowski, “AI agent self-assessment: deterministic gate, kill criteria and read-back in the pipeline” (Medium, member-only; I read the public section). https://medium.com/@wasowski.jarek/ai-agents-ai-agent-self-assessment-deterministic-gate-kill-criteria-and-read-back-in-the-17232b12fe02David R Oliver, “I Built A Software Factory: A Guide To Durable AI” (Medium, member-only; I read the public section). https://medium.com/@davidroliver/i-built-a-software-factory-a-guide-to-durable-ai-8e57ac1835ecMy earlier post: “Durable Agents in .NET: Kill the Process and See What Survives”.Tags: dotnet, csharp, temporal, ai-agents, durable-execution, idempotency, aspnetcore, ollama, software-architecture.NET Agents That Survive Restarts: Temporal, Typed Tool Outcomes, and the Call You Pay for Twice was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.