Cognitive Complexity metric vs rule

My question is about the cognitive complexity metric failing the quality gate.
In the issues area, there are absolutely no detected violations however quality gate is failing due to the metric. See below screenshots:

  1. zero
    No issues were detected about cognitive complexity on the left-side panel

  2. 138
    quality gate failing due to metric and calculating this for the entire code instead of the function scope.

If I understand this correctly, the cognitive complexity is being applied per function, as in it is calculated within the function scope. But this red message is basically telling me that I have to account complexity for the entire code base? it doesn’t make sense. With this logic, I can never implement a single if check anywhere. So even my cognitive complexity of a single function is only 1, and if I have lots of methods like this across other classes, my quality gate will never pass. What am I missing?

Note: the only thing we modified is the threshold value from 15(default) to 25, due to the nature of the product complexity (data pipeline).

Hi Mehmet,

Welcome to the Sonar Community!

It sounds like you have some Quality Gate conditions set that are not having the desired effect.

The “Cognitive Complexity” metric used in the Quality Gate is calculated on the overall code base. Even though no individual method is violating the rule, the sum of their complexity is what is used in this condition. As your code base grows, this will continue to increase, and whatever threshold you set will be arbitrary. This is likely to cause more headaches for you than value.

If complexity is a critical issue for you, meaning you will fix these violations immediately, I recommend you raise the Severity of the complexity Rule to “Blocker” in a custom Quality Profile and add a “Blocker issues is greater than zero” condition to your New Code Quality Gate. This way, no new overly-complex functions will be allowed.


Thank you for your response Brian.
Although I am still confused.

So the original value, which is 15, is also arbitrary?

Can you guide me on how to increase the value of cognitive complexity without affecting the metric value for overall code-base? basically, we need the issue to be raised when the per-function complexity count is above 25 (instead of 15) not for entire code-base.
here is a screenshot from the rules tab