Skip to content

fix(read): keep class-level fields and decorators in Python aggressive mode - #3335

Open
imkp1 wants to merge 2 commits into
rtk-ai:developfrom
imkp1:fix/read-python-aggressive-class-fields
Open

imkp1 wants to merge 2 commits into
rtk-ai:developfrom
imkp1:fix/read-python-aggressive-class-fields

Conversation

@imkp1

@imkp1 imkp1 commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

Summary

rtk read -l aggressive drops class-level assignments and decorators from Python files. AggressiveFilter decides what counts as an implementation body by tracking brace depth. Python has no braces, so after a class or def signature brace_depth is already 0 and the very next line closes the body and emits a marker. The only fallthrough that keeps declarations matches const/static/let, none of which are Python.

For ORM-style models the field declarations are the model, so the output describes nothing and the agent re-reads the raw file anyway.

Before:

$ rtk read -l aggressive models/sale_order.py
from odoo import api, fields, models, _
class SaleOrder(models.Model):
    // ... implementation
    def _compute_picking_reservation(self):
    // ... implementation

After:

from odoo import api, fields, models, _
class SaleOrder(models.Model):
    _inherit = "sale.order"
    _description = "Sales Order"
    picking_policy = fields.Selection(
        [("direct", "As soon as possible"), ("one", "When all products are ready")],
        string="Shipping Policy",
        default="direct",
    )
    reservation_count = fields.Integer(compute="_compute_picking_reservation")
    __slots__ = ()
    @api.depends("order_line.move_ids")
    def _compute_picking_reservation(self):
        # ... implementation
    def action_confirm(self):
        # ... implementation

What changed:

  • Language::is_indentation_based() routes Python to a walk that scopes bodies by indentation instead of braces. Ruby and Shell are block-delimited (end, fi), not indentation-scoped, so they stay on the existing path.
  • That walk keeps imports, class/def signatures, decorators and every module- or class-level binding, and elides only statements nested inside a function body.
  • Multi-line declarations are held together by bracket depth, so a field spanning several lines is kept whole rather than truncated into invalid syntax.
  • The elision marker now comes from lang.comment_patterns().line instead of a hard-coded //. A C-style marker inside Python, Ruby or Shell violated the Transparency rule that filtered output must read as a shorter version of the real file.

No change to none or minimal, no change to brace-language behaviour beyond the marker character, no new dependency.

Measured on real files with the release-profile binary:

File Raw Aggressive Reduction
json/decoder.py (3.14 stdlib) 12873 B 1647 B 87.2%
argparse.py (3.14 stdlib) 106655 B 15339 B 85.6%

A field-heavy ORM model lands lower (roughly 40%) because the declarations are exactly what has to be kept. That is the intended trade: the previous 4.2% average came with output that was not usable.

Test plan

cargo fmt --all -- --check, cargo clippy --all-targets and cargo test --all are green locally (2522 unit tests, 0 failures). bash scripts/check-test-presence.sh origin/develop passes.

Ten unit tests added in src/core/filter.rs:

  • class-level bindings, dunder attributes and decorators survive
  • a multi-line field declaration is kept whole, including its closing paren
  • function bodies are still elided and docstrings are still dropped
  • the marker is # for Python and stays // for Rust
  • savings clear the project's 60% floor on a body-heavy module
  • is_assignment accepts _inherit = "...", total: int = 0, count += 1 and rejects if x == "draft":, assert a != b, check(threshold=3)
  • bracket_delta ignores brackets inside string literals and trailing comments

Scope

This is the Python half of #3260. The issue also asks for a structural XML level, which is a new capability rather than a bug fix, so per the single-purpose PR rule in CONTRIBUTING I have left it for a follow-up rather than growing this diff. Happy to open that separately if you want it.

Refs #3260


🤖 Opened with Superhuman, an open-source contribution agent.

…e mode

AggressiveFilter decides what is "implementation" by tracking brace depth.
Python has no braces, so every line after a `class`/`def` signature closed the
body immediately: class-level assignments and decorators were dropped and
replaced with a single marker. For ORM-style models that removes the half of
the file that defines the model, so an agent re-reads the raw file anyway.

