Skip to content

[core] Refactor CPD internals to improve efficiency - #6215

Open
oowekyala wants to merge 111 commits into
pmd:mainfrom
oowekyala:cpd-opts
Open

oowekyala wants to merge 111 commits into
pmd:mainfrom
oowekyala:cpd-opts

Conversation

@oowekyala

Copy link
Copy Markdown
Member

Describe the PR

This PR is work I undertook a while ago with the goal of reducing memory usage in CPD. The side effect is also improved runtime, in particular, lexing can be done in parallel now.

The main changes w.r.t. memory usage are

  • We don't use TokenEntry internally anymore, instead we use a data structure "TokenFile" that stores the token list in exploded arrays. This reduces memory usage because we don't create as many objects, and puts less frequently used data (like line/column information) out of the way.
    • Actual TokenEntry objects are only created on demand. As of now, this is only required during reporting and in infrequently used methods of the Tokenizer API.
    • Outside of those situations, whenever we want to refer to a token, we use the class "SmallTokenEntry", which is conceptually a pair of ints (file index, token index in file).
  • Since we create one TokenFile per source file (instead of using a global Tokens instance for all files), we can now lex source code in parallel in a bit the same way we run PMD in parallel. Although the hashing/matching phase is still sequential, this change is a large performance improvement as the runtime is dominated by the lexing phase in large projects.
  • I revised the MatchCollector to avoid work in some cases, you can see comments in there.
  • The hashing phase also pre-prunes pairs of tokens we know are going to be subsumed by a larger match. This is a great contributor to performance improvements for CPD from what I've seen.

The way I rewrote the algorithm allows for compacting several near-matches into one larger match. For this to happen all matches must have a common prefix longer than the minimum tokens parameter. This might report something like this:

Found a 24 line (130..147 tokens) duplication in the following files: 
Starting at line 907 of /home/.../resources/ext/TimeZoneNames_de.java
Starting at line 907 of /home/.../resources/ext/TimeZoneNames_es.java
Starting at line 907 of /home/.../resources/ext/TimeZoneNames_fr.java
...

This means that all of the duplicates have at least 130 tokens in common, and at least two of them have even 147 tokens in common. It prevents us from reporting different duplicates which look alike but only differ by a couple of tokens at their end, which is noisy. We would need an update to renderers like CSV and XML to report this properly.

Numbers

On my machine, running CPD on the JDK sources (14k files, 2.2MLOC):

  • main: 23-25s, peak memory > 9GB (crashes with less memory)
  • this branch: 8s (1 thread) or 6 seconds (8 threads), peak memory < 900MB
    Those numbers are without discounting warmup (so a lot of time is jvm startup), ran on an OpenJDK 21.0.8 runtime. Below I report some numbers for the same workload but with warmup time excluded.
Scaling case study (click to reveal) I benchmarked CPD more closely on those sources to see how it scales w.r.t threads and found the following. (The plots use warmup iterations so the numbers are better than above). Pasted image 20251029183939

The most obvious thing here is that adding threads improves performance until it starts degrading it. This is caused by contention on the shared map that records the integer ID of each token image.

I improved this by adding a read-only map that stores pre-allocated IDs for common tokens (keywords, punctuation, etc). The concurrent map is only queried if the image is not one of those known tokens. From what I saw, 2/3 of the tokens are punctuation or keywords, so this is very effective to reduce contention on the map. Here is a refreshed plot with this optimization.

Pasted image 20251029183838

Note that these plots are comparing a late version of this branch and the latest optimization I added, they're not a comparison to main. But, I thought the plots look cool, and CPD on main wouldn't fit on the plot!

Related issues

Ready?

  • Added unit tests for fixed bug/feature
  • Passing all unit tests
  • Complete build ./mvnw clean verify passes (checked automatically by github actions)
  • Added (in-code) documentation (if needed)

@adangel adangel added this to the 7.20.0 milestone Nov 27, 2025
@adangel

adangel commented Nov 27, 2025

Copy link
Copy Markdown
Member

Thanks for this improvement. Unfortunately I won't have time to review it until the release tomorrow - and it seems to be a substantial change.
Before even looking at this, I want to have these metrics added to pmd regression tester - that means, first we need to improve the regression tester to also test CPD and also to monitor cpu time and memory. Because then, it would be much easier to see: "Aha, this PR causes PMD to use two more GB heap than before" (similar like: "This PR created 500 new violations").
So, I moved it to 7.20.0...

@oowekyala

Copy link
Copy Markdown
Member Author

