Skip to content

refactor(ci): one nesting metric module shared by the pre-commit hook and the scanner #773

Closed

Description

@dan-petty

Context & Rationale

The nesting and complexity metric is implemented twice with the same node sets: _ComplexityVisitor._visit_with_depth in security/complexity.py:100-136 and _measure in security/structural_invariants.py:27-45. The pre-commit hook keeps its own copy because complexity.py imports ai.review_schema.Finding, which took 8.9s to import. The gate's test stage took 5m 26s on the 9p workspace mount (2026-09-30) and 1m 42s after the workspace moved to ext4 (2026-10-01), so it is within its 5-minute budget; the per-test timings below were measured on 9p. Its slowest test, tests/test_structural_invariant_hook.py::test_the_metric_matches_the_projects_own_scanner (~38s), exists only to prove the two copies agree across the whole tree, and tests/test_architectural_invariants.py::test_no_excessive_nesting_in_src (~27s) scans the whole tree a third time.

Scope & Deliverables

  • Deliverable: the metric lives once, in the lightweight module. The hook (argv and stderr) and devops scan (results turned into Findings) are its two adapters, the parity test is removed, and the whole tree is scanned once.
  • Constraint: behaviour tests stay on small fixtures (tests/test_scan_complexity.py and the hook's fixture tests).

Strategic Alignment

  • Milestone: Backlog (no release)
  • Design: none
  • Depends on: none

Amendment (2026-10-01 assessment)

  • Context:
    • The hook counts nesting depth from 0 (security/structural_invariants.py:53); the scanner counts from 1 (security/complexity.py:81). Five nested ifs therefore pass the hook (depth 5) and fail the scanner (depth 6).
    • Under the scanner's metric, 5 functions in tests/ sit at depth 6, and nothing blocks them.
    • The complexity counts also differ: 235 from the scanner, 230 from the hook.
    • The parity test (~38 s on 9p) passes only because both report 0 nesting breaches in src.
    • The hook imports devops_cli.security, which eagerly imports every scanner (__init__.py:5-30), and devops_cli.config.defaults.
  • Deliverable:
    • The shared module's complexity follows mccabe: no +1 for assert, with or boolean operands.
    • Fix the depth origin, with a boundary fixture at depths 5 and 6.
    • The hook imports nothing from devops_cli.security or devops_cli.config. Its thresholds arrive as hook args, and a test pins those args to the defaults.
    • Consumers: devops scan complexity, MCP scan_complexity, ai/inspection.py, ai/benchmark/suite.py:33, and feat(review): branch and pr reviews compute their own base-vs-head symbol delta #593 PR2's content-taking entry.
    • Exactly one whole-tree test remains. It parses src once, through one helper that the planned import-graph invariant reuses.
    • Decide whether that test covers tests/.
  • Acceptance criteria:
    • A fresh-subprocess hook run leaves no devops_cli.security.* module and no pydantic_ai in sys.modules.
    • The set of (file, function) pairs the scanner flags at 10 equals the set ruff C901 flags.
    • A function with 4 asserts inside a with block scores 1.
    • The parity test is deleted.
    • The task file records the test-step --durations difference, which must be negative.
    • No new dependency.
  • Constraint: If hand-matching mccabe proves fiddly, delegate to ruff's JSON output instead of maintaining a third visitor.
  • Depends on: feat(cli): enforce the complexity cap with ruff C901 and an inline baseline that only shrinks #586

Activity

  1. added this to the v0.2.25 milestone on Oct 1, 2026
  2. added
    type/refactor
    priority/p0-critical
    scope/ci
    on Oct 1, 2026
  3. removed this from the v0.2.25 milestone on Oct 1, 2026
  4. added
    priority/p2-medium
    and removed
    priority/p0-critical
    on Oct 1, 2026
  5. added this to the v0.2.30 milestone on Oct 8, 2026
  6. dan-petty commented on Oct 8, 2026

    @dan-petty
    OwnerAuthor

    Placed in v0.2.30 on 2026-10-08 at the owner's request ("Populate 10 security and ci issues into each v0.2.30, v0.2.31, and v0.2.32 milestone"). This is a person's placement. Release theme: P1 secret and sandbox-boundary fixes, the review tools lock, kube-linter finding identity and a faster gate. Position 8 of 10 in the release's planned merge order. Its board Status is set to Ready, so the release-start fill keeps it.

  7. dan-petty-bot commented on Oct 9, 2026

    @dan-petty-bot
    Collaborator

    What changed

    #1466, merged into release/v0.2.30 as ea37ebf.

    Summary

    devops_cli.core.code_metrics is now the one copy of the nesting and complexity metric. Its own imports are stdlib only. The structural-invariants pre-commit hook runs it with --max-depth 5. devops scan complexity, MCP scan_complexity, the inspection hotspots and devops ai spec read it too.

    • Nesting counts the function body as depth 1, as CI already did. Five nested blocks now fail at commit. The six test functions that sat at depth 6 are flattened.
    • Complexity is Ruff C901's McCabe count. It equals ruff on all 18,000 functions in the tracked src/ and tests/ files, and flags the same 54 functions in src/ at a cap of 10, where the old scanner flagged 244.
    • devops ai spec uses the same nesting rule. An except, match, assert, async for or async with block now opens a level, and a try body no longer does.
    • One whole-tree test, test_the_source_tree_keeps_its_structural_invariants, parses src/devops_cli once through _parse_src(). It finds src/ from the test file's location, so it also checks the tree when pytest runs from another directory.
    • Hook cost. The parity test and the hook's subprocess spawns are gone. A hook run loads no scanner and no pydantic_ai and takes about 0.6 s instead of 8.5 s.
    • Unreadable files. The hook reports a file the parser cannot handle as a breach. This includes the MemoryError a long unary chain raises. The scanner skips such files with a narrow except clause instead of `…

    22 file(s) changed.

    How it was verified

    Check runs at a4284a1:

    • Prune PR DevContainer Images: pass
    • CodeQL: pass
    • Static Analysis: pass
    • Analyze (actions): pass
    • Analyze (python): pass
    • Tests & Coverage: pass
    • DevContainer Image: skipping
    • Service Image: skipping
    • Dependency Freshness: skipping

    Acceptance Criteria of docs/agent/tasks/task-773-one-nesting-metric-module.md:

    • A fresh-subprocess hook run leaves no devops_cli.security or devops_cli.security.* module, and no pydantic_ai, in sys.modules (test_the_hook_loads_no_scanner_and_no_pydantic_ai). The module's own imports are stdlib only.
    • The amendment's "imports nothing from devops_cli.config" holds for the module's own imports only. python -m devops_cli.core.code_metrics first runs the package inits. devops_cli/__init__.py imports devops_cli.config.metadata, and with it pydantic and the devops_cli.config barrel (commands, constants, defaults, env and options). devops_cli/core/__init__.py imports core.cli, and with it typer and 16 devops_cli.exceptions modules. A hook run loads 269 modules, and took 0.43 s against 0.07 s for an interpreter importing only the module's stdlib imports (medians of 5, load average about 12). refactor(config): the config barrel and the unused config names go, and the package inits stop re-exporting #776 removes the config barrel. Making devops_cli/__init__.py and devops_cli/core/__init__.py lazy is outside this item: moved to a follow-up issue, not yet filed.
    • The (file, function) pairs the scanner flags at 10 are the pairs Ruff C901 flags: 54/54 in src/, 0/0 in tests/. With ruff check --ignore-noqa --select C901 --config lint.mccabe.max-complexity=0 (ruff 0.16.8), all 18,000 functions in the tracked src/ and tests/ files on this branch get the same value from both, with no key or value difference. Without charging closures to the function that defines them, src/ would give 48. The six it would miss are ai/ext_langchain.py:24 and, in ai/harness/, agents.py:377, memory.py:629, planning.py:440, shell.py:371 and workflow.py:262.
    • A function with 4 asserts inside a with scores 1. test_complexity_is_ruffs_c901_count holds 12 fixtures, each value read once from Ruff and hard-coded.
    • The depth origin is fixed, with boundary fixtures at depths 5 and 6 (test_the_function_body_is_depth_one). On all 18,000 functions, the new depth equals the old hook depth plus 1.
    • The parity test is deleted, with the rest of tests/test_structural_invariant_hook.py. Its fixture tests now run in-process through main([...]) in tests/test_code_metrics.py.
    • Exactly one whole-tree test remains, test_the_source_tree_keeps_its_structural_invariants, which parses src/devops_cli once through _parse_src().
    • The test-step --durations difference is negative. Each pair below was run back to back with -n 0, on the exported base (edd2578) and then on this branch:
      • Pair 1 (load average about 17 for both runs):
        • Before: 60.9 s of call time. The parity test took 25.8 s, the three hook subprocess spawns 9.5, 9.1 and 11.3 s, and test_no_excessive_nesting_in_src 5.3 s.
        • After: about 5.1 s. test_the_source_tree_keeps_its_structural_invariants took 4.7 s and the import-check subprocess 0.3 s.
        • Difference: about −55.8 s.
      • Pair 2 (load average falling from 18 to 10):
        • Before: 31.7 s of call time, 42.9 s wall.
        • After: 3.9 s of call time, 11.1 s wall.
        • Difference: −27.8 s of call time.
      • The whole-tree test costs what the one it replaces did (3.47 s against 3.48 s in pair 2): most of it is parsing src/. The saving comes from deleting the parity test and the three hook subprocess spawns.
    • One hook run over one file (python -m, without uv run's own start-up) takes 0.58 s instead of 8.45 s, the medians of 5 interleaved runs each at a load average of about 18. At a load of about 5 it was 0.2 s against 3.0 s.
    • No new dependency: pyproject.toml and uv.lock are untouched.
    • changelog.d/773.md exists, and CHANGELOG.md and docs/ROADMAP.md are untouched.
  8. added a commit that references this issue on Oct 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority/p2-mediumscope/citype/refactor

    Type

    No type

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions