Path: redb/redb.Core/Providers/Base/ObjectStorageProviderBase.SaveAsyncBatch.cs Snapshot: redb, 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 Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Providers/Base/ObjectStorageProviderBase.SaveAsyncBatch.cs ---- #pragma warning disable CS0618 // implements or uses the deprecated object permissions and roles (RedbDeprecation) using redb.Core.Providers; using redb.Core.Data; using redb.Core.Utils; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Models.Configuration; using redb.Core.Models.Security; using redb.Core.Caching; using redb.Core.Query; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace redb.Core.Providers.Base { /// /// BATCH SAVE - high-performance saving of multiple objects /// Supports two strategies: DeleteInsert (bulk operations) and ChangeTracking (EF diff) /// public abstract partial class ObjectStorageProviderBase { /// /// Convert IRedbObject to RedbObjectRow for bulk operations /// Uses 'as' optimization for direct access to RedbObject fields. /// protected RedbObjectRow ConvertToObjectRecord(IRedbObject obj) { var redbObj = obj as RedbObject; // Optimization: direct access to fields var record = new RedbObjectRow { Id = redbObj?.id ?? obj.Id, IdScheme = redbObj?.scheme_id ?? obj.SchemeId, IdParent = (redbObj?.parent_id ?? obj.ParentId) == 0 ? null : (redbObj?.parent_id ?? obj.ParentId), IdOwner = redbObj?.owner_id ?? obj.OwnerId, IdWhoChange = redbObj?.who_change_id ?? obj.WhoChangeId, Name = redbObj?.name ?? obj.Name, Hash = redbObj?.hash ?? obj.Hash, ValueUnique = redbObj?.value_unique ?? obj.ValueUnique, DateBegin = redbObj?.date_begin ?? obj.DateBegin, DateComplete = redbObj?.date_complete ?? obj.DateComplete, Key = redbObj?.key ?? obj.Key, ValueLong = redbObj?.value_long ?? obj.ValueLong, ValueString = redbObj?.value_string ?? obj.ValueString, ValueGuid = redbObj?.value_guid ?? obj.ValueGuid, ValueBool = redbObj?.value_bool ?? obj.ValueBool, ValueDouble = redbObj?.value_double ?? obj.ValueDouble, ValueNumeric = redbObj?.value_numeric ?? obj.ValueNumeric, ValueDatetime = redbObj?.value_datetime ?? obj.ValueDatetime, ValueBytes = redbObj?.value_bytes ?? obj.ValueBytes, Note = redbObj?.note ?? obj.Note }; // Handle creation/modification dates based on configuration if (_configuration.AutoSetModifyDate) { if (record.Id == 0) { record.DateCreate = DateTimeOffset.UtcNow; } else { // For existing objects - take the old value var existingDate = redbObj?.date_create ?? obj.DateCreate; // If the date was not set (MinValue), use the current one record.DateCreate = existingDate == DateTimeOffset.MinValue ? DateTimeOffset.UtcNow : existingDate; } record.DateModify = DateTimeOffset.UtcNow; } else { var dateCreate = redbObj?.date_create ?? obj.DateCreate; // If the date was not set (MinValue), use the current one record.DateCreate = dateCreate == DateTimeOffset.MinValue ? DateTimeOffset.UtcNow : dateCreate; var dateModify = redbObj?.date_modify ?? obj.DateModify; record.DateModify = dateModify == DateTimeOffset.MinValue ? DateTimeOffset.UtcNow : dateModify; } // The saved object carries the dates its row gets. For an existing object DateCreate // already holds the stored value (SelectExistingAndTakeCreateDatesAsync), which the // update leaves untouched in the database. obj.DateCreate = record.DateCreate; obj.DateModify = record.DateModify; return record; } /// /// A row of the existing-objects query: an existing object (Id, DateCreate and its scheme's hash), or one of the /// listed schemes (Id 0, DateCreate null), so that a save of new objects only learns the hashes as well. /// private sealed class IdDateCreateRow { public long Id { get; set; } public DateTimeOffset? DateCreate { get; set; } /// The structure hash of the scheme as stored now; null from a dialect that does not read it. public Guid? SchemeHash { get; set; } public long SchemeId { get; set; } } /// /// The existing-objects query: the rows of that exist, and the stored structure hash /// of every scheme of , in one statement. The object part is the query it always was, /// on the object ids; the scheme part reads _schemes by its key. /// private async Task<(List Existing, Dictionary HashByScheme)> SelectExistingAndSchemeHashesAsync( long[] objectIds, IEnumerable objects, System.Threading.CancellationToken cancellationToken) { var schemeIds = objects.Select(o => o.SchemeId).Where(id => id != 0).Distinct().ToArray(); var rows = await _context.QueryAsync( Sql.ObjectStorage_SelectExistingCreateDates(), new object[] { objectIds, schemeIds }, cancellationToken); var hashByScheme = new Dictionary(); foreach (var row in rows) hashByScheme[row.SchemeId] = row.SchemeHash; return (rows.Where(r => r.Id != 0).ToList(), hashByScheme); } /// /// The save's view of each scheme against the database, from the hashes the existing-objects query already /// returns (no round trip of its own): a cached scheme whose hash differs is read again, so a field or a version a /// newer build wrote since is seen by this save. Then the version rule: a class older than the version the scheme /// was synchronised with saves nothing of it (a newer build may have removed fields or changed types). Every /// object of the save counts, new ones included. Returns whether a scheme was read again. /// private async Task RefreshStaleSchemesAsync( IEnumerable objects, Dictionary hashByScheme, System.Threading.CancellationToken cancellationToken) { var readAgain = false; foreach (var group in objects.Where(o => hashByScheme.ContainsKey(o.SchemeId)).GroupBy(o => (o.SchemeId, Type: o.GetType()))) { var generic = RedbObjectTypes.GenericOf(group.Key.Type); if (generic == null) continue; var propsType = generic.GetGenericArguments()[0]; var stored = hashByScheme[group.Key.SchemeId]; var scheme = await _schemeSync.GetSchemeByTypeAsync(propsType, cancellationToken); if (scheme == null || scheme.Id != group.Key.SchemeId) continue; if (stored.HasValue && scheme.StructureHash != stored) { // The invalidation drops the structure trees of the scheme as well (GlobalMetadataCache). Cache.InvalidateScheme(scheme.Id); Cache.InvalidateScheme(scheme.Name); readAgain = true; scheme = await _schemeSync.GetSchemeByIdAsync(scheme.Id, cancellationToken); if (scheme == null) continue; } var classVersion = System.Reflection.CustomAttributeExtensions.GetCustomAttribute(propsType)?.Version ?? 0; var storedVersion = (scheme as RedbScheme)?.Version ?? 0; if (storedVersion > classVersion) throw new Exceptions.RedbPropsClassOlderException(scheme.Name, propsType, classVersion, storedVersion); } return readAgain; } /// /// A scheme of the save was changed by another process since this one cached it, and was read again before /// anything was written: the save builds its value rows again from the current structures and runs once more. /// The check is the first statement of each strategy, after the object locks only. /// private sealed class SchemeReadAgainException : Exception { } /// How many times one save builds its rows again after a scheme changed under it. private const int SchemeReadAgainLimit = 2; /// /// Ids of the objects that exist in the database. Each existing object takes its stored /// creation date: an object built in memory (from JSON, say) and saved onto an existing row /// had DateCreate 0001-01-01 after the save, while the row kept its own date. /// Only the ids the caller set are looked up: an object this save gave its id is new (); /// a save of new objects only sends the scheme part of the statement alone. /// /// /// An object saved under the id of a stored object of another scheme (a different class, or an object in the trash, /// scheme -10): the update kept the stored scheme, deleted its values and wrote the values of the saved class /// into it. Refused before anything is written, from the scheme the existing-objects query already returns. /// private static void RefuseOtherSchemeObjects(List objects, List rows) { if (rows.Count == 0) return; var storedScheme = rows.ToDictionary(r => r.Id, r => r.SchemeId); foreach (var obj in objects) { if (obj.Id != 0 && obj.SchemeId != 0 && storedScheme.TryGetValue(obj.Id, out var stored) && stored != obj.SchemeId) { var type = obj.GetType().IsGenericType ? obj.GetType().GetGenericArguments()[0] : obj.GetType(); throw new Exceptions.RedbSchemeMismatchException(obj.Id, type, obj.SchemeId, stored, $"Object {obj.Id} belongs to scheme {stored}" + (stored == Utils.RedbTypeIds.DeletedScheme ? " (it is in the trash)" : "") + $", but was saved as '{type.FullName ?? type.Name}' which maps to scheme {obj.SchemeId}. " + "Saving it would delete its values and write the values of another class into it; nothing was " + "written. Save a new object (id 0) or load the object under its own class."); } } } protected async Task> SelectExistingAndTakeCreateDatesAsync( List objects, System.Threading.CancellationToken cancellationToken) { if (objects.Count == 0) return new HashSet(); var created = _createdBySave; var ids = objects.Where(o => created == null || !created.Contains(o)).Select(o => o.Id).ToArray(); var (rows, hashByScheme) = await SelectExistingAndSchemeHashesAsync(ids, objects, cancellationToken); RefuseOtherSchemeObjects(objects, rows); var createdById = rows.ToDictionary(r => r.Id, r => r.DateCreate!.Value); // The value rows of this save were built from the trees of the schemes as they were cached: built again. if (await RefreshStaleSchemesAsync(objects, hashByScheme, cancellationToken)) throw new SchemeReadAgainException(); foreach (var obj in objects) { if (createdById.TryGetValue(obj.Id, out var dateCreate)) obj.DateCreate = dateCreate; } return createdById.Keys.ToHashSet(); } // ===== PUBLIC BATCH SAVE METHODS ===== /// /// BATCH SAVE: Save multiple objects (new + updates) /// Uses _securityContext to get the user /// public async Task> SaveAsync(IEnumerable objects, CancellationToken cancellationToken = default) { var effectiveUser = _securityContext.GetEffectiveUser(); return await SaveAsync(objects, effectiveUser, cancellationToken); } /// /// BATCH SAVE with explicit user /// Supports two strategy modes: /// - DeleteInsert: delete ALL values → BulkInsert/BulkUpdate of objects → BulkInsert of values /// - ChangeTracking: tree-based diff → two-phase EF SaveChanges /// public async Task> SaveAsync(IEnumerable objects, IRedbUser user, CancellationToken cancellationToken = default) { // CT-4 (решение владельца 2026-09-04, «как у EF»): контракт «один scope - один // поток» защищён операционным детектором уровня EF DbContext. Командный страж // соединения ловит только НАЛОЖИВШИЕСЯ команды; два перемежающихся async-сохранения // могли молча перемешать pending-состояние ChangeTracking и транзакции. Вход - // синхронно, до первого await, поэтому второй параллельный заход детерминированно // получает исключение. if (System.Threading.Interlocked.CompareExchange(ref _saveOperationInFlight, 1, 0) != 0) throw new InvalidOperationException( "A second SaveAsync started on this IRedbService scope before a previous one " + "completed. Один scope - это одно соединение и одно операционное состояние " + "(как DbContext в EF): параллельные сохранения ведите через отдельные scoped-сервисы."); try { return await SaveBatchCoreAsync(objects, user, cancellationToken); } finally { _createdBySave = null; System.Threading.Interlocked.Exchange(ref _saveOperationInFlight, 0); } } private int _saveOperationInFlight; /// /// The objects of the running save that got their id from it (AssignMissingIds). They are new by definition and /// are never looked up as existing: an id the key cache handed out twice (a block cached before a restore or an /// import) then fails on the primary key instead of updating the row that has the id. Set and cleared by the /// batch save; one save at a time per scope (CT-4). /// private HashSet? _createdBySave; private sealed class IdHashRow { public long Id { get; set; } public Guid? Hash { get; set; } } /// /// F1 (CT hash shortcut): ids of existing objects whose freshly recomputed content hash /// equals the persisted _objects._hash. Root hashes come free with the phase-1 /// existence check; one extra SELECT runs only when the collected graph brought nested /// existing objects. An object with no in-memory hash or no persisted hash is never listed /// (legacy hashes computed by an older canon simply fail the comparison and take the full /// path, migrating on save). /// private async Task?> SelectUnchangedByHashAsync( List allObjectsToSave, Dictionary dbHashById, CancellationToken cancellationToken) { var candidates = allObjectsToSave.Where(o => o.Id > 0 && o.Hash.HasValue).ToList(); if (candidates.Count == 0) return null; var missingIds = candidates.Where(o => !dbHashById.ContainsKey(o.Id)) .Select(o => o.Id).Distinct().ToArray(); if (missingIds.Length > 0) { var rows = await _context.QueryAsync( Sql.ObjectStorage_SelectIdHashPairs(), new object[] { missingIds }, cancellationToken); foreach (var row in rows) dbHashById[row.Id] = row.Hash; } var unchanged = new HashSet(); foreach (var obj in candidates) { if (dbHashById.TryGetValue(obj.Id, out var dbHash) && dbHash.HasValue && dbHash.Value == obj.Hash!.Value) unchanged.Add(obj.Id); } return unchanged.Count > 0 ? unchanged : null; } private async Task> SaveBatchCoreAsync(IEnumerable objects, IRedbUser user, CancellationToken cancellationToken) { var objList = objects.ToList(); if (objList.Count == 0) return new List(); foreach (var obj in objList) RefuseUnloadedReference(obj); // === PHASE 1: VALIDATION AND PREPARATION (BATCH OPTIMIZATION) === // STEP 1: Hash recomputation (in-memory, no DB queries) // Supports: RedbObject with Props, RedbObject with Props=null, RedbObject (non-generic) foreach (var obj in objList) RecomputeHash(obj); // STEP 2: BATCH existence check (1 query instead of N!) // F1: under ChangeTracking the same query also returns the persisted hash of each // existing root, so the hash shortcut costs no extra round-trip for the typical save. // Other strategies keep the id-only query - they never consult the hashes. var ctShortcutActive = _configuration.PropsSaveStrategy == PropsSaveStrategy.ChangeTracking && _configuration.AutoRecomputeHash; var existingIds = objList.Where(o => o.Id != 0).Select(o => o.Id).ToArray(); var dbHashById = new Dictionary(existingIds.Length); HashSet existingIdsSet; if (existingIds.Length == 0) { existingIdsSet = new HashSet(); } else if (ctShortcutActive) { var idHashRows = await _context.QueryAsync( Sql.ObjectStorage_SelectIdHashPairs(), new object[] { existingIds }, cancellationToken); foreach (var row in idHashRows) dbHashById[row.Id] = row.Hash; existingIdsSet = dbHashById.Keys.ToHashSet(); } else { var loadedIds = await _context.QueryScalarListAsync( Sql.ObjectStorage_SelectExistingIds(), new object[] { existingIds }, cancellationToken); existingIdsSet = loadedIds.ToHashSet(); } // Processing of missing objects foreach (var obj in objList.Where(o => o.Id != 0 && !existingIdsSet.Contains(o.Id))) { switch (_configuration.MissingObjectStrategy) { case MissingObjectStrategy.AutoSwitchToInsert: obj.Id = 0; break; case MissingObjectStrategy.ReturnNull: throw new InvalidOperationException($"Object with id {obj.Id} not found. Strategy: ReturnNull is not supported."); case MissingObjectStrategy.ThrowException: default: throw new InvalidOperationException($"Object with id {obj.Id} not found."); } } // STEP 3: BATCH auto-detection of schemes (caching by type) var schemeCache = new Dictionary(); long? objectSchemeId = null; // Cache for non-generic RedbObject scheme foreach (var obj in objList.Where(o => o.SchemeId == 0 && _configuration.AutoSyncSchemesOnSave)) { var objType = obj.GetType(); var genericObjType = Utils.RedbObjectTypes.GenericOf(objType); if (genericObjType != null) { var propsType = genericObjType.GetGenericArguments()[0]; // Check cache if (schemeCache.TryGetValue(propsType, out var cachedSchemeId)) { obj.SchemeId = cachedSchemeId; continue; } // Load/sync the scheme (select generic overload without parameters) var getSchemeMethod = typeof(ISchemeSyncProvider) .GetMethods() .FirstOrDefault(m => m.Name == nameof(ISchemeSyncProvider.GetSchemeByTypeAsync) && m.IsGenericMethod && m.GetParameters() is [{ ParameterType.Name: nameof(CancellationToken) }])? .MakeGenericMethod(propsType); if (getSchemeMethod != null) { var existingSchemeTask = (Task?)getSchemeMethod.Invoke(_schemeSync, new object[] { cancellationToken }); if (existingSchemeTask != null) { await existingSchemeTask.ConfigureAwait(false); var existingScheme = existingSchemeTask.GetType().GetProperty("Result")?.GetValue(existingSchemeTask) as IRedbScheme; if (existingScheme != null) { obj.SchemeId = existingScheme.Id; schemeCache[propsType] = existingScheme.Id; } else if (_configuration.AutoSyncSchemesOnSave) { var syncMethod = typeof(ISchemeSyncProvider) .GetMethods() .FirstOrDefault(m => m.Name == nameof(ISchemeSyncProvider.SyncSchemeAsync) && m.IsGenericMethod && m.GetParameters() is [{ ParameterType.Name: nameof(CancellationToken) }])? .MakeGenericMethod(propsType); if (syncMethod != null) { var syncTask = (Task?)syncMethod.Invoke(_schemeSync, new object[] { cancellationToken }); if (syncTask != null) { await syncTask.ConfigureAwait(false); var scheme = syncTask.GetType().GetProperty("Result")?.GetValue(syncTask) as IRedbScheme; if (scheme != null) { obj.SchemeId = scheme.Id; schemeCache[propsType] = scheme.Id; } } } } } } } else if (objType == typeof(RedbObject)) { // Non-generic RedbObject - use Object scheme if (objectSchemeId == null) { var objectScheme = await _schemeSync.EnsureObjectSchemeAsync("RedbObject"); objectSchemeId = objectScheme.Id; } obj.SchemeId = objectSchemeId.Value; } } // STEP 4: BATCH permissions check if (_configuration.DefaultCheckPermissionsOnSave) { // Load unique schemes once var uniqueSchemeIds = objList.Select(o => o.SchemeId).Distinct().ToArray(); var schemesList = await _context.QueryAsync( Sql.ObjectStorage_SelectSchemesByIds(), new object[] { uniqueSchemeIds }, cancellationToken); var schemesDict = schemesList.ToDictionary(s => s.Id, s => s); // Check INSERT permissions for new objects var newObjectsByScheme = objList.Where(o => o.Id == 0).GroupBy(o => o.SchemeId); foreach (var group in newObjectsByScheme) { if (schemesDict.TryGetValue(group.Key, out var schemeContract)) { var canInsert = await _permissionProvider.CanUserInsertScheme(schemeContract, user); if (!canInsert) { throw new UnauthorizedAccessException($"User {user.Id} has no create permission for objects in scheme {group.Key}"); } } } // Check UPDATE permissions for existing objects foreach (var obj in objList.Where(o => o.Id != 0)) { var canUpdate = await _permissionProvider.CanUserEditObject(obj, user); if (!canUpdate) { throw new UnauthorizedAccessException($"User {user.Id} has no update permission for object {obj.Id}"); } } } // === PHASE 2: COLLECTION OF ALL OBJECTS (MAIN + NESTED) === var allObjectsToSave = new List(); var allValuesToSave = new List(); var processedObjectIds = new HashSet(); var seenInstances = new HashSet(ReferenceEqualityComparer.Instance); var referenceStubs = new List(); foreach (var obj in objList) { await CollectAllObjectsRecursively(obj, allObjectsToSave, processedObjectIds, seenInstances, referenceStubs); } await ResolveReferenceHashesAsync(referenceStubs, cancellationToken); await EnsureNoHeldShapesAsync(allObjectsToSave, cancellationToken); // Interceptors, EF-style (discussion #12, review pass): Saving runs right after the // graph is collected and BEFORE ids, hashes and the unchanged-set are computed - so an // interceptor may MUTATE Props (EF's own SavingChanges contract) and everything below // is derived from what it left. Ran later, an edit here would desynchronize the stored // hash from the content and let the F1 shortcut silently skip the edited object. The // price is EF's too: objects this save creates still show Id == 0 (temporary-key // semantics) - their final ids arrive in SavedAsync. An exception here cancels the // save cleanly: no id was burned, nothing touched the database. // One snapshot for the whole save: Saving and Saved reach the same interceptors even when a run-time // subscription comes or goes meanwhile, and the change feed is collected exactly when they listen. InterceptorChangeSink = null; List? newObjectRefs = null; var interceptors = SnapshotSaveInterceptors(); if (interceptors.Count > 0) { if (_configuration.PropsSaveStrategy == PropsSaveStrategy.ChangeTracking) InterceptorChangeSink = new List(); // "Created by this save" = arrived without an id; the references keep carrying // their final ids once assigned below (SavedAsync reads them then). newObjectRefs = allObjectsToSave.Where(o => o.Id == 0).ToList(); await InvokeSavingInterceptorsAsync(interceptors, new Interception.RedbSavingContext { RootObjects = objList, AllObjects = allObjectsToSave, EffectiveUser = user, Strategy = _configuration.PropsSaveStrategy, NewObjects = newObjectRefs, }, cancellationToken); } // The objects that existed before this save, taken before AssignMissingIds gives the new ones their ids: // only these rows are locked in phase 4. Locking the ids of objects this save creates locked rows that do // not exist yet, and on SQL Server the lock statement then read the rows of concurrent writers. var existingObjectIds = allObjectsToSave.Where(o => o.Id > 0).Select(o => o.Id).ToArray(); _createdBySave = new HashSet(allObjectsToSave.Where(o => o.Id == 0), ReferenceEqualityComparer.Instance); // === PHASE 3: BATCH PROCESSING (REUSING PROTECTED METHODS) === await AssignMissingIds(allObjectsToSave, user, cancellationToken); // V4 (L.2): hashes are final only once ids exist - the parent's hash carries "id:hash" of // every reference, so an object created in this save (id 0 until now) would leave "0:" // in its parent's persisted hash: unreproducible on reload, a props-cache miss for ever // and a hash shift on the first re-save. Children first, then their parents, across the // graph; an existing nested object re-saved through its parent gets its content hash // refreshed the same way - its row is rewritten anyway (review). if (_configuration.AutoRecomputeHash) RecomputeHashesPostOrder(allObjectsToSave); await EnsureSchemesForAllTypes(allObjectsToSave, cancellationToken); // F1 (CT hash shortcut, perf wave 1): under ChangeTracking, existing objects whose // recomputed hash equals the persisted one skip the whole value pipeline - building // value records, the existing-values SELECT, both trees and the diff. Their _objects // row is still updated as before (name/date_modify live their own life). Guarded by // AutoRecomputeHash: with recomputation off the in-memory hash cannot be trusted. // Objects without a hash (either side) never shortcut. ISet? ctUnchangedByHash = null; if (ctShortcutActive) ctUnchangedByHash = await SelectUnchangedByHashAsync(allObjectsToSave, dbHashById, cancellationToken); // A scheme another process changed since this one cached it is noticed by the first statement of the strategy, // before anything is written (RefreshStaleSchemesAsync): the rows are then built again from the scheme // as read now, and the strategy runs once more. for (var readAgain = 0; ; readAgain++) { try { await ProcessAllObjectsPropertiesRecursively(allObjectsToSave, allValuesToSave, ctUnchangedByHash, cancellationToken); // === PHASE 4: STRATEGY SELECTION AND TRANSACTIONAL SAVE === // Wrapped in deadlock retry: ORDER BY _id prevents most deadlocks, // but cross-table edge cases may still occur in cluster environments. var strategy = _configuration.PropsSaveStrategy; // EF pattern: if already in transaction (explicit or ambient TransactionScope) — execute inline var diagIsIn = _context.IsInTransaction; // var diagAmbient = System.Transactions.Transaction.Current?.TransactionInformation.LocalIdentifier ?? ""; // System.Console.WriteLine( // $"[Diag-TX-SAVE] DECISION IsInTransaction={diagIsIn} ambient={diagAmbient} " + // $"branch={(diagIsIn ? "INLINE" : "BEGIN-NEW")} thread={System.Environment.CurrentManagedThreadId} " + // $"objsToSave={allObjectsToSave.Count}"); if (diagIsIn) { // Lock existing objects within the caller's transaction if (existingObjectIds.Length > 0) { await _context.ExecuteAsync( Sql.ObjectStorage_LockObjectsForUpdate(), new object[] { existingObjectIds }, cancellationToken); } // The caller owns the transaction, and a unique violation must not leave it aborted // (PostgreSQL 25P02: every follow-up statement of a catch-and-recover pattern died, // SaveByUniqueAsync's own retry included - bug report п.2, 2026-09-02). The batch // runs under a savepoint; the violation rolls back TO it - the transaction stays // alive - and only then the typed exception leaves. Other failures propagate as // before: they are not the documented recoverable case. await _context.ExecuteAsync(Sql.Transaction_SavepointBegin(), System.Array.Empty(), cancellationToken); try { await ExecuteBatchByStrategy(strategy, allObjectsToSave, allValuesToSave, ctUnchangedByHash, cancellationToken); if (Sql.Transaction_SavepointRelease() is { } release) await _context.ExecuteAsync(release, System.Array.Empty(), cancellationToken); } catch (Exception ex) when (Data.DbErrorClassifier.IsUniqueViolation(ex)) { // Roll back BEFORE translating: the translation itself queries the database. // Deliberately WITHOUT ct (s3.4): the rollback must land even on a cancelled token. await _context.ExecuteAsync(Sql.Transaction_SavepointRollback()); throw await TranslateUniqueViolationAsync(ex, null); } catch (Exception ex) when (IsStaleKeyCache(ex, _createdBySave!.Count > 0)) { await _context.ExecuteAsync(Sql.Transaction_SavepointRollback()); throw StaleKeyCacheFailure(ex, _createdBySave!); } catch (SchemeReadAgainException) { // Nothing was written under the savepoint; the rows are built again and the batch runs anew. await _context.ExecuteAsync(Sql.Transaction_SavepointRollback()); throw; } } else { // Top-level: wrap in DeadlockRetry + Transaction + FOR UPDATE await DeadlockRetryHelper.ExecuteWithRetryAsync(async () => { await using var transaction = await _context.BeginTransactionAsync(cancellationToken: cancellationToken); try { // FOR UPDATE: lock ALL existing objects to prevent race condition if (existingObjectIds.Length > 0) { await _context.ExecuteAsync( Sql.ObjectStorage_LockObjectsForUpdate(), new object[] { existingObjectIds }, cancellationToken); } await ExecuteBatchByStrategy(strategy, allObjectsToSave, allValuesToSave, ctUnchangedByHash, cancellationToken); // The point of no return (s3.3): the LAST ct read - after a successful commit // nothing below ever consults the token again. cancellationToken.ThrowIfCancellationRequested(); await transaction.CommitAsync(); } catch (Exception ex) { await Data.RollbackAfterFailure.RollbackAsync(transaction, ex); if (Data.DbErrorClassifier.IsUniqueViolation(ex)) throw await TranslateUniqueViolationAsync(ex, null); if (IsStaleKeyCache(ex, _createdBySave!.Count > 0)) throw StaleKeyCacheFailure(ex, _createdBySave!); throw; } }, cancellationToken: cancellationToken); } break; } catch (SchemeReadAgainException) { if (readAgain >= SchemeReadAgainLimit) throw new InvalidOperationException( $"A scheme of this save kept changing during the save ({readAgain + 1} times, another process synchronising it); nothing was written."); allValuesToSave.Clear(); } } // === PHASE 5: LOADERS FOR THE SAVED GRAPH, CACHE UPDATE === // The caller's graph lives on after the save, hand-made references included: their stubs get the loader // of this database, as the load path gives its boundary stubs - a stub without a loader cannot answer its // Props (it answered null from a cache hit, with no query and no exception). With the props cache on, the // graph is published once the transaction commits (CachePublication). // Loaded ones only: an unloaded instance in the cache cannot be validated without a lazy load inside the // probe - which deadlocks with the load that probes. var savedGeneric = allObjectsToSave .Where(o => Utils.RedbObjectTypes.GenericOf(o.GetType()) != null && o is RedbObject { IsPropsLoaded: true }) .ToList(); if (savedGeneric.Count > 0) { var loader = CreateLazyPropsLoader(); foreach (var savedObj in savedGeneric) Utils.LazyReferenceInstaller.Install(savedObj, loader); } if (_configuration.EnablePropsCache && PropsCache.Instance != null) { // Not a graph holding a hand-made reference without its header ({ id = 42 }): served from the cache, its // lazy load would fill Props only. The next load reads it from the database with the header. var toCache = savedGeneric .Where(o => o.Hash.HasValue && !Utils.LoadedGraphInspector.HasHeaderlessReference( o.GetType().GetMethod("GetPropsDirectly")?.Invoke(o, null))) .ToList(); if (toCache.Count > 0) { Caching.CachePublication.AfterCommit(_context, () => { foreach (var savedObj in toCache) Caching.CacheDelegates.Set(PropsCache.Instance!, savedObj); }); } } var savedIds = objList.Select(o => o.Id).ToList(); // Saved runs AFTER the commit: the data is in, and (EF-style) an exception from an // interceptor propagates to the caller - but cannot un-commit anything. if (interceptors.Count > 0) { var changes = InterceptorChangeSink; InterceptorChangeSink = null; await InvokeSavedInterceptorsAsync(interceptors, new Interception.RedbSavedContext { RootObjects = objList, AllObjects = allObjectsToSave, EffectiveUser = user, Strategy = _configuration.PropsSaveStrategy, SavedIds = savedIds, // The references captured before id assignment now carry their final ids. NewObjectIds = newObjectRefs!.Select(o => o.Id).ToHashSet(), UnchangedByHash = ctUnchangedByHash as IReadOnlySet, Changes = changes, }, CancellationToken.None); // past the commit - cancelling the notification would lie (s3.3) } return savedIds; } /// /// The object hash as the save writes it: from Props when they are loaded, from the base /// fields when the object has none (Props null, or the non-generic RedbObject). /// private static void RecomputeHash(IRedbObject obj) { var objType = obj.GetType(); // The type or a base type: a TreeRedbObject hashes its Props like the RedbObject it is. var isGeneric = Utils.RedbObjectTypes.GenericOf(objType) != null; if (isGeneric) { // Raw Props: a collected object is loaded by definition, but never risk the getter. var propsValue = objType.GetMethod("GetPropsDirectly")?.Invoke(obj, null); if (propsValue != null) { var currentHash = RedbHash.ComputeFor(obj); if (currentHash.HasValue) obj.Hash = currentHash.Value; } else { obj.Hash = RedbHash.ComputeForBaseFields(obj); } } else { obj.Hash = RedbHash.ComputeForBaseFields(obj); } } /// /// V4 (L.2): a reference written by hand as { id = x } carries no hash, while the /// parent hashes "id:hash" of every reference and writes that hash into the reference row /// (_Guid). One query resolves the persisted hashes, so the first save writes the /// same parent hash every reload will compute - no first-resave shift, no perpetual /// props-cache miss (review). /// private async Task ResolveReferenceHashesAsync(List referenceStubs, CancellationToken cancellationToken) { if (referenceStubs.Count == 0) return; var ids = referenceStubs.Select(s => s.Id).Distinct().ToArray(); var rows = await _context.QueryAsync(Sql.ObjectStorage_SelectObjectsByIds(), new object[] { ids }, cancellationToken); var hashById = new Dictionary(); foreach (var row in rows) hashById[row.Id] = row.Hash; foreach (var stub in referenceStubs) { if (hashById.TryGetValue(stub.Id, out var hash)) stub.Hash = hash; } } /// /// Executes batch save by strategy. OpenSource: only DeleteInsert. /// Pro: override to support ChangeTracking. /// F1: lists existing objects excluded from the value /// pipeline by the hash shortcut - only the ChangeTracking strategy consults it (their /// _objects row still updates; their values were never built and must not be diffed). /// protected virtual async Task ExecuteBatchByStrategy( PropsSaveStrategy strategy, List allObjectsToSave, List allValuesToSave, ISet? ctUnchangedByHash = null, CancellationToken cancellationToken = default) { if (strategy == PropsSaveStrategy.ChangeTracking) { throw new NotSupportedException( "PropsSaveStrategy.ChangeTracking (batch) is not implemented in this provider. " + "Use PropsSaveStrategy.DeleteInsert."); } await SaveBatchWithDeleteInsertStrategy(allObjectsToSave, allValuesToSave, cancellationToken); } // ===== VALUE ROW IDS ===== // A value row built for a save carries a temporary id until the save knows which rows it inserts: the builders // link a child to its parent row by id, and ChangeTracking aligns the rows of an existing object to their stored // ids, so only the rows inserted in the end need a key. Drawing a key for every built row spent one key per row // of every changed object on every save. The range is far from stored value ids and from the reserved negative // ids of the type and system rows (about -9.2e18). private const long TemporaryValueIdTop = -1_000_000_000_000_000L; private const long TemporaryValueIdBottom = -2_000_000_000_000_000L; private long _lastTemporaryValueId = TemporaryValueIdTop; /// A unique temporary id for a value row being built; see . protected long NextTemporaryValueId() { var id = System.Threading.Interlocked.Decrement(ref _lastTemporaryValueId); if (id <= TemporaryValueIdBottom) { System.Threading.Interlocked.CompareExchange(ref _lastTemporaryValueId, TemporaryValueIdTop, id); id = System.Threading.Interlocked.Decrement(ref _lastTemporaryValueId); } return id; } /// Whether is a temporary value row id that still needs a key. protected internal static bool IsTemporaryValueId(long id) => id < TemporaryValueIdTop && id > TemporaryValueIdBottom; /// /// Gives the rows about to be inserted their keys, in one draw of as many keys as there are rows with a temporary /// id, and points every parent link of the save ( and , the /// rows updated) from the temporary id to the key. A link to a temporary id that no inserted row holds is a defect /// of the save, and stops it before anything is written. /// protected internal async Task AssignValueIdsAsync(IReadOnlyCollection inserted, IEnumerable others, CancellationToken cancellationToken) { var temporary = inserted.Where(v => IsTemporaryValueId(v.Id)).ToList(); if (temporary.Count == 0) return; var keys = await _context.Keys.NextObjectIdBatchAsync(temporary.Count, cancellationToken); var map = new Dictionary(temporary.Count); for (var i = 0; i < temporary.Count; i++) { map[temporary[i].Id] = keys[i]; temporary[i].Id = keys[i]; } foreach (var value in inserted.Concat(others)) { if (value.ArrayParentId is not { } parent || !IsTemporaryValueId(parent)) continue; value.ArrayParentId = map.TryGetValue(parent, out var key) ? key : throw new InvalidOperationException( $"A value row (object {value.IdObject}, structure {value.IdStructure}) points to a parent row the save does not insert."); // A collection-scoped element key is salted with the owning collection row id, which was the temporary // one when the key was built: salt it again with the key. Only a key salted that way matches the probe. if (value.Unique is { } unique && value.ArrayIndex != null && Utils.UniqueKeyEncoder.Compute(value, parent) == unique) value.Unique = Utils.UniqueKeyEncoder.Compute(value, key); } } // ===== THE STRUCTURES A CLASS KNOWS ===== /// /// What a Props class knows of its scheme as read from the database: the structures its /// properties match; the structures it lacks below one it knows (a field a /// newer build added inside a nested class, an array or a dictionary), with their paths. /// is false on the normal path: the scheme is the class. /// protected internal sealed record ClassStructures( HashSet Known, IReadOnlyList<(long Id, string Path)> UnknownUnderKnown, bool AnyUnknown, IReadOnlyList ShapeMismatches); // Per scheme instance (the cached scheme is replaced when it changes) and Props type: computed once. Both keys // are weak: a Props type of a collectible AssemblyLoadContext (a module) must not be pinned by this cache. private static readonly System.Runtime.CompilerServices.ConditionalWeakTable>>> ClassStructuresByScheme = new(); /// /// The structures the class of knows of its scheme, from the cached scheme (no round /// trip). Null when the object has no Props type or the cached scheme is another one: the save then treats the /// class as knowing the whole scheme, as before. /// protected internal async Task ClassStructuresOfAsync(IRedbObject obj, CancellationToken cancellationToken) { var generic = RedbObjectTypes.GenericOf(obj.GetType()); if (generic == null) return null; var propsType = generic.GetGenericArguments()[0]; var scheme = await _schemeSync.GetSchemeByTypeAsync(propsType, cancellationToken); if (scheme == null || scheme.Id != obj.SchemeId) return null; var byType = ClassStructuresByScheme.GetValue(scheme, _ => new()); var lazy = byType.GetValue(propsType, type => new Lazy>(() => ComputeAsync(type, scheme.Structures))); try { return await lazy.Value; } catch { // A failed computation (the database unreachable) is not kept: the next save computes again. byType.Remove(propsType); throw; } async Task ComputeAsync(Type type, IReadOnlyCollection structures) { var mismatches = _schemeSync is SchemeSyncProviderBase sync ? await sync.ShapeMismatchesAsync(type, structures) : (IReadOnlyList)[]; var known = SchemeSyncProviderBase.ClassStructureIds(type, structures); if (known.Count == structures.Count) return new ClassStructures(known, [], false, mismatches); var byId = structures.ToDictionary(s => s.Id); string PathOf(IRedbStructure s) => s.IdParent is { } p && byId.TryGetValue(p, out var parent) ? PathOf(parent) + "." + s.Name : s.Name; bool UnderKnown(IRedbStructure s) { for (var p = s.IdParent; p is { } id && byId.TryGetValue(id, out var parent); p = parent.IdParent) if (known.Contains(id)) return true; return false; } var underKnown = structures.Where(s => !known.Contains(s.Id) && UnderKnown(s)) .Select(s => (s.Id, PathOf(s))).OrderBy(x => x.Item2, StringComparer.Ordinal).ToList(); return new ClassStructures(known, underKnown, true, mismatches); } } /// /// Refuses a save of a class whose property has another type or collection kind than the structure stored for /// it (a type change the sync held under the version rule): the value would go into the wrong column and be /// lost. From the cached class structures, so no round trip; it holds whether or not this process synced. /// protected internal async Task EnsureNoHeldShapesAsync(IEnumerable objects, CancellationToken cancellationToken) { foreach (var group in objects.Where(o => o.SchemeId != 0).GroupBy(o => (o.SchemeId, Type: o.GetType()))) { var classStructures = await ClassStructuresOfAsync(group.First(), cancellationToken); if (classStructures is not { ShapeMismatches.Count: > 0 }) continue; var scheme = await _schemeSync.GetSchemeByTypeAsync(RedbObjectTypes.GenericOf(group.Key.Type)!.GetGenericArguments()[0], cancellationToken); throw new Exceptions.RedbPropertyTypeHeldException( scheme?.Name ?? group.Key.SchemeId.ToString(System.Globalization.CultureInfo.InvariantCulture), RedbObjectTypes.GenericOf(group.Key.Type)!.GetGenericArguments()[0], classStructures.ShapeMismatches); } } /// /// Refuses the save when the stored objects have values under a structure the class knows that the class /// does not know: replacing that nested class or collection would delete them. One query, run only when the /// scheme in the database has such structures (an older class next to a newer build). /// protected internal async Task EnsureNothingUnknownUnderKnownAsync( ClassStructures classStructures, IRedbObject sample, IReadOnlyCollection objectIds, CancellationToken cancellationToken) { if (classStructures.UnknownUnderKnown.Count == 0 || objectIds.Count == 0) return; var present = new HashSet(); foreach (var (structureId, _) in classStructures.UnknownUnderKnown) foreach (var chunk in objectIds.Chunk(1000)) { var count = await _context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _values WHERE _id_structure = {structureId} AND _id_object IN ({string.Join(",", chunk)})", System.Array.Empty(), cancellationToken); if (count > 0) { present.Add(structureId); break; } } if (present.Count == 0) return; var scheme = await _schemeSync.GetSchemeByIdAsync(sample.SchemeId, cancellationToken); var propsType = RedbObjectTypes.GenericOf(sample.GetType())!.GetGenericArguments()[0]; throw new Exceptions.RedbPropsClassOlderException( scheme?.Name ?? sample.SchemeId.ToString(System.Globalization.CultureInfo.InvariantCulture), propsType, classStructures.UnknownUnderKnown.Where(u => present.Contains(u.Id)).Select(u => u.Path).ToList()); } /// /// DeleteInsert's delete of the old values: all values of the objects whose class knows its whole scheme (the /// normal path, unchanged); for a class that knows less, only the values of the structures it knows, after the /// refusal check above. A newer build's top-level field is kept. /// private async Task DeleteValuesTheClassKnowsAsync(List existingObjects, CancellationToken cancellationToken) { var whole = new List(); var partial = new List<(ClassStructures Classes, List Ids)>(); foreach (var group in existingObjects.GroupBy(o => (o.SchemeId, Type: o.GetType()))) { var classStructures = await ClassStructuresOfAsync(group.First(), cancellationToken); var ids = group.Select(o => o.Id).Distinct().ToList(); if (classStructures is not { AnyUnknown: true }) { whole.AddRange(ids); continue; } await EnsureNothingUnknownUnderKnownAsync(classStructures, group.First(), ids, cancellationToken); partial.Add((classStructures, ids)); } if (whole.Count > 0) await _context.Bulk.BulkDeleteValuesByObjectIdsAsync(whole, cancellationToken); foreach (var (classes, ids) in partial) { if (classes.Known.Count == 0) continue; var structureIds = string.Join(",", classes.Known); foreach (var chunk in ids.Chunk(1000)) await _context.ExecuteAsync( $"DELETE FROM _values WHERE _id_object IN ({string.Join(",", chunk)}) AND _id_structure IN ({structureIds})", System.Array.Empty(), cancellationToken); } } // ===== DELETEINSERT STRATEGY ===== /// /// DeleteInsert batch strategy: delete ALL values, BulkInsert/BulkUpdate of objects, BulkInsert of values. /// protected async Task SaveBatchWithDeleteInsertStrategy( List allObjectsToSave, List allValuesToSave, CancellationToken cancellationToken = default) { // Step 1: Determine which objects ACTUALLY exist in the DB var existingIdsSet = await SelectExistingAndTakeCreateDatesAsync(allObjectsToSave, cancellationToken); var existingIdsInDb = existingIdsSet.ToList(); // Step 2: Delete the old values of the structures each object's class knows. A field a newer build of the // class added is kept; one under a nested class or collection the class knows refuses the save. if (existingIdsInDb.Any()) { await DeleteValuesTheClassKnowsAsync( allObjectsToSave.Where(o => existingIdsSet.Contains(o.Id)).ToList(), cancellationToken); } // Step 3: Separation and BulkInsert of new objects var newObjects = allObjectsToSave.Where(o => !existingIdsSet.Contains(o.Id)).ToList(); var existingObjects = allObjectsToSave.Where(o => existingIdsSet.Contains(o.Id)).ToList(); if (newObjects.Any()) { var newRecords = newObjects.Select(ConvertToObjectRecord).ToList(); await _context.Bulk.BulkInsertObjectsAsync(newRecords, cancellationToken); } // Step 4: BulkUpdate of existing objects if (existingObjects.Any()) { // P7 (UNIQUE stage 1): release the keys of EVERY existing object in the batch before the // row updates run - an in-batch key exchange otherwise trips the unique index mid-way. // Every existing object, not only those taking a key: the one giving its key up (new key // NULL) must release it before the one taking it is written. The statement touches rows // that hold a key only. Same transaction as the updates, so no outside reader sees a gap. var existingIdsToRelease = existingObjects.Select(o => o.Id).ToList(); if (existingIdsToRelease.Count > 0) await _context.ExecuteAsync(Sql.ObjectStorage_ClearValueUniqueByIds(existingIdsToRelease), System.Array.Empty(), cancellationToken); var existingRecords = existingObjects.Select(ConvertToObjectRecord).ToList(); await _context.Bulk.BulkUpdateObjectsAsync(existingRecords, cancellationToken); } // Step 5: BulkInsert of all values if (allValuesToSave.Any()) { await AssignValueIdsAsync(allValuesToSave, [], cancellationToken); var deduplicated = DeduplicateValueInserts(allValuesToSave, "SaveBatchWithDeleteInsertStrategy"); var sortedValues = ValuesTopologicalSort.SortByFkDependency(deduplicated); await _context.Bulk.BulkInsertValuesAsync(sortedValues, cancellationToken); } } } }