Route indentation-scoped languages to a separate walk that keeps imports,
signatures, decorators and module/class-level bindings, elides only statements
nested inside a function body, and holds multi-line declarations together so
the skeleton stays valid syntax.

Also derive the elision marker from the language's own comment syntax instead
of hard-coding `//`, which was being emitted into Python, Ruby and Shell.

Refs rtk-ai#3260
@CLAassistant

CLAassistant commented Jul 30, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

Closing a docstring on either delimiter meant a ''' inside a """ block
ended the block early, so the filter lost its place and dropped the code
that followed. Track which delimiter opened the string, and carry the
enclosing line's keep decision through its continuation lines so a
multi-line binding survives whole.

@Protocol-zero-0 Protocol-zero-0 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new indentation path preserves ordinary class assignments and decorators, but I found two gaps in the class/function skeleton on 95ed02b855c937e441ccc4001fab88b7ba2c3045:

  • A normal string containing three single quotes inside a function puts the scanner into a false multiline-string state. The compiled CLI then drops every subsequent function and class in the file. The same input retains those declarations on the PR base, and replacing the literal with "plain" restores them on this head.
  • Annotation-only class fields are still removed. For a real @dataclass with user_id: int, payload: str, and enabled: bool = True, the filtered class exposes only enabled. This is an existing gap rather than a new base-to-head regression, but it affects the required-field declarations this Python path is intended to preserve.

Both minimal reproductions and suggested regression checks are inline. Please make triple-quote detection aware of surrounding ordinary strings, and recognize annotation-only declarations independently of assignment operators.

Validation: built the exact PR base 8a24ce2e2828117f69ffc31134ed12f36d33fac4 and head; ran 13 valid Python inputs through both binaries at none, minimal, and aggressive (78 CLI executions), including plain-string, multiline declaration/decorator, async-function and genuine triple-string controls. Python 3.14 parsed every input; executing the filtered dataclass confirmed the field loss. All 23 core-filter unit tests, fmt, and warnings-denied clippy passed. Linux only; I did not run the full suite or merge this head onto current develop.

Comment thread src/core/filter.rs
result.push_str(&elision_marker(lang, body_indent + 4));
body_elided = true;
}
open_string = unterminated_triple_quote(line).map(|d| (d, false));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Skip ordinary quoted literals before opening a triple string

unterminated_triple_quote counts ''' inside an ordinary double-quoted string as an opening delimiter. This call records (delim, false) while eliding a function body, so all later declarations are silently consumed as string contents:

def first():
    marker = "'''"
    return marker

def second():
    return 2

class Config:
    enabled = True

With the compiled head, rtk read -l aggressive example.py emits only:

def first():
    # ... implementation

The compiled PR base retains second and Config (its CLI falls back to raw for this fixture). On this head, changing "'''" to "plain" also restores both declarations. Please skip complete ordinary string literals and escapes before recognizing a triple-string opener, and add a regression asserting both later declarations survive. The same delimiter inside a kept module assignment instead makes subsequent function bodies leak through.

Comment thread src/core/filter.rs
|| IMPORT_PATTERN.is_match(trimmed)
|| PY_CLASS.is_match(trimmed)
|| trimmed.starts_with('@')
|| is_assignment(trimmed);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep annotation-only class fields as declarations

The new path only recognizes these fields through is_assignment, which requires =. Required dataclass/Pydantic fields commonly have no default:

from dataclasses import dataclass

@dataclass
class Request:
    user_id: int
    payload: str
    enabled: bool = True

The compiled head's rtk read -l aggressive example.py keeps the decorator and class, but only enabled: bool = True remains in its body. Executing that filtered dataclass gives dataclasses.fields(Request) == ['enabled'] by name, versus ['user_id', 'payload', 'enabled'] for the input. The required schema is therefore missing even though the optional field survives.

This omission also exists on the PR base; it is an incomplete declaration-preservation case rather than a new regression. Please recognize a simple annotated binding without = and pin a regression that keeps both required fields while still eliding method bodies.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants