{"results":{"result":{"added-files":{"code-health":0.0,"old-code-health":0.0,"files":[]},"external-review-url":"https://github.com/BrighterCommand/Brighter/pull/4185","old-code-health":8.785707115362154,"modified-files":{"code-health":8.80214933379466,"old-code-health":8.785707115362154,"files":[{"file":"src/Paramore.Brighter.Archive.Azure/AzureBlobArchiveProvider.cs","loc":83,"old-loc":83,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.BoxProvisioning.MsSql/MsSqlBoxMigrationRunner.cs","loc":296,"old-loc":294,"code-health":8.816158827775617,"old-code-health":8.816158827775617},{"file":"src/Paramore.Brighter.BoxProvisioning.MySql/MySqlBoxMigrationRunner.cs","loc":179,"old-loc":177,"code-health":8.816158827775617,"old-code-health":8.816158827775617},{"file":"src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxDetectionHelper.cs","loc":163,"old-loc":164,"code-health":8.031638343271364,"old-code-health":8.031638343271364},{"file":"src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxMigrationRunner.cs","loc":304,"old-loc":302,"code-health":8.545379580978913,"old-code-health":8.545379580978913},{"file":"src/Paramore.Brighter.BoxProvisioning.Spanner/SpannerBoxMigrationRunner.cs","loc":264,"old-loc":263,"code-health":9.387218218812514,"old-code-health":9.387218218812514},{"file":"src/Paramore.Brighter.BoxProvisioning.Sqlite/SqliteBoxMigrationRunner.cs","loc":216,"old-loc":214,"code-health":8.816158827775617,"old-code-health":8.816158827775617},{"file":"src/Paramore.Brighter.BoxProvisioning/SqlBoxProvisioner.cs","loc":123,"old-loc":121,"code-health":9.6882083290695,"old-code-health":9.6882083290695},{"file":"src/Paramore.Brighter.Extensions.DependencyInjection/ServiceCollectionExtensions.cs","loc":607,"old-loc":607,"code-health":7.624891450768529,"old-code-health":7.624891450768529},{"file":"src/Paramore.Brighter.Inbox.MsSql/MsSqlInbox.cs","loc":36,"old-loc":35,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.Inbox.MySql/MySqlInbox.cs","loc":35,"old-loc":34,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.Inbox.Postgres/PostgreSqlInbox.cs","loc":40,"old-loc":39,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.Inbox.Spanner/SpannerInboxAsync.cs","loc":63,"old-loc":61,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.Inbox.Sqlite/SqliteInbox.cs","loc":36,"old-loc":35,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.Locking.Azure/AzureBlobLockingProvider.cs","loc":65,"old-loc":65,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.Locking.DynamoDB.V4/DynamoDbLockingProvider.cs","loc":109,"old-loc":108,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.Locking.DynamoDB/DynamoDbLockingProvider.cs","loc":111,"old-loc":110,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.Locking.MsSql/MsSqlLockingProvider.cs","loc":96,"old-loc":96,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.Locking.MySql/MySqlLockingProvider.cs","loc":152,"old-loc":152,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.Mediator/InMemoryJobChannel.cs","loc":59,"old-loc":58,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.Mediator/InMemoryStateStoreAsync.cs","loc":62,"old-loc":61,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.Mediator/Runner.cs","loc":82,"old-loc":81,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.Mediator/Steps.cs","loc":187,"old-loc":183,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.Mediator/Waker.cs","loc":43,"old-loc":42,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessageScheduler.Azure/AzureServiceBusScheduler.cs","loc":204,"old-loc":203,"code-health":8.816158827775617,"old-code-health":8.816158827775617},{"file":"src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/AWSMessagingGateway.cs","loc":407,"old-loc":401,"code-health":9.6882083290695,"old-code-health":9.6882083290695},{"file":"src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/ChannelFactory.cs","loc":227,"old-loc":227,"code-health":9.387218218812514,"old-code-health":9.387218218812514},{"file":"src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SnsMessageProducer.cs","loc":112,"old-loc":111,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SnsMessageProducerFactory.cs","loc":68,"old-loc":64,"code-health":9.6882083290695,"old-code-health":9.6882083290695},{"file":"src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SnsProducerRegistryFactory.cs","loc":32,"old-loc":28,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsInlineMessageCreator.cs","loc":410,"old-loc":406,"code-health":9.536386775820924,"old-code-health":8.95517096544394},{"file":"src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageConsumer.cs","loc":430,"old-loc":426,"code-health":9.139589479072994,"old-code-health":9.139589479072994},{"file":"src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageConsumerFactory.cs","loc":52,"old-loc":48,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageCreator.cs","loc":370,"old-loc":366,"code-health":6.833126887016521,"old-code-health":6.833126887016521},{"file":"src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageCreatorFactory.cs","loc":15,"old-loc":14,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageProducer.cs","loc":105,"old-loc":102,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageProducerFactory.cs","loc":63,"old-loc":59,"code-health":9.6882083290695,"old-code-health":9.6882083290695},{"file":"src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageSender.cs","loc":131,"old-loc":130,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsProducerRegistryFactory.cs","loc":32,"old-loc":28,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.AWSSQS/AWSMessagingGateway.cs","loc":413,"old-loc":407,"code-health":9.6882083290695,"old-code-health":9.6882083290695},{"file":"src/Paramore.Brighter.MessagingGateway.AWSSQS/ChannelFactory.cs","loc":227,"old-loc":227,"code-health":9.387218218812514,"old-code-health":9.387218218812514},{"file":"src/Paramore.Brighter.MessagingGateway.AWSSQS/SnsMessageProducer.cs","loc":112,"old-loc":111,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.AWSSQS/SnsMessageProducerFactory.cs","loc":68,"old-loc":64,"code-health":9.6882083290695,"old-code-health":9.6882083290695},{"file":"src/Paramore.Brighter.MessagingGateway.AWSSQS/SnsProducerRegistryFactory.cs","loc":32,"old-loc":28,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsInlineMessageCreator.cs","loc":417,"old-loc":413,"code-health":9.387218218812514,"old-code-health":9.387218218812514},{"file":"src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageConsumer.cs","loc":433,"old-loc":429,"code-health":9.139589479072994,"old-code-health":9.139589479072994},{"file":"src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageConsumerFactory.cs","loc":54,"old-loc":50,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageCreator.cs","loc":355,"old-loc":351,"code-health":9.062471366024122,"old-code-health":9.062471366024122},{"file":"src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageCreatorFactory.cs","loc":17,"old-loc":16,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageProducer.cs","loc":105,"old-loc":102,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageProducerFactory.cs","loc":63,"old-loc":59,"code-health":9.6882083290695,"old-code-health":9.6882083290695},{"file":"src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageSender.cs","loc":133,"old-loc":132,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsProducerRegistryFactory.cs","loc":32,"old-loc":28,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusChannelFactory.cs","loc":55,"old-loc":55,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusConsumer.cs","loc":249,"old-loc":248,"code-health":8.434468632705734,"old-code-health":8.434468632705734},{"file":"src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusConsumerFactory.cs","loc":63,"old-loc":56,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusMessageProducerFactory.cs","loc":62,"old-loc":58,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusMesssageCreator.cs","loc":243,"old-loc":243,"code-health":9.096655465156704,"old-code-health":9.096655465156704},{"file":"src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusProducerRegistryFactory.cs","loc":45,"old-loc":39,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusQueueConsumer.cs","loc":97,"old-loc":95,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusQueueMessageProducer.cs","loc":57,"old-loc":55,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusTopicConsumer.cs","loc":102,"old-loc":100,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusTopicMessageProducer.cs","loc":55,"old-loc":53,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusWrappers/AdministrationClientWrapper.cs","loc":272,"old-loc":271,"code-health":8.283981080161325,"old-code-health":8.283981080161325},{"file":"src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusWrappers/ServiceBusReceiverProvider.cs","loc":62,"old-loc":60,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusWrappers/ServiceBusReceiverWrapper.cs","loc":67,"old-loc":66,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.GcpPubSub/GcpPubSubConsumerFactory.cs","loc":70,"old-loc":67,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.GcpPubSub/GcpPubSubStreamMessageConsumer.cs","loc":159,"old-loc":158,"code-health":9.096655465156704,"old-code-health":9.096655465156704},{"file":"src/Paramore.Brighter.MessagingGateway.GcpPubSub/GcpPullMessageConsumer.cs","loc":279,"old-loc":278,"code-health":8.816158827775617,"old-code-health":8.816158827775617},{"file":"src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessageConsumer.cs","loc":898,"old-loc":896,"code-health":6.864471644346768,"old-code-health":6.871920039156297},{"file":"src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessageConsumerFactory.cs","loc":67,"old-loc":62,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessageCreator.cs","loc":377,"old-loc":373,"code-health":8.413528317237752,"old-code-health":8.413528317237752},{"file":"src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessageProducer.cs","loc":269,"old-loc":267,"code-health":8.747566364082143,"old-code-health":8.747566364082143},{"file":"src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessageProducerFactory.cs","loc":49,"old-loc":45,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessagingGateway.cs","loc":132,"old-loc":126,"code-health":8.796891954397736,"old-code-health":8.796891954397736},{"file":"src/Paramore.Brighter.MessagingGateway.Kafka/KafkaProducerRegistryFactory.cs","loc":42,"old-loc":38,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.MQTT/MQTTMessageConsumer.cs","loc":354,"old-loc":350,"code-health":9.096655465156704,"old-code-health":9.096655465156704},{"file":"src/Paramore.Brighter.MessagingGateway.MQTT/MQTTMessagePublisher.cs","loc":92,"old-loc":91,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.MQTT/MqttMessageConsumerFactory.cs","loc":38,"old-loc":34,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.MsSql/ChannelFactory.cs","loc":64,"old-loc":63,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.MsSql/MsSqlMessageConsumer.cs","loc":301,"old-loc":296,"code-health":8.036598498867646,"old-code-health":8.036598498867646},{"file":"src/Paramore.Brighter.MessagingGateway.MsSql/MsSqlMessageConsumerFactory.cs","loc":49,"old-loc":46,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.MsSql/MsSqlMessageProducer.cs","loc":110,"old-loc":107,"code-health":9.387218218812514,"old-code-health":9.387218218812514},{"file":"src/Paramore.Brighter.MessagingGateway.MsSql/MsSqlMessageProducerFactory.cs","loc":46,"old-loc":42,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.MsSql/MsSqlProducerRegistryFactory.cs","loc":44,"old-loc":40,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.MsSql/SqlQueues/MsSqlMessageQueue.cs","loc":182,"old-loc":181,"code-health":9.387218218812514,"old-code-health":9.387218218812514},{"file":"src/Paramore.Brighter.MessagingGateway.Postgres/PostgresChannelFactory.cs","loc":59,"old-loc":58,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.Postgres/PostgresConsumerFactory.cs","loc":24,"old-loc":22,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.Postgres/PostgresMessageConsumer.cs","loc":529,"old-loc":527,"code-health":7.290276124915766,"old-code-health":7.290276124915766},{"file":"src/Paramore.Brighter.MessagingGateway.Postgres/PostgresMessageProducer.cs","loc":124,"old-loc":123,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.Postgres/PostgresMessageProducerFactory.cs","loc":50,"old-loc":49,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.Postgres/PostgresProducerRegistryFactory.cs","loc":18,"old-loc":17,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.RMQ.Async/ConnectionPolicyFactory.cs","loc":56,"old-loc":55,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.RMQ.Async/PullConsumer.cs","loc":84,"old-loc":84,"code-health":9.6882083290695,"old-code-health":9.6882083290695},{"file":"src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageConsumer.cs","loc":474,"old-loc":469,"code-health":8.479163401604131,"old-code-health":8.479163401604131},{"file":"src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageConsumerFactory.cs","loc":65,"old-loc":60,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageCreator.cs","loc":346,"old-loc":342,"code-health":8.283981080161325,"old-code-health":8.283981080161325},{"file":"src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageGateway.cs","loc":138,"old-loc":135,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageGatewayConnectionPool.cs","loc":138,"old-loc":138,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageProducer.cs","loc":341,"old-loc":340,"code-health":9.6882083290695,"old-code-health":9.6882083290695},{"file":"src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessageProducerFactory.cs","loc":36,"old-loc":34,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.RMQ.Async/RmqMessagePublisher.cs","loc":205,"old-loc":204,"code-health":9.096655465156704,"old-code-health":9.096655465156704},{"file":"src/Paramore.Brighter.MessagingGateway.RMQ.Sync/ConnectionPoolFactory.cs","loc":58,"old-loc":57,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.RMQ.Sync/PullConsumer.cs","loc":87,"old-loc":86,"code-health":9.6882083290695,"old-code-health":9.6882083290695},{"file":"src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageConsumer.cs","loc":412,"old-loc":407,"code-health":8.720298221085535,"old-code-health":8.720298221085535},{"file":"src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageConsumerFactory.cs","loc":47,"old-loc":43,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageCreator.cs","loc":336,"old-loc":332,"code-health":8.283981080161325,"old-code-health":8.283981080161325},{"file":"src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageGateway.cs","loc":118,"old-loc":115,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageGatewayConnectionPool.cs","loc":122,"old-loc":121,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageProducer.cs","loc":166,"old-loc":165,"code-health":9.387218218812514,"old-code-health":9.387218218812514},{"file":"src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessageProducerFactory.cs","loc":36,"old-loc":34,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.RMQ.Sync/RmqMessagePublisher.cs","loc":175,"old-loc":174,"code-health":9.096655465156704,"old-code-health":9.096655465156704},{"file":"src/Paramore.Brighter.MessagingGateway.Redis/RedisMessageConsumer.cs","loc":561,"old-loc":552,"code-health":6.717068846404382,"old-code-health":6.717068846404382},{"file":"src/Paramore.Brighter.MessagingGateway.Redis/RedisMessageConsumerFactory.cs","loc":56,"old-loc":51,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.Redis/RedisMessageCreator.cs","loc":290,"old-loc":286,"code-health":8.77219002921793,"old-code-health":8.77219002921793},{"file":"src/Paramore.Brighter.MessagingGateway.Redis/RedisMessageProducer.cs","loc":146,"old-loc":145,"code-health":9.387218218812514,"old-code-health":9.387218218812514},{"file":"src/Paramore.Brighter.MessagingGateway.Redis/RedisMessageProducerFactory.cs","loc":44,"old-loc":40,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.Redis/RedisProducerRegistryFactory.cs","loc":23,"old-loc":21,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.RocketMQ/RocketMessageConsumer.cs","loc":443,"old-loc":442,"code-health":9.536386775820924,"old-code-health":9.536386775820924},{"file":"src/Paramore.Brighter.MessagingGateway.RocketMQ/RocketMessageConsumerFactory.cs","loc":33,"old-loc":32,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.MessagingGateway.RocketMQ/RocketMessageProducerFactory.cs","loc":55,"old-loc":55,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.Outbox.Hosting/HostedServiceCollectionExtensions.cs","loc":42,"old-loc":40,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.Outbox.Hosting/TimedOutboxArchiver.cs","loc":101,"old-loc":99,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.Outbox.Hosting/TimedOutboxSweeper.cs","loc":94,"old-loc":92,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.Outbox.MsSql/MsSqlOutbox.cs","loc":64,"old-loc":62,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.Outbox.MySql/MySqlOutbox.cs","loc":50,"old-loc":48,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.Outbox.PostgreSql/PostgreSqlOutbox.cs","loc":45,"old-loc":42,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.Outbox.Spanner/SpannerOutbox.cs","loc":86,"old-loc":87,"code-health":9.6882083290695,"old-code-health":9.6882083290695},{"file":"src/Paramore.Brighter.Outbox.Sqlite/SqliteOutbox.cs","loc":52,"old-loc":50,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.ServiceActivator.Extensions.DependencyInjection/ServiceCollectionExtensions.cs","loc":154,"old-loc":155,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.ServiceActivator/ConsumerFactory.cs","loc":113,"old-loc":107,"code-health":9.6882083290695,"old-code-health":9.6882083290695},{"file":"src/Paramore.Brighter.ServiceActivator/DispatchBuilder.cs","loc":128,"old-loc":119,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.ServiceActivator/Dispatcher.cs","loc":315,"old-loc":311,"code-health":9.387218218812514,"old-code-health":9.387218218812514},{"file":"src/Paramore.Brighter.ServiceActivator/MessagePump.cs","loc":91,"old-loc":89,"code-health":9.6882083290695,"old-code-health":10.0},{"file":"src/Paramore.Brighter.ServiceActivator/Ports/Handlers/ConfigurationCommandHandler.cs","loc":74,"old-loc":73,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter.ServiceActivator/Proactor.cs","loc":481,"old-loc":480,"code-health":7.788037646779413,"old-code-health":7.788037646779413},{"file":"src/Paramore.Brighter.ServiceActivator/Reactor.cs","loc":479,"old-loc":478,"code-health":7.788037646779413,"old-code-health":7.788037646779413},{"file":"src/Paramore.Brighter.Transformers.AWS.V4/S3LuggageStore.cs","loc":348,"old-loc":347,"code-health":8.87646692473966,"old-code-health":8.603598393240393},{"file":"src/Paramore.Brighter.Transformers.AWS/S3LuggageStore.cs","loc":348,"old-loc":347,"code-health":8.87646692473966,"old-code-health":8.603598393240393},{"file":"src/Paramore.Brighter.Transformers.Gcp/GcsLuggageStore.cs","loc":258,"old-loc":258,"code-health":8.283981080161325,"old-code-health":8.283981080161325},{"file":"src/Paramore.Brighter/CommandProcessor.cs","loc":1056,"old-loc":1047,"code-health":6.30344731029596,"old-code-health":6.30344731029596},{"file":"src/Paramore.Brighter/CommandProcessorBuilder.cs","loc":254,"old-loc":242,"code-health":9.387218218812514,"old-code-health":9.387218218812514},{"file":"src/Paramore.Brighter/Defer/Handlers/DeferMessageOnErrorHandler.cs","loc":38,"old-loc":34,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter/Defer/Handlers/DeferMessageOnErrorHandlerAsync.cs","loc":40,"old-loc":36,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter/HandlerLifetimeScope.cs","loc":71,"old-loc":70,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter/InMemoryScheduler.cs","loc":242,"old-loc":241,"code-health":8.816158827775617,"old-code-health":8.816158827775617},{"file":"src/Paramore.Brighter/Inbox/Handlers/UseInboxHandler.cs","loc":73,"old-loc":72,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter/Inbox/Handlers/UseInboxHandlerAsync.cs","loc":79,"old-loc":78,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter/Logging/ApplicationLogging.cs","loc":24,"old-loc":9,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter/Logging/Handlers/RequestLoggingHandler.cs","loc":43,"old-loc":38,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter/Logging/Handlers/RequestLoggingHandlerAsync.cs","loc":42,"old-loc":37,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter/NullOutboxArchiveProvider.cs","loc":30,"old-loc":30,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter/OutboxArchiver.cs","loc":129,"old-loc":127,"code-health":9.6882083290695,"old-code-health":9.6882083290695},{"file":"src/Paramore.Brighter/OutboxProducerMediator.cs","loc":875,"old-loc":872,"code-health":6.947345647493966,"old-code-health":6.966247769888114},{"file":"src/Paramore.Brighter/PipelineBuilder.cs","loc":404,"old-loc":398,"code-health":7.325861446783724,"old-code-health":7.788037646779413},{"file":"src/Paramore.Brighter/Reject/Handlers/RejectMessageOnErrorHandler.cs","loc":33,"old-loc":29,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter/Reject/Handlers/RejectMessageOnErrorHandlerAsync.cs","loc":35,"old-loc":31,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter/RequestHandler.cs","loc":71,"old-loc":71,"code-health":9.387218218812514,"old-code-health":9.387218218812514},{"file":"src/Paramore.Brighter/RequestHandlerAsync.cs","loc":76,"old-loc":76,"code-health":9.387218218812514,"old-code-health":9.387218218812514},{"file":"src/Paramore.Brighter/TransformLifetimeScope.cs","loc":48,"old-loc":47,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter/TransformLifetimeScopeAsync.cs","loc":48,"old-loc":47,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter/TransformPipelineBuilder.cs","loc":198,"old-loc":196,"code-health":9.387218218812514,"old-code-health":9.387218218812514},{"file":"src/Paramore.Brighter/TransformPipelineBuilderAsync.cs","loc":163,"old-loc":161,"code-health":9.387218218812514,"old-code-health":9.387218218812514},{"file":"src/Paramore.Brighter/Transforms/Transformers/CloudEventsTransformer.cs","loc":264,"old-loc":260,"code-health":8.783158986130568,"old-code-health":8.783158986130568},{"file":"src/Paramore.Brighter/WrapPipeline.cs","loc":68,"old-loc":66,"code-health":10.0,"old-code-health":10.0},{"file":"src/Paramore.Brighter/WrapPipelineAsync.cs","loc":73,"old-loc":71,"code-health":10.0,"old-code-health":10.0}]},"removed-files":{"code-health":0.0,"old-code-health":0.0,"files":[]},"external-review-id":"4185","analysis-time":"2026-06-15T17:39:00Z","negative-impact-count":4,"suppressions":{"number-of-types":0,"number-of-files-touched":0,"findings":[]},"affected-hotspots":10,"commits":["f7d6314810eb70df71ec1ce7d01e2b45d1c141d4","7d5a2047517c104aab40f1442e31f62dbaeccecb","8297e267665042d8fd0f9b6b071025ff8108fdb2","bcb4dbfaceb3c8392cddd88e0534ea1f9bdf56e2","5ae5396a4750120e88123bb19d90c5f41db2cefa"],"is-negative-review":true,"negative-findings":{"number-of-types":3,"number-of-files-touched":4,"findings":[{"method":"KafkaMessageConsumer","why-it-occurs":"A Complex Method has a high cyclomatic complexity. The recommended threshold for the C# language is a cyclomatic complexity lower than 9.","name":"Complex Method","file":"src/Paramore.Brighter.MessagingGateway.Kafka/KafkaMessageConsumer.cs","refactoring-examples":[{"architectural-component-id":null,"author-name":"DevJonny","training-data":{"loc-added":"1","loc-deleted":"2","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.0","delta-n-functions":"0","current-file-score":"10.0"},"author-email":"jonny.ollifflee@gmail.com","commit-full-message":"NJsonSchema represents class inheritance via an embedded\n{ definitions: { Base: {...} }, allOf: [{$ref: \"#/definitions/Base\"}, ...] }\nblock on every derived message schema. The previous output duplicated the base\ntype once per message and rewrote refs to resolve inside each message's payload\nsubtree.\n\nThis commit lifts all definitions/$defs entries to a single shared pool under\ncomponents.schemas, dedupes by name (first-seen content wins), and rewrites refs\nacross both the message bodies and the hoisted definitions themselves so\ncross-definition refs continue to resolve. A class hierarchy like\nPaymentReceivedEvent and OrderCreatedEvent both inheriting Event now produces a\nsingle Event entry under components.schemas, with each message's allOf pointing\nat #/components/schemas/Event.\n\nSide benefits:\n- Smaller output (~18% on the sample documents).\n- Tooling consuming the spec sees the base type once and can generate a shared\n  parent class on the client side.\n\nDrops the last open CodeScene Complex Method finding by collapsing the\nJsonValueKind.True / False arms in JsonElementToObject into a single\nGetBoolean() arm.\n\nTests rewritten to assert the new ref shape (#/components/schemas/X) and the\npresence of the hoisted entries under Components.Schemas.\n\nCo-Authored-By: Claude <noreply@anthropic.com>","commit-date":"2026-05-16T19:26:51Z","current-rev":"f5003d644","filename":"Brighter/src/Paramore.Brighter.AsyncAPI/AsyncApiHostExtensions.cs","previous-rev":"f38857a51","commit-title":"feat(#3828): hoist shared JSON Schema definitions to components.schemas","language":"C#","id":"a281e7924ca426d627f9bb709daa231724381400","model-score":0.92,"author-id":null,"project-id":32198,"delta-file-score":0.31179166,"diff":"diff --git a/src/Paramore.Brighter.AsyncAPI/AsyncApiHostExtensions.cs b/src/Paramore.Brighter.AsyncAPI/AsyncApiHostExtensions.cs\nindex 5bc24c0a6..6022aa42b 100644\n--- a/src/Paramore.Brighter.AsyncAPI/AsyncApiHostExtensions.cs\n+++ b/src/Paramore.Brighter.AsyncAPI/AsyncApiHostExtensions.cs\n@@ -191,4 +191,3 @@ private static string SerializeAsYaml(object? tree)\n             JsonValueKind.Number => ReadNumber(element),\n-            JsonValueKind.True => true,\n-            JsonValueKind.False => false,\n+            JsonValueKind.True or JsonValueKind.False => element.GetBoolean(),\n             _ => null,\n","improvement-type":"Complex Method"},{"architectural-component-id":null,"author-name":"gabisonia","training-data":{"loc-added":"7","loc-deleted":"10","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.0","delta-n-functions":"0","current-file-score":"9.6882083290695"},"author-email":"irakli.gabisonia94@gmail.com","commit-full-message":"Expose optional sync and async requeue scheduler capabilities and use native scheduling on the consuming broker. Assign stable per-attempt delivery IDs to survive duplicate detection, and acknowledge only after scheduling succeeds.\n\nPreserve direct-subscription startup and abandon with a warning when delays cannot be honored. Cover failure recovery, broker ownership, forwarding isolation, sessions, and retry identity through regenerated conformance assertions.\n\nValidation: 26 focused cases pass on .NET 9 and 10; full ASB suite has 553 passed, 4 skipped, and the same 10 baseline emulator TTL failures. Azure scheduler tests: 13 passed. Generator tests: 312 passed. Release packages build for all supported targets.","commit-date":"2026-10-09T17:18:14Z","current-rev":"dba7b72f7","filename":"Brighter/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusConsumerFactory.cs","previous-rev":"161b226f3","commit-title":"feat(asb): add native queue-targeted retry scheduling","language":"C#","id":"1024f351788320889cd72fe4675f0158c5d550f3","model-score":0.64,"author-id":null,"project-id":32198,"delta-file-score":0.59155285,"diff":"diff --git a/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusConsumerFactory.cs b/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusConsumerFactory.cs\nindex 8fc288e5c..daf001786 100644\n--- a/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusConsumerFactory.cs\n+++ b/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusConsumerFactory.cs\n@@ -38,2 +38,6 @@ public class AzureServiceBusConsumerFactory : IAmAMessageConsumerFactory\n \n+    /// <summary>The fallback scheduler for custom producers without native queue retry support.</summary>\n+    /// <remarks>Built-in ASB queue producers schedule retries on their own broker and take precedence.</remarks>\n+    public IAmAMessageScheduler? Scheduler { get; set; }\n+\n     /// <summary>\n@@ -72,9 +76,2 @@ public IAmAMessageConsumerSync Create(Subscription subscription)\n \n-        if (sub.RequeueDelay > TimeSpan.Zero && !sub.Configuration.UseServiceBusQueue\n-            && sub.Configuration.ForwardTo is null)\n-        {\n-            throw new ConfigurationException(\n-                \"Delayed topic retries require ForwardTo to a dedicated queue, or UseServiceBusQueue with externally provisioned forwarding.\");\n-        }\n-\n         var receiverProvider = new ServiceBusReceiverProvider(_clientProvider, sub.Configuration.MaxAutoLockRenewalDuration);\n@@ -99,3 +96,3 @@ public IAmAMessageConsumerSync Create(Subscription subscription)\n             return new AzureServiceBusForwardingConsumer(sub, messageProducer,\n-                nameSpaceManagerWrapper, receiverProvider);\n+                nameSpaceManagerWrapper, receiverProvider) { Scheduler = Scheduler };\n         }\n@@ -113,3 +110,3 @@ public IAmAMessageConsumerSync Create(Subscription subscription)\n                 nameSpaceManagerWrapper,\n-                receiverProvider);\n+                receiverProvider) { Scheduler = Scheduler };\n         }\n@@ -126,3 +123,3 @@ public IAmAMessageConsumerSync Create(Subscription subscription)\n                 nameSpaceManagerWrapper,\n-                receiverProvider);\n+                receiverProvider) { Scheduler = Scheduler };\n         }\n","improvement-type":"Complex Method"},{"architectural-component-id":null,"author-name":"DevJonny","training-data":{"loc-added":"17","loc-deleted":"14","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.08","delta-n-functions":"0","current-file-score":"10.0"},"author-email":"jonny.ollifflee@gmail.com","commit-full-message":"Extract LoadAssemblyTypes (handles ReflectionTypeLoadException) and\nTryGetPublicationTopic (per-type filter + topic resolution) from\nGetPublicationTopicTypes. Targets the last CodeScene advisory finding\n(Complex Method).\n\n46/46 AsyncAPI tests pass on net9.0 and net10.0.\n\nCo-Authored-By: Claude (claude-opus-4-7) <noreply@anthropic.com>","commit-date":"2026-05-17T06:26:45Z","current-rev":"7f8b45280","filename":"Brighter/src/Paramore.Brighter.AsyncAPI/AsyncApiDocumentGenerator.cs","previous-rev":"6be065b71","commit-title":"refactor(#3828): split GetPublicationTopicTypes for clarity","language":"C#","id":"2287bc725ce16bc068f9b3178aae023ee15b02f8","model-score":0.5,"author-id":null,"project-id":32198,"delta-file-score":0.33626333,"diff":"diff --git a/src/Paramore.Brighter.AsyncAPI/AsyncApiDocumentGenerator.cs b/src/Paramore.Brighter.AsyncAPI/AsyncApiDocumentGenerator.cs\nindex 4a13108c1..6f8bd66a9 100644\n--- a/src/Paramore.Brighter.AsyncAPI/AsyncApiDocumentGenerator.cs\n+++ b/src/Paramore.Brighter.AsyncAPI/AsyncApiDocumentGenerator.cs\n@@ -248,6 +248,14 @@ private IEnumerable<Assembly> GetAssembliesToScan()\n         {\n-            Type[] types;\n+            foreach (var type in LoadAssemblyTypes(assembly))\n+            {\n+                var topic = TryGetPublicationTopic(type);\n+                if (topic != null) yield return (type, topic);\n+            }\n+        }\n+\n+        private static IEnumerable<Type> LoadAssemblyTypes(Assembly assembly)\n+        {\n             try\n             {\n-                types = assembly.GetTypes();\n+                return assembly.GetTypes();\n             }\n@@ -255,18 +263,13 @@ private IEnumerable<Assembly> GetAssembliesToScan()\n             {\n-                types = ex.Types.Where(t => t != null).ToArray()!;\n+                return ex.Types.Where(t => t != null).ToArray()!;\n             }\n+        }\n \n-            foreach (var type in types)\n-            {\n-                if (type.IsAbstract || type.IsInterface) continue;\n-                if (!typeof(IRequest).IsAssignableFrom(type)) continue;\n-\n-                var attr = type.GetCustomAttribute<PublicationTopicAttribute>();\n-                if (attr == null) continue;\n-\n-                var topic = attr.Destination?.RoutingKey?.Value;\n-                if (string.IsNullOrEmpty(topic)) continue;\n+        private static string? TryGetPublicationTopic(Type type)\n+        {\n+            if (type.IsAbstract || type.IsInterface) return null;\n+            if (!typeof(IRequest).IsAssignableFrom(type)) return null;\n \n-                yield return (type, topic);\n-            }\n+            var topic = type.GetCustomAttribute<PublicationTopicAttribute>()?.Destination?.RoutingKey?.Value;\n+            return string.IsNullOrEmpty(topic) ? null : topic;\n         }\n","improvement-type":"Complex Method"},{"architectural-component-id":null,"author-name":"Ian Cooper","training-data":{"loc-added":"39","loc-deleted":"20","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.0","delta-n-functions":"0","current-file-score":"10.0"},"author-email":"ian_hammond_cooper@yahoo.co.uk","commit-full-message":"* chore: fix casing on ADR\n\n* fix: update the ADR for a better understanding of how we propogate context\n\n* chore: update the name of InMemoryMessageProducer.cs to better fit the pattern used elsewhere\n\n* chore: swap Assert.True to Assert.Contains for collections\n\n* feat: failing test checks that we have added trace context to headers of outgoing message\n\n* feat: add a class to support trace state explicity\n\n* feat: modify tests\n\n* chore: filename issue\n\n* chore: switch to assert contains\n\n* feat: ensure that we propogate trace context\n\n* fix: allow trace context to serialize for tests\n\n* fixing broken tests\n\n* feat: add async tests\n\n* feat: add sync version of propogation tests\n\n* chore: whitespace\n\n* feat: add RMQ support for traceparent and tracestate.\n\n* fix: baggage is not tracecontext, although format is similar; baggage is user-defined\n\n* fix: tests were using tracestate not baggage\n\n* fix: crate link spans as MS committed change; propogate tracecontext and baggage through pipeline\n\n* fix: adjust test to ensure baggage on parent activity\n\n* fix: rename test class\n\n* chore: add tracestring and baggage to test\n\n* fix RMQ propogates the context\n\n* chore: port between RMQ instances\n\n* fix: add trace propogation to RMQ\n\n* fix: add kafka context propogation\n\n* chore: Add some primitive types to avoid primitive obsession warnings from codescene\n\n* chore: missing XML comments on public methods\n\n* chore: lower primitive obsession for message and request id\n\n* chore: usages of content type for new header\n\n* fix: adjust for reply to as a routing key\n\n* fix: add serialization for new value objects\n\n* chore: adjust docs\n\n* fix: issues with serialization of new primitive types\n\n* fix: ContentType.cs value may be null in constructor\n\n* fix: increase test delay as fragile\n\n* Update src/Paramore.Brighter/Id.cs\n\nCo-authored-by: Rafael Lillo <rafael.andrade@justeattakeaway.com>\n\n* fix: need to convert header types to primitives for bag\n\n* fix: make sync RMQ tests serial for reliability\n\n* fix: refactor LLM code\n\n* chore: move converters to own directory, add them for NewtonSoft for Kafka serdes\n\n* chore: remove spurious directory\n\n* fix: use a string base type for Id in a request, to make serializing it easily.\n\n* chore: unneeded namespace on attribute\n\n* feat: adding cloud events to Redis\n\n* fix: tests failing due to bad test string, does not use cloud events names\n\n* feat: add additional tests of persistence of message headers for new properties\n\n* fix: ASB tests need to check all properties\n\n* feat: use MS ContentType as used on public SDK and user defined type is awkward in that context (although MS type has limitations)\n\n* fix: body equality test not working\n\n* fix: errors with tests around cloud events transform; need to use strings, similar to params\n\n* fix: use charset with MS contenttype\n\n* feat: adding cloudevents support to ASB\n\n* feat: add cloud events and tracing to ASB\n\n* fix: correct tests for contenttype changes and cloudevents json specification\n\n* fix: correct for new content type\n\n---------\n\nCo-authored-by: Rafael Lillo <rafael.andrade@justeattakeaway.com>","commit-date":"2025-06-14T15:20:36Z","current-rev":"bc93b511c","filename":"Brighter/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageSender.cs","previous-rev":"5767656ad","commit-title":"OTel Transports (#3605)","language":"C#","id":"4136886c0cbe98b6d426b5645ff6ddf0f5b82421","model-score":0.49,"author-id":null,"project-id":32198,"delta-file-score":0.4636132,"diff":"diff --git a/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageSender.cs b/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageSender.cs\nindex 65e3b1f20..18a8d7a88 100644\n--- a/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageSender.cs\n+++ b/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageSender.cs\n@@ -4,2 +4,3 @@\n using System.Net;\n+using System.Net.Mime;\n using System.Text.Json;\n@@ -10,3 +11,5 @@\n using Microsoft.Extensions.Logging;\n+using Newtonsoft.Json;\n using Paramore.Brighter.Extensions;\n+using Paramore.Brighter.JsonConverters;\n using Paramore.Brighter.Logging;\n@@ -48,2 +51,16 @@ public SqsMessageSender(string queueUrl, SqsType queueType, AmazonSQSClient clie\n     public async Task<string?> SendAsync(Message message, TimeSpan? delay, CancellationToken cancellationToken)\n+    {\n+        var request = CreateSendMessageRequest(message, delay);\n+\n+        var response = await _client.SendMessageAsync(request, cancellationToken);\n+        if (response.HttpStatusCode is HttpStatusCode.OK or HttpStatusCode.Created\n+            or HttpStatusCode.Accepted)\n+        {\n+            return response.MessageId;\n+        }\n+\n+        return null;\n+    }\n+\n+    private SendMessageRequest CreateSendMessageRequest(Message message, TimeSpan? delay)\n     {\n@@ -51,3 +68,3 @@ public SqsMessageSender(string queueUrl, SqsType queueType, AmazonSQSClient clie\n         {\n-            QueueUrl = _queueUrl, \n+            QueueUrl = _queueUrl,\n             MessageBody = message.Body.Value\n@@ -55,2 +72,11 @@ public SqsMessageSender(string queueUrl, SqsType queueType, AmazonSQSClient clie\n \n+        SetMessageDelay(request, delay);\n+        SetFifoQueueProperties(request, message);\n+        SetMessageAttributes(request, message);\n+\n+        return request;\n+    }\n+\n+    private void SetMessageDelay(SendMessageRequest request, TimeSpan? delay)\n+    {\n         delay ??= TimeSpan.Zero;\n@@ -58,3 +84,2 @@ public SqsMessageSender(string queueUrl, SqsType queueType, AmazonSQSClient clie\n         {\n-            // SQS has a hard limit of 15min for Delay in Seconds\n             if (delay.Value > s_maxDelay)\n@@ -67,27 +92,30 @@ public SqsMessageSender(string queueUrl, SqsType queueType, AmazonSQSClient clie\n         }\n+    }\n \n-        if (_queueType == SqsType.Fifo)\n+    private void SetFifoQueueProperties(SendMessageRequest request, Message message)\n+    {\n+        if (_queueType != SqsType.Fifo) return;\n+        request.MessageGroupId = message.Header.PartitionKey;\n+        if (message.Header.Bag.TryGetValue(HeaderNames.DeduplicationId, out var deduplicationId))\n         {\n-            request.MessageGroupId = message.Header.PartitionKey;\n-            if (message.Header.Bag.TryGetValue(HeaderNames.DeduplicationId, out var deduplicationId))\n-            {\n-                request.MessageDeduplicationId = (string)deduplicationId;\n-            }\n+            request.MessageDeduplicationId = (string)deduplicationId;\n         }\n-        \n-        // Combine cloud event headers into a single JSON object\n+    }\n+\n+    private void SetMessageAttributes(SendMessageRequest request, Message message)\n+    {\n         string cloudEventHeadersJson = CreateCloudEventHeadersJson(message);\n \n-        // we can set up to 10 attributes;  we use a single JSON object as the cloud event headers; we can set nine others directly \n+        var contentType = message.Header.ContentType ?? new ContentType(MediaTypeNames.Text.Plain);\n         var messageAttributes = new Dictionary<string, MessageAttributeValue>\n-        { \n-            [HeaderNames.Id] = new (){ StringValue = message.Header.MessageId, DataType = \"String\" },\n+        {\n+            [HeaderNames.Id] = new() { StringValue = message.Header.MessageId, DataType = \"String\" },\n             [HeaderNames.CloudEventHeaders] = new() { StringValue = cloudEventHeadersJson, DataType = \"String\" },\n-            [HeaderNames.Topic] = new() { StringValue = _queueUrl ,DataType = \"String\" },\n+            [HeaderNames.Topic] = new() { StringValue = _queueUrl, DataType = \"String\" },\n             [HeaderNames.MessageType] = new() { StringValue = message.Header.MessageType.ToString(), DataType = \"String\" },\n-            [HeaderNames.ContentType] = new() { StringValue = message.Header.ContentType, DataType = \"String\" },\n+            [HeaderNames.ContentType] = new() { StringValue = contentType.ToString(), DataType = \"String\" },\n             [HeaderNames.Timestamp] = new() { StringValue = Convert.ToString(message.Header.TimeStamp.ToRfc3339()), DataType = \"String\" }\n         };\n-        \n-        if (!string.IsNullOrEmpty(message.Header.ReplyTo))\n+\n+        if (!RoutingKey.IsNullOrEmpty(message.Header.ReplyTo))\n             messageAttributes.Add(HeaderNames.ReplyTo, new MessageAttributeValue { StringValue = message.Header.ReplyTo, DataType = \"String\" });\n@@ -97,20 +125,10 @@ public SqsMessageSender(string queueUrl, SqsType queueType, AmazonSQSClient clie\n \n-        if (!string.IsNullOrEmpty(message.Header.CorrelationId))\n-            messageAttributes.Add(HeaderNames.CorrelationId,  new MessageAttributeValue { StringValue = message.Header.CorrelationId, DataType = \"String\" });\n-        \n-        //we have to add some attributes into our bag, to prevent overloading the message attributes\n+        if (!Id.IsNullOrEmpty(message.Header.CorrelationId))\n+            messageAttributes.Add(HeaderNames.CorrelationId, new MessageAttributeValue { StringValue = message.Header.CorrelationId, DataType = \"String\" });\n+\n         message.Header.Bag[HeaderNames.HandledCount] = message.Header.HandledCount.ToString(CultureInfo.InvariantCulture);\n-        \n-        var bagJson = JsonSerializer.Serialize(message.Header.Bag, JsonSerialisationOptions.Options);\n+\n+        var bagJson = System.Text.Json.JsonSerializer.Serialize(message.Header.Bag, JsonSerialisationOptions.Options);\n         messageAttributes[HeaderNames.Bag] = new() { StringValue = bagJson, DataType = \"String\" };\n         request.MessageAttributes = messageAttributes;\n-\n-        var response = await _client.SendMessageAsync(request, cancellationToken);\n-        if (response.HttpStatusCode is HttpStatusCode.OK or HttpStatusCode.Created\n-            or HttpStatusCode.Accepted)\n-        {\n-            return response.MessageId;\n-        }\n-\n-        return null;\n     }\n@@ -119,2 +137,3 @@ private static string CreateCloudEventHeadersJson(Message message)\n     {\n+        var contentType = message.Header.ContentType ?? new ContentType(MediaTypeNames.Text.Plain);\n         var cloudEventHeaders = new Dictionary<string, string>\n@@ -122,3 +141,3 @@ private static string CreateCloudEventHeadersJson(Message message)\n             [HeaderNames.Id] = Convert.ToString(message.Header.MessageId),\n-            [HeaderNames.DataContentType] = message.Header.ContentType ?? \"plain/text\",\n+            [HeaderNames.DataContentType] = contentType.ToString(),\n             [HeaderNames.DataSchema] = message.Header.DataSchema?.ToString() ?? string.Empty,\n@@ -139,3 +158,3 @@ private static string CreateCloudEventHeadersJson(Message message)\n \n-        var cloudEventHeadersJson = JsonSerializer.Serialize(cloudEventHeaders, JsonSerialisationOptions.Options);\n+        var cloudEventHeadersJson = System.Text.Json.JsonSerializer.Serialize(cloudEventHeaders, JsonSerialisationOptions.Options);\n         return cloudEventHeadersJson;\n@@ -149,2 +168 @@ private static partial class Log\n }\n-\n","improvement-type":"Complex Method"},{"architectural-component-id":null,"author-name":"Ian Cooper","training-data":{"loc-added":"17","loc-deleted":"16","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.0","delta-n-functions":"0","current-file-score":"8.816158827775617"},"author-email":"ian_hammond_cooper@yahoo.co.uk","commit-full-message":"Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>\nClaude-Session: https://claude.ai/code/session_01HsKD52dnGHFLSEr93VZyR7","commit-date":"2026-10-12T13:23:04Z","current-rev":"90502e627","filename":"Brighter/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxDetectionHelper.cs","previous-rev":"7aca96a83","commit-title":"refactor: extract methods to express intent in BoxProvisioning.PostgreSql","language":"C#","id":"b7d978856416855c51d6c33293e8dacf04776f5b","model-score":0.3,"author-id":null,"project-id":32198,"delta-file-score":0.7845205,"diff":"diff --git a/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxDetectionHelper.cs b/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxDetectionHelper.cs\nindex 3b5bcf962..525808711 100644\n--- a/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxDetectionHelper.cs\n+++ b/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxDetectionHelper.cs\n@@ -115,19 +115,4 @@ public async Task<bool> DoesHistoryExistAsync(\n \n-        // System-table existence: __BrighterMigrationHistory is created via quoted DDL\n-        // (`CREATE TABLE IF NOT EXISTS <schema>.\"__BrighterMigrationHistory\"`), so its name\n-        // is case-PRESERVED in pg_class. Routing through DoesTableExistAsync would lowercase\n-        // the lookup to `'__brightermigrationhistory'` and miss. Inline the literal-name check,\n-        // parameterising only the (folded) schema.\n-        using (var existsCmd = connection.CreateCommand())\n-        {\n-            if (transaction != null) existsCmd.Transaction = transaction;\n-            existsCmd.CommandText = @\"\n-SELECT EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.TABLES\n-WHERE TABLE_SCHEMA = @HistorySchema AND TABLE_NAME = '__BrighterMigrationHistory')\";\n-            existsCmd.Parameters.AddWithValue(\"@HistorySchema\", foldedHistorySchema);\n-            var existsRaw = await existsCmd.ExecuteScalarAsync(cancellationToken);\n-            var historyTableExists = existsRaw is bool b && b;\n-            if (!historyTableExists)\n-                return false;\n-        }\n+        if (!await HistoryTableExistsAsync(connection, foldedHistorySchema, cancellationToken, transaction))\n+            return false;\n \n@@ -159,2 +144,18 @@ SELECT COUNT(1) FROM {quotedHistorySchema}.\"\"__BrighterMigrationHistory\"\"\n \n+    // The history table is created with a quoted name, so its case is preserved; this cannot use\n+    // DoesTableExistAsync, which folds the name to lowercase.\n+    private static async Task<bool> HistoryTableExistsAsync(\n+        NpgsqlConnection connection, string foldedHistorySchema,\n+        CancellationToken cancellationToken, NpgsqlTransaction? transaction)\n+    {\n+        using var command = connection.CreateCommand();\n+        if (transaction != null) command.Transaction = transaction;\n+        command.CommandText = @\"\n+SELECT EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.TABLES\n+WHERE TABLE_SCHEMA = @HistorySchema AND TABLE_NAME = '__BrighterMigrationHistory')\";\n+        command.Parameters.AddWithValue(\"@HistorySchema\", foldedHistorySchema);\n+        var raw = await command.ExecuteScalarAsync(cancellationToken);\n+        return raw is bool exists && exists;\n+    }\n+\n     /// <summary>\n","improvement-type":"Complex Method"},{"architectural-component-id":null,"author-name":"Steve Bush","training-data":{"loc-added":"46","loc-deleted":"63","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.17","delta-n-functions":"0","current-file-score":"10.0"},"author-email":"stevebu@bushchang.com","commit-full-message":"* Refactoring of MQTT Support to use 4.3 MQTTnet\n\n* Removed MQTTnet v5 support for UserProperties.  Removed Comments.\n\n* Fix logging of Exception when Test context is not available\n\n* Increase wait to 1 sec before testing for number of messages\n\n* SpinUntil instead of trying to time when requests will be processed\n\n* Update target platforms for test helpers to net8.0;net9.0\n\n* Adjust timeout to see if all messages are processed.\n\n* Reworking logging to reduce logging for routine message delivery\n\n* Fixed static Log class merge errors\n\n* Fix up passing of exception and port to new Log API.","commit-date":"2025-04-09T08:57:56Z","current-rev":"099708800","filename":"Brighter/src/Paramore.Brighter.MessagingGateway.MQTT/MQTTMessageConsumer.cs","previous-rev":"0741b9ef1","commit-title":"feature: refactoring of MQTT Support to use 4.3 MQTTnet (#3578)","language":"C#","id":"d27e8bc6b9d615c647eca3faefa2e0371bd11b02","model-score":0.3,"author-id":null,"project-id":32198,"delta-file-score":0.51462585,"diff":"diff --git a/src/Paramore.Brighter.MessagingGateway.MQTT/MQTTMessageConsumer.cs b/src/Paramore.Brighter.MessagingGateway.MQTT/MQTTMessageConsumer.cs\nindex 974658e30..dfeca6cff 100644\n--- a/src/Paramore.Brighter.MessagingGateway.MQTT/MQTTMessageConsumer.cs\n+++ b/src/Paramore.Brighter.MessagingGateway.MQTT/MQTTMessageConsumer.cs\n@@ -1,5 +1,3 @@\n ﻿using System;\n-using System.Buffers;\n using System.Collections.Generic;\n-using System.Text;\n using System.Text.Json;\n@@ -9,2 +7,3 @@\n using MQTTnet;\n+using MQTTnet.Client;\n using MQTTnet.Packets;\n@@ -16,12 +15,12 @@ namespace Paramore.Brighter.MessagingGateway.MQTT\n     /// <summary>\n-    /// Class MQTTMessageConsumer.\n-    /// The <see cref=\"MQTTMessageConsumer\"/> is used on the server to receive messages from the broker. It abstracts away the details of \n+    /// Class MqttMessageConsumer.\n+    /// The <see cref=\"MqttMessageConsumer\"/> is used on the server to receive messages from the broker. It abstracts away the details of \n     /// inter-process communication tasks from the server. It handles subscription establishment, request reception and dispatching.\n     /// </summary>\n-    public partial class MQTTMessageConsumer : IAmAMessageConsumerSync, IAmAMessageConsumerAsync\n+    public partial class MqttMessageConsumer : IAmAMessageConsumerSync, IAmAMessageConsumerAsync\n     {\n         private readonly string _topic;\n-        private readonly Queue<Message> _messageQueue = new Queue<Message>();\n-        private static readonly ILogger s_logger = ApplicationLogging.CreateLogger<MQTTMessageConsumer>();\n-        private readonly Message _noopMessage = new Message();\n+        private readonly Queue<Message> _messageQueue = new();\n+        private static readonly ILogger s_logger = ApplicationLogging.CreateLogger<MqttMessageConsumer>();\n+        private readonly Message _noopMessage = new();\n         private readonly IMqttClient _mqttClient;\n@@ -30,10 +29,22 @@ public partial class MQTTMessageConsumer : IAmAMessageConsumerSync, IAmAMessageC\n         /// <summary>\n-        /// Initializes a new instance of the <see cref=\"MQTTMessageConsumer\" /> class.\n-        /// Sync over Async within constructor\n+        /// Initializes a new instance of the <see cref=\"MqttMessageConsumer\"/> class.\n         /// </summary>\n-        /// <param name=\"configuration\"></param>\n-        public MQTTMessageConsumer(MQTTMessagingGatewayConsumerConfiguration configuration)\n+        /// <param name=\"configuration\">\n+        /// The configuration settings for the MQTT message consumer, including connection details, \n+        /// topic prefix, client credentials, and other options.\n+        /// </param>\n+        /// <exception cref=\"ArgumentNullException\">\n+        /// Thrown when the <paramref name=\"configuration.TopicPrefix\"/> is null.\n+        /// </exception>\n+        /// <remarks>\n+        /// This constructor sets up the MQTT client with the provided configuration, establishes \n+        /// the connection to the broker, and subscribes to the specified topic.\n+        ///\n+        /// 04/03/2025:\n+        ///     - Removed support for user properties as they are not supported in v3.1.1 of the MQTT protocol.\n+        /// </remarks>\n+        public MqttMessageConsumer(MqttMessagingGatewayConsumerConfiguration configuration)\n         {\n-            _topic =  $\"{configuration.TopicPrefix}/#\" ?? throw new ArgumentNullException(nameof(configuration.TopicPrefix));\n-            \n+            _topic = $\"{configuration.TopicPrefix}/#\" ?? throw new ArgumentNullException(nameof(configuration.TopicPrefix));\n+\n             MqttClientOptionsBuilder mqttClientOptionsBuilder = new MqttClientOptionsBuilder()\n@@ -52,7 +63,9 @@ public MQTTMessageConsumer(MQTTMessagingGatewayConsumerConfiguration configurati\n \n-            _mqttClientOptions = mqttClientOptionsBuilder.Build();\n+            _mqttClientOptions = mqttClientOptionsBuilder\n+                .WithTcpServer(configuration.Hostname, configuration.Port)\n+                .Build();\n \n-            //TODO: Switch to using the low level client here, as it allows us explicit control over ack, recieve etc.\n+            //TODO: Switch to using the low level client here, as it allows us explicit control over ack, receive etc.\n             //This is slated for post V10, for now, we just want to upgrade this support the V10 release\n-            _mqttClient = new MqttClientFactory().CreateMqttClient();\n+            _mqttClient = new MqttFactory().CreateMqttClient();\n \n@@ -61,36 +74,4 @@ public MQTTMessageConsumer(MQTTMessagingGatewayConsumerConfiguration configurati\n                 Log.MqttMessageConsumerReceivedMessage(s_logger, configuration.TopicPrefix);\n-                var message = JsonSerializer.Deserialize<Message>(e.ApplicationMessage.Payload.ToArray(), JsonSerialisationOptions.Options);\n-                foreach (MqttUserProperty property in e.ApplicationMessage.UserProperties)\n-                {\n-                    if (property.Name == HeaderNames.Type)\n-                    {\n-                        message.Header.Type = property.Value;\n-                    }\n-                    else if (property.Name == HeaderNames.SpecVersion)\n-                    {\n-                        message.Header.SpecVersion = property.Value;\n-                    }\n-                    else if (property.Name == HeaderNames.Source)\n-                    {\n-                        if (Uri.TryCreate(property.Value, UriKind.RelativeOrAbsolute, out var source))\n-                        {\n-                            message.Header.Source = source;\n-                        }\n-                    }\n-                    else if (property.Name == HeaderNames.Subject)\n-                    {\n-                        message.Header.Subject = property.Value;\n-                    }\n-                    else if (property.Name == HeaderNames.DataContentType)\n-                    {\n-                        message.Header.ContentType = property.Value;\n-                    }\n-                    else if (property.Name == HeaderNames.DataSchema)\n-                    {\n-                        if (Uri.TryCreate(property.Value, UriKind.RelativeOrAbsolute, out var dataSchema))\n-                        {\n-                            message.Header.DataSchema = dataSchema;\n-                        }\n-                    }\n-                }\n+                var message = JsonSerializer.Deserialize<Message>(e.ApplicationMessage.PayloadSegment.ToArray(), JsonSerialisationOptions.Options);\n+\n                 _messageQueue.Enqueue(message);\n@@ -112,3 +93,3 @@ public void Acknowledge(Message message)\n         }\n-        \n+\n         /// <summary>\n@@ -117,3 +98,3 @@ public void Acknowledge(Message message)\n         /// <param name=\"message\"></param>\n-        public Task AcknowledgeAsync(Message message, CancellationToken cancellationToken = default(CancellationToken))\n+        public Task AcknowledgeAsync(Message message, CancellationToken cancellationToken = default)\n         {\n@@ -127,8 +108,8 @@ public void Dispose()\n         }\n-        \n-        \n+\n+\n         public ValueTask DisposeAsync()\n         {\n-           _mqttClient.Dispose();\n-           return new ValueTask(Task.CompletedTask);\n+            _mqttClient.Dispose();\n+            return new ValueTask(Task.CompletedTask);\n         }\n@@ -142,3 +123,3 @@ public void Purge()\n         }\n-        \n+\n         /// <summary>\n@@ -147,6 +128,6 @@ public void Purge()\n         /// <param name=\"cancellationToken\">Allows cancellation of the purge task</param>\n-        public Task PurgeAsync(CancellationToken cancellationToken = default(CancellationToken))\n+        public Task PurgeAsync(CancellationToken cancellationToken = default)\n         {\n-           Purge();\n-           return Task.CompletedTask;\n+            Purge();\n+            return Task.CompletedTask;\n         }\n@@ -159,4 +140,6 @@ public Message[] Receive(TimeSpan? timeOut = null)\n         {\n-            if (_messageQueue.Count==0)\n+            if (_messageQueue.Count == 0)\n+            {\n                 return new[] { _noopMessage };\n+            }\n \n@@ -175,5 +158,5 @@ public Message[] Receive(TimeSpan? timeOut = null)\n                     }\n-                    catch (TimeoutException)\n+                    catch (TimeoutException te)\n                     {\n-                        Log.MqttMessageConsumerTimedOutRetrievingMessages(s_logger, _messageQueue.Count);\n+                        Log.MqttMessageConsumerTimedOutRetrievingMessages(s_logger, te, _messageQueue.Count);\n                     }\n@@ -184,4 +167,4 @@ public Message[] Receive(TimeSpan? timeOut = null)\n         }\n-        \n-        public Task<Message[]> ReceiveAsync(TimeSpan? timeOut = null, CancellationToken cancellationToken = default(CancellationToken))\n+\n+        public Task<Message[]> ReceiveAsync(TimeSpan? timeOut = null, CancellationToken cancellationToken = default)\n         {\n@@ -203,3 +186,3 @@ public void Reject(Message message)\n         /// <param name=\"cancellationToken\"></param>\n-        public Task RejectAsync(Message message, CancellationToken cancellationToken = default(CancellationToken))\n+        public Task RejectAsync(Message message, CancellationToken cancellationToken = default)\n         {\n@@ -218,5 +201,5 @@ public bool Requeue(Message message, TimeSpan? delay = null)\n         }\n-        \n+\n         public Task<bool> RequeueAsync(Message message, TimeSpan? delay = null,\n-            CancellationToken cancellationToken = default(CancellationToken))\n+            CancellationToken cancellationToken = default)\n         {\n@@ -239,5 +222,5 @@ private async Task Connect(int connectionAttempts)\n                 }\n-                catch (Exception)\n+                catch (Exception ex)\n                 {\n-                    Log.UnableToConnectMqttConsumerClient(s_logger);\n+                    Log.UnableToConnectMqttConsumerClient(s_logger, ex);\n                 }\n@@ -248,7 +231,7 @@ private static partial class Log\n         {\n-            [LoggerMessage(LogLevel.Information, \"MQTTMessageConsumer: Received message from queue {TopicPrefix}\")]\n+            [LoggerMessage(LogLevel.Trace, \"MQTTMessageConsumer: Received message from queue {TopicPrefix}\")]\n             public static partial void MqttMessageConsumerReceivedMessage(ILogger logger, object topicPrefix);\n \n-            [LoggerMessage(LogLevel.Warning, \"MQTTMessageConsumer: Timed out retrieving messages.  Queue length: {QueueLength}\")]\n-            public static partial void MqttMessageConsumerTimedOutRetrievingMessages(ILogger logger, int queueLength);\n+            [LoggerMessage(Level = LogLevel.Warning, Message = \"MQTTMessageConsumer: Timed out retrieving messages.  Queue length: {QueueLength}\")]\n+            public static partial void MqttMessageConsumerTimedOutRetrievingMessages(ILogger logger, Exception ex, int queueLength);\n \n@@ -259,5 +242,5 @@ private static partial class Log\n             public static partial void SubscribedToTopic(ILogger logger, string topic);\n-            \n-            [LoggerMessage(LogLevel.Error, \"Unable to connect MQTT Consumer Client\")]\n-            public static partial void UnableToConnectMqttConsumerClient(ILogger logger);\n+\n+            [LoggerMessage(Level = LogLevel.Error, Message = \"Unable to connect MQTT Consumer Client\")]\n+            public static partial void UnableToConnectMqttConsumerClient(ILogger logger, Exception ex);\n         }\n","improvement-type":"Complex Method"},{"architectural-component-id":null,"author-name":"Tom Longhurst","training-data":{"loc-added":"74","loc-deleted":"33","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.0","delta-n-functions":"0","current-file-score":"9.387218218812514"},"author-email":"30480171+thomhurst@users.noreply.github.com","commit-full-message":"* fix: serialise Dispatcher.Start so consumers are Open before Receive() returns (#4075)\n\nDispatcher.Start() flipped State to DS_RUNNING before opening consumers, so\nReceive()'s busy-wait could return while some consumers were still Shut. A\nShut()/End() racing into that window no-op'd against not-yet-Open consumers\n(Consumer.Shut only acts when State == Open). The control task then opened\nthose consumers, leaving orphan performers parked in Task.Delay forever and\nhanging End() in Task.WaitAny.\n\nOpen every consumer and register its task before publishing DS_RUNNING, and\nreplace the 100ms poll with a TaskCompletionSource that gives callers an\nexplicit happens-before edge over the opens. Add a lock + pending-shut flag\non Consumer so a Shut() arriving before Open() is honoured (defence in depth\nfor any future caller path that opens off the control task).\n\n* chore: trim verbose comments on #4075 fix\n\n* refactor: flatten Dispatcher.Start nesting (CodeScene Bumpy Road)\n\nExtract control-loop body into RunControlLoop, then split into\nTryOpenConsumers, WaitForPerformersToStop, HandleNextStoppedPerformer,\nand RemoveConsumerForTask. Each helper has at most one level of\nconditional nesting, killing the \"Bumpy Road Ahead\" flag on\nPR #4081 without changing behavior.\n\n* refactor: simplify TryOpenConsumers and drop redundant OfType\n\n- Collapse TryOpenConsumers (bool, dead false-branch) into void\n  OpenConsumers; move TCS signalling and try/catch up into\n  RunControlLoop where they belong.\n- Iterate Consumers directly instead of OfType<Consumer>(); the\n  IAmAConsumer interface already exposes Open/Job/JobId.\n\n---------\n\nCo-authored-by: Ian Cooper <ian_hammond_cooper@yahoo.co.uk>","commit-date":"2026-04-26T17:18:29Z","current-rev":"f94246cd8","filename":"Brighter/src/Paramore.Brighter.ServiceActivator/Dispatcher.cs","previous-rev":"3a0528638","commit-title":"fix: Dispatcher shutdown race leaves late-opened Reactor consumers running (#4075) (#4081)","language":"C#","id":"b453d2853c4228105b707fea96483f93cd8ee3c1","model-score":0.1,"author-id":null,"project-id":32198,"delta-file-score":0.84183866,"diff":"diff --git a/src/Paramore.Brighter.ServiceActivator/Dispatcher.cs b/src/Paramore.Brighter.ServiceActivator/Dispatcher.cs\nindex 8abdbe43d..a9ca4b575 100644\n--- a/src/Paramore.Brighter.ServiceActivator/Dispatcher.cs\n+++ b/src/Paramore.Brighter.ServiceActivator/Dispatcher.cs\n@@ -284,63 +284,104 @@ private void Start()\n         {\n-            _controlTask = Task.Factory.StartNew(() =>\n+            // Block Start() callers until every consumer is Open. A Shut()/End() racing in\n+            // immediately after Receive() returns must not see a still-Shut consumer, or the\n+            // late-opened performer leaks and End() hangs forever in Task.WaitAny.\n+            var startup = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);\n+\n+            _controlTask = Task.Factory.StartNew(\n+                () => RunControlLoop(startup),\n+                CancellationToken.None,\n+                TaskCreationOptions.LongRunning,\n+                TaskScheduler.Default);\n+\n+            startup.Task.GetAwaiter().GetResult();\n+        }\n+\n+        private void RunControlLoop(TaskCompletionSource<bool> startup)\n+        {\n+            if (State != DispatcherState.DS_AWAITING && State != DispatcherState.DS_STOPPED)\n             {\n-                if (State == DispatcherState.DS_AWAITING || State == DispatcherState.DS_STOPPED)\n-                {\n-                    Log.DispatcherStarting(s_logger);\n-                    State = DispatcherState.DS_RUNNING;\n+                startup.TrySetResult(true);\n+                return;\n+            }\n+\n+            Log.DispatcherStarting(s_logger);\n+\n+            try\n+            {\n+                OpenConsumers();\n+                State = DispatcherState.DS_RUNNING;\n+                startup.TrySetResult(true);\n+            }\n+            catch (Exception ex)\n+            {\n+                Log.ErrorOnConsumer(s_logger, ex);\n+                startup.TrySetException(ex);\n+                throw;\n+            }\n+\n+            Log.DispatcherStartingPerformers(s_logger, _tasks.Count);\n \n-                    var consumers = Consumers.ToArray();\n-                    consumers.Each(consumer => consumer.Open());\n-                    consumers.Each(consumer => _tasks.TryAdd(consumer.JobId, consumer.Job!));\n+            WaitForPerformersToStop();\n+\n+            State = DispatcherState.DS_STOPPED;\n+            Log.DispatcherStopped(s_logger);\n+        }\n \n-                    Log.DispatcherStartingPerformers(s_logger, _tasks.Count);\n+        private void OpenConsumers()\n+        {\n+            foreach (var consumer in Consumers)\n+            {\n+                consumer.Open();\n+                if (consumer.Job is not null)\n+                    _tasks.TryAdd(consumer.JobId, consumer.Job);\n+            }\n+        }\n \n-                    while (_tasks.Any())\n+        private void WaitForPerformersToStop()\n+        {\n+            while (!_tasks.IsEmpty)\n+            {\n+                try\n+                {\n+                    HandleNextStoppedPerformer();\n+                }\n+                catch (AggregateException ae)\n+                {\n+                    ae.Handle(ex =>\n                     {\n-                        try\n-                        {\n-                            var runningTasks = _tasks.Values.ToArray();\n-                            var index = Task.WaitAny(runningTasks);\n-                            var stoppingConsumer = runningTasks[index];\n-                            Log.PerformerStopped(s_logger, stoppingConsumer.Status);\n-\n-                            var consumer = Consumers.SingleOrDefault(c => c.JobId == stoppingConsumer.Id);\n-                            if (consumer != null)\n-                            {\n-                                Log.RemovingConsumer(s_logger, consumer.Name);\n-\n-                                if (_consumers.TryRemove(consumer.Name, out consumer))\n-                                {\n-                                    consumer.Dispose();\n-                                }\n-                            }\n-\n-                            if (_tasks.TryRemove(stoppingConsumer.Id, out var removedTask))\n-                            {\n-                                removedTask?.Dispose();\n-                            }\n-\n-                            stoppingConsumer.Dispose();\n-                        }\n-                        catch (AggregateException ae)\n-                        {\n-                            ae.Handle(ex =>\n-                            {\n-                                Log.ErrorOnConsumer(s_logger, ex);\n-                                return true;\n-                            });\n-                        }\n-                    }\n-\n-                    State = DispatcherState.DS_STOPPED;\n-                    Log.DispatcherStopped(s_logger);\n+                        Log.ErrorOnConsumer(s_logger, ex);\n+                        return true;\n+                    });\n                 }\n-            },\n-            CancellationToken.None,\n-            TaskCreationOptions.LongRunning,\n-            TaskScheduler.Default);\n+            }\n+        }\n+\n+        private void HandleNextStoppedPerformer()\n+        {\n+            var runningTasks = _tasks.Values.ToArray();\n+            var index = Task.WaitAny(runningTasks);\n+            var stoppingConsumer = runningTasks[index];\n+            Log.PerformerStopped(s_logger, stoppingConsumer.Status);\n+\n+            RemoveConsumerForTask(stoppingConsumer);\n+\n+            if (_tasks.TryRemove(stoppingConsumer.Id, out var removedTask))\n+            {\n+                removedTask?.Dispose();\n+            }\n+\n+            stoppingConsumer.Dispose();\n+        }\n+\n+        private void RemoveConsumerForTask(Task stoppingConsumer)\n+        {\n+            var consumer = Consumers.SingleOrDefault(c => c.JobId == stoppingConsumer.Id);\n+            if (consumer is null)\n+                return;\n+\n+            Log.RemovingConsumer(s_logger, consumer.Name);\n \n-            while (State != DispatcherState.DS_RUNNING)\n+            if (_consumers.TryRemove(consumer.Name, out consumer))\n             {\n-                Thread.Sleep(100); //Block main Dispatcher thread whilst control plane starts\n+                consumer.Dispose();\n             }\n","improvement-type":"Complex Method"},{"architectural-component-id":null,"author-name":"Ian Cooper","training-data":{"loc-added":"30","loc-deleted":"42","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.0","delta-n-functions":"0","current-file-score":"8.816158827775617"},"author-email":"ian_hammond_cooper@yahoo.co.uk","commit-full-message":"Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>\nClaude-Session: https://claude.ai/code/session_01HsKD52dnGHFLSEr93VZyR7","commit-date":"2026-10-12T13:23:04Z","current-rev":"90502e627","filename":"Brighter/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxMigrationRunner.cs","previous-rev":"7aca96a83","commit-title":"refactor: extract methods to express intent in BoxProvisioning.PostgreSql","language":"C#","id":"0d77d6fdfc8105fa700f57319eb18dbc943942d9","model-score":0.1,"author-id":null,"project-id":32198,"delta-file-score":0.27077925,"diff":"diff --git a/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxMigrationRunner.cs b/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxMigrationRunner.cs\nindex 6a49eb25c..0634c4503 100644\n--- a/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxMigrationRunner.cs\n+++ b/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxMigrationRunner.cs\n@@ -118,14 +118,14 @@ protected override string LockResourceFor(string? schemaName, string tableName)\n \n-    // Quoted, and so folded, the same way the detection helper reads it.\n-    private string QuotedHistorySchema()\n+    // Never null here: DefaultHistorySchema is \"public\", and the base rejects PerSchema without a\n+    // SchemaName before migrating.\n+    private string ValidatedHistorySchema()\n     {\n-        // The `!` is safe: DefaultHistorySchema returns the non-null \"public\" const on this runner\n-        // and the D3 guard rejects PerSchema with a null SchemaName before MigrateAsync proceeds,\n-        // so ResolveHistorySchema() is provably non-null here. If a future refactor breaks that\n-        // invariant, NRE points at this line.\n-        var schema = ResolveHistorySchema()!;\n-        Identifiers.AssertSafe(schema, nameof(schema));\n-        return PgIdentifier.Quote(schema);\n+        var resolvedHistorySchema = ResolveHistorySchema()!;\n+        Identifiers.AssertSafe(resolvedHistorySchema, nameof(resolvedHistorySchema));\n+        return resolvedHistorySchema;\n     }\n \n+    // Quoted, and so folded, the same way the detection helper reads it.\n+    private string QuotedHistorySchema() => PgIdentifier.Quote(ValidatedHistorySchema());\n+\n     protected override async Task EnsureHistoryTableAsync(\n@@ -134,11 +134,3 @@ protected override async Task EnsureHistoryTableAsync(\n     {\n-        // Resolve the physical history schema once. Under PerSchema it's the configured (non-null)\n-        // SchemaName; under Global it is the backend default (\"public\"). The detection helper folds\n-        // the same value the same way (PgIdentifier.Quote / Normalize), so write and read never\n-        // diverge. AssertSafe guards against any unsafe schema literal leaking into the inline DDL.\n-        // The `!` is safe: DefaultHistorySchema returns the non-null \"public\" const on this runner\n-        // and the D3 guard rejects PerSchema with a null SchemaName before MigrateAsync proceeds,\n-        // so ResolveHistorySchema() is provably non-null here.\n-        var resolvedHistorySchema = ResolveHistorySchema()!;\n-        Identifiers.AssertSafe(resolvedHistorySchema, nameof(resolvedHistorySchema));\n+        var resolvedHistorySchema = ValidatedHistorySchema();\n         var historySchemaQuoted = PgIdentifier.Quote(resolvedHistorySchema);\n@@ -146,14 +138,24 @@ protected override async Task EnsureHistoryTableAsync(\n \n-        // D5 (ADR 0060): on a PerSchema run that follows a Global predecessor, copy this tenant's\n-        // prior history rows from the legacy public.__BrighterMigrationHistory so the runner does\n-        // NOT mis-detect the box as needing a bootstrap re-stamp (which would silently re-run\n-        // migration accounting and break FR5). Skipped when the folded resolved history schema\n-        // equals the folded backend default (Global, or PerSchema with SchemaName == \"public\") —\n-        // then per-schema and legacy are the same table and there is nothing to copy.\n-        var needsSeedCheck = !string.Equals(historySchemaFolded, HISTORY_TABLE_SCHEMA, StringComparison.Ordinal);\n+        var historyIsSeparateFromLegacy = !string.Equals(historySchemaFolded, HISTORY_TABLE_SCHEMA, StringComparison.Ordinal);\n \n-        using (var command = connection.CreateCommand())\n+        await CreateHistoryTableAsync(connection, transaction, historySchemaQuoted, cancellationToken);\n+\n+        if (historyIsSeparateFromLegacy)\n         {\n-            command.Transaction = transaction;\n-            command.CommandText = $@\"\n+            await SeedHistoryFromLegacyAsync(\n+                connection, transaction, historySchemaQuoted, resolvedHistorySchema,\n+                schemaName ?? resolvedHistorySchema, tableName, cancellationToken);\n+        }\n+    }\n+\n+    // A provisioner for another box can race this CREATE (ADR 0057 §3). Postgres aborts the whole\n+    // transaction on the loser's duplicate error even when it is caught, so the CREATE runs inside\n+    // a savepoint that the catch rolls back to.\n+    private async Task CreateHistoryTableAsync(\n+        NpgsqlConnection connection, NpgsqlTransaction? transaction, string historySchemaQuoted,\n+        CancellationToken cancellationToken)\n+    {\n+        using var command = connection.CreateCommand();\n+        command.Transaction = transaction;\n+        command.CommandText = $@\"\n CREATE TABLE IF NOT EXISTS {historySchemaQuoted}.\"\"{MIGRATION_HISTORY_TABLE}\"\" (\n@@ -166,43 +168,29 @@ PRIMARY KEY (\"\"SchemaName\"\", \"\"BoxTableName\"\", \"\"MigrationVersion\"\")\n )\";\n-            // Postgres marks the outer transaction as aborted on a catalog-level duplicate-type\n-            // error from CREATE TABLE IF NOT EXISTS regardless of whether we catch it. Without a\n-            // savepoint the catch below leaves the transaction \"poisoned\" — RedetectStateAsync's\n-            // next statement then fails with 25P02 even though our swallow was intentional. A\n-            // SAVEPOINT around the CREATE narrows the abort to the inner sub-transaction, so\n-            // ROLLBACK TO SAVEPOINT restores a usable transaction state on the racing path.\n+        if (transaction is not null)\n+        {\n+            await transaction.SaveAsync(HistoryTableSavepoint, cancellationToken);\n+        }\n+        try\n+        {\n+            await command.ExecuteNonQueryAsync(cancellationToken);\n             if (transaction is not null)\n             {\n-                await transaction.SaveAsync(HistoryTableSavepoint, cancellationToken);\n-            }\n-            try\n-            {\n-                await command.ExecuteNonQueryAsync(cancellationToken);\n-                if (transaction is not null)\n-                {\n-                    await transaction.ReleaseAsync(HistoryTableSavepoint, cancellationToken);\n-                }\n+                await transaction.ReleaseAsync(HistoryTableSavepoint, cancellationToken);\n             }\n-            catch (PostgresException ex) when (\n-                ex.SqlState == PostgresErrorCodes.UniqueViolation\n-                || ex.SqlState == PostgresErrorCodes.DuplicateTable\n-                || ex.SqlState == PostgresErrorCodes.DuplicateObject)\n+        }\n+        catch (PostgresException ex) when (\n+            ex.SqlState == PostgresErrorCodes.UniqueViolation\n+            || ex.SqlState == PostgresErrorCodes.DuplicateTable\n+            || ex.SqlState == PostgresErrorCodes.DuplicateObject)\n+        {\n+            if (transaction is not null)\n             {\n-                if (transaction is not null)\n-                {\n-                    await transaction.RollbackAsync(HistoryTableSavepoint, cancellationToken);\n-                }\n-\n-                Logger.LogDebug(ex,\n-                    \"{HistoryTable} already created by racing session (Postgres SqlState {SqlState})\",\n-                    MIGRATION_HISTORY_TABLE, ex.SqlState);\n-                Activity.Current?.AddEvent(new ActivityEvent(\n-                    BrighterSemanticConventions.BoxMigrationEventHistoryTableRaceSwallowed));\n+                await transaction.RollbackAsync(HistoryTableSavepoint, cancellationToken);\n             }\n-        }\n \n-        if (needsSeedCheck)\n-        {\n-            await SeedHistoryFromLegacyAsync(\n-                connection, transaction, historySchemaQuoted, resolvedHistorySchema,\n-                schemaName ?? resolvedHistorySchema, tableName, cancellationToken);\n+            Logger.LogDebug(ex,\n+                \"{HistoryTable} already created by racing session (Postgres SqlState {SqlState})\",\n+                MIGRATION_HISTORY_TABLE, ex.SqlState);\n+            Activity.Current?.AddEvent(new ActivityEvent(\n+                BrighterSemanticConventions.BoxMigrationEventHistoryTableRaceSwallowed));\n         }\n@@ -301,3 +289,3 @@ SELECT 1 FROM {perSchemaQuoted}.\"\"{MIGRATION_HISTORY_TABLE}\"\" AS tgt\n     private static bool IsLegacyHistoryReadPermissionDenied(PostgresException ex) =>\n-        ex.SqlState == \"42501\";\n+        ex.SqlState == PostgresErrorCodes.InsufficientPrivilege;\n \n","improvement-type":"Complex Method"},{"architectural-component-id":null,"author-name":"Ian Cooper","training-data":{"loc-added":"69","loc-deleted":"78","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.944","delta-n-functions":"0","current-file-score":"8.715400157423334"},"author-email":"ian_hammond_cooper@yahoo.co.uk","commit-full-message":"Replace explanatory comments in SqlBoxMigrationRunner.MigrateAsync,\nSqlBoxProvisioner.ProvisionAsync and UseBoxProvisioning with private\nmethods whose names carry the intent (GuardIdentifiers, GetMigrations,\nRollbackWithoutMaskingAsync, ReleaseAsync, ReadHistoryExistsHintAsync,\nRegisterProvisionersThenMarker, ...), keeping a short comment above a\nsignature only where the name cannot carry a trap.\n\nCo-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>\nClaude-Session: https://claude.ai/code/session_01HsKD52dnGHFLSEr93VZyR7","commit-date":"2026-10-11T18:52:01Z","current-rev":"5253c5133","filename":"Brighter/src/Paramore.Brighter.BoxProvisioning/SqlBoxMigrationRunner.cs","previous-rev":"0dcac0a6e","commit-title":"refactor: extract methods to express intent in BoxProvisioning","language":"C#","id":"7f99866c7425afba46bf58093b14e41f01bacae6","model-score":0.02,"author-id":null,"project-id":32198,"delta-file-score":0.15510798,"diff":"diff --git a/src/Paramore.Brighter.BoxProvisioning/SqlBoxMigrationRunner.cs b/src/Paramore.Brighter.BoxProvisioning/SqlBoxMigrationRunner.cs\nindex 33df98923..491109e0e 100644\n--- a/src/Paramore.Brighter.BoxProvisioning/SqlBoxMigrationRunner.cs\n+++ b/src/Paramore.Brighter.BoxProvisioning/SqlBoxMigrationRunner.cs\n@@ -182,49 +182,6 @@ public async Task MigrateAsync(\n     {\n-        // Defence-in-depth at the framework chokepoint. Catalogs gate AssertSafe at the entry to\n-        // All(...), but the runner is independently reachable (callers can construct a migration\n-        // list and invoke MigrateAsync directly), so the public entry point must validate too.\n-        Identifiers.AssertSafe(tableName.Value, nameof(tableName));\n-\n-        // schemaName is optional: SQLite has no schema concept per ADR 0057 §6, so an absent value\n-        // is legitimate and must not be rejected as \"missing\". A SchemaName is \"absent\" when it is\n-        // a null reference OR wraps a null/empty string — callers commonly reach the latter via the\n-        // implicit string->SchemaName conversion of a null/empty value (e.g. an unconfigured\n-        // RelationalDatabaseConfiguration.SchemaName). Collapse every absent form to a single null\n-        // using SchemaName.IsNullOrEmpty (the canonical \"absent\" check, mirroring Id.IsNullOrEmpty)\n-        // so the AssertSafe gate and every downstream `schemaName?.Value ?? <backend default>` treat\n-        // them identically — preserving the semantics of the `string?` parameter this value type\n-        // replaced (spec 0030), which a bare `is not null` reference check silently broke.\n-        if (SchemaName.IsNullOrEmpty(schemaName))\n-        {\n-            schemaName = null;\n-        }\n-        else\n-        {\n-            Identifiers.AssertSafe(schemaName.Value, nameof(schemaName));\n-        }\n-\n-        // D3 misconfiguration guard (FR1a/AC1a): on a placement backend, PerSchema needs a schema\n-        // to place history in. A null SchemaName is an operator misconfiguration — reject it at the\n-        // entry point rather than silently falling back to Global. Backends that do not support\n-        // PerSchema (MySQL/SQLite) never trip this; for them PerSchema is a no-op.\n-        if (Scope == MigrationHistoryScope.PerSchema && SupportsPerSchemaHistory && Configuration.SchemaName is null)\n-        {\n-            throw new ConfigurationException(\n-                \"MigrationHistoryScope.PerSchema requires a non-null SchemaName; there is no schema to place history in.\");\n-        }\n-\n-        // The runner sources its migration chain and fresh-install DDL\n-        // from the injected catalog rather than via parameter. A catalog returning null for\n-        // either would surface inside ValidateMigrationsMonotonic / ExecuteFreshInstallAsync as\n-        // an opaque NRE; replace with a descriptive operator-facing diagnostic. Empty migration\n-        // lists are intentionally permitted: relational catalogs always return ≥V1, and\n-        // internal tests use Array.Empty<IAmABoxMigration>() as a \"don't care\" payload when\n-        // exercising hook-ordering, re-detection, or failure-path contracts.\n-        var migrations = _catalog.All(_configuration);\n-        if (migrations is null)\n-        {\n-            throw new ConfigurationException(\n-                $\"Migration list for '{(schemaName is null ? tableName : $\"{schemaName}.{tableName}\")}' was null. The injected IAmABoxMigrationCatalog must return a non-null list from All(...).\");\n-        }\n+        schemaName = GuardIdentifiers(tableName, schemaName);\n+        ThrowIfPerSchemaHasNoSchema();\n \n+        var migrations = GetMigrations(tableName, schemaName);\n         ValidateMigrationsMonotonic(schemaName?.Value, tableName.Value, migrations);\n@@ -233,16 +190,4 @@ public async Task MigrateAsync(\n \n-        // Spec 0029 NF5/AC7 (ADR 0060 D6): surface the placement decision per run so an operator\n-        // can answer \"where did THIS tenant's migration history go?\" without correlating to the\n-        // provisioner config. The single Information log carries the table, the resolved physical\n-        // history schema (or the placeholder \"<backend default>\" on backends with no distinct\n-        // history schema concept, e.g. SQLite / MySQL), and the active MigrationHistoryScope.\n-        // Fires once per run regardless of which path (fresh / bootstrap / normal) dispatches.\n-        Logger.LogInformation(\n-            \"Box migration history for {BoxTable} resolved to schema {HistorySchema} (scope {Scope})\",\n-            tableName, ResolveHistorySchema() ?? \"<backend default>\", _scope);\n+        LogHistoryPlacement(tableName);\n \n-        // Sync Dispose for the connection: DbConnection does not implement IAsyncDisposable\n-        // on netstandard2.0, so DisposeAsync is unavailable across the shared-assembly TFM\n-        // matrix. The UoW implements IAsyncDisposable (see IAmAProvisioningUnitOfWork) and\n-        // is awaited explicitly in the finally.\n         TConnection? connection = null;\n@@ -305,22 +250,3 @@ await RunNormalPathAsync(\n                 activity?.AddException(ex);\n-                // Pass CancellationToken.None: a signalled caller token must not abandon the unwind.\n-                // See ADR 0058 §B.3 cancellation contract.\n-                try\n-                {\n-                    await uow.RollbackAsync(CancellationToken.None);\n-                }\n-                catch (Exception rollbackEx)\n-                {\n-                    // Defense in depth: the IAmAProvisioningUnitOfWork contract says RollbackAsync\n-                    // MUST NOT throw, and the four per-backend impls comply (PG and MySQL tightened\n-                    // explicitly in 3c8417fd6). If a future regression breaks that, do NOT let the\n-                    // rollback exception mask the original triggering exception — the primary cause\n-                    // is more diagnostically valuable than a defect in our own unwind, and callers\n-                    // pattern-match on the type they actually threw. Log the rollback failure at\n-                    // Error level so operators see both: the primary failure surfaces via rethrow,\n-                    // the rollback defect surfaces via the log.\n-                    Logger.LogError(rollbackEx,\n-                        \"Box migration unit-of-work RollbackAsync threw while unwinding from a primary failure for table '{Table}'; rollback exception is logged, primary exception is rethrown.\",\n-                        tableName);\n-                }\n+                await RollbackWithoutMaskingAsync(uow, tableName);\n                 throw;\n@@ -330,13 +256,78 @@ await RunNormalPathAsync(\n         {\n-            // Disposal order mirrors the previous `await using var uow` / `using var connection`\n-            // pair: UoW first (releases any per-backend advisory lock + transaction state),\n-            // then the connection. Null checks defend the bootstrap-failure-before-assignment\n-            // case: if OpenConnectionAsync threw, both locals stay null; if BeginAsync threw,\n-            // both are assigned and need disposal.\n-            if (uow is not null)\n-            {\n-                await uow.DisposeAsync();\n-            }\n-            connection?.Dispose();\n+            await ReleaseAsync(uow, connection);\n+        }\n+    }\n+\n+    // The runner is callable without going through a catalog, so it asserts identifier safety\n+    // itself. A SchemaName that wraps a null or empty string is absent, the same as a null one.\n+    private static SchemaName? GuardIdentifiers(BoxTableName tableName, SchemaName? schemaName)\n+    {\n+        Identifiers.AssertSafe(tableName.Value, nameof(tableName));\n+\n+        if (SchemaName.IsNullOrEmpty(schemaName))\n+        {\n+            return null;\n+        }\n+\n+        Identifiers.AssertSafe(schemaName.Value, nameof(schemaName));\n+        return schemaName;\n+    }\n+\n+    private void ThrowIfPerSchemaHasNoSchema()\n+    {\n+        if (Scope == MigrationHistoryScope.PerSchema && SupportsPerSchemaHistory && Configuration.SchemaName is null)\n+        {\n+            throw new ConfigurationException(\n+                \"MigrationHistoryScope.PerSchema requires a non-null SchemaName; there is no schema to place history in.\");\n+        }\n+    }\n+\n+    // An empty chain is allowed; a null one is a catalog defect, reported here rather than as an\n+    // NRE further in.\n+    private IReadOnlyList<IAmABoxMigration> GetMigrations(BoxTableName tableName, SchemaName? schemaName)\n+    {\n+        var migrations = _catalog.All(_configuration);\n+        if (migrations is null)\n+        {\n+            throw new ConfigurationException(\n+                $\"Migration list for '{(schemaName is null ? tableName : $\"{schemaName}.{tableName}\")}' was null. The injected IAmABoxMigrationCatalog must return a non-null list from All(...).\");\n+        }\n+\n+        return migrations;\n+    }\n+\n+    // Lets an operator see where this run's migration history lives without reading the\n+    // provisioner configuration (ADR 0060).\n+    private void LogHistoryPlacement(BoxTableName tableName) =>\n+        Logger.LogInformation(\n+            \"Box migration history for {BoxTable} resolved to schema {HistorySchema} (scope {Scope})\",\n+            tableName, ResolveHistorySchema() ?? \"<backend default>\", _scope);\n+\n+    // Rolls back with CancellationToken.None so a cancelled caller cannot abandon the unwind\n+    // (ADR 0058 §B.3). RollbackAsync must not throw; if it does, the failure is logged rather\n+    // than allowed to mask the primary exception the caller is about to see.\n+    private async Task RollbackWithoutMaskingAsync(IAmAProvisioningUnitOfWork<TTransaction> uow, BoxTableName tableName)\n+    {\n+        try\n+        {\n+            await uow.RollbackAsync(CancellationToken.None);\n+        }\n+        catch (Exception rollbackEx)\n+        {\n+            Logger.LogError(rollbackEx,\n+                \"Box migration unit-of-work RollbackAsync threw while unwinding from a primary failure for table '{Table}'; rollback exception is logged, primary exception is rethrown.\",\n+                tableName);\n+        }\n+    }\n+\n+    // Releases the unit of work (lock and transaction) before the connection. Either may be null\n+    // if setup failed part way. The connection is disposed synchronously because DbConnection has\n+    // no DisposeAsync on netstandard2.0.\n+    private static async Task ReleaseAsync(IAmAProvisioningUnitOfWork<TTransaction>? uow, TConnection? connection)\n+    {\n+        if (uow is not null)\n+        {\n+            await uow.DisposeAsync();\n         }\n+        connection?.Dispose();\n     }\n","improvement-type":"Complex Method"}],"change-level":"warning","is-hotspot?":true,"line":113,"what-changed":"KafkaMessageConsumer increases in cyclomatic complexity from 19 to 20, threshold = 9","how-to-fix":"There are many reasons for Complex Method. Sometimes, another design approach is beneficial such as a) modeling state using an explicit state machine rather than conditionals, or b) using table lookup rather than long chains of logic. In other scenarios, the function can be split using [EXTRACT FUNCTION](https://refactoring.com/catalog/extractFunction.html). Just make sure you extract natural and cohesive functions. Complex Methods can also be addressed by identifying complex conditional expressions and then using the [DECOMPOSE CONDITIONAL](https://refactoring.com/catalog/decomposeConditional.html) refactoring.","change-type":"degraded"},{"method":"MessagePump","why-it-occurs":"Counts the maximum number of arguments to each class' constructor. Too many arguments give a lower code health score. The rationale is that many constructor arguments indicate either a unit with low cohesion or an injection of dependencies on the wrong abstraction level.","name":"Constructor Over-Injection","file":"src/Paramore.Brighter.ServiceActivator/MessagePump.cs","refactoring-examples":[{"architectural-component-id":null,"author-name":"Ian Cooper","training-data":{"loc-added":"9","loc-deleted":"8","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.0","delta-n-functions":"0","current-file-score":"10.0"},"author-email":"ian_hammond_cooper@yahoo.co.uk","commit-full-message":"* fix: add support for Send to our synchronization context, to allow it to work in more use cases\r\n\r\n* fix: remove blocking wait from consumers that do not have a built in delay function.\r\n\r\n* fix: document where wait completes on the synchronizationcontext via the performer thread.\r\n\r\n* fix: update comments for sync and async, fix one where appropriate\r\n\r\n* feat: add adr describing approach; rename to use reactor and proactor to align with documentation.\r\n\r\n* feat: improve the adr about Brighter's usage of threading.\r\n\r\n* fix: use GetAwaiter().GetResult() for better call stack\r\n\r\n* feat: Update the ADR for IAmAMessageConsumerAsync\r\n\r\n* feat: add IAmAMessageConsumerAsync.cs and initial tests.\r\n\r\n* feat: additional tests for InMemoryConsumerAsync\r\n\r\n* feat: allow proactor to use async methods on transports, if they exist\r\n\r\n* feat: expose async methods from AWS to Proactor.cs\r\n\r\n* fix: nullability of AWS transport\r\n\r\n* fix: add async options to ASB\r\n\r\n* chore: branch switch\r\n\r\n* feat: add async support to Kafka\r\n\r\n* chore: separate summary from remarks\r\n\r\n* feat: add async to RMQ; update to RMQ V7\r\n\r\n* feat: add nullability to RMQ transport\r\n\r\n* feat: add async operations to mssql transport\r\n\r\n* chore: fix nullable issues for MS SQL transport\r\n\r\n* chore: move Redis to using ChannelName and RoutingKey over string, to reduce primitive obsession.\r\n\r\n* feat: upgrade the sychronizationcontext to work with the scheduler, derived from Stephen Cleary work\r\n\r\n* chore: reorg tests around reactor and proactor\r\n\r\n* Shift to run whole loop through synchronizationcontext over parts\r\n\r\n* Make the choice of proactor/reactor easier to understand\r\n\r\n* fix: switch to close implementation of Stephen Cleary's Nito as a starting point; can't use direct as not strong named, and adds depenency we can't fix\r\n\r\n* fix: update ADR to reflect sources changes; update sources to reflect code origins\r\n\r\n* fix: need to be explicit about your pump type if not proactor now\r\n\r\n* fix: license file URI for Stephen Cleary was wrong\r\n\r\n* feat: update ADR to show native support for proactor or reactor\r\n\r\n* fix: match proactor tests to reactor tests to flush issues\r\n\r\n* fix: add duplicates for the tests within Reactor, not in Proactor\r\n\r\n* fix: make rmq broker creation async; add cancellationtoken to sendasync\r\n\r\n* fix: add async tests for RMQ, use to flush out issues with synchronization context, particularly in test scenarios (as runner and framework also have contexts)\r\n\r\n* feat: add tests for internal syncrhonizationcontext, derived from Stephen Cleary\r\n\r\n* fix: tests show that we should remove the reentrancy check; there may be an issue, but this was not how to solve\r\n\r\n* fix: add async disposable pattern to consumer\r\n\r\n* feat: support IAsyncDisposable\r\n\r\n* fix: remove GetAwaiter().GetResult() from hot paths\r\n\r\n* fix: Improve the ADR to reflect results; attribution in the README.md file\r\n\r\n* chore: add some debugging support for thornier issues\r\n\r\n* chore: add better debug statements; helps to diagnose scheduler & context issues. Issue with scheduler being used outside of helper context.\r\n\r\n* chore: add async versions of AWS tests\r\n\r\n* chore: fix missing interface member\r\n\r\n* chore: add missing interface methods\r\n\r\n* chore: async service bus tests\r\n\r\n* fix: confirm that if task scheduler reset correctly, we don't get a spurious callback\r\n\r\n* fix: note concerns on TaskScheduler and ConfigureAwait\r\n\r\n* fix: another pass at exploring the edge case, that causes work to be accidentally queued to our scheduler\r\n\r\n* fix: some fallback approaches in Post\r\n\r\n* Pull one issue with blocking in the Proactor pipeline out.\r\n\r\n* fix: Notes on TaskScheduler and ConfigureAwait\r\n\r\n* fix: update ADR link\r\n\r\n* fix: allow asynchronous producer creation (mainly useful for AWS now)\r\n\r\n* fix: add async tests to Kafka; remove spurious finalize call\r\n\r\n* fix: add async to mqtt\r\n\r\n* fix: add async for mssql\r\n\r\n* fix: Add async Redis tests\r\n\r\n* chore: syntax modernization\r\n\r\n* fix: accidental sample drop","commit-date":"2024-12-29T17:51:50Z","current-rev":"9af3c0b15","filename":"Brighter/src/Paramore.Brighter.MessagingGateway.MsSql/SqlQueues/ReceivedResult.cs","previous-rev":"8438dd9ee","commit-title":"Fix: Sync Over Async Improvements (#3409)","language":"C#","id":"67d626571410b5b5d0fa09b4ccda9573e7d98690","model-score":0.66,"author-id":null,"project-id":32198,"delta-file-score":0.31179166,"diff":"diff --git a/src/Paramore.Brighter.MessagingGateway.MsSql/SqlQueues/ReceivedResult.cs b/src/Paramore.Brighter.MessagingGateway.MsSql/SqlQueues/ReceivedResult.cs\nindex 1b17df802..65e91b1c5 100644\n--- a/src/Paramore.Brighter.MessagingGateway.MsSql/SqlQueues/ReceivedResult.cs\n+++ b/src/Paramore.Brighter.MessagingGateway.MsSql/SqlQueues/ReceivedResult.cs\n@@ -27,11 +27,12 @@ public ReceivedResult(bool isDataValid, string jsonContent, string topic, string\n     /// <typeparam name=\"T\">The type of the message</typeparam>\n-    public class ReceivedResult<T> : ReceivedResult\n+    public class ReceivedResult<T>(\n+        bool isDataValid,\n+        string jsonContent,\n+        string topic,\n+        string messageType,\n+        long id,\n+        T? message)\n+        : ReceivedResult(isDataValid, jsonContent, topic, messageType, id)\n     {\n-        public ReceivedResult(bool isDataValid, string jsonContent, string topic, string messageType, long id, T message)\n-            : base(isDataValid, jsonContent, topic, messageType, id)\n-        {\n-            Message = message;\n-        }\n-\n-        public T Message { get; }\n+        public T? Message { get; } = message;\n \n","improvement-type":"Constructor Over-Injection"}],"change-level":"warning","is-hotspot?":false,"line":156,"what-changed":"MessagePump has 6 arguments, max arguments = 5","how-to-fix":"There are multiple ways of addressing constructor over-injection. Sometimes you can introduce [FACADE](https://en.wikipedia.org/wiki/Facade_pattern) services that encapsulate lower-level dependencies.\n\nIn many cases, Constructor Over-Injection is a symptom of a deeper problem. Make sure to investigate the root cause, and get some inspiration and examples from [Mark Seemann's article](https://blog.ploeh.dk/2018/08/27/on-constructor-over-injection/) on the issue.","change-type":"introduced"},{"method":"OutboxProducerMediator","why-it-occurs":"A Complex Method has a high cyclomatic complexity. The recommended threshold for the C# language is a cyclomatic complexity lower than 9.","name":"Complex Method","file":"src/Paramore.Brighter/OutboxProducerMediator.cs","refactoring-examples":[{"architectural-component-id":null,"author-name":"DevJonny","training-data":{"loc-added":"1","loc-deleted":"2","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.0","delta-n-functions":"0","current-file-score":"10.0"},"author-email":"jonny.ollifflee@gmail.com","commit-full-message":"NJsonSchema represents class inheritance via an embedded\n{ definitions: { Base: {...} }, allOf: [{$ref: \"#/definitions/Base\"}, ...] }\nblock on every derived message schema. The previous output duplicated the base\ntype once per message and rewrote refs to resolve inside each message's payload\nsubtree.\n\nThis commit lifts all definitions/$defs entries to a single shared pool under\ncomponents.schemas, dedupes by name (first-seen content wins), and rewrites refs\nacross both the message bodies and the hoisted definitions themselves so\ncross-definition refs continue to resolve. A class hierarchy like\nPaymentReceivedEvent and OrderCreatedEvent both inheriting Event now produces a\nsingle Event entry under components.schemas, with each message's allOf pointing\nat #/components/schemas/Event.\n\nSide benefits:\n- Smaller output (~18% on the sample documents).\n- Tooling consuming the spec sees the base type once and can generate a shared\n  parent class on the client side.\n\nDrops the last open CodeScene Complex Method finding by collapsing the\nJsonValueKind.True / False arms in JsonElementToObject into a single\nGetBoolean() arm.\n\nTests rewritten to assert the new ref shape (#/components/schemas/X) and the\npresence of the hoisted entries under Components.Schemas.\n\nCo-Authored-By: Claude <noreply@anthropic.com>","commit-date":"2026-05-16T19:26:51Z","current-rev":"f5003d644","filename":"Brighter/src/Paramore.Brighter.AsyncAPI/AsyncApiHostExtensions.cs","previous-rev":"f38857a51","commit-title":"feat(#3828): hoist shared JSON Schema definitions to components.schemas","language":"C#","id":"a281e7924ca426d627f9bb709daa231724381400","model-score":0.92,"author-id":null,"project-id":32198,"delta-file-score":0.31179166,"diff":"diff --git a/src/Paramore.Brighter.AsyncAPI/AsyncApiHostExtensions.cs b/src/Paramore.Brighter.AsyncAPI/AsyncApiHostExtensions.cs\nindex 5bc24c0a6..6022aa42b 100644\n--- a/src/Paramore.Brighter.AsyncAPI/AsyncApiHostExtensions.cs\n+++ b/src/Paramore.Brighter.AsyncAPI/AsyncApiHostExtensions.cs\n@@ -191,4 +191,3 @@ private static string SerializeAsYaml(object? tree)\n             JsonValueKind.Number => ReadNumber(element),\n-            JsonValueKind.True => true,\n-            JsonValueKind.False => false,\n+            JsonValueKind.True or JsonValueKind.False => element.GetBoolean(),\n             _ => null,\n","improvement-type":"Complex Method"},{"architectural-component-id":null,"author-name":"gabisonia","training-data":{"loc-added":"7","loc-deleted":"10","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.0","delta-n-functions":"0","current-file-score":"9.6882083290695"},"author-email":"irakli.gabisonia94@gmail.com","commit-full-message":"Expose optional sync and async requeue scheduler capabilities and use native scheduling on the consuming broker. Assign stable per-attempt delivery IDs to survive duplicate detection, and acknowledge only after scheduling succeeds.\n\nPreserve direct-subscription startup and abandon with a warning when delays cannot be honored. Cover failure recovery, broker ownership, forwarding isolation, sessions, and retry identity through regenerated conformance assertions.\n\nValidation: 26 focused cases pass on .NET 9 and 10; full ASB suite has 553 passed, 4 skipped, and the same 10 baseline emulator TTL failures. Azure scheduler tests: 13 passed. Generator tests: 312 passed. Release packages build for all supported targets.","commit-date":"2026-10-09T17:18:14Z","current-rev":"dba7b72f7","filename":"Brighter/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusConsumerFactory.cs","previous-rev":"161b226f3","commit-title":"feat(asb): add native queue-targeted retry scheduling","language":"C#","id":"1024f351788320889cd72fe4675f0158c5d550f3","model-score":0.64,"author-id":null,"project-id":32198,"delta-file-score":0.59155285,"diff":"diff --git a/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusConsumerFactory.cs b/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusConsumerFactory.cs\nindex 8fc288e5c..daf001786 100644\n--- a/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusConsumerFactory.cs\n+++ b/src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusConsumerFactory.cs\n@@ -38,2 +38,6 @@ public class AzureServiceBusConsumerFactory : IAmAMessageConsumerFactory\n \n+    /// <summary>The fallback scheduler for custom producers without native queue retry support.</summary>\n+    /// <remarks>Built-in ASB queue producers schedule retries on their own broker and take precedence.</remarks>\n+    public IAmAMessageScheduler? Scheduler { get; set; }\n+\n     /// <summary>\n@@ -72,9 +76,2 @@ public IAmAMessageConsumerSync Create(Subscription subscription)\n \n-        if (sub.RequeueDelay > TimeSpan.Zero && !sub.Configuration.UseServiceBusQueue\n-            && sub.Configuration.ForwardTo is null)\n-        {\n-            throw new ConfigurationException(\n-                \"Delayed topic retries require ForwardTo to a dedicated queue, or UseServiceBusQueue with externally provisioned forwarding.\");\n-        }\n-\n         var receiverProvider = new ServiceBusReceiverProvider(_clientProvider, sub.Configuration.MaxAutoLockRenewalDuration);\n@@ -99,3 +96,3 @@ public IAmAMessageConsumerSync Create(Subscription subscription)\n             return new AzureServiceBusForwardingConsumer(sub, messageProducer,\n-                nameSpaceManagerWrapper, receiverProvider);\n+                nameSpaceManagerWrapper, receiverProvider) { Scheduler = Scheduler };\n         }\n@@ -113,3 +110,3 @@ public IAmAMessageConsumerSync Create(Subscription subscription)\n                 nameSpaceManagerWrapper,\n-                receiverProvider);\n+                receiverProvider) { Scheduler = Scheduler };\n         }\n@@ -126,3 +123,3 @@ public IAmAMessageConsumerSync Create(Subscription subscription)\n                 nameSpaceManagerWrapper,\n-                receiverProvider);\n+                receiverProvider) { Scheduler = Scheduler };\n         }\n","improvement-type":"Complex Method"},{"architectural-component-id":null,"author-name":"DevJonny","training-data":{"loc-added":"17","loc-deleted":"14","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.08","delta-n-functions":"0","current-file-score":"10.0"},"author-email":"jonny.ollifflee@gmail.com","commit-full-message":"Extract LoadAssemblyTypes (handles ReflectionTypeLoadException) and\nTryGetPublicationTopic (per-type filter + topic resolution) from\nGetPublicationTopicTypes. Targets the last CodeScene advisory finding\n(Complex Method).\n\n46/46 AsyncAPI tests pass on net9.0 and net10.0.\n\nCo-Authored-By: Claude (claude-opus-4-7) <noreply@anthropic.com>","commit-date":"2026-05-17T06:26:45Z","current-rev":"7f8b45280","filename":"Brighter/src/Paramore.Brighter.AsyncAPI/AsyncApiDocumentGenerator.cs","previous-rev":"6be065b71","commit-title":"refactor(#3828): split GetPublicationTopicTypes for clarity","language":"C#","id":"2287bc725ce16bc068f9b3178aae023ee15b02f8","model-score":0.5,"author-id":null,"project-id":32198,"delta-file-score":0.33626333,"diff":"diff --git a/src/Paramore.Brighter.AsyncAPI/AsyncApiDocumentGenerator.cs b/src/Paramore.Brighter.AsyncAPI/AsyncApiDocumentGenerator.cs\nindex 4a13108c1..6f8bd66a9 100644\n--- a/src/Paramore.Brighter.AsyncAPI/AsyncApiDocumentGenerator.cs\n+++ b/src/Paramore.Brighter.AsyncAPI/AsyncApiDocumentGenerator.cs\n@@ -248,6 +248,14 @@ private IEnumerable<Assembly> GetAssembliesToScan()\n         {\n-            Type[] types;\n+            foreach (var type in LoadAssemblyTypes(assembly))\n+            {\n+                var topic = TryGetPublicationTopic(type);\n+                if (topic != null) yield return (type, topic);\n+            }\n+        }\n+\n+        private static IEnumerable<Type> LoadAssemblyTypes(Assembly assembly)\n+        {\n             try\n             {\n-                types = assembly.GetTypes();\n+                return assembly.GetTypes();\n             }\n@@ -255,18 +263,13 @@ private IEnumerable<Assembly> GetAssembliesToScan()\n             {\n-                types = ex.Types.Where(t => t != null).ToArray()!;\n+                return ex.Types.Where(t => t != null).ToArray()!;\n             }\n+        }\n \n-            foreach (var type in types)\n-            {\n-                if (type.IsAbstract || type.IsInterface) continue;\n-                if (!typeof(IRequest).IsAssignableFrom(type)) continue;\n-\n-                var attr = type.GetCustomAttribute<PublicationTopicAttribute>();\n-                if (attr == null) continue;\n-\n-                var topic = attr.Destination?.RoutingKey?.Value;\n-                if (string.IsNullOrEmpty(topic)) continue;\n+        private static string? TryGetPublicationTopic(Type type)\n+        {\n+            if (type.IsAbstract || type.IsInterface) return null;\n+            if (!typeof(IRequest).IsAssignableFrom(type)) return null;\n \n-                yield return (type, topic);\n-            }\n+            var topic = type.GetCustomAttribute<PublicationTopicAttribute>()?.Destination?.RoutingKey?.Value;\n+            return string.IsNullOrEmpty(topic) ? null : topic;\n         }\n","improvement-type":"Complex Method"},{"architectural-component-id":null,"author-name":"Ian Cooper","training-data":{"loc-added":"39","loc-deleted":"20","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.0","delta-n-functions":"0","current-file-score":"10.0"},"author-email":"ian_hammond_cooper@yahoo.co.uk","commit-full-message":"* chore: fix casing on ADR\n\n* fix: update the ADR for a better understanding of how we propogate context\n\n* chore: update the name of InMemoryMessageProducer.cs to better fit the pattern used elsewhere\n\n* chore: swap Assert.True to Assert.Contains for collections\n\n* feat: failing test checks that we have added trace context to headers of outgoing message\n\n* feat: add a class to support trace state explicity\n\n* feat: modify tests\n\n* chore: filename issue\n\n* chore: switch to assert contains\n\n* feat: ensure that we propogate trace context\n\n* fix: allow trace context to serialize for tests\n\n* fixing broken tests\n\n* feat: add async tests\n\n* feat: add sync version of propogation tests\n\n* chore: whitespace\n\n* feat: add RMQ support for traceparent and tracestate.\n\n* fix: baggage is not tracecontext, although format is similar; baggage is user-defined\n\n* fix: tests were using tracestate not baggage\n\n* fix: crate link spans as MS committed change; propogate tracecontext and baggage through pipeline\n\n* fix: adjust test to ensure baggage on parent activity\n\n* fix: rename test class\n\n* chore: add tracestring and baggage to test\n\n* fix RMQ propogates the context\n\n* chore: port between RMQ instances\n\n* fix: add trace propogation to RMQ\n\n* fix: add kafka context propogation\n\n* chore: Add some primitive types to avoid primitive obsession warnings from codescene\n\n* chore: missing XML comments on public methods\n\n* chore: lower primitive obsession for message and request id\n\n* chore: usages of content type for new header\n\n* fix: adjust for reply to as a routing key\n\n* fix: add serialization for new value objects\n\n* chore: adjust docs\n\n* fix: issues with serialization of new primitive types\n\n* fix: ContentType.cs value may be null in constructor\n\n* fix: increase test delay as fragile\n\n* Update src/Paramore.Brighter/Id.cs\n\nCo-authored-by: Rafael Lillo <rafael.andrade@justeattakeaway.com>\n\n* fix: need to convert header types to primitives for bag\n\n* fix: make sync RMQ tests serial for reliability\n\n* fix: refactor LLM code\n\n* chore: move converters to own directory, add them for NewtonSoft for Kafka serdes\n\n* chore: remove spurious directory\n\n* fix: use a string base type for Id in a request, to make serializing it easily.\n\n* chore: unneeded namespace on attribute\n\n* feat: adding cloud events to Redis\n\n* fix: tests failing due to bad test string, does not use cloud events names\n\n* feat: add additional tests of persistence of message headers for new properties\n\n* fix: ASB tests need to check all properties\n\n* feat: use MS ContentType as used on public SDK and user defined type is awkward in that context (although MS type has limitations)\n\n* fix: body equality test not working\n\n* fix: errors with tests around cloud events transform; need to use strings, similar to params\n\n* fix: use charset with MS contenttype\n\n* feat: adding cloudevents support to ASB\n\n* feat: add cloud events and tracing to ASB\n\n* fix: correct tests for contenttype changes and cloudevents json specification\n\n* fix: correct for new content type\n\n---------\n\nCo-authored-by: Rafael Lillo <rafael.andrade@justeattakeaway.com>","commit-date":"2025-06-14T15:20:36Z","current-rev":"bc93b511c","filename":"Brighter/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageSender.cs","previous-rev":"5767656ad","commit-title":"OTel Transports (#3605)","language":"C#","id":"4136886c0cbe98b6d426b5645ff6ddf0f5b82421","model-score":0.49,"author-id":null,"project-id":32198,"delta-file-score":0.4636132,"diff":"diff --git a/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageSender.cs b/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageSender.cs\nindex 65e3b1f20..18a8d7a88 100644\n--- a/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageSender.cs\n+++ b/src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsMessageSender.cs\n@@ -4,2 +4,3 @@\n using System.Net;\n+using System.Net.Mime;\n using System.Text.Json;\n@@ -10,3 +11,5 @@\n using Microsoft.Extensions.Logging;\n+using Newtonsoft.Json;\n using Paramore.Brighter.Extensions;\n+using Paramore.Brighter.JsonConverters;\n using Paramore.Brighter.Logging;\n@@ -48,2 +51,16 @@ public SqsMessageSender(string queueUrl, SqsType queueType, AmazonSQSClient clie\n     public async Task<string?> SendAsync(Message message, TimeSpan? delay, CancellationToken cancellationToken)\n+    {\n+        var request = CreateSendMessageRequest(message, delay);\n+\n+        var response = await _client.SendMessageAsync(request, cancellationToken);\n+        if (response.HttpStatusCode is HttpStatusCode.OK or HttpStatusCode.Created\n+            or HttpStatusCode.Accepted)\n+        {\n+            return response.MessageId;\n+        }\n+\n+        return null;\n+    }\n+\n+    private SendMessageRequest CreateSendMessageRequest(Message message, TimeSpan? delay)\n     {\n@@ -51,3 +68,3 @@ public SqsMessageSender(string queueUrl, SqsType queueType, AmazonSQSClient clie\n         {\n-            QueueUrl = _queueUrl, \n+            QueueUrl = _queueUrl,\n             MessageBody = message.Body.Value\n@@ -55,2 +72,11 @@ public SqsMessageSender(string queueUrl, SqsType queueType, AmazonSQSClient clie\n \n+        SetMessageDelay(request, delay);\n+        SetFifoQueueProperties(request, message);\n+        SetMessageAttributes(request, message);\n+\n+        return request;\n+    }\n+\n+    private void SetMessageDelay(SendMessageRequest request, TimeSpan? delay)\n+    {\n         delay ??= TimeSpan.Zero;\n@@ -58,3 +84,2 @@ public SqsMessageSender(string queueUrl, SqsType queueType, AmazonSQSClient clie\n         {\n-            // SQS has a hard limit of 15min for Delay in Seconds\n             if (delay.Value > s_maxDelay)\n@@ -67,27 +92,30 @@ public SqsMessageSender(string queueUrl, SqsType queueType, AmazonSQSClient clie\n         }\n+    }\n \n-        if (_queueType == SqsType.Fifo)\n+    private void SetFifoQueueProperties(SendMessageRequest request, Message message)\n+    {\n+        if (_queueType != SqsType.Fifo) return;\n+        request.MessageGroupId = message.Header.PartitionKey;\n+        if (message.Header.Bag.TryGetValue(HeaderNames.DeduplicationId, out var deduplicationId))\n         {\n-            request.MessageGroupId = message.Header.PartitionKey;\n-            if (message.Header.Bag.TryGetValue(HeaderNames.DeduplicationId, out var deduplicationId))\n-            {\n-                request.MessageDeduplicationId = (string)deduplicationId;\n-            }\n+            request.MessageDeduplicationId = (string)deduplicationId;\n         }\n-        \n-        // Combine cloud event headers into a single JSON object\n+    }\n+\n+    private void SetMessageAttributes(SendMessageRequest request, Message message)\n+    {\n         string cloudEventHeadersJson = CreateCloudEventHeadersJson(message);\n \n-        // we can set up to 10 attributes;  we use a single JSON object as the cloud event headers; we can set nine others directly \n+        var contentType = message.Header.ContentType ?? new ContentType(MediaTypeNames.Text.Plain);\n         var messageAttributes = new Dictionary<string, MessageAttributeValue>\n-        { \n-            [HeaderNames.Id] = new (){ StringValue = message.Header.MessageId, DataType = \"String\" },\n+        {\n+            [HeaderNames.Id] = new() { StringValue = message.Header.MessageId, DataType = \"String\" },\n             [HeaderNames.CloudEventHeaders] = new() { StringValue = cloudEventHeadersJson, DataType = \"String\" },\n-            [HeaderNames.Topic] = new() { StringValue = _queueUrl ,DataType = \"String\" },\n+            [HeaderNames.Topic] = new() { StringValue = _queueUrl, DataType = \"String\" },\n             [HeaderNames.MessageType] = new() { StringValue = message.Header.MessageType.ToString(), DataType = \"String\" },\n-            [HeaderNames.ContentType] = new() { StringValue = message.Header.ContentType, DataType = \"String\" },\n+            [HeaderNames.ContentType] = new() { StringValue = contentType.ToString(), DataType = \"String\" },\n             [HeaderNames.Timestamp] = new() { StringValue = Convert.ToString(message.Header.TimeStamp.ToRfc3339()), DataType = \"String\" }\n         };\n-        \n-        if (!string.IsNullOrEmpty(message.Header.ReplyTo))\n+\n+        if (!RoutingKey.IsNullOrEmpty(message.Header.ReplyTo))\n             messageAttributes.Add(HeaderNames.ReplyTo, new MessageAttributeValue { StringValue = message.Header.ReplyTo, DataType = \"String\" });\n@@ -97,20 +125,10 @@ public SqsMessageSender(string queueUrl, SqsType queueType, AmazonSQSClient clie\n \n-        if (!string.IsNullOrEmpty(message.Header.CorrelationId))\n-            messageAttributes.Add(HeaderNames.CorrelationId,  new MessageAttributeValue { StringValue = message.Header.CorrelationId, DataType = \"String\" });\n-        \n-        //we have to add some attributes into our bag, to prevent overloading the message attributes\n+        if (!Id.IsNullOrEmpty(message.Header.CorrelationId))\n+            messageAttributes.Add(HeaderNames.CorrelationId, new MessageAttributeValue { StringValue = message.Header.CorrelationId, DataType = \"String\" });\n+\n         message.Header.Bag[HeaderNames.HandledCount] = message.Header.HandledCount.ToString(CultureInfo.InvariantCulture);\n-        \n-        var bagJson = JsonSerializer.Serialize(message.Header.Bag, JsonSerialisationOptions.Options);\n+\n+        var bagJson = System.Text.Json.JsonSerializer.Serialize(message.Header.Bag, JsonSerialisationOptions.Options);\n         messageAttributes[HeaderNames.Bag] = new() { StringValue = bagJson, DataType = \"String\" };\n         request.MessageAttributes = messageAttributes;\n-\n-        var response = await _client.SendMessageAsync(request, cancellationToken);\n-        if (response.HttpStatusCode is HttpStatusCode.OK or HttpStatusCode.Created\n-            or HttpStatusCode.Accepted)\n-        {\n-            return response.MessageId;\n-        }\n-\n-        return null;\n     }\n@@ -119,2 +137,3 @@ private static string CreateCloudEventHeadersJson(Message message)\n     {\n+        var contentType = message.Header.ContentType ?? new ContentType(MediaTypeNames.Text.Plain);\n         var cloudEventHeaders = new Dictionary<string, string>\n@@ -122,3 +141,3 @@ private static string CreateCloudEventHeadersJson(Message message)\n             [HeaderNames.Id] = Convert.ToString(message.Header.MessageId),\n-            [HeaderNames.DataContentType] = message.Header.ContentType ?? \"plain/text\",\n+            [HeaderNames.DataContentType] = contentType.ToString(),\n             [HeaderNames.DataSchema] = message.Header.DataSchema?.ToString() ?? string.Empty,\n@@ -139,3 +158,3 @@ private static string CreateCloudEventHeadersJson(Message message)\n \n-        var cloudEventHeadersJson = JsonSerializer.Serialize(cloudEventHeaders, JsonSerialisationOptions.Options);\n+        var cloudEventHeadersJson = System.Text.Json.JsonSerializer.Serialize(cloudEventHeaders, JsonSerialisationOptions.Options);\n         return cloudEventHeadersJson;\n@@ -149,2 +168 @@ private static partial class Log\n }\n-\n","improvement-type":"Complex Method"},{"architectural-component-id":null,"author-name":"Ian Cooper","training-data":{"loc-added":"17","loc-deleted":"16","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.0","delta-n-functions":"0","current-file-score":"8.816158827775617"},"author-email":"ian_hammond_cooper@yahoo.co.uk","commit-full-message":"Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>\nClaude-Session: https://claude.ai/code/session_01HsKD52dnGHFLSEr93VZyR7","commit-date":"2026-10-12T13:23:04Z","current-rev":"90502e627","filename":"Brighter/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxDetectionHelper.cs","previous-rev":"7aca96a83","commit-title":"refactor: extract methods to express intent in BoxProvisioning.PostgreSql","language":"C#","id":"b7d978856416855c51d6c33293e8dacf04776f5b","model-score":0.3,"author-id":null,"project-id":32198,"delta-file-score":0.7845205,"diff":"diff --git a/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxDetectionHelper.cs b/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxDetectionHelper.cs\nindex 3b5bcf962..525808711 100644\n--- a/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxDetectionHelper.cs\n+++ b/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxDetectionHelper.cs\n@@ -115,19 +115,4 @@ public async Task<bool> DoesHistoryExistAsync(\n \n-        // System-table existence: __BrighterMigrationHistory is created via quoted DDL\n-        // (`CREATE TABLE IF NOT EXISTS <schema>.\"__BrighterMigrationHistory\"`), so its name\n-        // is case-PRESERVED in pg_class. Routing through DoesTableExistAsync would lowercase\n-        // the lookup to `'__brightermigrationhistory'` and miss. Inline the literal-name check,\n-        // parameterising only the (folded) schema.\n-        using (var existsCmd = connection.CreateCommand())\n-        {\n-            if (transaction != null) existsCmd.Transaction = transaction;\n-            existsCmd.CommandText = @\"\n-SELECT EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.TABLES\n-WHERE TABLE_SCHEMA = @HistorySchema AND TABLE_NAME = '__BrighterMigrationHistory')\";\n-            existsCmd.Parameters.AddWithValue(\"@HistorySchema\", foldedHistorySchema);\n-            var existsRaw = await existsCmd.ExecuteScalarAsync(cancellationToken);\n-            var historyTableExists = existsRaw is bool b && b;\n-            if (!historyTableExists)\n-                return false;\n-        }\n+        if (!await HistoryTableExistsAsync(connection, foldedHistorySchema, cancellationToken, transaction))\n+            return false;\n \n@@ -159,2 +144,18 @@ SELECT COUNT(1) FROM {quotedHistorySchema}.\"\"__BrighterMigrationHistory\"\"\n \n+    // The history table is created with a quoted name, so its case is preserved; this cannot use\n+    // DoesTableExistAsync, which folds the name to lowercase.\n+    private static async Task<bool> HistoryTableExistsAsync(\n+        NpgsqlConnection connection, string foldedHistorySchema,\n+        CancellationToken cancellationToken, NpgsqlTransaction? transaction)\n+    {\n+        using var command = connection.CreateCommand();\n+        if (transaction != null) command.Transaction = transaction;\n+        command.CommandText = @\"\n+SELECT EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.TABLES\n+WHERE TABLE_SCHEMA = @HistorySchema AND TABLE_NAME = '__BrighterMigrationHistory')\";\n+        command.Parameters.AddWithValue(\"@HistorySchema\", foldedHistorySchema);\n+        var raw = await command.ExecuteScalarAsync(cancellationToken);\n+        return raw is bool exists && exists;\n+    }\n+\n     /// <summary>\n","improvement-type":"Complex Method"},{"architectural-component-id":null,"author-name":"Steve Bush","training-data":{"loc-added":"46","loc-deleted":"63","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.17","delta-n-functions":"0","current-file-score":"10.0"},"author-email":"stevebu@bushchang.com","commit-full-message":"* Refactoring of MQTT Support to use 4.3 MQTTnet\n\n* Removed MQTTnet v5 support for UserProperties.  Removed Comments.\n\n* Fix logging of Exception when Test context is not available\n\n* Increase wait to 1 sec before testing for number of messages\n\n* SpinUntil instead of trying to time when requests will be processed\n\n* Update target platforms for test helpers to net8.0;net9.0\n\n* Adjust timeout to see if all messages are processed.\n\n* Reworking logging to reduce logging for routine message delivery\n\n* Fixed static Log class merge errors\n\n* Fix up passing of exception and port to new Log API.","commit-date":"2025-04-09T08:57:56Z","current-rev":"099708800","filename":"Brighter/src/Paramore.Brighter.MessagingGateway.MQTT/MQTTMessageConsumer.cs","previous-rev":"0741b9ef1","commit-title":"feature: refactoring of MQTT Support to use 4.3 MQTTnet (#3578)","language":"C#","id":"d27e8bc6b9d615c647eca3faefa2e0371bd11b02","model-score":0.3,"author-id":null,"project-id":32198,"delta-file-score":0.51462585,"diff":"diff --git a/src/Paramore.Brighter.MessagingGateway.MQTT/MQTTMessageConsumer.cs b/src/Paramore.Brighter.MessagingGateway.MQTT/MQTTMessageConsumer.cs\nindex 974658e30..dfeca6cff 100644\n--- a/src/Paramore.Brighter.MessagingGateway.MQTT/MQTTMessageConsumer.cs\n+++ b/src/Paramore.Brighter.MessagingGateway.MQTT/MQTTMessageConsumer.cs\n@@ -1,5 +1,3 @@\n ﻿using System;\n-using System.Buffers;\n using System.Collections.Generic;\n-using System.Text;\n using System.Text.Json;\n@@ -9,2 +7,3 @@\n using MQTTnet;\n+using MQTTnet.Client;\n using MQTTnet.Packets;\n@@ -16,12 +15,12 @@ namespace Paramore.Brighter.MessagingGateway.MQTT\n     /// <summary>\n-    /// Class MQTTMessageConsumer.\n-    /// The <see cref=\"MQTTMessageConsumer\"/> is used on the server to receive messages from the broker. It abstracts away the details of \n+    /// Class MqttMessageConsumer.\n+    /// The <see cref=\"MqttMessageConsumer\"/> is used on the server to receive messages from the broker. It abstracts away the details of \n     /// inter-process communication tasks from the server. It handles subscription establishment, request reception and dispatching.\n     /// </summary>\n-    public partial class MQTTMessageConsumer : IAmAMessageConsumerSync, IAmAMessageConsumerAsync\n+    public partial class MqttMessageConsumer : IAmAMessageConsumerSync, IAmAMessageConsumerAsync\n     {\n         private readonly string _topic;\n-        private readonly Queue<Message> _messageQueue = new Queue<Message>();\n-        private static readonly ILogger s_logger = ApplicationLogging.CreateLogger<MQTTMessageConsumer>();\n-        private readonly Message _noopMessage = new Message();\n+        private readonly Queue<Message> _messageQueue = new();\n+        private static readonly ILogger s_logger = ApplicationLogging.CreateLogger<MqttMessageConsumer>();\n+        private readonly Message _noopMessage = new();\n         private readonly IMqttClient _mqttClient;\n@@ -30,10 +29,22 @@ public partial class MQTTMessageConsumer : IAmAMessageConsumerSync, IAmAMessageC\n         /// <summary>\n-        /// Initializes a new instance of the <see cref=\"MQTTMessageConsumer\" /> class.\n-        /// Sync over Async within constructor\n+        /// Initializes a new instance of the <see cref=\"MqttMessageConsumer\"/> class.\n         /// </summary>\n-        /// <param name=\"configuration\"></param>\n-        public MQTTMessageConsumer(MQTTMessagingGatewayConsumerConfiguration configuration)\n+        /// <param name=\"configuration\">\n+        /// The configuration settings for the MQTT message consumer, including connection details, \n+        /// topic prefix, client credentials, and other options.\n+        /// </param>\n+        /// <exception cref=\"ArgumentNullException\">\n+        /// Thrown when the <paramref name=\"configuration.TopicPrefix\"/> is null.\n+        /// </exception>\n+        /// <remarks>\n+        /// This constructor sets up the MQTT client with the provided configuration, establishes \n+        /// the connection to the broker, and subscribes to the specified topic.\n+        ///\n+        /// 04/03/2025:\n+        ///     - Removed support for user properties as they are not supported in v3.1.1 of the MQTT protocol.\n+        /// </remarks>\n+        public MqttMessageConsumer(MqttMessagingGatewayConsumerConfiguration configuration)\n         {\n-            _topic =  $\"{configuration.TopicPrefix}/#\" ?? throw new ArgumentNullException(nameof(configuration.TopicPrefix));\n-            \n+            _topic = $\"{configuration.TopicPrefix}/#\" ?? throw new ArgumentNullException(nameof(configuration.TopicPrefix));\n+\n             MqttClientOptionsBuilder mqttClientOptionsBuilder = new MqttClientOptionsBuilder()\n@@ -52,7 +63,9 @@ public MQTTMessageConsumer(MQTTMessagingGatewayConsumerConfiguration configurati\n \n-            _mqttClientOptions = mqttClientOptionsBuilder.Build();\n+            _mqttClientOptions = mqttClientOptionsBuilder\n+                .WithTcpServer(configuration.Hostname, configuration.Port)\n+                .Build();\n \n-            //TODO: Switch to using the low level client here, as it allows us explicit control over ack, recieve etc.\n+            //TODO: Switch to using the low level client here, as it allows us explicit control over ack, receive etc.\n             //This is slated for post V10, for now, we just want to upgrade this support the V10 release\n-            _mqttClient = new MqttClientFactory().CreateMqttClient();\n+            _mqttClient = new MqttFactory().CreateMqttClient();\n \n@@ -61,36 +74,4 @@ public MQTTMessageConsumer(MQTTMessagingGatewayConsumerConfiguration configurati\n                 Log.MqttMessageConsumerReceivedMessage(s_logger, configuration.TopicPrefix);\n-                var message = JsonSerializer.Deserialize<Message>(e.ApplicationMessage.Payload.ToArray(), JsonSerialisationOptions.Options);\n-                foreach (MqttUserProperty property in e.ApplicationMessage.UserProperties)\n-                {\n-                    if (property.Name == HeaderNames.Type)\n-                    {\n-                        message.Header.Type = property.Value;\n-                    }\n-                    else if (property.Name == HeaderNames.SpecVersion)\n-                    {\n-                        message.Header.SpecVersion = property.Value;\n-                    }\n-                    else if (property.Name == HeaderNames.Source)\n-                    {\n-                        if (Uri.TryCreate(property.Value, UriKind.RelativeOrAbsolute, out var source))\n-                        {\n-                            message.Header.Source = source;\n-                        }\n-                    }\n-                    else if (property.Name == HeaderNames.Subject)\n-                    {\n-                        message.Header.Subject = property.Value;\n-                    }\n-                    else if (property.Name == HeaderNames.DataContentType)\n-                    {\n-                        message.Header.ContentType = property.Value;\n-                    }\n-                    else if (property.Name == HeaderNames.DataSchema)\n-                    {\n-                        if (Uri.TryCreate(property.Value, UriKind.RelativeOrAbsolute, out var dataSchema))\n-                        {\n-                            message.Header.DataSchema = dataSchema;\n-                        }\n-                    }\n-                }\n+                var message = JsonSerializer.Deserialize<Message>(e.ApplicationMessage.PayloadSegment.ToArray(), JsonSerialisationOptions.Options);\n+\n                 _messageQueue.Enqueue(message);\n@@ -112,3 +93,3 @@ public void Acknowledge(Message message)\n         }\n-        \n+\n         /// <summary>\n@@ -117,3 +98,3 @@ public void Acknowledge(Message message)\n         /// <param name=\"message\"></param>\n-        public Task AcknowledgeAsync(Message message, CancellationToken cancellationToken = default(CancellationToken))\n+        public Task AcknowledgeAsync(Message message, CancellationToken cancellationToken = default)\n         {\n@@ -127,8 +108,8 @@ public void Dispose()\n         }\n-        \n-        \n+\n+\n         public ValueTask DisposeAsync()\n         {\n-           _mqttClient.Dispose();\n-           return new ValueTask(Task.CompletedTask);\n+            _mqttClient.Dispose();\n+            return new ValueTask(Task.CompletedTask);\n         }\n@@ -142,3 +123,3 @@ public void Purge()\n         }\n-        \n+\n         /// <summary>\n@@ -147,6 +128,6 @@ public void Purge()\n         /// <param name=\"cancellationToken\">Allows cancellation of the purge task</param>\n-        public Task PurgeAsync(CancellationToken cancellationToken = default(CancellationToken))\n+        public Task PurgeAsync(CancellationToken cancellationToken = default)\n         {\n-           Purge();\n-           return Task.CompletedTask;\n+            Purge();\n+            return Task.CompletedTask;\n         }\n@@ -159,4 +140,6 @@ public Message[] Receive(TimeSpan? timeOut = null)\n         {\n-            if (_messageQueue.Count==0)\n+            if (_messageQueue.Count == 0)\n+            {\n                 return new[] { _noopMessage };\n+            }\n \n@@ -175,5 +158,5 @@ public Message[] Receive(TimeSpan? timeOut = null)\n                     }\n-                    catch (TimeoutException)\n+                    catch (TimeoutException te)\n                     {\n-                        Log.MqttMessageConsumerTimedOutRetrievingMessages(s_logger, _messageQueue.Count);\n+                        Log.MqttMessageConsumerTimedOutRetrievingMessages(s_logger, te, _messageQueue.Count);\n                     }\n@@ -184,4 +167,4 @@ public Message[] Receive(TimeSpan? timeOut = null)\n         }\n-        \n-        public Task<Message[]> ReceiveAsync(TimeSpan? timeOut = null, CancellationToken cancellationToken = default(CancellationToken))\n+\n+        public Task<Message[]> ReceiveAsync(TimeSpan? timeOut = null, CancellationToken cancellationToken = default)\n         {\n@@ -203,3 +186,3 @@ public void Reject(Message message)\n         /// <param name=\"cancellationToken\"></param>\n-        public Task RejectAsync(Message message, CancellationToken cancellationToken = default(CancellationToken))\n+        public Task RejectAsync(Message message, CancellationToken cancellationToken = default)\n         {\n@@ -218,5 +201,5 @@ public bool Requeue(Message message, TimeSpan? delay = null)\n         }\n-        \n+\n         public Task<bool> RequeueAsync(Message message, TimeSpan? delay = null,\n-            CancellationToken cancellationToken = default(CancellationToken))\n+            CancellationToken cancellationToken = default)\n         {\n@@ -239,5 +222,5 @@ private async Task Connect(int connectionAttempts)\n                 }\n-                catch (Exception)\n+                catch (Exception ex)\n                 {\n-                    Log.UnableToConnectMqttConsumerClient(s_logger);\n+                    Log.UnableToConnectMqttConsumerClient(s_logger, ex);\n                 }\n@@ -248,7 +231,7 @@ private static partial class Log\n         {\n-            [LoggerMessage(LogLevel.Information, \"MQTTMessageConsumer: Received message from queue {TopicPrefix}\")]\n+            [LoggerMessage(LogLevel.Trace, \"MQTTMessageConsumer: Received message from queue {TopicPrefix}\")]\n             public static partial void MqttMessageConsumerReceivedMessage(ILogger logger, object topicPrefix);\n \n-            [LoggerMessage(LogLevel.Warning, \"MQTTMessageConsumer: Timed out retrieving messages.  Queue length: {QueueLength}\")]\n-            public static partial void MqttMessageConsumerTimedOutRetrievingMessages(ILogger logger, int queueLength);\n+            [LoggerMessage(Level = LogLevel.Warning, Message = \"MQTTMessageConsumer: Timed out retrieving messages.  Queue length: {QueueLength}\")]\n+            public static partial void MqttMessageConsumerTimedOutRetrievingMessages(ILogger logger, Exception ex, int queueLength);\n \n@@ -259,5 +242,5 @@ private static partial class Log\n             public static partial void SubscribedToTopic(ILogger logger, string topic);\n-            \n-            [LoggerMessage(LogLevel.Error, \"Unable to connect MQTT Consumer Client\")]\n-            public static partial void UnableToConnectMqttConsumerClient(ILogger logger);\n+\n+            [LoggerMessage(Level = LogLevel.Error, Message = \"Unable to connect MQTT Consumer Client\")]\n+            public static partial void UnableToConnectMqttConsumerClient(ILogger logger, Exception ex);\n         }\n","improvement-type":"Complex Method"},{"architectural-component-id":null,"author-name":"Tom Longhurst","training-data":{"loc-added":"74","loc-deleted":"33","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.0","delta-n-functions":"0","current-file-score":"9.387218218812514"},"author-email":"30480171+thomhurst@users.noreply.github.com","commit-full-message":"* fix: serialise Dispatcher.Start so consumers are Open before Receive() returns (#4075)\n\nDispatcher.Start() flipped State to DS_RUNNING before opening consumers, so\nReceive()'s busy-wait could return while some consumers were still Shut. A\nShut()/End() racing into that window no-op'd against not-yet-Open consumers\n(Consumer.Shut only acts when State == Open). The control task then opened\nthose consumers, leaving orphan performers parked in Task.Delay forever and\nhanging End() in Task.WaitAny.\n\nOpen every consumer and register its task before publishing DS_RUNNING, and\nreplace the 100ms poll with a TaskCompletionSource that gives callers an\nexplicit happens-before edge over the opens. Add a lock + pending-shut flag\non Consumer so a Shut() arriving before Open() is honoured (defence in depth\nfor any future caller path that opens off the control task).\n\n* chore: trim verbose comments on #4075 fix\n\n* refactor: flatten Dispatcher.Start nesting (CodeScene Bumpy Road)\n\nExtract control-loop body into RunControlLoop, then split into\nTryOpenConsumers, WaitForPerformersToStop, HandleNextStoppedPerformer,\nand RemoveConsumerForTask. Each helper has at most one level of\nconditional nesting, killing the \"Bumpy Road Ahead\" flag on\nPR #4081 without changing behavior.\n\n* refactor: simplify TryOpenConsumers and drop redundant OfType\n\n- Collapse TryOpenConsumers (bool, dead false-branch) into void\n  OpenConsumers; move TCS signalling and try/catch up into\n  RunControlLoop where they belong.\n- Iterate Consumers directly instead of OfType<Consumer>(); the\n  IAmAConsumer interface already exposes Open/Job/JobId.\n\n---------\n\nCo-authored-by: Ian Cooper <ian_hammond_cooper@yahoo.co.uk>","commit-date":"2026-04-26T17:18:29Z","current-rev":"f94246cd8","filename":"Brighter/src/Paramore.Brighter.ServiceActivator/Dispatcher.cs","previous-rev":"3a0528638","commit-title":"fix: Dispatcher shutdown race leaves late-opened Reactor consumers running (#4075) (#4081)","language":"C#","id":"b453d2853c4228105b707fea96483f93cd8ee3c1","model-score":0.1,"author-id":null,"project-id":32198,"delta-file-score":0.84183866,"diff":"diff --git a/src/Paramore.Brighter.ServiceActivator/Dispatcher.cs b/src/Paramore.Brighter.ServiceActivator/Dispatcher.cs\nindex 8abdbe43d..a9ca4b575 100644\n--- a/src/Paramore.Brighter.ServiceActivator/Dispatcher.cs\n+++ b/src/Paramore.Brighter.ServiceActivator/Dispatcher.cs\n@@ -284,63 +284,104 @@ private void Start()\n         {\n-            _controlTask = Task.Factory.StartNew(() =>\n+            // Block Start() callers until every consumer is Open. A Shut()/End() racing in\n+            // immediately after Receive() returns must not see a still-Shut consumer, or the\n+            // late-opened performer leaks and End() hangs forever in Task.WaitAny.\n+            var startup = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);\n+\n+            _controlTask = Task.Factory.StartNew(\n+                () => RunControlLoop(startup),\n+                CancellationToken.None,\n+                TaskCreationOptions.LongRunning,\n+                TaskScheduler.Default);\n+\n+            startup.Task.GetAwaiter().GetResult();\n+        }\n+\n+        private void RunControlLoop(TaskCompletionSource<bool> startup)\n+        {\n+            if (State != DispatcherState.DS_AWAITING && State != DispatcherState.DS_STOPPED)\n             {\n-                if (State == DispatcherState.DS_AWAITING || State == DispatcherState.DS_STOPPED)\n-                {\n-                    Log.DispatcherStarting(s_logger);\n-                    State = DispatcherState.DS_RUNNING;\n+                startup.TrySetResult(true);\n+                return;\n+            }\n+\n+            Log.DispatcherStarting(s_logger);\n+\n+            try\n+            {\n+                OpenConsumers();\n+                State = DispatcherState.DS_RUNNING;\n+                startup.TrySetResult(true);\n+            }\n+            catch (Exception ex)\n+            {\n+                Log.ErrorOnConsumer(s_logger, ex);\n+                startup.TrySetException(ex);\n+                throw;\n+            }\n+\n+            Log.DispatcherStartingPerformers(s_logger, _tasks.Count);\n \n-                    var consumers = Consumers.ToArray();\n-                    consumers.Each(consumer => consumer.Open());\n-                    consumers.Each(consumer => _tasks.TryAdd(consumer.JobId, consumer.Job!));\n+            WaitForPerformersToStop();\n+\n+            State = DispatcherState.DS_STOPPED;\n+            Log.DispatcherStopped(s_logger);\n+        }\n \n-                    Log.DispatcherStartingPerformers(s_logger, _tasks.Count);\n+        private void OpenConsumers()\n+        {\n+            foreach (var consumer in Consumers)\n+            {\n+                consumer.Open();\n+                if (consumer.Job is not null)\n+                    _tasks.TryAdd(consumer.JobId, consumer.Job);\n+            }\n+        }\n \n-                    while (_tasks.Any())\n+        private void WaitForPerformersToStop()\n+        {\n+            while (!_tasks.IsEmpty)\n+            {\n+                try\n+                {\n+                    HandleNextStoppedPerformer();\n+                }\n+                catch (AggregateException ae)\n+                {\n+                    ae.Handle(ex =>\n                     {\n-                        try\n-                        {\n-                            var runningTasks = _tasks.Values.ToArray();\n-                            var index = Task.WaitAny(runningTasks);\n-                            var stoppingConsumer = runningTasks[index];\n-                            Log.PerformerStopped(s_logger, stoppingConsumer.Status);\n-\n-                            var consumer = Consumers.SingleOrDefault(c => c.JobId == stoppingConsumer.Id);\n-                            if (consumer != null)\n-                            {\n-                                Log.RemovingConsumer(s_logger, consumer.Name);\n-\n-                                if (_consumers.TryRemove(consumer.Name, out consumer))\n-                                {\n-                                    consumer.Dispose();\n-                                }\n-                            }\n-\n-                            if (_tasks.TryRemove(stoppingConsumer.Id, out var removedTask))\n-                            {\n-                                removedTask?.Dispose();\n-                            }\n-\n-                            stoppingConsumer.Dispose();\n-                        }\n-                        catch (AggregateException ae)\n-                        {\n-                            ae.Handle(ex =>\n-                            {\n-                                Log.ErrorOnConsumer(s_logger, ex);\n-                                return true;\n-                            });\n-                        }\n-                    }\n-\n-                    State = DispatcherState.DS_STOPPED;\n-                    Log.DispatcherStopped(s_logger);\n+                        Log.ErrorOnConsumer(s_logger, ex);\n+                        return true;\n+                    });\n                 }\n-            },\n-            CancellationToken.None,\n-            TaskCreationOptions.LongRunning,\n-            TaskScheduler.Default);\n+            }\n+        }\n+\n+        private void HandleNextStoppedPerformer()\n+        {\n+            var runningTasks = _tasks.Values.ToArray();\n+            var index = Task.WaitAny(runningTasks);\n+            var stoppingConsumer = runningTasks[index];\n+            Log.PerformerStopped(s_logger, stoppingConsumer.Status);\n+\n+            RemoveConsumerForTask(stoppingConsumer);\n+\n+            if (_tasks.TryRemove(stoppingConsumer.Id, out var removedTask))\n+            {\n+                removedTask?.Dispose();\n+            }\n+\n+            stoppingConsumer.Dispose();\n+        }\n+\n+        private void RemoveConsumerForTask(Task stoppingConsumer)\n+        {\n+            var consumer = Consumers.SingleOrDefault(c => c.JobId == stoppingConsumer.Id);\n+            if (consumer is null)\n+                return;\n+\n+            Log.RemovingConsumer(s_logger, consumer.Name);\n \n-            while (State != DispatcherState.DS_RUNNING)\n+            if (_consumers.TryRemove(consumer.Name, out consumer))\n             {\n-                Thread.Sleep(100); //Block main Dispatcher thread whilst control plane starts\n+                consumer.Dispose();\n             }\n","improvement-type":"Complex Method"},{"architectural-component-id":null,"author-name":"Ian Cooper","training-data":{"loc-added":"30","loc-deleted":"42","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.0","delta-n-functions":"0","current-file-score":"8.816158827775617"},"author-email":"ian_hammond_cooper@yahoo.co.uk","commit-full-message":"Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>\nClaude-Session: https://claude.ai/code/session_01HsKD52dnGHFLSEr93VZyR7","commit-date":"2026-10-12T13:23:04Z","current-rev":"90502e627","filename":"Brighter/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxMigrationRunner.cs","previous-rev":"7aca96a83","commit-title":"refactor: extract methods to express intent in BoxProvisioning.PostgreSql","language":"C#","id":"0d77d6fdfc8105fa700f57319eb18dbc943942d9","model-score":0.1,"author-id":null,"project-id":32198,"delta-file-score":0.27077925,"diff":"diff --git a/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxMigrationRunner.cs b/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxMigrationRunner.cs\nindex 6a49eb25c..0634c4503 100644\n--- a/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxMigrationRunner.cs\n+++ b/src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxMigrationRunner.cs\n@@ -118,14 +118,14 @@ protected override string LockResourceFor(string? schemaName, string tableName)\n \n-    // Quoted, and so folded, the same way the detection helper reads it.\n-    private string QuotedHistorySchema()\n+    // Never null here: DefaultHistorySchema is \"public\", and the base rejects PerSchema without a\n+    // SchemaName before migrating.\n+    private string ValidatedHistorySchema()\n     {\n-        // The `!` is safe: DefaultHistorySchema returns the non-null \"public\" const on this runner\n-        // and the D3 guard rejects PerSchema with a null SchemaName before MigrateAsync proceeds,\n-        // so ResolveHistorySchema() is provably non-null here. If a future refactor breaks that\n-        // invariant, NRE points at this line.\n-        var schema = ResolveHistorySchema()!;\n-        Identifiers.AssertSafe(schema, nameof(schema));\n-        return PgIdentifier.Quote(schema);\n+        var resolvedHistorySchema = ResolveHistorySchema()!;\n+        Identifiers.AssertSafe(resolvedHistorySchema, nameof(resolvedHistorySchema));\n+        return resolvedHistorySchema;\n     }\n \n+    // Quoted, and so folded, the same way the detection helper reads it.\n+    private string QuotedHistorySchema() => PgIdentifier.Quote(ValidatedHistorySchema());\n+\n     protected override async Task EnsureHistoryTableAsync(\n@@ -134,11 +134,3 @@ protected override async Task EnsureHistoryTableAsync(\n     {\n-        // Resolve the physical history schema once. Under PerSchema it's the configured (non-null)\n-        // SchemaName; under Global it is the backend default (\"public\"). The detection helper folds\n-        // the same value the same way (PgIdentifier.Quote / Normalize), so write and read never\n-        // diverge. AssertSafe guards against any unsafe schema literal leaking into the inline DDL.\n-        // The `!` is safe: DefaultHistorySchema returns the non-null \"public\" const on this runner\n-        // and the D3 guard rejects PerSchema with a null SchemaName before MigrateAsync proceeds,\n-        // so ResolveHistorySchema() is provably non-null here.\n-        var resolvedHistorySchema = ResolveHistorySchema()!;\n-        Identifiers.AssertSafe(resolvedHistorySchema, nameof(resolvedHistorySchema));\n+        var resolvedHistorySchema = ValidatedHistorySchema();\n         var historySchemaQuoted = PgIdentifier.Quote(resolvedHistorySchema);\n@@ -146,14 +138,24 @@ protected override async Task EnsureHistoryTableAsync(\n \n-        // D5 (ADR 0060): on a PerSchema run that follows a Global predecessor, copy this tenant's\n-        // prior history rows from the legacy public.__BrighterMigrationHistory so the runner does\n-        // NOT mis-detect the box as needing a bootstrap re-stamp (which would silently re-run\n-        // migration accounting and break FR5). Skipped when the folded resolved history schema\n-        // equals the folded backend default (Global, or PerSchema with SchemaName == \"public\") —\n-        // then per-schema and legacy are the same table and there is nothing to copy.\n-        var needsSeedCheck = !string.Equals(historySchemaFolded, HISTORY_TABLE_SCHEMA, StringComparison.Ordinal);\n+        var historyIsSeparateFromLegacy = !string.Equals(historySchemaFolded, HISTORY_TABLE_SCHEMA, StringComparison.Ordinal);\n \n-        using (var command = connection.CreateCommand())\n+        await CreateHistoryTableAsync(connection, transaction, historySchemaQuoted, cancellationToken);\n+\n+        if (historyIsSeparateFromLegacy)\n         {\n-            command.Transaction = transaction;\n-            command.CommandText = $@\"\n+            await SeedHistoryFromLegacyAsync(\n+                connection, transaction, historySchemaQuoted, resolvedHistorySchema,\n+                schemaName ?? resolvedHistorySchema, tableName, cancellationToken);\n+        }\n+    }\n+\n+    // A provisioner for another box can race this CREATE (ADR 0057 §3). Postgres aborts the whole\n+    // transaction on the loser's duplicate error even when it is caught, so the CREATE runs inside\n+    // a savepoint that the catch rolls back to.\n+    private async Task CreateHistoryTableAsync(\n+        NpgsqlConnection connection, NpgsqlTransaction? transaction, string historySchemaQuoted,\n+        CancellationToken cancellationToken)\n+    {\n+        using var command = connection.CreateCommand();\n+        command.Transaction = transaction;\n+        command.CommandText = $@\"\n CREATE TABLE IF NOT EXISTS {historySchemaQuoted}.\"\"{MIGRATION_HISTORY_TABLE}\"\" (\n@@ -166,43 +168,29 @@ PRIMARY KEY (\"\"SchemaName\"\", \"\"BoxTableName\"\", \"\"MigrationVersion\"\")\n )\";\n-            // Postgres marks the outer transaction as aborted on a catalog-level duplicate-type\n-            // error from CREATE TABLE IF NOT EXISTS regardless of whether we catch it. Without a\n-            // savepoint the catch below leaves the transaction \"poisoned\" — RedetectStateAsync's\n-            // next statement then fails with 25P02 even though our swallow was intentional. A\n-            // SAVEPOINT around the CREATE narrows the abort to the inner sub-transaction, so\n-            // ROLLBACK TO SAVEPOINT restores a usable transaction state on the racing path.\n+        if (transaction is not null)\n+        {\n+            await transaction.SaveAsync(HistoryTableSavepoint, cancellationToken);\n+        }\n+        try\n+        {\n+            await command.ExecuteNonQueryAsync(cancellationToken);\n             if (transaction is not null)\n             {\n-                await transaction.SaveAsync(HistoryTableSavepoint, cancellationToken);\n-            }\n-            try\n-            {\n-                await command.ExecuteNonQueryAsync(cancellationToken);\n-                if (transaction is not null)\n-                {\n-                    await transaction.ReleaseAsync(HistoryTableSavepoint, cancellationToken);\n-                }\n+                await transaction.ReleaseAsync(HistoryTableSavepoint, cancellationToken);\n             }\n-            catch (PostgresException ex) when (\n-                ex.SqlState == PostgresErrorCodes.UniqueViolation\n-                || ex.SqlState == PostgresErrorCodes.DuplicateTable\n-                || ex.SqlState == PostgresErrorCodes.DuplicateObject)\n+        }\n+        catch (PostgresException ex) when (\n+            ex.SqlState == PostgresErrorCodes.UniqueViolation\n+            || ex.SqlState == PostgresErrorCodes.DuplicateTable\n+            || ex.SqlState == PostgresErrorCodes.DuplicateObject)\n+        {\n+            if (transaction is not null)\n             {\n-                if (transaction is not null)\n-                {\n-                    await transaction.RollbackAsync(HistoryTableSavepoint, cancellationToken);\n-                }\n-\n-                Logger.LogDebug(ex,\n-                    \"{HistoryTable} already created by racing session (Postgres SqlState {SqlState})\",\n-                    MIGRATION_HISTORY_TABLE, ex.SqlState);\n-                Activity.Current?.AddEvent(new ActivityEvent(\n-                    BrighterSemanticConventions.BoxMigrationEventHistoryTableRaceSwallowed));\n+                await transaction.RollbackAsync(HistoryTableSavepoint, cancellationToken);\n             }\n-        }\n \n-        if (needsSeedCheck)\n-        {\n-            await SeedHistoryFromLegacyAsync(\n-                connection, transaction, historySchemaQuoted, resolvedHistorySchema,\n-                schemaName ?? resolvedHistorySchema, tableName, cancellationToken);\n+            Logger.LogDebug(ex,\n+                \"{HistoryTable} already created by racing session (Postgres SqlState {SqlState})\",\n+                MIGRATION_HISTORY_TABLE, ex.SqlState);\n+            Activity.Current?.AddEvent(new ActivityEvent(\n+                BrighterSemanticConventions.BoxMigrationEventHistoryTableRaceSwallowed));\n         }\n@@ -301,3 +289,3 @@ SELECT 1 FROM {perSchemaQuoted}.\"\"{MIGRATION_HISTORY_TABLE}\"\" AS tgt\n     private static bool IsLegacyHistoryReadPermissionDenied(PostgresException ex) =>\n-        ex.SqlState == \"42501\";\n+        ex.SqlState == PostgresErrorCodes.InsufficientPrivilege;\n \n","improvement-type":"Complex Method"},{"architectural-component-id":null,"author-name":"Ian Cooper","training-data":{"loc-added":"69","loc-deleted":"78","delta-cc-mean":"0.0","delta-cc-total":"0","delta-penalties":"1.944","delta-n-functions":"0","current-file-score":"8.715400157423334"},"author-email":"ian_hammond_cooper@yahoo.co.uk","commit-full-message":"Replace explanatory comments in SqlBoxMigrationRunner.MigrateAsync,\nSqlBoxProvisioner.ProvisionAsync and UseBoxProvisioning with private\nmethods whose names carry the intent (GuardIdentifiers, GetMigrations,\nRollbackWithoutMaskingAsync, ReleaseAsync, ReadHistoryExistsHintAsync,\nRegisterProvisionersThenMarker, ...), keeping a short comment above a\nsignature only where the name cannot carry a trap.\n\nCo-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>\nClaude-Session: https://claude.ai/code/session_01HsKD52dnGHFLSEr93VZyR7","commit-date":"2026-10-11T18:52:01Z","current-rev":"5253c5133","filename":"Brighter/src/Paramore.Brighter.BoxProvisioning/SqlBoxMigrationRunner.cs","previous-rev":"0dcac0a6e","commit-title":"refactor: extract methods to express intent in BoxProvisioning","language":"C#","id":"7f99866c7425afba46bf58093b14e41f01bacae6","model-score":0.02,"author-id":null,"project-id":32198,"delta-file-score":0.15510798,"diff":"diff --git a/src/Paramore.Brighter.BoxProvisioning/SqlBoxMigrationRunner.cs b/src/Paramore.Brighter.BoxProvisioning/SqlBoxMigrationRunner.cs\nindex 33df98923..491109e0e 100644\n--- a/src/Paramore.Brighter.BoxProvisioning/SqlBoxMigrationRunner.cs\n+++ b/src/Paramore.Brighter.BoxProvisioning/SqlBoxMigrationRunner.cs\n@@ -182,49 +182,6 @@ public async Task MigrateAsync(\n     {\n-        // Defence-in-depth at the framework chokepoint. Catalogs gate AssertSafe at the entry to\n-        // All(...), but the runner is independently reachable (callers can construct a migration\n-        // list and invoke MigrateAsync directly), so the public entry point must validate too.\n-        Identifiers.AssertSafe(tableName.Value, nameof(tableName));\n-\n-        // schemaName is optional: SQLite has no schema concept per ADR 0057 §6, so an absent value\n-        // is legitimate and must not be rejected as \"missing\". A SchemaName is \"absent\" when it is\n-        // a null reference OR wraps a null/empty string — callers commonly reach the latter via the\n-        // implicit string->SchemaName conversion of a null/empty value (e.g. an unconfigured\n-        // RelationalDatabaseConfiguration.SchemaName). Collapse every absent form to a single null\n-        // using SchemaName.IsNullOrEmpty (the canonical \"absent\" check, mirroring Id.IsNullOrEmpty)\n-        // so the AssertSafe gate and every downstream `schemaName?.Value ?? <backend default>` treat\n-        // them identically — preserving the semantics of the `string?` parameter this value type\n-        // replaced (spec 0030), which a bare `is not null` reference check silently broke.\n-        if (SchemaName.IsNullOrEmpty(schemaName))\n-        {\n-            schemaName = null;\n-        }\n-        else\n-        {\n-            Identifiers.AssertSafe(schemaName.Value, nameof(schemaName));\n-        }\n-\n-        // D3 misconfiguration guard (FR1a/AC1a): on a placement backend, PerSchema needs a schema\n-        // to place history in. A null SchemaName is an operator misconfiguration — reject it at the\n-        // entry point rather than silently falling back to Global. Backends that do not support\n-        // PerSchema (MySQL/SQLite) never trip this; for them PerSchema is a no-op.\n-        if (Scope == MigrationHistoryScope.PerSchema && SupportsPerSchemaHistory && Configuration.SchemaName is null)\n-        {\n-            throw new ConfigurationException(\n-                \"MigrationHistoryScope.PerSchema requires a non-null SchemaName; there is no schema to place history in.\");\n-        }\n-\n-        // The runner sources its migration chain and fresh-install DDL\n-        // from the injected catalog rather than via parameter. A catalog returning null for\n-        // either would surface inside ValidateMigrationsMonotonic / ExecuteFreshInstallAsync as\n-        // an opaque NRE; replace with a descriptive operator-facing diagnostic. Empty migration\n-        // lists are intentionally permitted: relational catalogs always return ≥V1, and\n-        // internal tests use Array.Empty<IAmABoxMigration>() as a \"don't care\" payload when\n-        // exercising hook-ordering, re-detection, or failure-path contracts.\n-        var migrations = _catalog.All(_configuration);\n-        if (migrations is null)\n-        {\n-            throw new ConfigurationException(\n-                $\"Migration list for '{(schemaName is null ? tableName : $\"{schemaName}.{tableName}\")}' was null. The injected IAmABoxMigrationCatalog must return a non-null list from All(...).\");\n-        }\n+        schemaName = GuardIdentifiers(tableName, schemaName);\n+        ThrowIfPerSchemaHasNoSchema();\n \n+        var migrations = GetMigrations(tableName, schemaName);\n         ValidateMigrationsMonotonic(schemaName?.Value, tableName.Value, migrations);\n@@ -233,16 +190,4 @@ public async Task MigrateAsync(\n \n-        // Spec 0029 NF5/AC7 (ADR 0060 D6): surface the placement decision per run so an operator\n-        // can answer \"where did THIS tenant's migration history go?\" without correlating to the\n-        // provisioner config. The single Information log carries the table, the resolved physical\n-        // history schema (or the placeholder \"<backend default>\" on backends with no distinct\n-        // history schema concept, e.g. SQLite / MySQL), and the active MigrationHistoryScope.\n-        // Fires once per run regardless of which path (fresh / bootstrap / normal) dispatches.\n-        Logger.LogInformation(\n-            \"Box migration history for {BoxTable} resolved to schema {HistorySchema} (scope {Scope})\",\n-            tableName, ResolveHistorySchema() ?? \"<backend default>\", _scope);\n+        LogHistoryPlacement(tableName);\n \n-        // Sync Dispose for the connection: DbConnection does not implement IAsyncDisposable\n-        // on netstandard2.0, so DisposeAsync is unavailable across the shared-assembly TFM\n-        // matrix. The UoW implements IAsyncDisposable (see IAmAProvisioningUnitOfWork) and\n-        // is awaited explicitly in the finally.\n         TConnection? connection = null;\n@@ -305,22 +250,3 @@ await RunNormalPathAsync(\n                 activity?.AddException(ex);\n-                // Pass CancellationToken.None: a signalled caller token must not abandon the unwind.\n-                // See ADR 0058 §B.3 cancellation contract.\n-                try\n-                {\n-                    await uow.RollbackAsync(CancellationToken.None);\n-                }\n-                catch (Exception rollbackEx)\n-                {\n-                    // Defense in depth: the IAmAProvisioningUnitOfWork contract says RollbackAsync\n-                    // MUST NOT throw, and the four per-backend impls comply (PG and MySQL tightened\n-                    // explicitly in 3c8417fd6). If a future regression breaks that, do NOT let the\n-                    // rollback exception mask the original triggering exception — the primary cause\n-                    // is more diagnostically valuable than a defect in our own unwind, and callers\n-                    // pattern-match on the type they actually threw. Log the rollback failure at\n-                    // Error level so operators see both: the primary failure surfaces via rethrow,\n-                    // the rollback defect surfaces via the log.\n-                    Logger.LogError(rollbackEx,\n-                        \"Box migration unit-of-work RollbackAsync threw while unwinding from a primary failure for table '{Table}'; rollback exception is logged, primary exception is rethrown.\",\n-                        tableName);\n-                }\n+                await RollbackWithoutMaskingAsync(uow, tableName);\n                 throw;\n@@ -330,13 +256,78 @@ await RunNormalPathAsync(\n         {\n-            // Disposal order mirrors the previous `await using var uow` / `using var connection`\n-            // pair: UoW first (releases any per-backend advisory lock + transaction state),\n-            // then the connection. Null checks defend the bootstrap-failure-before-assignment\n-            // case: if OpenConnectionAsync threw, both locals stay null; if BeginAsync threw,\n-            // both are assigned and need disposal.\n-            if (uow is not null)\n-            {\n-                await uow.DisposeAsync();\n-            }\n-            connection?.Dispose();\n+            await ReleaseAsync(uow, connection);\n+        }\n+    }\n+\n+    // The runner is callable without going through a catalog, so it asserts identifier safety\n+    // itself. A SchemaName that wraps a null or empty string is absent, the same as a null one.\n+    private static SchemaName? GuardIdentifiers(BoxTableName tableName, SchemaName? schemaName)\n+    {\n+        Identifiers.AssertSafe(tableName.Value, nameof(tableName));\n+\n+        if (SchemaName.IsNullOrEmpty(schemaName))\n+        {\n+            return null;\n+        }\n+\n+        Identifiers.AssertSafe(schemaName.Value, nameof(schemaName));\n+        return schemaName;\n+    }\n+\n+    private void ThrowIfPerSchemaHasNoSchema()\n+    {\n+        if (Scope == MigrationHistoryScope.PerSchema && SupportsPerSchemaHistory && Configuration.SchemaName is null)\n+        {\n+            throw new ConfigurationException(\n+                \"MigrationHistoryScope.PerSchema requires a non-null SchemaName; there is no schema to place history in.\");\n+        }\n+    }\n+\n+    // An empty chain is allowed; a null one is a catalog defect, reported here rather than as an\n+    // NRE further in.\n+    private IReadOnlyList<IAmABoxMigration> GetMigrations(BoxTableName tableName, SchemaName? schemaName)\n+    {\n+        var migrations = _catalog.All(_configuration);\n+        if (migrations is null)\n+        {\n+            throw new ConfigurationException(\n+                $\"Migration list for '{(schemaName is null ? tableName : $\"{schemaName}.{tableName}\")}' was null. The injected IAmABoxMigrationCatalog must return a non-null list from All(...).\");\n+        }\n+\n+        return migrations;\n+    }\n+\n+    // Lets an operator see where this run's migration history lives without reading the\n+    // provisioner configuration (ADR 0060).\n+    private void LogHistoryPlacement(BoxTableName tableName) =>\n+        Logger.LogInformation(\n+            \"Box migration history for {BoxTable} resolved to schema {HistorySchema} (scope {Scope})\",\n+            tableName, ResolveHistorySchema() ?? \"<backend default>\", _scope);\n+\n+    // Rolls back with CancellationToken.None so a cancelled caller cannot abandon the unwind\n+    // (ADR 0058 §B.3). RollbackAsync must not throw; if it does, the failure is logged rather\n+    // than allowed to mask the primary exception the caller is about to see.\n+    private async Task RollbackWithoutMaskingAsync(IAmAProvisioningUnitOfWork<TTransaction> uow, BoxTableName tableName)\n+    {\n+        try\n+        {\n+            await uow.RollbackAsync(CancellationToken.None);\n+        }\n+        catch (Exception rollbackEx)\n+        {\n+            Logger.LogError(rollbackEx,\n+                \"Box migration unit-of-work RollbackAsync threw while unwinding from a primary failure for table '{Table}'; rollback exception is logged, primary exception is rethrown.\",\n+                tableName);\n+        }\n+    }\n+\n+    // Releases the unit of work (lock and transaction) before the connection. Either may be null\n+    // if setup failed part way. The connection is disposed synchronously because DbConnection has\n+    // no DisposeAsync on netstandard2.0.\n+    private static async Task ReleaseAsync(IAmAProvisioningUnitOfWork<TTransaction>? uow, TConnection? connection)\n+    {\n+        if (uow is not null)\n+        {\n+            await uow.DisposeAsync();\n         }\n+        connection?.Dispose();\n     }\n","improvement-type":"Complex Method"}],"change-level":"warning","is-hotspot?":true,"line":104,"what-changed":"OutboxProducerMediator increases in cyclomatic complexity from 14 to 15, threshold = 9","how-to-fix":"There are many reasons for Complex Method. Sometimes, another design approach is beneficial such as a) modeling state using an explicit state machine rather than conditionals, or b) using table lookup rather than long chains of logic. In other scenarios, the function can be split using [EXTRACT FUNCTION](https://refactoring.com/catalog/extractFunction.html). Just make sure you extract natural and cohesive functions. Complex Methods can also be addressed by identifying complex conditional expressions and then using the [DECOMPOSE CONDITIONAL](https://refactoring.com/catalog/decomposeConditional.html) refactoring.","change-type":"degraded"},{"why-it-occurs":"Duplicated code often leads to code that's harder to change since the same logical change has to be done in multiple functions. More duplication gives lower code health.","name":"Code Duplication","file":"src/Paramore.Brighter/PipelineBuilder.cs","refactoring-examples":null,"change-level":"warning","is-hotspot?":false,"line":59,"what-changed":"introduced similar code in: PipelineBuilder,PipelineBuilder,PipelineBuilder","how-to-fix":"A certain degree of duplicated code might be acceptable. The problems start when it is the same behavior that is duplicated across the functions in the module, ie. a violation of the Don't Repeat Yourself (DRY) principle. DRY violations lead to code that is changed together in predictable patterns, which is both expensive and risky. DRY violations can be identified using CodeScene's X-Ray analysis to detect clusters of change coupled functions with high code similarity. [Read More](https://codescene.com/blog/software-revolution-part3/)\n\nOnce you have identified the similarities across functions, look to extract and encapsulate the concept that varies into its own function(s). These shared abstractions can then be re-used, which minimizes the amount of duplication and simplifies change.","change-type":"degraded"}]},"positive-impact-count":17,"repo":"Brighter","code-health":8.80214933379466,"version":"3.0","authors":["Tom Longhurst"],"directives":{"added":[],"removed":[]},"positive-findings":{"number-of-types":3,"number-of-files-touched":13,"findings":[{"name":"Primitive Obsession","file":"src/Paramore.Brighter.BoxProvisioning.MsSql/MsSqlBoxMigrationRunner.cs","change-type":"improved","change-level":"improvement","is-hotspot?":true,"why-it-occurs":"Code that uses a high degree of built-in, primitives such as integers, strings, floats, lacks a domain language that encapsulates the validation and semantics of function arguments. Primitive Obsession has several consequences: 1) In a statically typed language, the compiler will detect less erroneous assignments. 2) Security impact since the possible value range of a variable/argument isn't retricted.\n\nIn this module, 32 % of all functions have primitive types as arguments.","how-to-fix":"Primitive Obsession indicates a missing domain language. Introduce data types that encapsulate the details and constraints of your domain. For example, instead of `int userId`, consider `User clicked`.","what-changed":"The ratio of primitive types in function arguments decreases from 32.89% to 32.05%, threshold = 30.0%"},{"name":"Primitive Obsession","file":"src/Paramore.Brighter.BoxProvisioning.MySql/MySqlBoxMigrationRunner.cs","change-type":"improved","change-level":"improvement","is-hotspot?":true,"why-it-occurs":"Code that uses a high degree of built-in, primitives such as integers, strings, floats, lacks a domain language that encapsulates the validation and semantics of function arguments. Primitive Obsession has several consequences: 1) In a statically typed language, the compiler will detect less erroneous assignments. 2) Security impact since the possible value range of a variable/argument isn't retricted.\n\nIn this module, 32 % of all functions have primitive types as arguments.","how-to-fix":"Primitive Obsession indicates a missing domain language. Introduce data types that encapsulate the details and constraints of your domain. For example, instead of `int userId`, consider `User clicked`.","what-changed":"The ratio of primitive types in function arguments decreases from 33.33% to 32.26%, threshold = 30.0%"},{"name":"Primitive Obsession","file":"src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxDetectionHelper.cs","change-type":"improved","change-level":"improvement","is-hotspot?":false,"why-it-occurs":"Code that uses a high degree of built-in, primitives such as integers, strings, floats, lacks a domain language that encapsulates the validation and semantics of function arguments. Primitive Obsession has several consequences: 1) In a statically typed language, the compiler will detect less erroneous assignments. 2) Security impact since the possible value range of a variable/argument isn't retricted.\n\nIn this module, 39 % of all functions have primitive types as arguments.","how-to-fix":"Primitive Obsession indicates a missing domain language. Introduce data types that encapsulate the details and constraints of your domain. For example, instead of `int userId`, consider `User clicked`.","what-changed":"The ratio of primitive types in function arguments decreases from 40.54% to 39.47%, threshold = 30.0%"},{"name":"String Heavy Function Arguments","file":"src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxDetectionHelper.cs","change-type":"improved","change-level":"improvement","is-hotspot?":false,"why-it-occurs":"String is a generic type that fail to capture the constraints of the domain object it represents. In this module, 39 % of all function arguments are string types.","how-to-fix":"Heavy string usage indicates a missing domain language. Introduce data types that encapsulate the semantics. For example, a user_name is better represented as a constrained User type rather than a pure string, which could be anything.","what-changed":"The ratio of strings in function arguments decreases from 40.54% to 39.47%, threshold = 39.0%"},{"name":"Primitive Obsession","file":"src/Paramore.Brighter.BoxProvisioning.PostgreSql/PostgreSqlBoxMigrationRunner.cs","change-type":"improved","change-level":"improvement","is-hotspot?":true,"why-it-occurs":"Code that uses a high degree of built-in, primitives such as integers, strings, floats, lacks a domain language that encapsulates the validation and semantics of function arguments. Primitive Obsession has several consequences: 1) In a statically typed language, the compiler will detect less erroneous assignments. 2) Security impact since the possible value range of a variable/argument isn't retricted.\n\nIn this module, 33 % of all functions have primitive types as arguments.","how-to-fix":"Primitive Obsession indicates a missing domain language. Introduce data types that encapsulate the details and constraints of your domain. For example, instead of `int userId`, consider `User clicked`.","what-changed":"The ratio of primitive types in function arguments decreases from 33.77% to 32.91%, threshold = 30.0%"},{"name":"Primitive Obsession","file":"src/Paramore.Brighter.BoxProvisioning.Spanner/SpannerBoxMigrationRunner.cs","change-type":"improved","change-level":"improvement","is-hotspot?":true,"why-it-occurs":"Code that uses a high degree of built-in, primitives such as integers, strings, floats, lacks a domain language that encapsulates the validation and semantics of function arguments. Primitive Obsession has several consequences: 1) In a statically typed language, the compiler will detect less erroneous assignments. 2) Security impact since the possible value range of a variable/argument isn't retricted.\n\nIn this module, 37 % of all functions have primitive types as arguments.","how-to-fix":"Primitive Obsession indicates a missing domain language. Introduce data types that encapsulate the details and constraints of your domain. For example, instead of `int userId`, consider `User clicked`.","what-changed":"The ratio of primitive types in function arguments decreases from 38.00% to 36.54%, threshold = 30.0%"},{"name":"Primitive Obsession","file":"src/Paramore.Brighter.BoxProvisioning.Sqlite/SqliteBoxMigrationRunner.cs","change-type":"improved","change-level":"improvement","is-hotspot?":true,"why-it-occurs":"Code that uses a high degree of built-in, primitives such as integers, strings, floats, lacks a domain language that encapsulates the validation and semantics of function arguments. Primitive Obsession has several consequences: 1) In a statically typed language, the compiler will detect less erroneous assignments. 2) Security impact since the possible value range of a variable/argument isn't retricted.\n\nIn this module, 31 % of all functions have primitive types as arguments.","how-to-fix":"Primitive Obsession indicates a missing domain language. Introduce data types that encapsulate the details and constraints of your domain. For example, instead of `int userId`, consider `User clicked`.","what-changed":"The ratio of primitive types in function arguments decreases from 31.43% to 30.56%, threshold = 30.0%"},{"name":"Overall Code Complexity","file":"src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsInlineMessageCreator.cs","change-type":"fixed","change-level":"improvement","is-hotspot?":false,"why-it-occurs":"Overall Code Complexity is measured by the mean cyclomatic complexity across all functions in the file. The lower the number, the better.\n\nCyclomatic complexity is a function level metric that measures the number of logical branches (if-else, loops, etc.). Cyclomatic complexity is a rough complexity measure, but useful as a way of estimating the minimum number of unit tests you would need. As such, prefer functions with low cyclomatic complexity (2-3 branches).","how-to-fix":"You address the overall cyclomatic complexity by a) modularizing the code, and b) abstract away the complexity. Let's look at some examples:\n\nModularizing the Code: Do an X-Ray and inspect the local hotspots. Are there any complex conditional expressions? If yes, then do a [DECOMPOSE CONDITIONAL](https://refactoring.com/catalog/decomposeConditional.html) refactoring. Extract the conditional logic into a separate function and put a good name on that function. This clarifies the intent and makes the original function easier to read. Repeat until all complex conditional expressions have been simplified.\n\n","what-changed":"The mean cyclomatic complexity in this module is no longer above the threshold"},{"name":"Overall Code Complexity","file":"src/Paramore.Brighter.MessagingGateway.AWSSQS.V4/SqsMessageCreator.cs","change-type":"improved","change-level":"improvement","is-hotspot?":false,"why-it-occurs":"Overall Code Complexity is measured by the mean cyclomatic complexity across all functions in the file. The lower the number, the better.\n\nCyclomatic complexity is a function level metric that measures the number of logical branches (if-else, loops, etc.). Cyclomatic complexity is a rough complexity measure, but useful as a way of estimating the minimum number of unit tests you would need. As such, prefer functions with low cyclomatic complexity (2-3 branches).","how-to-fix":"You address the overall cyclomatic complexity by a) modularizing the code, and b) abstract away the complexity. Let's look at some examples:\n\nModularizing the Code: Do an X-Ray and inspect the local hotspots. Are there any complex conditional expressions? If yes, then do a [DECOMPOSE CONDITIONAL](https://refactoring.com/catalog/decomposeConditional.html) refactoring. Extract the conditional logic into a separate function and put a good name on that function. This clarifies the intent and makes the original function easier to read. Repeat until all complex conditional expressions have been simplified.\n\n","what-changed":"The mean cyclomatic complexity decreases from 4.22 to 4.13, threshold = 4"},{"name":"Primitive Obsession","file":"src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusWrappers/AdministrationClientWrapper.cs","change-type":"improved","change-level":"improvement","is-hotspot?":false,"why-it-occurs":"Code that uses a high degree of built-in, primitives such as integers, strings, floats, lacks a domain language that encapsulates the validation and semantics of function arguments. Primitive Obsession has several consequences: 1) In a statically typed language, the compiler will detect less erroneous assignments. 2) Security impact since the possible value range of a variable/argument isn't retricted.\n\nIn this module, 70 % of all functions have primitive types as arguments.","how-to-fix":"Primitive Obsession indicates a missing domain language. Introduce data types that encapsulate the details and constraints of your domain. For example, instead of `int userId`, consider `User clicked`.","what-changed":"The ratio of primitive types in function arguments decreases from 73.68% to 70.00%, threshold = 30.0%"},{"name":"String Heavy Function Arguments","file":"src/Paramore.Brighter.MessagingGateway.AzureServiceBus/AzureServiceBusWrappers/AdministrationClientWrapper.cs","change-type":"improved","change-level":"improvement","is-hotspot?":false,"why-it-occurs":"String is a generic type that fail to capture the constraints of the domain object it represents. In this module, 60 % of all function arguments are string types.","how-to-fix":"Heavy string usage indicates a missing domain language. Introduce data types that encapsulate the semantics. For example, a user_name is better represented as a constrained User type rather than a pure string, which could be anything.","what-changed":"The ratio of strings in function arguments decreases from 63.16% to 60.00%, threshold = 39.0%"},{"name":"Primitive Obsession","file":"src/Paramore.Brighter.Outbox.Spanner/SpannerOutbox.cs","change-type":"improved","change-level":"improvement","is-hotspot?":false,"why-it-occurs":"Code that uses a high degree of built-in, primitives such as integers, strings, floats, lacks a domain language that encapsulates the validation and semantics of function arguments. Primitive Obsession has several consequences: 1) In a statically typed language, the compiler will detect less erroneous assignments. 2) Security impact since the possible value range of a variable/argument isn't retricted.\n\nIn this module, 46 % of all functions have primitive types as arguments.","how-to-fix":"Primitive Obsession indicates a missing domain language. Introduce data types that encapsulate the details and constraints of your domain. For example, instead of `int userId`, consider `User clicked`.","what-changed":"The ratio of primitive types in function arguments decreases from 48.00% to 46.15%, threshold = 30.0%"},{"name":"Primitive Obsession","file":"src/Paramore.Brighter.Transformers.AWS.V4/S3LuggageStore.cs","change-type":"improved","change-level":"improvement","is-hotspot?":false,"why-it-occurs":"Code that uses a high degree of built-in, primitives such as integers, strings, floats, lacks a domain language that encapsulates the validation and semantics of function arguments. Primitive Obsession has several consequences: 1) In a statically typed language, the compiler will detect less erroneous assignments. 2) Security impact since the possible value range of a variable/argument isn't retricted.\n\nIn this module, 45 % of all functions have primitive types as arguments.","how-to-fix":"Primitive Obsession indicates a missing domain language. Introduce data types that encapsulate the details and constraints of your domain. For example, instead of `int userId`, consider `User clicked`.","what-changed":"The ratio of primitive types in function arguments decreases from 46.67% to 45.16%, threshold = 30.0%"},{"name":"String Heavy Function Arguments","file":"src/Paramore.Brighter.Transformers.AWS.V4/S3LuggageStore.cs","change-type":"fixed","change-level":"improvement","is-hotspot?":false,"why-it-occurs":"String is a generic type that fail to capture the constraints of the domain object it represents. In this module, 39 % of all function arguments are string types.","how-to-fix":"Heavy string usage indicates a missing domain language. Introduce data types that encapsulate the semantics. For example, a user_name is better represented as a constrained User type rather than a pure string, which could be anything.","what-changed":"The ratio of strings in function arguments is no longer above the threshold"},{"name":"Primitive Obsession","file":"src/Paramore.Brighter.Transformers.AWS/S3LuggageStore.cs","change-type":"improved","change-level":"improvement","is-hotspot?":false,"why-it-occurs":"Code that uses a high degree of built-in, primitives such as integers, strings, floats, lacks a domain language that encapsulates the validation and semantics of function arguments. Primitive Obsession has several consequences: 1) In a statically typed language, the compiler will detect less erroneous assignments. 2) Security impact since the possible value range of a variable/argument isn't retricted.\n\nIn this module, 45 % of all functions have primitive types as arguments.","how-to-fix":"Primitive Obsession indicates a missing domain language. Introduce data types that encapsulate the details and constraints of your domain. For example, instead of `int userId`, consider `User clicked`.","what-changed":"The ratio of primitive types in function arguments decreases from 46.67% to 45.16%, threshold = 30.0%"},{"name":"String Heavy Function Arguments","file":"src/Paramore.Brighter.Transformers.AWS/S3LuggageStore.cs","change-type":"fixed","change-level":"improvement","is-hotspot?":false,"why-it-occurs":"String is a generic type that fail to capture the constraints of the domain object it represents. In this module, 39 % of all function arguments are string types.","how-to-fix":"Heavy string usage indicates a missing domain language. Introduce data types that encapsulate the semantics. For example, a user_name is better represented as a constrained User type rather than a pure string, which could be anything.","what-changed":"The ratio of strings in function arguments is no longer above the threshold"},{"name":"Overall Code Complexity","file":"src/Paramore.Brighter/Transforms/Transformers/CloudEventsTransformer.cs","change-type":"improved","change-level":"improvement","is-hotspot?":false,"why-it-occurs":"Overall Code Complexity is measured by the mean cyclomatic complexity across all functions in the file. The lower the number, the better.\n\nCyclomatic complexity is a function level metric that measures the number of logical branches (if-else, loops, etc.). Cyclomatic complexity is a rough complexity measure, but useful as a way of estimating the minimum number of unit tests you would need. As such, prefer functions with low cyclomatic complexity (2-3 branches).","how-to-fix":"You address the overall cyclomatic complexity by a) modularizing the code, and b) abstract away the complexity. Let's look at some examples:\n\nModularizing the Code: Do an X-Ray and inspect the local hotspots. Are there any complex conditional expressions? If yes, then do a [DECOMPOSE CONDITIONAL](https://refactoring.com/catalog/decomposeConditional.html) refactoring. Extract the conditional logic into a separate function and put a good name on that function. This clarifies the intent and makes the original function easier to read. Repeat until all complex conditional expressions have been simplified.\n\n","what-changed":"The mean cyclomatic complexity decreases from 4.27 to 4.08, threshold = 4"}]},"notices":{"number-of-types":0,"number-of-files-touched":0,"findings":[]},"external-review-provider":"GitHub"},"analysistime":"2026-06-15T17:38:59.000Z","project-name":"Brighter","repository":"https://github.com/BrighterCommand/Brighter.git"}}