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.
Parsing strategy
Section titled “Parsing strategy”parse_diff (opentremor_pack_python_code_change/parser.py) reads the diff hunk by hunk:
- Read the diff with core’s
iter_hunks(text, path_suffix=".py")(opentremor_core.libs.diff). It returns hunks for.pyfiles, each with Git’s section heading. The heading can name the enclosing class of a changed method. - 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. - Include decorators. A run of
@decoratorlines immediately above an opener becomes part of that unit. This preserves evidence such as a route’s auth dependency. - Keep changed blocks. A block with only context (
-prefixed) lines is discarded. Changed+or-lines that no block claimed become onemoduleunit per hunk.
Why not ast?
Section titled “Why not ast?”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-to-identity mapping
Section titled “Block-to-identity mapping”| Block opens with | type | name |
|---|---|---|
def load_settings(path): at column 0 | function | load_settings |
async def fetch(url): at column 0 | async_function | fetch |
def reset_password(self, ...) indented | method | MemberService.reset_password |
async def run(self, ...) indented | async_method | JobRunner.run |
class Repository: | class | Repository |
| changed imports or module constants | module | (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
Section titled “Metadata”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.
Routing
Section titled “Routing”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:
| Variant | File | For |
|---|---|---|
| default | rules/python-code-change-rules.md | Any Python code; examples use FastAPI-style Depends(...) and async def routes |
django | rules/django-python-code-change-rules.md | Django 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.
| Rule | Severity | What it catches |
|---|---|---|
PYCC-001 | CRITICAL | Tenant org_id taken from the request instead of the authenticated principal |
PYCC-010 | CRITICAL | Tenant-owned data read or written without a tenant scope |
PYCC-011 | CRITICAL | An auth guard removed or weakened by the diff |
PYCC-002 | HIGH | A new route with no visible auth dependency |
PYCC-003 | HIGH | A secret, key, or credentialed connection string in plain text |
PYCC-005 | HIGH | Request data reaching shell=True, os.system, or eval/exec |
PYCC-012 | HIGH | Request data passed to pickle.loads or an unsafe yaml.load |
PYCC-013 | HIGH | SQL built from request values without parameters |
PYCC-014 | HIGH | An outbound URL built from request values (SSRF) |
PYCC-015 | HIGH | A file path built from request values with no containment check |
PYCC-004 | MEDIUM | A blocking call added to an async def |
PYCC-PERF-001 to -006 | LOW–MEDIUM | Calls in a loop, unbounded result sets, concurrency or body reads, sequential independent awaits, a client per call |
PYCC-006 | MEDIUM | An outbound call with no timeout, or one removed |
PYCC-007 | MEDIUM | An exception handler that swallows without logging or re-raising |
PYCC-REL-001, -002 | MEDIUM | A retry with no backoff or bound, or a task started and forgotten |
PYCC-009 | LOW | A 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.