Skip to content
DashboardWebsite

Python Code-Change Pack

URL slug: python-code-change

This page explains how the Python code-change pack turns a unified git diff of Python (.py) files into analysis units and reviews them against rules a linter cannot express. A unit can cover a changed function, method, class, or module-level change. When a hunk includes a class and its methods, they share one class unit.

parse_diff (opentremor_pack_python_code_change/parser.py) reads the diff hunk by hunk:

  1. Read the diff with core’s iter_hunks(text, path_suffix=".py") (opentremor_core.libs.diff). It returns hunks for .py files, each with Git’s section heading. The heading can name the enclosing class of a changed method.
  2. Find block-opening lines (def, async def, class) and locate where each block ends by indentation: the first non-blank line indented at or below the opener. Blank lines do not end a block.
  3. Include decorators. A run of @decorator lines immediately above an opener becomes part of that unit. This preserves evidence such as a route’s auth dependency.
  4. Keep changed blocks. A block with only context ( -prefixed) lines is discarded. Changed + or - lines that no block claimed become one module unit per hunk.

A diff hunk is a fragment. It can be unbalanced, start mid-function, or omit the enclosing class statement, so ast.parse raises SyntaxError on many real inputs. Regex and indentation over the diff text work with these fragments.

Block opens withtypename
def load_settings(path): at column 0functionload_settings
async def fetch(url): at column 0async_functionfetch
def reset_password(self, ...) indentedmethodMemberService.reset_password
async def run(self, ...) indentedasync_methodJobRunner.run
class Repository:classRepository
changed imports or module constantsmodule(module-level)

Indentation determines whether a def is a function or method. When a hunk includes the enclosing class statement, the class unit absorbs its indented methods. When a hunk starts inside a class, a changed method can form its own unit.

Where the class name in a method’s name comes from

Section titled “Where the class name in a method’s name comes from”

When a hunk starts mid-class, the class statement is above the hunk and its name is not in the diff body. Git can include it in the hunk’s section heading — the text after the second @@:

@@ -40,7 +40,7 @@ class MemberService:
def reset_password(self, user_id):

When the heading names the class, the parser uses it to qualify the method’s name. If Git emits no class heading, the method’s name stays unqualified.

  • metadata.source_path — the changed file’s path, from the diff header.
  • metadata.group_path — the containing Python package (src/opentremor_core/controllers/routers/admin.py → opentremor_core.controllers.routers). This fills the same slot that a Terramate stack path fills for other packs.

file_globs is ["*.py"], so auto-routing sends .py files in a diff to this pack by path glob. The pack does not override sniff(): ingest() only understands unified-diff input, so a bare .py file pasted into the Analyze form would sniff as Python and then produce zero units. Diff-shaped input routes by path glob.

The glob includes test files, migrations, and __init__.py. An organization can disable the pack with its per-org toggle.

The pack has two variants with the same rule IDs and categories:

VariantFileFor
defaultrules/python-code-change-rules.mdAny Python code; examples use FastAPI-style Depends(...) and async def routes
djangorules/django-python-code-change-rules.mdDjango and Django REST Framework: querysets and managers, permission_classes, @csrf_exempt, .raw() and .extra(), select_related, settings

Choose a variant for the repository, or pass rule_type=django on ingest or analyze. suggest_rule_type() suggests django when a diff imports django or rest_framework. It does not switch the variant by itself.

The rules cover security, performance, and reliability. Performance and reliability findings are LOW or MEDIUM and do not fail the merge check on their own.

RuleSeverityWhat it catches
PYCC-001CRITICALTenant org_id taken from the request instead of the authenticated principal
PYCC-010CRITICALTenant-owned data read or written without a tenant scope
PYCC-011CRITICALAn auth guard removed or weakened by the diff
PYCC-002HIGHA new route with no visible auth dependency
PYCC-003HIGHA secret, key, or credentialed connection string in plain text
PYCC-005HIGHRequest data reaching shell=True, os.system, or eval/exec
PYCC-012HIGHRequest data passed to pickle.loads or an unsafe yaml.load
PYCC-013HIGHSQL built from request values without parameters
PYCC-014HIGHAn outbound URL built from request values (SSRF)
PYCC-015HIGHA file path built from request values with no containment check
PYCC-004MEDIUMA blocking call added to an async def
PYCC-PERF-001 to -006LOW–MEDIUMCalls in a loop, unbounded result sets, concurrency or body reads, sequential independent awaits, a client per call
PYCC-006MEDIUMAn outbound call with no timeout, or one removed
PYCC-007MEDIUMAn exception handler that swallows without logging or re-raising
PYCC-REL-001, -002MEDIUMA retry with no backoff or bound, or a task started and forgotten
PYCC-009LOWA comment or docstring that now contradicts the code

Like every pack’s built-in ruleset, these rules seed an organization’s custom_rules as editable rows. An organization can reword, disable, or replace them without changing this package. Core keeps rows an organization has not edited in sync with this file (OpenTremor-core#0034).

PYCC-009 has no static-analysis equivalent. It ships at LOW severity, so it does not gate anything while its false-positive rate is still unknown.

Two constraints apply to every finding. A finding reports on the code, never on the author. It does not speculate about why a change was made or whether it was meant well. Reviewers can check a claim about code, such as a query with no org_id, but cannot verify an accusation about intent. A title belongs to its rule_id. Titles label rules; a change no rule covers gets no finding. A finding with a title that does not match its rule ID is unreviewable because readers check it against the wrong definition.