Path: redb/redb.Tests.Integration/Tests/MsSqlPro/MsSqlProBulkInsertTimeoutTests.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.Tests.Integration/Tests/MsSqlPro/MsSqlProBulkInsertTimeoutTests.cs ---- using System.Diagnostics; using Microsoft.Data.SqlClient; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Models.Configuration; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Pro.Extensions; using redb.MSSql.Pro.Extensions; using redb.Tests.Integration.Fixtures; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.MsSqlPro; /// /// The SqlBulkCopy of AddNewObjectsAsync waits for a lock that another session holds on _values. Without /// BulkInsertTimeout it gives up after the driver's 30 seconds whatever the connection string says; with the option it /// waits as long as configured. The wait costs the server nothing: one table lock, no load. 300 objects of SimpleProps /// put both tables past the statement path (250 rows), so the objects and the values go through SqlBulkCopy. /// [Collection("MsSqlPro")] public class MsSqlProBulkInsertTimeoutTests { private const int Objects = 300; private static readonly TimeSpan LockHeld = TimeSpan.FromSeconds(35); private readonly string _connectionString; public MsSqlProBulkInsertTimeoutTests(MsSqlProFixture fixture) { _ = fixture; // the fixture created the database and synced the schemes _connectionString = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetConnectionString("MSSql")!; } [Fact] public async Task BulkLoad_WaitsPastThirtySeconds_WithTheOption_AndIsCutAtThirty_WithoutIt() { // Without the option: the driver's 30 seconds cut the load while the lock is held. await using (var plain = await ServiceAsync(null)) await using (var blocker = await HoldValuesLockAsync()) { var watch = Stopwatch.StartNew(); var act = () => plain.Redb.AddNewObjectsAsync(NewObjects("bulk-timeout-plain")); var thrown = await act.Should().ThrowAsync(); watch.Stop(); HasSqlTimeout(thrown.Which).Should().BeTrue($"the load is cut by the client timeout, got: {thrown.Which}"); watch.Elapsed.Should().BeGreaterThan(TimeSpan.FromSeconds(25)).And.BeLessThan(TimeSpan.FromSeconds(90), "the driver's default of 30 seconds applies"); } // With the option: the load outwaits a lock held longer than 30 seconds and saves every object. await using (var configured = await ServiceAsync(TimeSpan.FromSeconds(120))) { await using var blocker = await HoldValuesLockAsync(); var release = Task.Run(async () => { await Task.Delay(LockHeld); await blocker.DisposeAsync(); }); var watch = Stopwatch.StartNew(); var ids = await configured.Redb.AddNewObjectsAsync(NewObjects("bulk-timeout-set")); watch.Stop(); await release; ids.Should().HaveCount(Objects); watch.Elapsed.Should().BeGreaterThan(TimeSpan.FromSeconds(30), "the load waited for the lock past the old cut"); (await configured.Redb.Query().Where(p => p.Title == "bulk-timeout-set").CountAsync()) .Should().Be(Objects); (await configured.Redb.Query().Where(p => p.Title == "bulk-timeout-plain").CountAsync()) .Should().Be(0, "the cut load rolled back"); await configured.Redb.DeleteAsync(ids); } } private static List> NewObjects(string title) => Enumerable.Range(0, Objects).Select(i => (IRedbObject)new RedbObject { name = $"{title}-{i}", Props = new SimpleProps { Title = title, Count = i, Price = i, CreatedAt = DateTime.UtcNow, IsActive = true, Code = Guid.NewGuid(), Description = "d", OptionalNumber = i } }).ToList(); private static bool HasSqlTimeout(Exception? e) { for (; e != null; e = e.InnerException) if (e is SqlException { Number: -2 }) return true; return false; } /// A session that holds an exclusive table lock on _values until it is disposed. private async Task HoldValuesLockAsync() { // Not pooled: a pooled connection would go back to the pool with the transaction still open. var connection = new SqlConnection(new SqlConnectionStringBuilder(_connectionString) { Pooling = false }.ConnectionString); await connection.OpenAsync(); await using var command = new SqlCommand( "BEGIN TRANSACTION; SELECT TOP (1) _id FROM _values WITH (TABLOCKX, HOLDLOCK);", connection); await command.ExecuteNonQueryAsync(); return new ValuesLock(connection); } private sealed class ValuesLock(SqlConnection connection) : IAsyncDisposable { private int _released; public async ValueTask DisposeAsync() { if (Interlocked.Exchange(ref _released, 1) == 1) return; try { await using var rollback = new SqlCommand("IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;", connection); await rollback.ExecuteNonQueryAsync(); } finally { await connection.DisposeAsync(); } } } private async Task ServiceAsync(TimeSpan? bulkInsertTimeout) { var services = new ServiceCollection(); services.AddRedbPro(o => o.UseMsSql(_connectionString).Configure(c => { c.PropsSaveStrategy = PropsSaveStrategy.ChangeTracking; c.EnablePropsCache = false; c.BulkInsertTimeout = bulkInsertTimeout; })); var provider = services.BuildServiceProvider(); var redb = provider.GetRequiredService(); await redb.InitializeAsync(); await redb.SyncSchemeAsync(); return new Service(provider, redb); } private sealed record Service(ServiceProvider Provider, IRedbService Redb) : IAsyncDisposable { public ValueTask DisposeAsync() => Provider.DisposeAsync(); } }