diff --git a/src/ServiceControl.Audit.Persistence.EFCore.PostgreSql/Migrations/20261126045230_AddEndpointTimeSentIndex.Designer.cs b/src/ServiceControl.Audit.Persistence.EFCore.PostgreSql/Migrations/20261126045230_AddEndpointTimeSentIndex.Designer.cs
new file mode 100644
index 0000000000..a7e5fb16c2
--- /dev/null
+++ b/src/ServiceControl.Audit.Persistence.EFCore.PostgreSql/Migrations/20261126045230_AddEndpointTimeSentIndex.Designer.cs
@@ -0,0 +1,257 @@
+//
+using System;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
+using ServiceControl.Audit.Persistence.EFCore.PostgreSql;
+
+#nullable disable
+
+namespace ServiceControl.Audit.Persistence.EFCore.PostgreSql.Migrations
+{
+ [DbContext(typeof(PostgreSqlAuditDbContext))]
+ [Migration("20261126045230_AddEndpointTimeSentIndex")]
+ partial class AddEndpointTimeSentIndex
+ {
+ ///
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasAnnotation("ProductVersion", "10.0.15")
+ .HasAnnotation("Relational:MaxIdentifierLength", 63);
+
+ NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
+
+ modelBuilder.Entity("ServiceControl.Audit.Persistence.EFCore.Entities.AuditMessageEntity", b =>
+ {
+ b.Property("CreatedOn")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("created_on");
+
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint")
+ .HasColumnName("id");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id"));
+
+ b.Property("BodyContentType")
+ .HasColumnType("text")
+ .HasColumnName("body_content_type");
+
+ b.Property("BodySize")
+ .HasColumnType("integer")
+ .HasColumnName("body_size");
+
+ b.Property("BodyState")
+ .HasColumnType("integer")
+ .HasColumnName("body_state");
+
+ b.Property("BodyText")
+ .HasColumnType("text")
+ .HasColumnName("body_text");
+
+ b.Property("ConversationId")
+ .HasMaxLength(450)
+ .HasColumnType("character varying(450)")
+ .HasColumnName("conversation_id");
+
+ b.Property("CriticalTimeTicks")
+ .HasColumnType("bigint")
+ .HasColumnName("critical_time_ticks");
+
+ b.Property("DeliveryTimeTicks")
+ .HasColumnType("bigint")
+ .HasColumnName("delivery_time_ticks");
+
+ b.Property("HeadersJson")
+ .IsRequired()
+ .HasColumnType("text")
+ .HasColumnName("headers_json");
+
+ b.Property("IsSystemMessage")
+ .HasColumnType("boolean")
+ .HasColumnName("is_system_message");
+
+ b.Property("MessageId")
+ .HasColumnType("text")
+ .HasColumnName("message_id");
+
+ b.Property("MessageType")
+ .HasColumnType("text")
+ .HasColumnName("message_type");
+
+ b.Property("ProcessedAt")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("processed_at");
+
+ b.Property("ProcessingTimeTicks")
+ .HasColumnType("bigint")
+ .HasColumnName("processing_time_ticks");
+
+ b.Property("ReceivingEndpointHost")
+ .HasColumnType("text")
+ .HasColumnName("receiving_endpoint_host");
+
+ b.Property("ReceivingEndpointHostId")
+ .HasColumnType("uuid")
+ .HasColumnName("receiving_endpoint_host_id");
+
+ b.Property("ReceivingEndpointName")
+ .HasMaxLength(450)
+ .HasColumnType("character varying(450)")
+ .HasColumnName("receiving_endpoint_name");
+
+ b.Property("SendingEndpointHost")
+ .HasColumnType("text")
+ .HasColumnName("sending_endpoint_host");
+
+ b.Property("SendingEndpointHostId")
+ .HasColumnType("uuid")
+ .HasColumnName("sending_endpoint_host_id");
+
+ b.Property("SendingEndpointName")
+ .HasColumnType("text")
+ .HasColumnName("sending_endpoint_name");
+
+ b.Property("Status")
+ .HasColumnType("integer")
+ .HasColumnName("status");
+
+ b.Property("TimeSent")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("time_sent");
+
+ b.Property("UniqueMessageId")
+ .HasColumnType("uuid")
+ .HasColumnName("unique_message_id");
+
+ b.HasKey("CreatedOn", "Id")
+ .HasName("pk_audit_messages");
+
+ b.HasIndex("ConversationId")
+ .HasDatabaseName("ix_audit_messages_conversation_id");
+
+ b.HasIndex("ProcessedAt")
+ .HasDatabaseName("ix_audit_messages_processed_at");
+
+ b.HasIndex("TimeSent")
+ .HasDatabaseName("ix_audit_messages_time_sent");
+
+ b.HasIndex("UniqueMessageId")
+ .HasDatabaseName("ix_audit_messages_unique_message_id");
+
+ b.HasIndex("ReceivingEndpointName", "CreatedOn")
+ .HasDatabaseName("ix_audit_messages_receiving_endpoint_name_created_on");
+
+ b.HasIndex("ReceivingEndpointName", "TimeSent")
+ .HasDatabaseName("ix_audit_messages_receiving_endpoint_name_time_sent");
+
+ b.ToTable("audit_messages", (string)null);
+ });
+
+ modelBuilder.Entity("ServiceControl.Audit.Persistence.EFCore.Entities.FailedAuditImportEntity", b =>
+ {
+ b.Property("UniqueMessageId")
+ .HasColumnType("uuid")
+ .HasColumnName("unique_message_id");
+
+ b.Property("Body")
+ .IsRequired()
+ .HasColumnType("bytea")
+ .HasColumnName("body");
+
+ b.Property("ExceptionInfo")
+ .HasColumnType("text")
+ .HasColumnName("exception_info");
+
+ b.Property("FailedAt")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("failed_at");
+
+ b.Property("HeadersJson")
+ .IsRequired()
+ .HasColumnType("text")
+ .HasColumnName("headers_json");
+
+ b.Property("MessageId")
+ .HasColumnType("text")
+ .HasColumnName("message_id");
+
+ b.HasKey("UniqueMessageId")
+ .HasName("pk_failed_audit_imports");
+
+ b.HasIndex("FailedAt", "UniqueMessageId")
+ .HasDatabaseName("ix_failed_audit_imports_failed_at_unique_message_id");
+
+ b.ToTable("failed_audit_imports", (string)null);
+ });
+
+ modelBuilder.Entity("ServiceControl.Audit.Persistence.EFCore.Entities.SagaSnapshotEntity", b =>
+ {
+ b.Property("CreatedOn")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("created_on");
+
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint")
+ .HasColumnName("id");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id"));
+
+ b.Property("Endpoint")
+ .HasColumnType("text")
+ .HasColumnName("endpoint");
+
+ b.Property("FinishTime")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("finish_time");
+
+ b.Property("InitiatingMessageJson")
+ .HasColumnType("text")
+ .HasColumnName("initiating_message_json");
+
+ b.Property("OutgoingMessagesJson")
+ .HasColumnType("text")
+ .HasColumnName("outgoing_messages_json");
+
+ b.Property("ProcessedAt")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("processed_at");
+
+ b.Property("SagaId")
+ .HasColumnType("uuid")
+ .HasColumnName("saga_id");
+
+ b.Property("SagaType")
+ .HasColumnType("text")
+ .HasColumnName("saga_type");
+
+ b.Property("StartTime")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("start_time");
+
+ b.Property("StateAfterChange")
+ .HasColumnType("text")
+ .HasColumnName("state_after_change");
+
+ b.Property("Status")
+ .HasColumnType("integer")
+ .HasColumnName("status");
+
+ b.HasKey("CreatedOn", "Id")
+ .HasName("pk_saga_snapshots");
+
+ b.HasIndex("SagaId", "FinishTime")
+ .HasDatabaseName("ix_saga_snapshots_saga_id_finish_time");
+
+ b.ToTable("saga_snapshots", (string)null);
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/src/ServiceControl.Audit.Persistence.EFCore.PostgreSql/Migrations/20261126045230_AddEndpointTimeSentIndex.cs b/src/ServiceControl.Audit.Persistence.EFCore.PostgreSql/Migrations/20261126045230_AddEndpointTimeSentIndex.cs
new file mode 100644
index 0000000000..32eb35fb74
--- /dev/null
+++ b/src/ServiceControl.Audit.Persistence.EFCore.PostgreSql/Migrations/20261126045230_AddEndpointTimeSentIndex.cs
@@ -0,0 +1,27 @@
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace ServiceControl.Audit.Persistence.EFCore.PostgreSql.Migrations
+{
+ ///
+ public partial class AddEndpointTimeSentIndex : Migration
+ {
+ ///
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.CreateIndex(
+ name: "ix_audit_messages_receiving_endpoint_name_time_sent",
+ table: "audit_messages",
+ columns: new[] { "receiving_endpoint_name", "time_sent" });
+ }
+
+ ///
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropIndex(
+ name: "ix_audit_messages_receiving_endpoint_name_time_sent",
+ table: "audit_messages");
+ }
+ }
+}
diff --git a/src/ServiceControl.Audit.Persistence.EFCore.PostgreSql/Migrations/PostgreSqlAuditDbContextModelSnapshot.cs b/src/ServiceControl.Audit.Persistence.EFCore.PostgreSql/Migrations/PostgreSqlAuditDbContextModelSnapshot.cs
index eb646b0c01..657fc1ffe7 100644
--- a/src/ServiceControl.Audit.Persistence.EFCore.PostgreSql/Migrations/PostgreSqlAuditDbContextModelSnapshot.cs
+++ b/src/ServiceControl.Audit.Persistence.EFCore.PostgreSql/Migrations/PostgreSqlAuditDbContextModelSnapshot.cs
@@ -144,6 +144,9 @@ protected override void BuildModel(ModelBuilder modelBuilder)
b.HasIndex("ReceivingEndpointName", "CreatedOn")
.HasDatabaseName("ix_audit_messages_receiving_endpoint_name_created_on");
+ b.HasIndex("ReceivingEndpointName", "TimeSent")
+ .HasDatabaseName("ix_audit_messages_receiving_endpoint_name_time_sent");
+
b.ToTable("audit_messages", (string)null);
});
diff --git a/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/Migrations/20261126035956_AddEndpointTimeSentIndex.Designer.cs b/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/Migrations/20261126035956_AddEndpointTimeSentIndex.Designer.cs
new file mode 100644
index 0000000000..ad1253f967
--- /dev/null
+++ b/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/Migrations/20261126035956_AddEndpointTimeSentIndex.Designer.cs
@@ -0,0 +1,207 @@
+//
+using System;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Metadata;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+using ServiceControl.Audit.Persistence.EFCore.SqlServer;
+
+#nullable disable
+
+namespace ServiceControl.Audit.Persistence.EFCore.SqlServer.Migrations
+{
+ [DbContext(typeof(SqlServerAuditDbContext))]
+ [Migration("20261126035956_AddEndpointTimeSentIndex")]
+ partial class AddEndpointTimeSentIndex
+ {
+ ///
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasAnnotation("ProductVersion", "10.0.15")
+ .HasAnnotation("Relational:MaxIdentifierLength", 128);
+
+ SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
+
+ modelBuilder.Entity("ServiceControl.Audit.Persistence.EFCore.Entities.AuditMessageEntity", b =>
+ {
+ b.Property("CreatedOn")
+ .HasColumnType("datetime2");
+
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"));
+
+ b.Property("BodyContentType")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("BodySize")
+ .HasColumnType("int");
+
+ b.Property("BodyState")
+ .HasColumnType("int");
+
+ b.Property("BodyText")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("ConversationId")
+ .HasMaxLength(450)
+ .HasColumnType("nvarchar(450)");
+
+ b.Property("CriticalTimeTicks")
+ .HasColumnType("bigint");
+
+ b.Property("DeliveryTimeTicks")
+ .HasColumnType("bigint");
+
+ b.Property("HeadersJson")
+ .IsRequired()
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("IsSystemMessage")
+ .HasColumnType("bit");
+
+ b.Property("MessageId")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("MessageType")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("ProcessedAt")
+ .HasColumnType("datetime2");
+
+ b.Property("ProcessingTimeTicks")
+ .HasColumnType("bigint");
+
+ b.Property("ReceivingEndpointHost")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("ReceivingEndpointHostId")
+ .HasColumnType("uniqueidentifier");
+
+ b.Property("ReceivingEndpointName")
+ .HasMaxLength(450)
+ .HasColumnType("nvarchar(450)");
+
+ b.Property("SendingEndpointHost")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("SendingEndpointHostId")
+ .HasColumnType("uniqueidentifier");
+
+ b.Property("SendingEndpointName")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("Status")
+ .HasColumnType("int");
+
+ b.Property("TimeSent")
+ .HasColumnType("datetime2");
+
+ b.Property("UniqueMessageId")
+ .HasColumnType("uniqueidentifier");
+
+ b.HasKey("CreatedOn", "Id");
+
+ b.HasIndex("ConversationId");
+
+ b.HasIndex("Id")
+ .IsUnique();
+
+ b.HasIndex("ProcessedAt");
+
+ b.HasIndex("TimeSent");
+
+ b.HasIndex("UniqueMessageId");
+
+ b.HasIndex("ReceivingEndpointName", "CreatedOn");
+
+ b.HasIndex("ReceivingEndpointName", "TimeSent");
+
+ b.ToTable("AuditMessages");
+ });
+
+ modelBuilder.Entity("ServiceControl.Audit.Persistence.EFCore.Entities.FailedAuditImportEntity", b =>
+ {
+ b.Property("UniqueMessageId")
+ .HasColumnType("uniqueidentifier");
+
+ b.Property("Body")
+ .IsRequired()
+ .HasColumnType("varbinary(max)");
+
+ b.Property("ExceptionInfo")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("FailedAt")
+ .HasColumnType("datetime2");
+
+ b.Property("HeadersJson")
+ .IsRequired()
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("MessageId")
+ .HasColumnType("nvarchar(max)");
+
+ b.HasKey("UniqueMessageId");
+
+ b.HasIndex("FailedAt", "UniqueMessageId");
+
+ b.ToTable("FailedAuditImports");
+ });
+
+ modelBuilder.Entity("ServiceControl.Audit.Persistence.EFCore.Entities.SagaSnapshotEntity", b =>
+ {
+ b.Property("CreatedOn")
+ .HasColumnType("datetime2");
+
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint");
+
+ SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"));
+
+ b.Property("Endpoint")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("FinishTime")
+ .HasColumnType("datetime2");
+
+ b.Property("InitiatingMessageJson")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("OutgoingMessagesJson")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("ProcessedAt")
+ .HasColumnType("datetime2");
+
+ b.Property("SagaId")
+ .HasColumnType("uniqueidentifier");
+
+ b.Property("SagaType")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("StartTime")
+ .HasColumnType("datetime2");
+
+ b.Property("StateAfterChange")
+ .HasColumnType("nvarchar(max)");
+
+ b.Property("Status")
+ .HasColumnType("int");
+
+ b.HasKey("CreatedOn", "Id");
+
+ b.HasIndex("SagaId", "FinishTime");
+
+ b.ToTable("SagaSnapshots");
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/Migrations/20261126035956_AddEndpointTimeSentIndex.cs b/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/Migrations/20261126035956_AddEndpointTimeSentIndex.cs
new file mode 100644
index 0000000000..5e990c310f
--- /dev/null
+++ b/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/Migrations/20261126035956_AddEndpointTimeSentIndex.cs
@@ -0,0 +1,27 @@
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace ServiceControl.Audit.Persistence.EFCore.SqlServer.Migrations
+{
+ ///
+ public partial class AddEndpointTimeSentIndex : Migration
+ {
+ ///
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.CreateIndex(
+ name: "IX_AuditMessages_ReceivingEndpointName_TimeSent",
+ table: "AuditMessages",
+ columns: new[] { "ReceivingEndpointName", "TimeSent" });
+ }
+
+ ///
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropIndex(
+ name: "IX_AuditMessages_ReceivingEndpointName_TimeSent",
+ table: "AuditMessages");
+ }
+ }
+}
diff --git a/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/Migrations/SqlServerAuditDbContextModelSnapshot.cs b/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/Migrations/SqlServerAuditDbContextModelSnapshot.cs
index 397af20956..5af000d58c 100644
--- a/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/Migrations/SqlServerAuditDbContextModelSnapshot.cs
+++ b/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/Migrations/SqlServerAuditDbContextModelSnapshot.cs
@@ -117,6 +117,8 @@ protected override void BuildModel(ModelBuilder modelBuilder)
b.HasIndex("ReceivingEndpointName", "CreatedOn");
+ b.HasIndex("ReceivingEndpointName", "TimeSent");
+
b.ToTable("AuditMessages");
});
diff --git a/src/ServiceControl.Audit.Persistence.EFCore/EntityConfigurations/AuditMessageConfiguration.cs b/src/ServiceControl.Audit.Persistence.EFCore/EntityConfigurations/AuditMessageConfiguration.cs
index 3d85ce3114..332b34b7ae 100644
--- a/src/ServiceControl.Audit.Persistence.EFCore/EntityConfigurations/AuditMessageConfiguration.cs
+++ b/src/ServiceControl.Audit.Persistence.EFCore/EntityConfigurations/AuditMessageConfiguration.cs
@@ -25,6 +25,7 @@ public void Configure(EntityTypeBuilder builder)
builder.HasIndex(e => e.UniqueMessageId);
builder.HasIndex(e => new { e.ReceivingEndpointName, e.CreatedOn });
+ builder.HasIndex(e => new { e.ReceivingEndpointName, e.TimeSent });
builder.HasIndex(e => e.ConversationId);
builder.HasIndex(e => e.ProcessedAt);
builder.HasIndex(e => e.TimeSent);
diff --git a/src/ServiceControl.Audit.Persistence.Tests.PostgreSql/ApprovalFiles/SlowMigrationOperationApprovals.Verify_slow_migration_operations_are_unchanged.approved.txt b/src/ServiceControl.Audit.Persistence.Tests.PostgreSql/ApprovalFiles/SlowMigrationOperationApprovals.Verify_slow_migration_operations_are_unchanged.approved.txt
index 48a74dddcc..2b0028a333 100644
--- a/src/ServiceControl.Audit.Persistence.Tests.PostgreSql/ApprovalFiles/SlowMigrationOperationApprovals.Verify_slow_migration_operations_are_unchanged.approved.txt
+++ b/src/ServiceControl.Audit.Persistence.Tests.PostgreSql/ApprovalFiles/SlowMigrationOperationApprovals.Verify_slow_migration_operations_are_unchanged.approved.txt
@@ -1,3 +1,5 @@
20260928032745_AddFullTextSearch
Sql
CREATE INDEX ix_audit_messages_full_text ON audit_messages USING GIN (to_tsvector('simple', headers_json || ' ' || substring(COALESCE(body_text, ''), 1, 262144) || ' ' || replace(replace(COALESCE(message_type, ''), '.', ' '), '+', ' ')))
+20261126045230_AddEndpointTimeSentIndex
+ CreateIndex ix_audit_messages_receiving_endpoint_name_time_sent on audit_messages (receiving_endpoint_name, time_sent)
diff --git a/src/ServiceControl.Audit.Persistence.Tests.SqlServer/ApprovalFiles/SlowMigrationOperationApprovals.Verify_slow_migration_operations_are_unchanged.approved.txt b/src/ServiceControl.Audit.Persistence.Tests.SqlServer/ApprovalFiles/SlowMigrationOperationApprovals.Verify_slow_migration_operations_are_unchanged.approved.txt
index 16e598b9a5..01f121d2b4 100644
--- a/src/ServiceControl.Audit.Persistence.Tests.SqlServer/ApprovalFiles/SlowMigrationOperationApprovals.Verify_slow_migration_operations_are_unchanged.approved.txt
+++ b/src/ServiceControl.Audit.Persistence.Tests.SqlServer/ApprovalFiles/SlowMigrationOperationApprovals.Verify_slow_migration_operations_are_unchanged.approved.txt
@@ -22,3 +22,5 @@
ON ServiceControlFullTextCatalog
WITH (CHANGE_TRACKING AUTO, STOPLIST = OFF)');
END
+20261126035956_AddEndpointTimeSentIndex
+ CreateIndex IX_AuditMessages_ReceivingEndpointName_TimeSent on AuditMessages (ReceivingEndpointName, TimeSent)
diff --git a/src/ServiceControl.Audit.Persistence.Tests.SqlServer/EndpointFilterPlanReuseTests.cs b/src/ServiceControl.Audit.Persistence.Tests.SqlServer/EndpointFilterPlanReuseTests.cs
new file mode 100644
index 0000000000..40b47b6294
--- /dev/null
+++ b/src/ServiceControl.Audit.Persistence.Tests.SqlServer/EndpointFilterPlanReuseTests.cs
@@ -0,0 +1,85 @@
+namespace ServiceControl.Audit.Persistence.Tests
+{
+ using System.Collections.Generic;
+ using System.Threading.Tasks;
+ using Microsoft.Data.SqlClient;
+ using NUnit.Framework;
+ using ServiceControl.Audit.Infrastructure;
+
+ // SQL Server compiles the endpoint filter for the first endpoint asked for, then reuses that plan for every other endpoint.
+ class EndpointFilterPlanReuseTests : EFPersistenceTestFixture
+ {
+ [TestCase(BusyEndpoint, QuietEndpoint)]
+ [TestCase(QuietEndpoint, BusyEndpoint)]
+ public async Task The_page_for_an_endpoint_stays_cheap_on_a_plan_compiled_for_another_endpoint(string compiledFor, string listed)
+ {
+ await Seed();
+
+ await ListFirstPage(compiledFor);
+ await ListFirstPage(listed);
+
+ var pageReads = await PageQueryReads();
+
+ using (Assert.EnterMultipleScope())
+ {
+ Assert.That(pageReads, Is.Not.Empty, "The page query was not found in the plan cache.");
+ Assert.That(pageReads, Has.All.LessThan(MaxReads));
+ }
+ }
+
+ async Task Seed()
+ {
+ await using var connection = new SqlConnection(configuration.ConnectionString);
+ await connection.OpenAsync(TestTimeoutCancellationToken);
+
+ await using var command = connection.CreateCommand();
+ command.CommandText = $$"""
+ WITH n AS (SELECT TOP (50000) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) - 1 AS i FROM sys.all_objects a CROSS JOIN sys.all_objects b)
+ INSERT [{{configuration.Schema}}].[AuditMessages] (CreatedOn, UniqueMessageId, TimeSent, ProcessedAt, IsSystemMessage, Status, ReceivingEndpointName, HeadersJson, BodyState, BodySize)
+ SELECT DATEADD(hour, -(i % 168), @hour), NEWID(), DATEADD(second, i % 3600, DATEADD(hour, -(i % 168), @hour)), DATEADD(hour, -(i % 168), @hour), 0, 1,
+ CASE WHEN i % 2500 = 0 THEN @quiet WHEN i % 10 < 6 THEN @busy ELSE @other END, '{}', 0, 0
+ FROM n;
+ UPDATE STATISTICS [{{configuration.Schema}}].[AuditMessages] WITH FULLSCAN;
+ """;
+ command.Parameters.AddWithValue("@hour", TimeSent);
+ command.Parameters.AddWithValue("@quiet", QuietEndpoint);
+ command.Parameters.AddWithValue("@busy", BusyEndpoint);
+ command.Parameters.AddWithValue("@other", OtherEndpoint);
+ await command.ExecuteNonQueryAsync(TestTimeoutCancellationToken);
+ }
+
+ Task ListFirstPage(string endpoint) =>
+ MessagesViewStore.QueryMessagesByReceivingEndpoint(false, endpoint, new PagingInfo(pageSize: 100), new SortInfo("time_sent", "desc"), cancellationToken: TestTimeoutCancellationToken);
+
+ async Task> PageQueryReads()
+ {
+ await using var connection = new SqlConnection(configuration.ConnectionString);
+ await connection.OpenAsync(TestTimeoutCancellationToken);
+
+ await using var command = connection.CreateCommand();
+ command.CommandText = """
+ SELECT qs.last_logical_reads
+ FROM sys.dm_exec_query_stats AS qs
+ CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
+ WHERE CHARINDEX(@table, st.text) > 0 AND CHARINDEX('@endpointName', st.text) > 0 AND CHARINDEX('ORDER BY', st.text) > 0
+ """;
+ command.Parameters.AddWithValue("@table", $"[{configuration.Schema}].[AuditMessages]");
+
+ var reads = new List();
+ await using var reader = await command.ExecuteReaderAsync(TestTimeoutCancellationToken);
+ while (await reader.ReadAsync(TestTimeoutCancellationToken))
+ {
+ reads.Add(reader.GetInt64(0));
+ }
+
+ return reads;
+ }
+
+ const string BusyEndpoint = "Sales";
+ const string OtherEndpoint = "Billing";
+ const string QuietEndpoint = "Rare";
+
+ // Without an index that serves both the filter and the sort, each order reads 90,000 or more.
+ const long MaxReads = 1_000;
+ }
+}