Path: redb-route/redb.Route.Llm/Engine/Storage/IBatchStore.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Engine/Storage/IBatchStore.cs ---- using System.Collections.Concurrent; using redb.Route.Abstractions; namespace redb.Route.Llm.Engine.Storage; /// /// Tracks async-batch jobs submitted to LLM providers (Anthropic Message /// Batches, OpenAI Batch API, vLLM batch endpoints). The framework does not /// prescribe a submit protocol — providers stay free to implement /// SubmitAsync however they like — but every submitted batch should be /// registered here so that incoming webhooks can be correlated, deduplicated /// and routed back to the originating conversation. /// /// Idempotency of the callback itself is the caller's responsibility (use /// with the batch id as key); this store /// only persists the submit-time metadata. /// /// /// The optional exchange parameter on every method carries the route /// pipeline's current exchange; REDB-backed implementations resolve a /// per-exchange through /// IRouteContext.GetRedbService(name, exchange) using the named-redb /// hint stored in . In-memory implementations /// ignore it. /// Without an exchange a redb-backed implementation opens a redb scope of its own for the call. That scope joins an /// ambient (a , a /// route's .Transacted()) as every redb connection does, but not a transaction begun on the context's shared /// IRedbService (ExecuteAtomicAsync, BeginTransaction), which it does not see: pass the exchange, /// or use a TransactionScope, when the call must commit or roll back with that work. In-memory implementations /// take part in no transaction. /// /// public interface IBatchStore { /// Records a batch submission. Replaces an existing row with the same id. Task RegisterAsync(BatchJobRecord record, IExchange? exchange = null, CancellationToken ct = default); /// /// Records many batch submissions at once. Bulk-friendly stores commit the /// whole set in a single transaction; the default falls back to a loop. /// async Task RegisterManyAsync(IEnumerable records, IExchange? exchange = null, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(records); foreach (var record in records) { ct.ThrowIfCancellationRequested(); await RegisterAsync(record, exchange, ct).ConfigureAwait(false); } } /// Loads a previously-registered batch by id; null if unknown. Task GetAsync(string batchId, IExchange? exchange = null, CancellationToken ct = default); /// /// Updates lifecycle status and optional fields. Unknown ids are ignored /// silently — callers should treat a missing row as "not ours" and not as /// an error condition. /// Task UpdateStatusAsync( string batchId, string status, DateTimeOffset? completedAtUtc = null, string? errorMessage = null, IExchange? exchange = null, CancellationToken ct = default); /// Marks a batch as completed; convenience wrapper around . Task MarkCompletedAsync(string batchId, IExchange? exchange = null, CancellationToken ct = default) => UpdateStatusAsync(batchId, "completed", DateTimeOffset.UtcNow, null, exchange, ct); /// Marks a batch as failed; convenience wrapper around . Task MarkFailedAsync(string batchId, string errorMessage, IExchange? exchange = null, CancellationToken ct = default) => UpdateStatusAsync(batchId, "failed", DateTimeOffset.UtcNow, errorMessage, exchange, ct); } /// A persisted batch-submission record. public sealed class BatchJobRecord { /// Provider-issued batch identifier — the business key. public required string BatchId { get; init; } /// "anthropic", "openai", or any custom provider id. public required string ProviderId { get; init; } /// Model id at submit-time. public string ModelId { get; init; } = string.Empty; /// Optional conversation correlation; empty when the batch is conversation-less. public string ConversationId { get; init; } = string.Empty; /// Lifecycle: "submitted" / "running" / "completed" / "failed" / "cancelled". public string Status { get; init; } = "submitted"; /// When the host submitted the batch. public DateTime SubmittedAtUtc { get; init; } = DateTime.UtcNow; /// When the callback fired (or the host marked completion); null while pending. public DateTime? CompletedAtUtc { get; init; } /// Optional URL where the host can fetch results; null when results arrive inline. public string? ResultUrl { get; init; } /// Free-form metadata captured at submit time (caller-controlled JSON). public string? MetadataJson { get; init; } /// Last error message recorded against the batch; null while healthy. public string? ErrorMessage { get; init; } /// /// Opt-in: when true and the batch resolves to "completed", /// appends the assistant /// turn extracted from the callback body to /// under . Has no effect when the conversation /// id is empty or the conversation store is not registered. Default false. /// public bool AppendToConversation { get; init; } } /// In-memory — entries live only for the process lifetime. public sealed class InMemoryBatchStore : IBatchStore { private readonly ConcurrentDictionary _rows = new(StringComparer.Ordinal); /// public Task RegisterAsync(BatchJobRecord record, IExchange? exchange = null, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(record); ArgumentException.ThrowIfNullOrWhiteSpace(record.BatchId); _rows[record.BatchId] = record; return Task.CompletedTask; } /// public Task GetAsync(string batchId, IExchange? exchange = null, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrWhiteSpace(batchId); return Task.FromResult(_rows.TryGetValue(batchId, out var hit) ? hit : null); } /// public Task UpdateStatusAsync( string batchId, string status, DateTimeOffset? completedAtUtc = null, string? errorMessage = null, IExchange? exchange = null, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrWhiteSpace(batchId); ArgumentException.ThrowIfNullOrWhiteSpace(status); if (!_rows.TryGetValue(batchId, out var existing)) return Task.CompletedTask; var updated = new BatchJobRecord { BatchId = existing.BatchId, ProviderId = existing.ProviderId, ModelId = existing.ModelId, ConversationId = existing.ConversationId, Status = status, SubmittedAtUtc = existing.SubmittedAtUtc, CompletedAtUtc = completedAtUtc?.UtcDateTime ?? existing.CompletedAtUtc, ResultUrl = existing.ResultUrl, MetadataJson = existing.MetadataJson, ErrorMessage = errorMessage ?? existing.ErrorMessage, AppendToConversation = existing.AppendToConversation }; _rows[batchId] = updated; return Task.CompletedTask; } }