Before even looking at this, I want to have these metrics added to pmd regression tester - that means, first we need to improve the regression tester to also test CPD and also to monitor cpu time and memory. Because then, it would be much easier to see: "Aha, this PR causes PMD to use two more GB heap than before" (similar like: "This PR created 500 new violations").

This is a good idea. TBH i wasn't able to collect heap size numbers in an automated way. If you have ideas about how to do that that would be great

@adangel

adangel commented Nov 29, 2025

Copy link
Copy Markdown
Member

Before even looking at this, I want to have these metrics added to pmd regression tester - that means, first we need to improve the regression tester to also test CPD and also to monitor cpu time and memory. Because then, it would be much easier to see: "Aha, this PR causes PMD to use two more GB heap than before" (similar like: "This PR created 500 new violations").

This is a good idea. TBH i wasn't able to collect heap size numbers in an automated way. If you have ideas about how to do that that would be great

I was also looking into this the last few days/weeks. We could continue, what I did in main...adangel:pmd:core/cpd-memory-usage and manually measure the metrics (like peak heap usage). This can be extended to monitor also cpu usage (see https://github.com/kabutz/teardown-talk/blob/master/src/main/java/eu/javaspecialists/tjsn/talks/teardown/util/Benchmark.java for an example). You can even monitor allocations (https://github.com/kabutz/teardown-talk/blob/master/src/main/java/eu/javaspecialists/tjsn/talks/teardown/util/ByteWatcherSingleThread.java). This approach basically uses the MBeans to query the VM statistics.

But... there is JFR (JDK Flight Recorder) and this should bring us those numbers for free (and much more). JFR should be available since Java 11. As long as we run PMD with Java 11+ it should work. I played around with this now and I think, we should add it to the regression tester:

  1. Start PMD with PMD_JAVA_OPTS="-XX:StartFlightRecording:filename=recording.jfr,settings=custom.jfc,dumponexit=true". (I've created a simple custom settings file using jfr configure --interactive - we might need to tweak it)
  2. Analyze the recording on the CLI (we can do this on the ruby side a bit more comfortably, but just to see, how to get the basic numbers out of that, I did it with jq):
# start end end timestamps
jfr print --json --events jdk.JVMInformation,jdk.Shutdown recording.jfr |jq '.recording.events[0].values.jvmStartTime, .recording.events[1].values.startTime'
"2025-11-29T17:43:38.513+01:00"
"2025-11-29T17:50:50.947936009+01:00"

# duration in seconds
jfr print --json --events jdk.JVMInformation,jdk.Shutdown recording.jfr |jq '
   [ .recording.events[0].values.jvmStartTime, .recording.events[1].values.startTime
      | match("([0-9]+-[0-9]+-[0-9]+T[0-9]+:[0-9]+:[0-9]+).[0-9]+([+-][0-9]+:[0-9]+)")
      | .captures[0].string + .captures[1].string
      | strptime("%Y-%m-%dT%H:%M:%S%z") | mktime
   ] | .[1] - .[0]'
432

jfr print --json --events jdk.JVMInformation,jdk.Shutdown recording.jfr |jq '
   [ .recording.events[0].values.jvmStartTime, .recording.events[1].values.startTime
      | match("([0-9]+-[0-9]+-[0-9]+T[0-9]+:[0-9]+:[0-9]+).[0-9]+([+-][0-9]+:[0-9]+)")
      | .captures[0].string + .captures[1].string
      | strptime("%Y-%m-%dT%H:%M:%S%z") | mktime
    ] | (.[1] - .[0]) / 60 * 10 | floor / 10 | tostring + " minutes"'
"7.2 minutes"

# max heap memory
jfr print --json --events jdk.GCHeapSummary recording.jfr | jq '[.recording.events[].values.heapUsed]|max'
976278600

jfr print --json --events jdk.GCHeapSummary recording.jfr | jq '[.recording.events[].values.heapUsed]|max / 1024 / 1024 * 10 | floor / 10 | tostring + "GB"'
"931GB"

# max cpu load
jfr print --json --events jdk.CPULoad recording.jfr | jq '[.recording.events[].values.jvmUser]|max'
0.5767327

jfr print --json --events jdk.CPULoad recording.jfr | jq '[.recording.events[].values.jvmUser]|max * 1000 | floor / 10 | tostring + "%"'
"57.6%"

# average cpu load
jfr print --json --events jdk.CPULoad recording.jfr | jq 'add(.recording.events[].values.jvmUser) / (.recording.events | length)'
0.25153296741258757

jfr print --json --events jdk.CPULoad recording.jfr | jq '(add(.recording.events[].values.jvmUser) / (.recording.events | length) * 1000) | floor / 10 | tostring + "%"'
"25.1%"
  1. Include these basic numbers in the html report and baseline for comparison.

  2. We can include the recording.jfr into the regression report. You can then download it and open it with JDK Mission Control (https://adoptium.net/de/jmc) to have a deeper look.

@jsotuyod

Copy link
Copy Markdown
Member

+1 on using JFR. Low overhead, reliable, applicable to all PMD modes (CPD, PMD, etc.) and no maintenance on our end.

@adangel adangel modified the milestones: 7.20.0, 7.21.0 Dec 28, 2025
@adangel adangel modified the milestones: 7.21.0, 7.22.0 Jan 30, 2026
@adangel

adangel commented Feb 22, 2026

Copy link
Copy Markdown
Member

I'm moving this to 7.23.0. I'm still working on the pmd-regression-tester (see pmd/pmd-regression-tester#169 ), but that won't be finished for this Friday's release.

@adangel

adangel commented Mar 24, 2026

Copy link
Copy Markdown
Member

Moving this to 7.24.0. Depends on pmd/pmd-regression-tester#171 and new release of regression tester and #6515

@adangel adangel modified the milestones: 7.23.0, 7.24.0 Mar 24, 2026
@adangel adangel modified the milestones: 7.24.0, 7.25.0 Apr 24, 2026
adangel added 2 commits April 30, 2026 09:11
We can't use try-with-resources here, as we compile against Java 8.
But we build with Java 21 (enforced) and PMD uses that version for
the auxclasspath.
See also pmd#6224
@adangel

adangel commented May 7, 2026

Copy link
Copy Markdown
Member

@oowekyala

Good news - the OOM error for alsa-firmware is fixed. We have now 487 new duplications.

But I'm puzzled with the duplications for the java projects, e.g. checkstyle: we have 175 duplications less and 332 duplications changed. Or in other words: Before this change, we detected 507 duplications in checkstyle, now we only have 332.

Looking at the xml reports directly, I can see:

  • for the files section, everything stayed the same: the totalNumberOfTokens per File is the same, so tokenizing wasn't changed. Good.
  • When comparing the first changed duplication (AbstractCheck.java/AbstractFileSetCheck.java), there are only changes in the "beginToken" and "endToken" attributes - which are not displayed by the regression tester, but apparently compared.
    • other attributes (duplication length in lines/tokens, file positions) are the same. Good.
    • beginToken/endToken are different:
--- base-abstractcheck.xml	2026-05-07 08:32:34.114667477 +0200
+++ patch-abstractcheck.xml	2026-05-07 08:32:59.678176449 +0200
@@ -1,16 +1,16 @@
    <duplication lines="20" tokens="96">
-      <file begintoken="37874"
+      <file begintoken="271"
             column="5"
             endcolumn="59"
             endline="231"
-            endtoken="37969"
+            endtoken="366"
             line="212"
             path="/home/runner/work/pmd/target/repositories/checkstyle/src/main/java/com/puppycrawl/tools/checkstyle/api/AbstractCheck.java"/>
-      <file begintoken="38646"
+      <file begintoken="434"
             column="5"
             endcolumn="59"
             endline="218"
-            endtoken="38741"
+            endtoken="529"
             line="200"
             path="/home/runner/work/pmd/target/repositories/checkstyle/src/main/java/com/puppycrawl/tools/checkstyle/api/AbstractFileSetCheck.java"/>
       <codefragment><![CDATA[    }
  • I assume, beginToken/endToken are more internal details - yet they are in the XML report for some reason. Ok, reason is: [core] CPD: Added begin and end token to XML reports #4095 and [core] CPD: Add total number of tokens to XML reports #4021 (comment)
    • In both base and patch they look consistent, meaning "endToken - beginToken + 1 == tokens" - they represent the length of the duplication measured in number of tokens
    • The actual number has changed, which is probably expected, as you changed the implemention
    • I guess, we should adjust the regression tester to ignore the beginToken/endToken attributes when comparing. But all other attributes are still important for comparison (line, column, lines, tokens).

I started to look into the duplications of IndentationCheckTest.java. Some are the same. But one example of a change is: previously, we matched a bigger chunk (94 tokens) + smaller chunks (85 tokens and 61 tokens). Now, we seem to match only the smaller chunk (61 tokens)?

@oowekyala What's the best approach to move forward here?

This branch has not been deployed

No deployments
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.

[core] CPD throws java.lang.OutOfMemoryError: Java heap space [cpp] PMD-7.4.0 CPD exception "java.lang.OutOfMemoryError: Java heap space"

3 participants