Status: Draft

Author: Viquar Khan (Vaquar.khan@gmail.com)

Discussion thread: TBD

Jira:


Motivation

The open-source community is seeing a sharp increase in automated pull requests. While code generation tools can help developers, they frequently produce pull requests that look correct on the surface but contain empty boilerplate, unnecessary comments, and hallucinated logic. This puts a heavy burden on maintainers who spend limited review time on code with no real substance.

While this trend is accelerated by AI, the necessity for structural validation applies to all pull requests. Other major Apache projects are already dealing with this. Apache Airflow changed their contribution policies after automated bots started taking over open issues. Apache Iceberg wrote strict new contribution guidelines to protect their reviewers.

Why AGENTS.md is not enough

Adding an AGENTS.md or CLAUDE.md file is a "soft control." AI models use probabilistic reasoning; if their context window fills up or a user overrides the prompt, the agent will silently ignore markdown instructions and submit bad code anyway. We need a deterministic "hard control" that catches these failures before they reach a human reviewer.

I propose adding two focused validation tasks to Kafka's Gradle build known collectively as the Automated Integrity Validation (AIV) Gate that catch the two most damaging categories of low-quality contributions: scaffolding-heavy PRs with no real logic, and code that violates Kafka's specific architectural rules. This effectively addresses the "Reviewer Overload" crisis while maintaining Kafka's domain-specific invariants and ensuring 100% local data sovereignty.

Relationship to Existing Checks

To clarify why these new gates are required alongside existing tooling, the following table details how the proposed AIV Gate differs from Kafka's existing Checkstyle configurations:

Existing CheckWhat it EnforcesWhat the Proposed AIV Gate Does Differently
ImportControlRestricts which packages can import from which globally.The Design Gate enforces conditional architectural patterns within a file (e.g., if X is instantiated, it must be closed).
RegexpGlobally blocks specific string matches (e.g., System.exit()).The Design Gate handles complex AST relationships that regex cannot express safely, such as blocking ExecutorService only if KafkaConsumer is also present.
CyclomaticComplexity / MethodLength / NPathComplexityMeasures the complexity and size of individual methods.The Density Gate (LDR) measures the ratio of executable logic to empty scaffolding across the entire PR diff to catch boilerplate inflation.

Public Interfaces

This KIP introduces no changes to the Kafka protocol, public APIs, client behaviors, or broker metrics. It modifies only the project's internal build tools and CI workflow.

Proposed Changes

I propose adding an AIV Gate using Gradle's includeBuild composite build feature. This relies on native Java classes that live inside the Kafka repository  no external dependencies beyond JavaParser (build-time only, same pattern as Checkstyle/SpotBugs). Developers run them locally with ./gradlew checkContributionQuality, and CI runs them automatically as part of ./gradlew check.

Important: These tasks complement, not duplicate, Kafka's existing checks.

Task 1: Logic Density Validation (LDR)

The problem Checkstyle cannot solve: Checkstyle measures the complexity of individual methods. It cannot answer the question: "Did this PR add real logic, or is it 300 lines of scaffolding wrapping 2 lines of actual work?" High-volume, low-effort tools often generate massive PRs with very little executable logic empty class hierarchies, verbose documentation for trivial getters, and copy-pasted boilerplate.

How it works: The task uses JavaParser to build an Abstract Syntax Tree (AST) of each changed Java file in the PR diff and counts two categories of nodes:

Weighting Rationale:

Control-flow nodes (if, for, while) dictate cyclomatic complexity and represent actual human or algorithmic problem-solving. Class and method declarations are merely structural scaffolding. Weighting logic nodes at 5x ensures we measure the density of the solution, not the structure.

Worked Examples (LDR in Practice):

To understand the provisional threshold of 0.25, consider these three PR profiles using the exact weights defined above:

  1. Legitimate Core Fix (LDR = 0.91): A PR modifying replication logic inside ReplicaManager.java. It adds no new classes and one new private method (weight 1). It contains one if block (weight 5) and three variable assignments (weight 6). Total logic = 11, total structure = 1. LDR = 11 / 12 = 0.91. It passes easily.

  2. Interface/Config Addition (Bypassed): A PR adding a new ConfigDef or Java interface. Files where ≥80% of top-level type declarations are interface or @interface types are dynamically evaluated under a "declarative profile" exception, allowing them to pass regardless of the LDR score.

  3. AI Slop/Boilerplate (LDR = 0.18): A PR generating an expansive new module wrapper. It contains 3 new classes (weight 3), 15 empty methods or simple getters (weight 15), massive Javadoc blocks (ignored), and only 2 actual method calls (weight 4). Total logic = 4, total structure = 18. LDR = 4 / 22 = 0.18. It falls below the 0.25 threshold, and the PR is blocked.

