Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions packages/cli/src/commands/review/lib/path-rules.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,3 +103,75 @@ describe('pathRulesFor — scoped, or it is noise', () => {
expect(out).toContain('$GITHUB_STEP_SUMMARY');
});
});

describe('pathRulesFor — the Java/JVM rule', () => {
it('attaches when a .java file changes, and names only that file', () => {
const out = pathRulesFor(['src/main/java/com/x/Main.java', 'src/pay.ts']);
expect(out).toContain('Java / JVM performance');
expect(out).toContain('src/main/java/com/x/Main.java');
expect(out).not.toContain('src/pay.ts');
});

it.each([
['src/main/java/com/x/Main.java', true],
['Main.java', true],
['src/main/kotlin/Main.kt', false],
['src/pay.ts', false],
['docs/notes.java.md', false],
])('%s → Java rule applies: %s', (path, applies) => {
expect(pathRulesFor([path]).includes('Java / JVM performance')).toBe(
applies,
);
});

it('stacks with the workflow rule when a diff touches both', () => {
const out = pathRulesFor(['.github/workflows/ci.yml', 'src/Main.java']);
expect(out).toContain('GitHub Actions workflows');
expect(out).toContain('Java / JVM performance');
});

it('names the inline thresholds and both verification tiers', () => {
const out = pathRulesFor(['src/Main.java']);
// The table the whole JIT section hangs on: 325 is the user's case — a hot
// method that outgrows FreqInlineSize stops being inlined.
expect(out).toContain('FreqInlineSize');
expect(out).toContain('325');
expect(out).toContain('MaxInlineSize');
Comment thread
wenshao marked this conversation as resolved.
Resolved
// Static tier: compile and measure with javap; dynamic tier: PrintInlining.
expect(out).toContain('javap');
expect(out).toContain('PrintInlining');
});

it('refuses to estimate bytecode from source', () => {
// The one failure this checklist exists to prevent: an agent eyeballing a
// method and declaring it un-inlinable. The honest form is the mechanism,
// at low confidence, with the measurement named.
const out = pathRulesFor(['src/Main.java']);
expect(out).toMatch(/do not estimate bytecode from source/);
expect(out).toContain('Confidence: low');
});

it('names hot/cold splitting as the fix, and rules out @ForceInline', () => {
// A/B-measured: without the checklist the performance agent missed an
// 80→338-byte threshold crossing entirely; with it, the agent proposed
// extracting a named bytecode range into a helper. The fix shape is the
// part the model does not supply on its own — pin it, and pin the
// anti-pattern it must not suggest (@ForceInline bloats every caller).
const out = pathRulesFor(['src/Main.java']);
expect(out).toContain('hot/cold splitting');
expect(out).toContain('@ForceInline');
expect(out).toMatch(/bytecode range to extract/);
});

it('keeps the severity and scoping discipline of the skill', () => {
const out = pathRulesFor(['src/Main.java']);
expect(out).toContain('reviewing this diff, not auditing this file');
expect(out).toContain('Favour precision over recall');
// Inlining only matters where the call is hot; otherwise the rule is a
// lint sweep over every method in the file.
expect(out).toMatch(/cold method over 325 bytes is \*\*not\*\* a finding/);
// Slow is a cost, not a wrongness — perf findings are Suggestions, and the
// Criticals are reserved for the correctness traps.
expect(out).toMatch(/Performance findings are \*\*Suggestions\*\*/);
Comment thread
wenshao marked this conversation as resolved.
Resolved
});
});
53 changes: 52 additions & 1 deletion packages/cli/src/commands/review/lib/path-rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,59 @@ const GITHUB_ACTIONS: PathRule = {
**Favour precision over recall here.** A false alarm on a workflow costs more reviewer trust than a missed minor nit, because a YAML finding is the easiest kind for an author to dismiss. Every finding needs the concrete trigger and the concrete outcome, like any other.`,
};

const JAVA: PathRule = {
title: 'Java / JVM performance',
matches: (p) => /\.java$/i.test(p),
checklist: `A Java change's most expensive regressions are decided by the JVM, not by anything a reader can see in the source: HotSpot chooses what to inline, what to scalar-replace, and what to compile at all — and a one-line change can flip each of those on a hot path. The general performance lens (N+1, repeated work, data structures) sees none of it.

**You are reviewing this diff, not auditing this file.** A JVM-cost weakness the code already had, on a line this change does not touch, is out of scope — the same rule as everywhere else. What is in scope: a line this diff **adds or changes**, and a cheap path this diff **makes hot** (a new caller in a request loop, a call moved inside a loop).

**Correctness traps dressed as concurrency or performance code (Critical):**

- **A \`SimpleDateFormat\` shared across threads.** It is not thread-safe: concurrent \`parse\`/\`format\` corrupts its calendar state and returns silently wrong values or throws. If the diff adds a shared (static or instance field) \`SimpleDateFormat\`, or makes an existing one reachable from more than one thread, that is wrong, not slow. The fix is \`java.time.format.DateTimeFormatter\` (immutable) or a \`ThreadLocal\`.
- **A compound action on \`ConcurrentHashMap\` built from two calls.** \`get\`-then-\`put\`, \`containsKey\`-then-\`put\`, check-then-act of any shape: the map's thread safety covers each call, not the pair, and the race loses an update or runs the guarded work twice. Say what the race corrupts — that is the finding. Fix with \`putIfAbsent\`, \`computeIfAbsent\`, or \`merge\`.
- **Double-checked locking without \`volatile\` on the field.** The reading thread can observe a partially constructed object. If the diff adds or touches the idiom, the field must be \`volatile\` (or replaced with the holder idiom).

**JVM-cost defects provable from the source (Suggestion — a cost, not a wrongness):**

- **A regex compiled per call.** \`Pattern.compile(...)\` in a method body or loop, and the \`String\` conveniences that hide it — \`matches\`, \`replaceAll\`, \`replaceFirst\`, and \`split\` with a real regex (single-character splits take a fast path) — recompile the pattern on every invocation. On a per-request or per-record path that is real CPU. Fix: \`private static final Pattern\`.
- **\`+=\` on a \`String\` inside a loop.** Each iteration rebuilds and copies the whole accumulated prefix; the loop is O(n²) in the final length. Fix: one \`StringBuilder\` outside the loop.
- **Boxing on a hot path.** A \`Long\`/\`Integer\` loop accumulator, a \`Map<Long, …>\` over dense \`int\` keys, \`.boxed()\` in a counted stream: every box past the small-integer cache is an allocation plus a pointer chase per iteration. Fix: primitives, or the primitive streams/collections.
- **A capturing lambda or method reference inside a hot loop.** A non-capturing lambda is a singleton; one that closes over a local allocates per iteration. If the diff moves a capturing lambda into a loop, hoist it or restructure it to capture nothing.
- **A log message built whether or not it is logged.** \`log.debug("result: " + value)\` pays the concatenation with the level off, and even \`log.debug("{}", expensive())\` still pays \`expensive()\`. Fix: parameterized messages, and guard expensive arguments with \`isDebugEnabled()\` or a supplier-based logging API.
- **A collection sized after the fact.** A \`HashMap\`/\`ArrayList\` the code then fills with a known N pays repeated rehash/grow-copy chains; presize it (a \`HashMap\` needs \`N/0.75 + 1\` to avoid rehashing at all).
- **Legacy synchronized types in new code.** \`Vector\`, \`Hashtable\`, \`StringBuffer\` put a monitor on every call; the unsynchronized equivalents are the default for a reason.
- **An exception used as control flow.** Validating by catching \`NumberFormatException\`, looping until \`EOFException\`: \`fillInStackTrace\` costs more than the work being guarded. Validate instead.
- **Reflection rediscovered per call.** \`getMethod\`/\`getField\` on every invocation of a hot path; cache the \`Method\`/\`Field\` — or a \`MethodHandle\` — once.

**JIT inlining — the regression no dimension can see, and you cannot prove from source:**

HotSpot inlines by the **bytecode size of the callee**, against these product defaults (a project's own \`-XX:\` flags, or a different JVM, change them — check before citing):

| callee bytecode size | inlinable |
| --- | --- |
| ≤ 6 (\`MaxTrivialSize\`) | always |
| ≤ 35 (\`MaxInlineSize\`) | even when cold |

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Critical] Treat these values as size caps, not inlining outcomes. MaxInlineSize only selects the normal size ceiling; C2 can still reject a <=35-byte callee because the call site was never executed, has low frequency, exceeds the inlining depth/recursion limits, or hits the node-count cutoff. I reproduced this on the default JDK 21 with a 10-byte callee reached from 0.1% of calls to a hot caller: level-4 compilation printed low call site frequency, contradicting even when cold. The static tier below then makes this consequential: it treats a javap size comparison as one of the two sufficient verification tiers, so a 300→330-byte method that was already not inlined for another reason can be reported as a new “can no longer be inlined” regression. Please label this table as C2 normal-policy size caps, remove always / even when cold / never, and state that static measurement proves only a size-gate crossing; an actual before/after inlining claim needs PrintInlining or equivalent runtime evidence. OpenJDK's policy shows the independent never executed and low call site frequency rejections here: https://github.com/openjdk/jdk/blob/5b2d6991a1279d375f9a3c00c7bcd0bbcc7081d6/src/hotspot/share/opto/bytecodeInfo.cpp#L293-L325

中文说明

这些数值应描述为 size cap,而不是内联结果。MaxInlineSize 只决定常规大小上限;即使 callee 不超过 35 字节,C2 仍会因调用点未执行、频率过低、内联/递归深度或节点数限制而拒绝。我在默认 JDK 21 上用一个 10-byte callee 复现:它只在 hot caller 的 0.1% 调用中出现,level-4 编译明确输出 low call site frequency,与 even when cold 矛盾。下方静态档又把 javap 尺寸对比当作足够的验证档,因此一个 300→330 bytes、但 base 本来就因其他限制未内联的方法,会被误报成新的“无法再内联”回归。建议把表改成 C2 常规策略的 size caps,删掉 always / even when cold / never,并明确静态档只能证明跨过大小门槛;实际前后内联状态必须用 PrintInlining 或等价运行证据确认。

| ≤ 325 (\`FreqInlineSize\`) | only at a hot call site |
| > 325 | never |
| ≥ 8000 (\`HugeMethodLimit\`) | never even JIT-compiled |

Two more ways a diff can flip it: an already-compiled callee whose **native** size passes \`InlineSmallCode\` (~1000, product) stops being inlined to protect the code cache, and a call site that gains a **third** receiver implementation goes megamorphic — vtable dispatch, no inlining at any size. So the diff-shapes that matter: a small method on a hot path the change **grows** (added validation, logging, a branch), a new layer in a hot call chain, a new implementation registered for an interface invoked in a hot loop. A cold method over 325 bytes is **not** a finding — inlining only matters where the call is hot.

**Measure it; do not estimate bytecode from source.** Two tiers, in order of cost:

1. **Static — available whenever the project builds.** Compile (\`mvn -q -DskipTests compile\`, \`gradle classes\`, or \`javac\` the module), then \`javap -c -p <ClassName>\` and read the method's size: the offset of its last instruction plus that instruction's width. Compare against 35 and 325. For the **crossing** claim — "this diff pushed it over the threshold" — compile the base revision the same way and measure the same method on both sides; a method that was already over is pre-existing, not a finding.
2. **Dynamic — when the code is runnable.** Run the workload with \`-XX:+UnlockDiagnosticVMOptions -XX:+PrintInlining\` and grep for the method: \`callee is too large\` / \`hot method too big\` is the JVM itself declining to inline. JMH gives the before/after throughput; JITWatch visualizes the same decision logs.

A finding that a method "can no longer be inlined" without one of these two tiers is a guess stated as fact. Report the **mechanism** instead, at \`Confidence: low\`: the threshold at risk, what the diff added to the method, and the measurement still to run. And if the diff *claims* this path got faster while the mechanism above says it cannot have, the finding is the unsubstantiated claim.

**When the finding IS a grown hot method, the fix to suggest is hot/cold splitting — not reverting the change, and not \`@ForceInline\`** (which copies the callee's full body into every caller, bloating their bytecode and their own inline budgets). Move the cold paths — error handling, rare branches, defensive validation, the \`switch\` arms that almost never fire — into a small private helper, leaving the common path under the threshold; the helper, now called from one site, is itself inlinable. Name the bytecode range to extract and the size it leaves behind, the way the measurement names them: "extract bytecodes 212–311 (~100 bytes) into \`applyRounding\`, leaving \`parseAmount\` at ~238 bytes" is a finding an author can act on; "consider splitting the method" is not.

**Favour precision over recall here.** A guessed JVM finding is the easiest kind for an author to dismiss, and one dismissal teaches them to skip the rest of the review. Every finding needs the concrete hot path and the concrete cost, like any other. Performance findings are **Suggestions**: slow is a cost, not incorrect behaviour — the Critical entries above are Critical because they are *wrong*.`,
};

/** Every rule, in the order their checklists are appended. */
export const PATH_RULES: PathRule[] = [GITHUB_ACTIONS];
export const PATH_RULES: PathRule[] = [GITHUB_ACTIONS, JAVA];

/**
* The checklists that govern `paths`, as a brief section — or `''` when none do.
Expand Down
Loading