[jnigen] Gemini's friction log
Maintainers usually reply within 2 days
@liamappelbe is already working on this.
Since Dec 2, 2026.
Assessment
This issue has not been assessed yet.
Description
This is an AI generated summary of all the issues Gemini has run into while using JNIgen. I haven't fully reviewed the contents. I need to go through these in detail and triage them/file separate issues. I'm pasting it into an issue to make review easier for myself.
JNIgen & package:jni Pain Points & Improvement Roadmap
Consolidated summary of recurring pain points and prioritized tooling improvements for package:jnigen and package:jni in dart-lang/native.
Overview
Across both consumer and maintainer workflows, high-latency failures in package:jnigen and package:jni cluster into six core themes:
- Gradle Bootstrap Deadlocks & Brittle Android/Kotlin Classpath Plumbing: Running JNIgen with
add_gradle_deps: truetriggers Flutter's:app:compileFlutterBuildRelease, creating a chicken-and-egg deadlock whenever Dart code does not yet compile. Binding local Java+Kotlin code requires manualflutter build apkpre-builds and hardcoded AGP/KGP internal output directories; pluginimplementation(...)dependencies are invisible unless leaked asapi(...);addGradleDepsmutatesbuild.gradle(.kts)in-place across 4 dual-DSL templates with zero caching; andClassFinder.javashort-circuits package scanning on the first matching root, silently dropping Kotlin classes in split Android Java/Kotlin packages. - Error Masking & Swallowed Diagnostics: Every
ApiSummarizersubprocess failure (missing classes, glob patterns, Java syntax errors,Main.java:143NPE, Kotlin metadatareadStrictversion mismatches, or parallel races) is masked asFormatException: Unexpected end of input (at character 1)becausegetSummary(summary.dart) callsjsonDecodebefore checking exit codes or stderr. Similarly,_runDartFormathidesstderrand blames JNIgen syntax when the actual failure is a<3.3.0Dart SDK constraint (inline-class), andAndroidSdkTools._runGradleStubprints an unconditional troubleshooting wall ahead of the real Gradle error. - Silent Drops & Silent Type Degradation: JNIgen silently generates 0 classes for package-private classes (passing
dart analyze), drops Javarecorddeclarations without warning, omits.implement()on Javaabstract classes without explanation, ignores unknown or removed YAML keys (exclude:,output.c), no-opsConfig(dumpJsonTo: ...)ingenerateJniBindings, silently ignores unrecognized nullability annotations (javax.annotation.*), degradesArrayListsubclasses toJObjectdue to missingjava.util.ArrayListinjni_symbols.yaml, and can emitr'null'JNI descriptors that crash only at JVM runtime. - Runtime Compatibility, Versioning & Memory Safety Hazards: Minor-version runtime regressions (
jni 1.2.0breaking legacyjnigen <= 1.1.xbindings viaL...;descriptors inJni.findClass/JType.jClass, triggering a pub.dev retraction), manual version constants anddependency_overridesmasking lower-bound mismatches (jni_flutter 1.0.4), 103-file version-bump header diff spam, and silent JNI reference, port, and GC-cycle leaks acrossJImplementer, Kotlinsuspendcontinuations,PortContinuation,JByteBuffer.asUint8List(), andreleaseOriginal: true+Arena. - Generated Binding &
package:jniErgonomics: Single-file outputs interleave ~20-30 lines of FFI lookup boilerplate per method (37,853 lines inkotlin.dart);$/$$Methods/extension typenaming frustrates regex searches; Dart'sisA<ExtensionType>()silently false-positives for anyJObject;isInstanceOf(JClass)is inconsistent with.as(JType)andJArray.withLength(JType, ...); overload numbering depends on unstable classpath order; and single-constructornew$1bugs, checkedDartExceptionwrapping inUndeclaredThrowableException(withnullmessage), and hand-authored R8 keep rules trip up consumers. - Fragile Maintainer Tooling, Verification & Monorepo Hygiene:
ApiSummarizer.jarsuffers a rebuild catch-22 with multiple scattered copies across packages and examples;regenerate_examples_test.dartmutates tracked files in-place and swallows Gradle failures;runtime_test.dartcan hang indefinitely with no default test timeout; stale in-place.classfiles diverge local runs from CI; parallel Gradle runs corruptcaches-jvm; 12 standalone Gradle/Flutter projects drift in version and cause significant local Gradle/Android build cache disk bloat; and nojnigen:doctorpreflight command exists.
Suggested Improvements
P0: Critical Correctness, Deadlocks & Silent Failure Fixes
- Fix
ClassFinderClasspath Short-Circuiting: Union classes across allclass_pathandsource_pathentries for package inputs inClassFinder.java:96instead of short-circuiting on the first matching root so split Android Java and Kotlin packages scan completely. Log discovered class counts per entry and warn on 0-match roots or missing directories. - Surface
ApiSummarizer&dart formatExit Codes/Stderr, FixMain.java:143NPE & Handle Kotlin Metadata Gracefully: CheckApiSummarizerexit codes and emptystdoutinsummary.dartbeforejsonDecode, throwing a structuredSummaryExceptionwith stderr and targeted hints, and guardm == nullatMain.java:143. EvaluateKotlinClassMetadata.readLenient(header)with warnings plus Dependabot updates forkotlin-metadata-jvm, and printformatRes.stderrverbatim in_runDartFormatwith an'inline-class'SDK^3.3.0hint. - Break the
:app:compileFlutterBuildReleaseGradle Bootstrap Deadlock: Exclude Flutter's Dart-producedlibs.jaror pass-x compileFlutterBuildReleasewhen extractingreleaseCompileClasspathinandroid_sdk_tools.dartso JNIgen never compiles Dart code. If Gradle still fails onTarget kernel_snapshot_program failed, print a direct diagnostic rather than generic troubleshooting boilerplate. - Fix
PrimitiveTypeSerialization (@Nullable int[]) &fromJsonError Context: Serialize primitive names viaprimitiveType.getKind().toString().toLowerCase()instead oftoString()soTYPE_USEannotations are not embedded in the primitive name. Replace_primitives[json['name']]!inelements.dart:356with an explicit lookup that throws a descriptiveFormatExceptionnaming the offending value, class, and member. - Eliminate Silent 0-Class, Skipped-
record,r'null'Descriptor & Missingjni_symbols.yamlBugs: Log generated class/method/field counts and resolved output paths atINFOlevel, and warn prominently when 0 classes are generated or whenRECORDor non-public declarations are skipped. Assert non-empty descriptors inDartGenerator/Linker, addjava.util.ArrayListtopkgs/jni/lib/jni_symbols.yaml, and add a test enforcing parity withcore_bindings.dart. - Maintain Legacy
jnigenBackwards-Compatibility CI Tests & SafeJType.jClass/L...;Fallback: Keep checked-inJniVersionCheck(1, 0)legacy bindings exercised on Android CI (legacy_android_test_runner). EnsureJni.findClassandJType.jClasssafely handle or clearly diagnoseL...;descriptors so minorpackage:jnireleases cannot silently break published downstream packages. - Automate
jni/jnigen/jni_flutterVersion-Sync & Lower-Bound Checks: Replace manual// Keep in sync with pubspec.yamlcomments indart_generator.dartandversion_check.dartwith automated tests verifying version constants andJniVersionCheck(major, minor)againstpubspec.yamlconstraints. Run these checks withoutdependency_overridesmasking lower-bound mismatches. - Fix JNI, Kotlin
suspend,JImplementer&JByteBufferReference/Port Leaks: Register outgoingPortContinuationwithPortCleaner, releaseJGlobalReferenceinKotlinContinuation.resumeWithto break the 4-node KotlinsuspendGC cycle, and add a.release()escape hatch toJByteBuffer.asUint8List(). Clean up ports and_$implswhenJImplementer.implement()throws or is never called, and clarify/fixJImplementerdisposal ownership and multi-interface port coupling.
P1: High-Leverage Gradle, CLI, Freshness & Dev/Test Harness Improvements
- Replace In-Place
build.gradle(.kts)Mutation with Gradle--init-script, Cache Classpaths & Support Pluginimplementation(...)Deps: Use a single temporary--init-script(init.gradle) instead of mutating user build scripts across 4 dual-DSL templates, and cache resolved classpaths by build-file hash while deduplicating-c(android.jar). Inspect plugin subprojects' ownreleaseCompileClasspathsoimplementation(...)dependencies resolve withoutapi(...), pattern-match Gradle stderr before printing hints, and fix the unconditionalBuilding ApiSummarizer component...cache-hit log. - Auto-Discover App Module Java & Kotlin Compile Outputs via Gradle: Extend
AndroidSdkConfig(e.g.,includeProjectClasses: true) so Gradle compiles and exports the app module's own Java and Kotlin class output directories automatically. This removes the manualflutter build apkpre-build ritual and hardcoded AGP/KGP internal paths (intermediates/javac/...,tmp/kotlin-classes/...). - Add Strict Config/YAML Validation, Fix CLI Ergonomics & Add Declarative
stubClasses: Reject or warn on unknown/removed YAML keys (exclude:,output.c), infersingle_filefrom.dartoutput paths, and fix CLI rough edges (--helpexit0with example,-v/--verbose, case-insensitive-Dlog_level, fail-fast missing--config, and wiringdumpJsonToingenerateJniBindings). Add a declarativestubClassesoption in DartConfigto avoid 6,000+ lineContextbloat, and restore a shared CLI override helper fortool/jnigen.dart. - Add Native
--set-exit-if-changedFreshness Mode & Eliminate Version-Header Diff Spam: Compare generated output in memory and print a unified diff on mismatch without mutating tracked files, replacing brittlegit diff --exit-codechecks. Unify ignore rules across CI and tests, drop the patch/minor version from// AUTO GENERATED BY JNIGEN $versionto stop 103-file version-bump churn, and stop swallowing'Gradle execution failed.'inregenerate_examples_test.dart. - Unify
ApiSummarizer.jarCache with Auto-Rebuild & Eliminate CWD / Path /flutterDiscovery Coupling: Givedart run jnigen:setupthe sameisPackageModifiedAfterstaleness check astest_util.dart(plus--force) and store one canonicalApiSummarizer.jarresolved viaIsolate.resolvePackageUriwith file locking. StandardizeConfigpaths onUri, auto-detectANDROID_HOME/ANDROID_SDK_ROOT, unifyflutterExecutablediscovery acrossjdk_util.dartandandroid_sdk_tools.dart, and standardize all examples on a singledart test-safetool/jnigen.dartconvention. - Add
dart run jnigen:doctorEnvironment Preflight Command: ValidateJAVA_HOME, JDK 17/21 compatibility,javac/jar,kotlinc, Gradle/Maven, Android SDK, Windowsjvm.dll, andApiSummarizer.jarin one fast command with concise human and JSON output. Ensure it works cleanly even whenjnigenis installed as adev_dependency. - Harden
regenerate_all_bindings.dart& Local/CI Verification Ordering: Makeregenerate_all_bindings.dartCWD-independent, includepkgs/jniandpkgs/jni_fluttervia a shared target registry, add a fail-fast preflight compile check, and serialize Gradle-invoking targets to avoidcaches-jvmcorruption. Ensure verification workflows runjnigen:setupand binding regeneration before formatting, analysis, and APK builds (with streamed output and timeouts, without mutatingpubspec.lock). - Harden Test Harness & Add Pipeline Debug Introspection: Set a finite default timeout (
3mor5m) inpkgs/jnigen/dart_test.yamlto prevent indefinite hangs, compile test.javafiles into a wipedbuild/classes/directory (javac -d), move temp dirs toDirectory.systemTempwith cleanup, addkeepTempOnFailure: truetogenerateAndAnalyzeBindings, and stopcomparePathsfrom mutating checked-in files. Add a--dump-stage=<stage>debug flag, keepApiSummarizerstdout clean JSON, addandroid_sdk_tools.dartunit tests, and documentruntime_test_registrant.dartinpkgs/jnigen/test/README.md.
P2: Binding Ergonomics, Workspace Hygiene & Maintenance
- De-Clutter Generated Bindings, Stabilize Overload/Constructor Naming & Emit Optional R8 Keep Rules: Move
_id_*andProtectedJniExtensions.lookup(...)boilerplate out of line and emit a compact symbol index plus 5-line naming legend at the top of generated files. Sort methods and constructors deterministically by JVM descriptor before assigning$Nsuffixes, fixRenamer's single-constructornew$1bug (StringBox), and add optionalproguardOutputfor-keepand-keepattributes Exceptionsrules. - Make Nullability Annotations,
abstract classLimits &DartExceptionWrapping Transparent: Warn on unrecognized*Nullable/*NonNull/*Nonnullannotations, fix@NotNullon type-variable fields, and document the supported annotation allowlist. Emit an explicit warning and generated doc note on Javaabstract classes explaining the.implement()interface-only limit, and clearly document (or revisit for 2.0)PortProxyBuilder$DartExceptionwrapping inUndeclaredThrowableException. - Fix
package:jniType-Check & Lifecycle Ergonomics & Clean Stale Docs: AcceptJTypeinJObject.isInstanceOf(or addisInstanceOfType(JType)), document theisA<ExtensionType>()false-positive trap, and ship anisJInstanceOf(Foo.type)test matcher. DocumentreleaseOriginal: truevsreleasedBy(arena)hazards, clean stale pre-0.16 comments indart_generator.dart, and remove obsoleteflutter build apkprerequisites from the 5 README/doc/changelog files. - Unify Gradle/AGP/Kotlin/SDK Versions Across All 12
pkgs/jni*Projects, Fix Workspace/Analysis Config & Curb Disk Bloat: Enforce uniform Gradle/AGP/Kotlin versions across all 12pkgs/jni*projects in CI, bumppkgs/jni/exampleto>=3.3.0, add localanalysis_options.yamlto standalone examples, fix staleinvalid_null_aware_operatorwarnings, and excludeandroid_test_runner/**inpkgs/jnigen/analysis_options.yaml. Audit removingenvironment: flutter:frompkgs/jni/pubspec.yamlto unblock workspace integration, and add atool/clean_android_builds.darthelper to curb significant local Android/Gradle build directory disk bloat. - Fix Android GC Tests, Omitted On-Device Tests, Headless Emulator Helper & CI Doc Snippet Checks: Fix the
JGlobalReferenceleak injava_gc.dart:47and switch Android GC triggers fromjcmd/System.gc()toRuntime.getRuntime().gc(), register the 3 omitted tests inon_device_jni_test.dart, and add a reliable headless emulator helper. FixJni.setDylibsDiranddynamic libarariesinpkgs/jnigen/doc/threading.md:66-67, and wirepkgs/jnigen/doc/into CI snippet checks.
- Dominant language
- Dart
- Stars
- 280
- Forks
- 166
- Avg merge
- 3d 4h
- Merged PRs (30d)
- 33
Getting set up
- No Dockerfile or Docker Compose file
- Has a pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from dart-lang/native
-
lang-objective_c needs-triage package:objective_c
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
Maintainers usually reply within 2 days
-
Proposal: targetIOSVersion may need to be updated to 15 for Flutter 3.47+Possibly taken A pull request linked to this issue is open or already merged. Open
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
dart-lang/native#3594 · 1 comment ·
Maintainers usually reply within 2 days
-
package:ffigen
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
dart-lang/native#1564 · 2 comments ·
Maintainers usually reply within 2 days
-
[ffigen] Gemini's friction logPossibly taken @liamappelbe claimed this today. Openneeds-triage package:ffigen
dart-lang/native#3837 · 1 assignee ·
Maintainers usually reply within 2 days
-
[jni] Reference leaks in JNIPossibly taken @liamappelbe claimed this 7 days ago. Openlang-java package:jni package:jni_flutter package:jnigen
dart-lang/native#3822 · 1 assignee ·
Maintainers usually reply within 2 days
All issues in dart-lang/native
Similar issues
-
bug
Difficulty 1/5 Under an hour Newbie friendliness 75/100
nucleus-ffm/foss_warn#337 ·
-
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
-
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
-
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
Maintainers usually reply within 1 day
-
docs good first issue
Difficulty 2/5 1-3 hours Newbie friendliness 75/100