Default Thresholds & Exceptions:

Task 2: Design Compliance (Kafka Architecture Linter)

The problem Checkstyle cannot solve: While Checkstyle's Regexp module is excellent for globally blocking anti-patterns like System.exit(), it cannot express conditional rules like "if a file uses KafkaConsumer, then it must NOT use ExecutorService."

Governance Risk & Mitigation:

To prevent "rule creep," rules are defined in .validation/design-rules.yaml. Adding or removing a rule requires a standard pull request and lazy consensus on the dev@kafka.apache.org mailing list with a minimum 72-hour review period. A single PMC member can veto a rule addition to prevent bloat. The YAML schema explicitly requires an added-in-version and rationale field.

Kafka-Specific Rules to Ship With:

Implementation Details

Where the code lives: To prevent compilation errors from breaking the entire Gradle build (a common risk with buildSrc/), this tool will be implemented as an isolated composite build using includeBuild("build-plugins").

build-plugins/

├── build.gradle

└── src/

├── main/java/org/apache/kafka/gradle/integrity/

│ ├── DensityAnalyzer.java # LDR calculation

│ ├── DesignComplianceChecker.java # YAML rule enforcement

│ ├── ContributionQualityTask.java # Gradle task entry point

│ └── DiffParser.java # Reads GitHub PR.patch natively

└── test/java/org/apache/kafka/gradle/integrity/

├── DensityAnalyzerTest.java

└── DesignComplianceCheckerTest.java

Secure Human-in-the-Loop (HITL) Overrides:

Compatibility, Deprecation, and Migration Plan

This proposal does not change the Kafka protocol or public APIs. It adds only internal build logic.

Migration: None. Existing code passes both checks (validated against trunk). The tasks only evaluate changed files in a PR diff, not the entire codebase.

Test Plan

To guarantee zero disruption to developer velocity, this KIP relies on strict unit testing and a phased CI rollout.

1. Unit Tests (JUnit 5 in build-plugins/src/test/):

2. Shadow Mode (30-Day Data Collection):

Upon merge, the GitHub Action will run with continue-on-error: true. It will log results (Pass/Fail, LDR score, AST violations) to the GitHub Actions step summary for 30 days without blocking PRs. During this time, the PMC will publish a sensitivity analysis of the historical data.

Exit Criteria: The gate will be promoted to blocking status via lazy consensus on the dev list once the false-positive rate is below 2% over a minimum of 50 evaluated PRs.

Diagnostic Reports (A Mentorship Framework)

Instead of a cryptic failure once Shadow Mode ends, the tool posts a diagnostic summary in the CI output: "This PR's Logic Density is 0.18 (Threshold: 0.25). It appears to be mostly scaffolding. Try moving logic to the internal Config classes to improve density." This provides a clear, mentorship-oriented path to "ready" without bottlenecking legitimate contributions.

Future Work

To keep this KIP tightly scoped to achievable build validation tasks, the following enhancements are deferred to future proposals:

Review & Comparison: Industry Solutions

This solution moves beyond the "descriptive" nature of standard AI tools and introduces a "deterministic" layer of governance.

CapabilityStandard Industry Tools (Copilot/CodeRabbit)Proposed AIV-Gate Solution
Logic FilteringLLM-based summary; flags redundancy probabilistically.LDR (Logic Density Ratio): Deterministic AST-based mathematical gate.
Architectural RulesGeneral best practices (e.g., DRY, SOLID).Design Gate: Enforces Kafka-specific constraints (e.g., ZK blocking, Consumer thread safety).
Supply ChainGeneral CVE scanning (SAST).Planned for Future KIP: Cross-referencing imports with project lockfiles locally.
Data PrivacyCloud-based; requires indexing/API keys.100% Local: No data leaves the committer's environment or GitHub Action.

FAQ

General Concept

Logic Density Ratio (LDR)

Design Gate (Architecture)

CI & Build Integration

Security & Edge Cases

Rejected Alternatives