Sub topic 6
Collecting metadata with the tracing agent
Earlier chapters showed that Native Image only includes what static analysis can reach, and that reflection, resources and proxies need reachability metadata. Writing that metadata by hand is slow and easy to get wrong. The tracing agent automates the work by watching a real run of your program and writing the metadata files for you.
This chapter assumes you can run a JAR from the command line, know what reflect-config.json is for, and have a GraalVM JDK installed with java on your path.
What the agent does
The tracing agent is a JVMTI agent that ships with GraalVM. JVMTI is the JVM's tool interface, which lets a native library observe a running JVM. You attach the agent with the -agentlib:native-image-agent option. While your program runs on the normal JVM, the agent records each call that Native Image cannot predict statically:
- Reflection:
Class.forName,getDeclaredMethod,getDeclaredField,newInstanceand similar calls. - Resource access:
Class.getResource,ClassLoader.getResourceAsStreamandResourceBundlelookups. - Dynamic proxies created with
java.lang.reflect.Proxy. - JNI lookups of classes, methods and fields from native code.
- Java serialization of classes.
When the JVM exits, the agent writes JSON files that describe what it saw. The build then reads those files and keeps the registered elements in the image.
The agent only sees what your run actually does. It is a recorder, not an analyzer. If a code path never executes during the traced run, nothing about it is recorded.
Running the agent
Start from a program that uses reflection, like the one in the spine:
package com.example;
public class Reflective {
public static void main(String[] args) throws Exception {
Class<?> c = Class.forName("com.example.Greeter");
Object o = c.getDeclaredConstructor().newInstance();
System.out.println(o);
}
}Package it as app.jar, then run it with the agent:
java -agentlib:native-image-agent=config-output-dir=src/main/resources/META-INF/native-image -jar app.jarThe config-output-dir option names the directory that receives the files. Writing into src/main/resources/META-INF/native-image has a practical benefit. Files in META-INF/native-image on the classpath are picked up by native-image automatically, so the next build uses them with no extra flags. Putting them under src/main/resources also means they are copied into your JAR and kept in version control.
After the run, the directory contains files such as these:
| File | Contents |
|---|---|
| `reflect-config.json` | Classes, constructors, methods and fields used through reflection |
| `resource-config.json` | Resources and resource bundles that were loaded |
| `proxy-config.json` | Interface lists used to create dynamic proxies |
| `serialization-config.json` | Classes that were serialized or deserialized |
| `jni-config.json` | Classes, methods and fields reached from JNI |
| `reachability-metadata.json` | A single combined file, written by newer GraalVM releases |
Which files you get depends on your GraalVM version. Newer releases can write one combined reachability-metadata.json, while older ones write the separate files. Open the output directory and check what your version produced, then keep whatever it wrote.
For the example above, reflect-config.json will contain an entry for com.example.Greeter with its no-argument constructor. The entry is narrower than the hand-written one in the spine, because the agent records only the constructor that was called. That precision keeps the image smaller.
Coverage is the main limit
The agent records executed paths only. Consider an application with a REST endpoint that loads a template by reflection only when a rarely used /export route is called. If your traced run never calls /export, the metadata has no entry for it. The native executable will start fine and then fail with a ClassNotFoundException or a missing-resource error when someone first hits /export in production.
To get good coverage:
- Run your test suite under the agent. Integration tests that touch many features are the best source.
- Exercise the application manually or with a load script, including error paths, optional features and each configuration profile.
- Run it several times and merge the results, as described below.
- Test the finished native executable with the same tests, not only the JVM build.
Merging results from several runs
Different runs reach different code. Rather than overwriting the output each time, tell the agent to merge new observations into existing files. Use the config-merge-dir option:
java -agentlib:native-image-agent=config-merge-dir=src/main/resources/META-INF/native-image -jar app.jar --mode=import
java -agentlib:native-image-agent=config-merge-dir=src/main/resources/META-INF/native-image -jar app.jar --mode=exportEach run adds its observations to the files already in the directory. The difference between the two options matters:
| Option | Behavior |
|---|---|
| `config-output-dir` | Writes files into the directory, replacing the previous output of that run |
| `config-merge-dir` | Reads existing files in the directory and adds new entries to them |
If you keep hand-edited metadata in the same directory, check that merge mode preserved your changes. It is safer to keep manual entries in a separate file with a different name. The build reads every metadata file in the directory, so both sets apply.
Running tests under the agent
For tests, you usually pass the agent to the forked test JVM. With Maven Surefire, you can set argLine:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>-agentlib:native-image-agent=config-merge-dir=${project.basedir}/src/main/resources/META-INF/native-image</argLine>
</configuration>
</plugin>The GraalVM Maven and Gradle plugins, covered in a later chapter, also have built-in support for running the agent during tests. Use those when you can, because they handle the output location for you.
One consequence of tracing tests is noise. Test frameworks use reflection heavily, so the agent records entries for JUnit, Mockito and the test classes themselves. These entries are harmless but they enlarge the image. You can filter them out, as the next section shows.
Filtering what the agent records
By default the agent ignores classes from the JDK's own internal use of reflection, but it still records a lot. Access filters let you exclude packages. You supply a JSON file with the access-filter-file option:
{
"rules": [
{ "excludeClasses": "org.junit.**" },
{ "excludeClasses": "org.mockito.**" },
{ "excludeClasses": "com.example.test.**" }
]
}Save it as agent-filter.json and pass it to the agent:
java -agentlib:native-image-agent=config-merge-dir=src/main/resources/META-INF/native-image,access-filter-file=agent-filter.json -jar app.jarRules are evaluated in order, and ** matches a package and everything below it. Exclude test libraries and your own test packages, so that only production metadata reaches the image.
Caller-based filtering and other behavior
The agent tracks which class made each dynamic call. A call made from inside the JDK itself, for example while the JDK loads a security provider, is usually not recorded by default. This avoids a large amount of metadata that the Native Image runtime already includes. If you do need such entries, the agent has options for adjusting this, but start with the defaults.
Two more points are worth knowing:
- The agent writes its files when the JVM exits. If the process is killed with
kill -9or crashes, the files may be missing or incomplete. Stop applications with a normal shutdown so the exit hook runs. - For long-running servers, you can ask the agent to write output at a point other than exit by using the
config-write-period-secsandconfig-write-initial-delay-secsoptions. This is useful when you cannot easily stop the process cleanly.
Reviewing the generated files
Treat generated metadata as source code. Read it before you commit it.
- Look for entries that make no sense for production, such as test classes or a developer tool.
- Look for entries that are too broad. The agent usually records what was used, which is narrow. Hand-written
allDeclaredConstructors: trueentries are broader. - After a dependency upgrade, regenerate the metadata. Library internals change, and stale entries for removed classes can cause warnings.
- Check the files into version control, so that a metadata change appears in code review.
Many popular libraries already publish their own metadata. The GraalVM Reachability Metadata Repository supplies entries for common libraries, and the build tools can fetch them. That means the agent only has to cover your own code and any library that lacks published metadata.
Complete workflow
Putting the pieces together, a typical cycle looks like this:
- Build the JAR and run the full test suite under the agent, using
config-merge-dirand a filter file. - Run extra scenarios that the tests do not cover, merging into the same directory.
- Review and commit the generated files.
- Build the native executable with
native-image -jar app.jar -o app. - Run the tests against the native executable and fix any failure by adding missing scenarios or hand-written entries.
- Repeat from step 2 when you add features or upgrade dependencies.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Output directory is empty | The agent was not attached, or the JVM was killed before exit | Check the `-agentlib` spelling and stop the application normally |
| `ClassNotFoundException` or `NoSuchMethodException` in the native binary only | The code path was not run during tracing | Add a scenario that runs it and merge the new output |
| Missing resource at run time | The resource was loaded through a path the agent did not see | Run that feature under the agent or add a `resource-config.json` entry |
| Image is larger than expected | Test or tool classes were recorded | Add an access filter and regenerate |
| Hand-edited entries disappeared | They were in a file that the agent rewrote | Keep manual entries in a separate file |
| Agent fails to load | The JVM is not a GraalVM JDK | Use a GraalVM distribution for the traced run |
Exercise
Your team traced the application once with a single smoke test and built a native executable. It starts correctly, but a nightly export job fails with a missing-class error. Explain why this happened and give two ways to fix it.
Show answer
The tracing agent records only the code paths that actually execute during the traced run. The smoke test never ran the export job, so the reflective access it needs was never written to the metadata, and the closed-world analysis removed it from the image. Fix it by running the export job under the agent with config-merge-dir so its entries are merged into the existing files, or by adding the missing class to reflect-config.json by hand. Then rebuild and run the export job against the native executable to confirm.
Exercise
What is the difference between config-output-dir and config-merge-dir, and which would you use when tracing three separate scenarios one after another?
Show answer
config-output-dir writes the files for that run into the directory, replacing earlier output, while config-merge-dir reads the files already there and adds the new observations. For three scenarios in sequence you would use config-merge-dir, so that the final files contain the combined metadata from all three runs.