# Performance risk

Find code that wastes work as data grows, such as a database call inside a loop, grouped into one fix per cause and ranked by what it costs.

The performance layer finds code structure that wastes work: a database call
inside a loop, a blocking call in async code, a string rebuilt on every
iteration. It reads the parse tree and the call graph, follows calls across
functions, and groups findings into one fix per cause. Performance risk is one
of the three signals in [code health](https://docs.repowise.dev/intelligence/code-health); add
[runtime evidence](https://docs.repowise.dev/intelligence/runtime-evidence) and the queue also
reads what real runs measured.

## Quick start

Performance analysis runs during `repowise init` and `repowise update`.

```bash
repowise health          # performance work appears inside Fix first
repowise next            # the cross-layer Do next list
```

From an agent:

```python
get_health(include=["performance"], only=["performance_summary"])
get_health(include=["performance"], only=["performance_measured"])
get_health(opportunity_id="perf...")
```

In the dashboard, open **Code Health** and the **Performance** tab.

## What it finds

| Kind | Markers |
|---|---|
| I/O per loop iteration (N+1) | `io_in_loop`, `nested_loop_with_io`, `lazy_load_in_loop` (Django and sync SQLAlchemy) |
| Concurrency | `serial_await_in_loop`, `blocking_sync_in_async`, `hot_path_sync_io`, `blocking_io_under_lock`, `lock_in_loop`, `goroutine_in_unbounded_loop` |
| Repeated setup | `resource_construction_in_loop`, `regex_compile_in_loop`, `json_parse_in_loop`, `defer_in_loop` |
| Quadratic or wasteful data work | `string_concat_in_loop`, `nested_loop_quadratic`, `membership_test_against_list_in_loop`, `list_insert_zero_in_loop`, `array_spread_in_reduce`, `pd_concat_in_loop`, `pandas_iterrows_in_loop` |
| Over-fetch | `unbounded_read_reduced_in_memory`, `sql_cartesian_join` |

That is 21 performance detectors plus `sql_cartesian_join`. They never move the
defect score. Six of them are listed without moving any score, because the code
they find usually runs on a cold path (setup, once per connection, the error
path): `io_in_loop`, `nested_loop_with_io`, `lock_in_loop`,
`string_concat_in_loop`, `membership_test_against_list_in_loop` and
`list_insert_zero_in_loop`. The queue ranks them, and a proven cost turns one
into work.

Some shapes are left quiet on purpose, because they cost the same at any scale:

- A loop that appends to one string several times is one `string_concat_in_loop`
  finding listing every append line. TypeScript and JavaScript never get this
  finding, because JavaScript engines make repeated `+=` linear.
- A `+=` onto the name the loop header binds each pass (`for p in ps: p += "/32"`)
  grows a different string each pass, so it is not flagged.
- A TypeScript or JavaScript `includes` check against a short `const` table of
  literals the file never changes is not flagged.
- A Python schema statement (`CREATE`, `ALTER`, `PRAGMA` and peers) in a loop, or
  a loop over a split of a module string (`SCHEMA.split(";")`), runs a fixed
  number of times and is not an N+1.
- An awaited call on a line an ESLint `no-await-in-loop` suppression covers is
  not reported: the comment states the sequential await is intended.

### Across functions

The loop and the I/O call do not have to be in the same function. Repowise
follows the resolved call graph across a few call hops and attaches the
`caller -> ... -> sink` path to the finding. Per-function linters (clippy,
ruff PERF, ESLint, golangci-lint) look at one function at a time and cannot
see a loop whose I/O happens in a function it calls.

An I/O call is recognised by the library its receiver was imported from, and
classified as `db`, `network`, `filesystem`, `subprocess` or `lock`. Only a
classified call that makes a real round-trip fires, never a query-builder chain
or a same-named pure helper. In TypeScript and JavaScript only the module name
counts, so a local variable named like a package (`ws`) is not read as that
library. In Java, any call on a Spring Data repository or a MyBatis mapper
inside a `for` loop counts as a database call, whatever the method is named:
the receiver's declared type decides.

### Languages

Performance analysis covers Python, TypeScript and JavaScript (including Vue
and Svelte scripts), Java, Go, C# (including Razor), Rust, Kotlin, Scala, Ruby,
C++, Dart, Pascal and Apex, each through its own dialect, plus
language-specific markers such as Go `defer_in_loop`, Python
`pd_concat_in_loop` and JavaScript `array_spread_in_reduce`.

## From findings to a plan

Several findings often share one cause. Repowise groups them into an
**opportunity**: one place you would edit, such as the function that holds the
loop, a helper every caller goes through, or the module body for top-level code.
Two loops in one function are one opportunity.

Each opportunity gets one state:

| State | Meaning |
|---|---|
| `plan_ready` | A fix strategy whose transformation is proven safe |
| `advisory` | A strategy with a prerequisite Repowise cannot prove, such as bounded concurrency before parallelizing awaits against a database |
| `investigate` | No supported strategy; a person decides |
| `expected` | The repetition is real and nothing should change: deleting N files, a function switched off by a constant flag (reason `gated_off`), code that runs once per deploy, boot or incident (reason `cold_path`), a loop that runs a fixed number of times (reason `bounded_loop`) or one that grows only by reading tables that do not grow with the repository (reason `small_table`) |

A marker with no fix strategy at all (such as `hot_path_sync_io` or
`list_insert_zero_in_loop`) is an **observation**: it stays in the Performance
view in the `investigate` state, its rows store the queue reason
`observation`, and no queue counts it.

A plan lists its edits, one step per call site and loop, each naming the call
it repeats and the kind of I/O that call does. When every site reaches one
sink, the step that adds a bulk form of that sink comes first. The plan also
lists tests to run, found from coverage, the call graph and the import graph.
An opportunity with a supported shared fix links to a `performance_fix` plan in
[refactoring](https://docs.repowise.dev/intelligence/refactoring).

Each loop also says what it walks (rows a query returns, a collection its
caller passes in, the rows of one key, a registry or configuration table, a
fixed set, a directory listing or a stream), and plan steps name it. Python,
TypeScript and JavaScript, Go, Java, C#, Ruby, Rust, Kotlin, C++ and Pascal
loops say whether they grow with the data or are bounded; a loop whose size the
code does not show stays unknown and is never treated as bounded. A loop that
stops at the first call that answers, or feeds each call's result into the
next, gets no batch advice (reason `loop_not_batchable`).

## The default queue

The default queue holds production opportunities in the `plan_ready` and
`advisory` states, ranked by cost first, with state breaking ties. Only
opportunities with `cost_proof = proven` are in it: the code shows how the cost
scales (a loop that grows with the data or is bounded, a cost paid once per
call, or a shape that grows by itself, such as an unbounded goroutine loop or a
cartesian join), or a run measured the loop. A loop whose size the code does
not show and no run measured is `cost_proof = unproven` and shows with the
`proof=unproven` filter.

`static_cost` is the code's part of the cost alone: `grows_with_data`,
`grows_by_shape`, `per_call_reached`, `per_call_unreached`, `bounded` or
`size_unknown`. The dashboard counts it as the Loop size facet, and the REST
list narrows by it with `static_cost=<value>`. What a run showed is the row's
`runtime_evidence`.

Each opportunity also says what runs its loop (`execution_role`: request,
event consumer, scheduled job, startup, CLI, UI, tooling, test or unknown), and
loops run per request rank above the rest. Roles are read for Python and
TypeScript/JavaScript. Work a request hands to `asyncio.create_task` and never
waits for counts as a background job.

Everything else is counted by reason, never hidden:

| Reason | Left out because |
|---|---|
| `test` | The code is test code |
| `tooling` | The code is build, migration or developer tooling |
| `unknown` | Repowise cannot tell whether the code ships |
| `expected` | The repetition is intended |
| `gated_off` | The function is switched off by a constant flag |
| `cold_path` | The function is named for a migration, startup, shutdown or crash recovery, so it runs rarely |
| `no_strategy` | The state is `investigate`: a fix strategy exists for the marker, but a fact it needs is not proven |
| `cold_role` | Only startup, a CLI command, tooling, tests or client UI code run the loop, so no server pays it per request |
| `background_unproven` | A scheduled job runs the loop and nothing shows it grows with the data; listed under `proof=background_unproven` |

Every headline counts causes in the three scopes of the Performance tab: `now`
(the default queue, worth fixing now), `production` (every open production
cause) and `all`, plus `per_10k_loc`. The generated CLAUDE.md and AGENTS.md,
`get_health` `kpis`, `repowise health`, `repowise status`, the Overview card and
the Code Health page lead with `now`. The map's performance lens colours a file
by its causes in the default queue.

Performance work also appears in
[Fix first](https://docs.repowise.dev/intelligence/code-health#fix-first), where it competes with
other kinds of work. Fix first and Do next name a `plan_ready` default-queue
cause whose growth comes from a loop outside a registry and a cold path
(`growth_source = loop`). Every other cause stays in the Performance view and is
counted in Fix first as `unconfirmed_cost`.

## Measured costs

With profiles, benchmark results or query counts stored, the queue reads them
on every index and update:

```bash
repowise evidence setup      # prints what to run in this repository
repowise evidence add <file> # joins the result to the indexed functions
repowise evidence status     # what is stored and how fresh it is
```

- **Confirmed causes lead.** A cause carries `confirmed` when its query counts
  grow with the number of items (`query_count`), or when a benchmark, entry
  point, load test or production workload measured its loop owner above the
  lead bar (`measured`). The bar is set by `evidence.lead_min_share`,
  `evidence.lead_min_lower_bound` and `evidence.lead_min_runs`.
- **Three tiers.** With runtime evidence the queue orders confirmed causes
  first, then causes a leading workload measured, then the rest in their static
  order.
- **Measurement beats the cold-path guess.** When a leading run ranks a cause's
  loop owner among its costliest functions, the cause stays in the queue even
  where `cold_path` or `cold_role` would have set it aside. A unit-test run
  never does this.
- **Query counts.** The `queries` facet reads the newest complete
  `query_count` run: `grows` (more items, more statements: confirmed), `flat`
  (same count at different sizes: counter-evidence) or `ran` (anything else).
- **Every row says what the evidence showed:** `confirmed`, `measured` (with
  the workload), `counter_evidence`, `ran`, or `not_exercised` with the
  leading workloads that ran and never reached it.

`get_health(include=["performance"], only=["performance_measured"])` lists,
for each workload's newest run, the functions ranked by self time, each with
its workload class, age, sample size and where the run's time went. With no
profile stored it names `repowise evidence setup`. How to collect evidence is
on [Runtime evidence](https://docs.repowise.dev/intelligence/runtime-evidence).

## Reading it

| Surface | How |
|---|---|
| CLI | `repowise health` and `repowise next` list performance work inside Fix first |
| MCP | `get_health(include=["performance"])`; open one cause with `opportunity_id` |
| Dashboard | Code Health, Performance tab: one scope (Worth doing now, All production, Everything) with every count inside it, causes grouped by area, each with its steps and the raw observations as evidence |

`get_health` filters for the performance block:

| Parameter | Default | Values |
|---|---|---|
| `performance_view` | `detail` | `detail`, `summary` |
| `performance_context` | `production` | `production`, `tooling`, `test`, `unknown`, `all` |
| `performance_boundary` | none | `db`, `network`, `filesystem`, `subprocess`, `lock`, `none` |
| `performance_confidence` | none | `high`, `medium`, `low` |
| `performance_actionability` | none | `plan_ready`, `advisory`, `investigate`, `expected` |
| `performance_sort` | `rank` | `rank`, `leverage`, `observations` |

The linter comparison and ranking quality are published in
[repowise-bench](https://github.com/repowise-dev/repowise-bench/tree/master/perf-detection).

## Next

- [Runtime evidence](https://docs.repowise.dev/intelligence/runtime-evidence) add profiles, benchmarks and query counts.
- [Code health](https://docs.repowise.dev/intelligence/code-health) the other two signals and Fix first.
- [Refactoring](https://docs.repowise.dev/intelligence/refactoring) the shared-fix plans an opportunity links to.
- [`get_health`](https://docs.repowise.dev/mcp/get-health) every parameter.
