Path: redb/redb.Tests.Integration/Tests/PostgresPro/PostgresProFreshStatisticsTests.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/PostgresPro/PostgresProFreshStatisticsTests.cs
----
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Npgsql;
using redb.Core;
using redb.Core.Data;
using redb.Core.Pro.Extensions;
using redb.Core.Query;
using redb.Core.Query.Aggregation;
using redb.Postgres.Pro.Extensions;
using redb.Tests.Integration.Fixtures;
using redb.Tests.Integration.Helpers;
using redb.Tests.Integration.Models;
namespace redb.Tests.Integration.Tests.PostgresPro;
///
/// A new database whose tables hold rows but no planner statistics: never analyzed, or analyzed while empty. There
/// PostgreSQL took every stream of the streams form for one row and joined them by nested loops that rescan an index
/// range per object: a grouping and a window over a range of Props values, and a window over a narrow OR, ran for
/// minutes on 600 objects (a test of the equivalence suite ran ten minutes). Each test owns its database, so the
/// state of the statistics is its own, and autovacuum is off on both tables so nothing analyzes them meanwhile.
///
public class PostgresProFreshStatisticsTests : IClassFixture
{
private static readonly string AdminBase =
new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetConnectionString("Postgres")!;
private readonly SchemaUpgradeCleanup _cleanup;
private static readonly string[] Tags = ["q", "s", "k"];
public PostgresProFreshStatisticsTests(SchemaUpgradeCleanup cleanup)
{
_cleanup = cleanup;
cleanup.Register(async () =>
{
NpgsqlConnection.ClearAllPools();
// By name: xUnit makes an instance per test, and the cleanup keeps the removal of the first one only.
foreach (var tag in Tags)
await AdminAsync("postgres", $"DROP DATABASE IF EXISTS \"{DatabaseName(tag)}\" WITH (FORCE)");
});
}
///
/// The range grouping, the range window and the OR window answer within 30 seconds each while the tables have no
/// statistics. Before the guard each of them ran past it.
///
[Fact]
public async Task NoStatistics_GroupingAndWindows_AnswerInBoundedTime()
{
var (redb, database, provider) = await CreateSeededAsync("q");
(await ReltuplesAsync(database)).Should().BeLessThanOrEqualTo(0, "the test is about tables without statistics");
IRedbQueryable Range() => redb.Query().Where(e => e.Salary > 70000m && e.Age >= 30);
IRedbQueryable Or() => redb.Query().Where(e => e.EmployeeCode == "EMP-0010" || e.Age == 33);
var limit = TimeSpan.FromSeconds(30);
var groups = await Range().GroupBy(x => x.Department)
.SelectAsync(g => new { g.Key, Count = Agg.Count(g), Sum = Agg.Sum(g, x => x.Salary) })
.WaitAsync(limit);
groups.Should().NotBeEmpty();
var ranked = await Range().Take(20).WithWindow(w => w.PartitionBy(x => x.Department).OrderByDesc(x => x.Salary))
.SelectAsync(x => new { x.Props.Salary, Rank = Win.RowNumber() })
.WaitAsync(limit);
ranked.Should().NotBeEmpty();
var orRanked = await Or().Take(20).WithWindow(w => w.PartitionBy(x => x.Department).OrderByDesc(x => x.Salary))
.SelectAsync(x => new { x.Props.Salary, Rank = Win.RowNumber() })
.WaitAsync(limit);
orRanked.Should().NotBeEmpty();
(await provider.GetRequiredService().ExecuteScalarAsync("SELECT current_setting('enable_nestloop')"))
.Should().Be("on", "the guard puts the setting back after each statement");
}
///
/// Start-up analyzes _objects and _values when they hold rows without statistics, as after a pg_restore or a load
/// by COPY: a second service starting on the seeded database finds reltuples above zero afterwards.
///
[Fact]
public async Task Start_AnalyzesTablesThatHoldRowsWithoutStatistics()
{
var (_, database, _) = await CreateSeededAsync("s");
(await ReltuplesAsync(database)).Should().BeLessThanOrEqualTo(0);
await using var provider = BuildServices(database);
await provider.GetRequiredService().InitializeAsync();
(await ReltuplesAsync(database)).Should().BeGreaterThan(0, "start-up analyzed the tables");
}
///
/// A lookup by object id reads its rows by the primary key, which needs no statistics: while a query by a Props field
/// still runs with nested loops off, the same service's lookups by id (one id, an id list, an id with another
/// condition) send neither the statistics check nor the switch.
///
[Fact]
public async Task NoStatistics_LookupById_SendsNoGuard()
{
var (redb, database, _) = await CreateSeededAsync("k");
(await ReltuplesAsync(database)).Should().BeLessThanOrEqualTo(0, "the test is about tables without statistics");
var ids = (await redb.Query().Take(3).ToListAsync()).Select(o => o.Id).ToArray();
var byField = await GuardStatementsAsync(() => redb.Query().Where(e => e.Age >= 30).Take(5).ToListAsync());
byField.Should().BeGreaterThan(0, "a query by a Props field is still guarded while statistics are missing");
var one = ids[0];
(await GuardStatementsAsync(() => redb.Query().WhereRedb(o => o.Id == one).ToListAsync())).Should().Be(0);
(await GuardStatementsAsync(() => redb.Query().WhereRedb(o => ids.Contains(o.Id)).ToListAsync())).Should().Be(0);
(await GuardStatementsAsync(() => redb.Query().WhereRedb(o => o.Id == one).Where(e => e.Age >= 0).CountAsync()))
.Should().Be(0);
(await redb.Query().WhereRedb(o => ids.Contains(o.Id)).ToListAsync()).Select(o => o.Id).Should().BeEquivalentTo(ids);
}
/// The statements of that check the statistics or set enable_nestloop.
private static async Task GuardStatementsAsync(Func> call)
{
var texts = new List();
var probe = new System.Diagnostics.ActivitySource("redb.Tests.FreshStatisticsGuard");
using var listener = new System.Diagnostics.ActivityListener
{
ShouldListenTo = s => s.Name.StartsWith("Npgsql", StringComparison.Ordinal) || s.Name == probe.Name,
Sample = (ref System.Diagnostics.ActivityCreationOptions _) =>
System.Diagnostics.ActivitySamplingResult.AllDataAndRecorded,
ActivityStopped = a =>
{
var text = (a.GetTagItem("db.query.text") ?? a.GetTagItem("db.statement"))?.ToString();
if (a.Source.Name.StartsWith("Npgsql", StringComparison.Ordinal) && text != null)
lock (texts) texts.Add(a.TraceId + "|" + text);
},
};
System.Diagnostics.ActivitySource.AddActivityListener(listener);
System.Diagnostics.ActivityTraceId trace;
using (var parent = probe.StartActivity("guard")!)
{
trace = parent.TraceId;
await call();
}
lock (texts)
return texts.Count(t => t.StartsWith(trace + "|", StringComparison.Ordinal)
&& (t.Contains("reltuples", StringComparison.Ordinal) || t.Contains("enable_nestloop", StringComparison.Ordinal)));
}
private async Task<(IRedbService Redb, string Database, ServiceProvider Provider)> CreateSeededAsync(string tag)
{
var database = DatabaseName(tag);
await AdminAsync("postgres", $"DROP DATABASE IF EXISTS \"{database}\" WITH (FORCE)");
await AdminAsync("postgres", $"CREATE DATABASE \"{database}\"");
var provider = BuildServices(database);
var redb = provider.GetRequiredService();
await redb.InitializeAsync(ensureCreated: true);
await AdminAsync(database, "ALTER TABLE _objects SET (autovacuum_enabled = false); ALTER TABLE _values SET (autovacuum_enabled = false)");
await redb.SyncSchemeAsync();
await TestDataFactory.SeedEmployees(redb, 600);
return (redb, database, provider);
}
private string DatabaseName(string tag) => $"redb_freshstats_{tag}_{_cleanup.Suffix}";
private static ServiceProvider BuildServices(string database)
{
var cs = new NpgsqlConnectionStringBuilder(AdminBase) { Database = database }.ConnectionString;
var license = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build()["Redb:License"];
var services = new ServiceCollection();
services.AddLogging(b => b.AddConsole().SetMinimumLevel(LogLevel.Warning));
services.AddRedbPro(options =>
{
options.UsePostgres(cs).Configure(c => c.EnablePropsCache = false);
if (!string.IsNullOrWhiteSpace(license))
options.WithLicense(license);
});
return services.BuildServiceProvider();
}
private static async Task ReltuplesAsync(string database)
=> await AdminScalarAsync(database, "SELECT max(reltuples) FROM pg_class WHERE oid IN (to_regclass('_objects'), to_regclass('_values'))");
private static async Task AdminAsync(string database, string sql)
{
var cs = new NpgsqlConnectionStringBuilder(AdminBase) { Database = database, Pooling = false }.ConnectionString;
await using var conn = new NpgsqlConnection(cs);
await conn.OpenAsync();
await using var cmd = conn.CreateCommand();
cmd.CommandText = sql;
await cmd.ExecuteNonQueryAsync();
}
private static async Task AdminScalarAsync(string database, string sql)
{
var cs = new NpgsqlConnectionStringBuilder(AdminBase) { Database = database, Pooling = false }.ConnectionString;
await using var conn = new NpgsqlConnection(cs);
await conn.OpenAsync();
await using var cmd = conn.CreateCommand();
cmd.CommandText = sql;
return (T)(await cmd.ExecuteScalarAsync())!;
}
}