Skip to main content

SKY-Q306 · Quality, structure and performance

Cognitive complexity too high

Varies

The catalog gives no severity. Python reports MEDIUM for a score from 16 to 30 and HIGH above 30; TypeScript and JavaScript always report MEDIUM.

Cognitive complexity scores how hard a function is to follow. Each if, loop, except handler or conditional costs 1 plus how deeply it is nested, so a loop inside a loop inside an if costs far more than a flat list of checks. SKY-Q306 reports a function scoring above 15.

Languages
Python, TypeScript, JavaScript
Quality gate
counted toward the gate limits (full and diff scans). Listed only when SKY-Q301 or SKY-Q302 also reports the same function; that function's metrics then share one entry, led by the most severe, which the gate counts once. Otherwise it is hidden and counted only with --all-advice or when the rule is named in [tool.skylos.gate] rules.
Finding type
advice
Catalog name
Cognitive complexity
Wrong result? Report itA false positive, a missed case or a confusing message: it goes privately to the founder.

Why it matters

Deeply nested logic is where reviewers miss cases: which break leaves which loop, which else belongs to which if. Bugs hide there and stay hidden through code review.

What Skylos flags

app/invoices.py · PythonReported on line 4
"""Match bank payments to open invoices."""  def reconcile(payments, invoices, tolerance):    matched = []    for payment in payments:        if payment.status != "settled":            continue        for invoice in invoices:            if invoice.paid:                continue            if invoice.customer_id == payment.customer_id:                if abs(invoice.amount - payment.amount) <= tolerance:                    invoice.paid = True                    matched.append((payment.id, invoice.id))                    break                elif payment.reference and payment.reference in invoice.number:                    invoice.flag_partial(payment.amount)                    break        else:            payment.mark_unmatched()    return matched

What Skylos leaves alone

app/invoices.py · Python
"""Match bank payments to open invoices."""  def reconcile(payments, invoices, tolerance):    matched = []    for payment in payments:        if payment.status != "settled":            continue        for invoice in invoices:            if invoice.paid or invoice.customer_id != payment.customer_id:                continue            if abs(invoice.amount - payment.amount) <= tolerance:                invoice.paid = True                matched.append((payment.id, invoice.id))                break            elif payment.reference and payment.reference in invoice.number:                invoice.flag_partial(payment.amount)                break        else:            payment.mark_unmatched()    return matched

Why Skylos leaves it alone

The same logic with the two inner checks joined into one guard clause. The amount check moves up one nesting level and the score drops from 18 to 15; the rule reports only scores above 15.

More languages

TypeScript

Flagged

src/permissions.ts · TypeScriptReported on line 4
type User = { id: string; roles: string[]; suspended: boolean };type Doc = { ownerId: string; teamIds: string[]; archived: boolean }; export function canEdit(user: User, doc: Doc, teams: Map<string, string[]>) {  if (user.suspended || doc.archived) {    return false;  }  for (const role of user.roles) {    if (role === "admin") {      return true;    }    if (role === "editor") {      for (const teamId of doc.teamIds) {        const members = teams.get(teamId);        if (members && members.includes(user.id)) {          if (doc.ownerId === user.id || role === "editor") {            return true;          }        }      }    }  }  return false;}

Not flagged

src/region.ts · TypeScript
export function regionFor(country: string): string {  if (country === "US") {    return "us-east";  } else if (country === "CA") {    return "us-east";  } else if (country === "BR") {    return "sa-east";  } else if (country === "DE" || country === "FR") {    return "eu-central";  } else if (country === "GB" || country === "IE") {    return "eu-west";  } else if (country === "JP") {    return "ap-northeast";  } else if (country === "SG") {    return "ap-southeast";  } else if (country === "AU") {    return "ap-southeast-2";  } else if (country === "IN") {    return "ap-south";  } else {    return "us-east";  }}

Why Skylos leaves it alone

A long, flat else if chain. Each else if and the final else cost 1 whatever their position, and each || run costs 1: 12 in all. (Its cyclomatic score is 10, at the SKY-Q301 limit.)

How Skylos decides

  1. Runs with --quality on Python, TypeScript and JavaScript functions and methods. The limit is 15 in both languages; there is no setting for it.
  2. Python adds 1 plus the current nesting depth for each if, loop, conditional expression, except handler and match; an elif costs 1 and an else (on an if, loop or try) costs 1. A run of the same Boolean operator costs 1, and every switch between and and or costs 1 more.
  3. Nested function bodies are included, one level deeper (a decorator wrapper that only defines and returns its inner function does not add a level); a lambda body is one level deeper. A class inside the function starts again at depth 0. A nested function is also measured on its own.
  4. TypeScript and JavaScript work the same way: if, loops, switch, catch and ternaries cost 1 plus their depth, else if and else cost 1, each run of &&, || or ?? costs 1 plus 1 per change of operator, and a labelled break or continue costs 1.
  5. Python skips test code, examples and benchmarks folders, a top-level docs folder and the root setup.py, as SKY-Q301 does. Minified JavaScript is not scanned.
  6. Reports on the function's first line. Python reports MEDIUM up to 30 and HIGH above; TS/JS report MEDIUM.

How to fix it

Move the inner search into its own function and use guard clauses (continue, early return) instead of nested if blocks.

app/invoices.py · Python · the fix, against the flagged file
"""Match bank payments to open invoices."""  Added: def _match_invoice(payment, invoices, tolerance):Added:     for invoice in invoices:Added:         if invoice.paid or invoice.customer_id != payment.customer_id:Added:             continueAdded:         if abs(invoice.amount - payment.amount) <= tolerance:Added:             invoice.paid = TrueAdded:             return invoiceAdded:         if payment.reference and payment.reference in invoice.number:Added:             invoice.flag_partial(payment.amount)Added:             return NoneAdded:     payment.mark_unmatched()Added:     return NoneAdded:  Added:  def reconcile(payments, invoices, tolerance):    matched = []    for payment in payments:        if payment.status != "settled":            continueRemoved:         for invoice in invoices:Removed:             if invoice.paid:Removed:                 continueRemoved:             if invoice.customer_id == payment.customer_id:Removed:                 if abs(invoice.amount - payment.amount) <= tolerance:Removed:                     invoice.paid = TrueRemoved:                     matched.append((payment.id, invoice.id))Removed:                     breakRemoved:                 elif payment.reference and payment.reference in invoice.number:Removed:                     invoice.flag_partial(payment.amount)Removed:                     breakRemoved:         else:Removed:             payment.mark_unmatched()Added:         invoice = _match_invoice(payment, invoices, tolerance)Added:         if invoice is not None:Added:             matched.append((payment.id, invoice.id))    return matched

When it can be wrong

  • A function that is one large but regular state machine, such as a parser loop, can score high while being the clearest form for it.
  • Because nested function bodies count toward the outer function, a function that defines several callbacks inline is scored for all of them.
  • The limit of 15 cannot be changed; only ignoring the rule or a finding helps.

Seeing a case that isn't listed here? Report the wrong result so the rule can be fixed. Don't paste company code: describe the shape of it.

How to silence it

  • On the def line (the reported line):

    Python
    def reconcile(payments, invoices, tolerance):  # skylos: ignore[SKY-Q306] reviewed
  • [tool.skylos] ignore = ["SKY-Q306"] turns the rule off for the project. A baseline accepts existing findings, but it records the absolute file path and the line, so an entry stops matching when the checkout moves or the line shifts.

From the Skylos rule handbook, Skylos 5.8.0 (commit 5b880b0). All rules.