[jnigen] Gemini's friction log

Open
#3,836 0 comments 0 reactions 1 assignee View on GitHub

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

lang-java needs-triage package:jni package:jni_flutter package:jnigen

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:

  1. Gradle Bootstrap Deadlocks & Brittle Android/Kotlin Classpath Plumbing: Running JNIgen with add_gradle_deps: true triggers Flutter's :app:compileFlutterBuildRelease, creating a chicken-and-egg deadlock whenever Dart code does not yet compile. Binding local Java+Kotlin code requires manual flutter build apk pre-builds and hardcoded AGP/KGP internal output directories; plugin implementation(...) dependencies are invisible unless leaked as api(...); addGradleDeps mutates build.gradle(.kts) in-place across 4 dual-DSL templates with zero caching; and ClassFinder.java short-circuits package scanning on the first matching root, silently dropping Kotlin classes in split Android Java/Kotlin packages.
  2. Error Masking & Swallowed Diagnostics: Every ApiSummarizer subprocess failure (missing classes, glob patterns, Java syntax errors, Main.java:143 NPE, Kotlin metadata readStrict version mismatches, or parallel races) is masked as FormatException: Unexpected end of input (at character 1) because getSummary (summary.dart) calls jsonDecode before checking exit codes or stderr. Similarly, _runDartFormat hides stderr and blames JNIgen syntax when the actual failure is a <3.3.0 Dart SDK constraint (inline-class), and AndroidSdkTools._runGradleStub prints an unconditional troubleshooting wall ahead of the real Gradle error.
  3. Silent Drops & Silent Type Degradation: JNIgen silently generates 0 classes for package-private classes (passing dart analyze), drops Java record declarations without warning, omits .implement() on Java abstract classes without explanation, ignores unknown or removed YAML keys (exclude:, output.c), no-ops Config(dumpJsonTo: ...) in generateJniBindings, silently ignores unrecognized nullability annotations (javax.annotation.*), degrades ArrayList subclasses to JObject due to missing java.util.ArrayList in jni_symbols.yaml, and can emit r'null' JNI descriptors that crash only at JVM runtime.
  4. Runtime Compatibility, Versioning & Memory Safety Hazards: Minor-version runtime regressions (jni 1.2.0 breaking legacy jnigen <= 1.1.x bindings via L...; descriptors in Jni.findClass / JType.jClass, triggering a pub.dev retraction), manual version constants and dependency_overrides masking lower-bound mismatches (jni_flutter 1.0.4), 103-file version-bump header diff spam, and silent JNI reference, port, and GC-cycle leaks across JImplementer, Kotlin suspend continuations, PortContinuation, JByteBuffer.asUint8List(), and releaseOriginal: true + Arena.
  5. Generated Binding & package:jni Ergonomics: Single-file outputs interleave ~20-30 lines of FFI lookup boilerplate per method (37,853 lines in kotlin.dart); $ / $$Methods / extension type naming frustrates regex searches; Dart's isA<ExtensionType>() silently false-positives for any JObject; isInstanceOf(JClass) is inconsistent with .as(JType) and JArray.withLength(JType, ...); overload numbering depends on unstable classpath order; and single-constructor new$1 bugs, checked DartException wrapping in UndeclaredThrowableException (with null message), and hand-authored R8 keep rules trip up consumers.
  6. Fragile Maintainer Tooling, Verification & Monorepo Hygiene: ApiSummarizer.jar suffers a rebuild catch-22 with multiple scattered copies across packages and examples; regenerate_examples_test.dart mutates tracked files in-place and swallows Gradle failures; runtime_test.dart can hang indefinitely with no default test timeout; stale in-place .class files diverge local runs from CI; parallel Gradle runs corrupt caches-jvm; 12 standalone Gradle/Flutter projects drift in version and cause significant local Gradle/Android build cache disk bloat; and no jnigen:doctor preflight command exists.

Suggested Improvements

P0: Critical Correctness, Deadlocks & Silent Failure Fixes
  1. Fix ClassFinder Classpath Short-Circuiting: Union classes across all class_path and source_path entries for package inputs in ClassFinder.java:96 instead 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.
  2. Surface ApiSummarizer & dart format Exit Codes/Stderr, Fix Main.java:143 NPE & Handle Kotlin Metadata Gracefully: Check ApiSummarizer exit codes and empty stdout in summary.dart before jsonDecode, throwing a structured SummaryException with stderr and targeted hints, and guard m == null at Main.java:143. Evaluate KotlinClassMetadata.readLenient(header) with warnings plus Dependabot updates for kotlin-metadata-jvm, and print formatRes.stderr verbatim in _runDartFormat with an 'inline-class' SDK ^3.3.0 hint.
  3. Break the :app:compileFlutterBuildRelease Gradle Bootstrap Deadlock: Exclude Flutter's Dart-produced libs.jar or pass -x compileFlutterBuildRelease when extracting releaseCompileClasspath in android_sdk_tools.dart so JNIgen never compiles Dart code. If Gradle still fails on Target kernel_snapshot_program failed, print a direct diagnostic rather than generic troubleshooting boilerplate.
  4. Fix PrimitiveType Serialization (@Nullable int[]) & fromJson Error Context: Serialize primitive names via primitiveType.getKind().toString().toLowerCase() instead of toString() so TYPE_USE annotations are not embedded in the primitive name. Replace _primitives[json['name']]! in elements.dart:356 with an explicit lookup that throws a descriptive FormatException naming the offending value, class, and member.
  5. Eliminate Silent 0-Class, Skipped-record, r'null' Descriptor & Missing jni_symbols.yaml Bugs: Log generated class/method/field counts and resolved output paths at INFO level, and warn prominently when 0 classes are generated or when RECORD or non-public declarations are skipped. Assert non-empty descriptors in DartGenerator/Linker, add java.util.ArrayList to pkgs/jni/lib/jni_symbols.yaml, and add a test enforcing parity with core_bindings.dart.
  6. Maintain Legacy jnigen Backwards-Compatibility CI Tests & Safe JType.jClass / L...; Fallback: Keep checked-in JniVersionCheck(1, 0) legacy bindings exercised on Android CI (legacy_android_test_runner). Ensure Jni.findClass and JType.jClass safely handle or clearly diagnose L...; descriptors so minor package:jni releases cannot silently break published downstream packages.
  7. Automate jni / jnigen / jni_flutter Version-Sync & Lower-Bound Checks: Replace manual // Keep in sync with pubspec.yaml comments in dart_generator.dart and version_check.dart with automated tests verifying version constants and JniVersionCheck(major, minor) against pubspec.yaml constraints. Run these checks without dependency_overrides masking lower-bound mismatches.
  8. Fix JNI, Kotlin suspend, JImplementer & JByteBuffer Reference/Port Leaks: Register outgoing PortContinuation with PortCleaner, release JGlobalReference in KotlinContinuation.resumeWith to break the 4-node Kotlin suspend GC cycle, and add a .release() escape hatch to JByteBuffer.asUint8List(). Clean up ports and _$impls when JImplementer.implement() throws or is never called, and clarify/fix JImplementer disposal ownership and multi-interface port coupling.
P1: High-Leverage Gradle, CLI, Freshness & Dev/Test Harness Improvements
  1. Replace In-Place build.gradle(.kts) Mutation with Gradle --init-script, Cache Classpaths & Support Plugin implementation(...) 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' own releaseCompileClasspath so implementation(...) dependencies resolve without api(...), pattern-match Gradle stderr before printing hints, and fix the unconditional Building ApiSummarizer component... cache-hit log.
  2. 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 manual flutter build apk pre-build ritual and hardcoded AGP/KGP internal paths (intermediates/javac/..., tmp/kotlin-classes/...).
  3. Add Strict Config/YAML Validation, Fix CLI Ergonomics & Add Declarative stubClasses: Reject or warn on unknown/removed YAML keys (exclude:, output.c), infer single_file from .dart output paths, and fix CLI rough edges (--help exit 0 with example, -v/--verbose, case-insensitive -Dlog_level, fail-fast missing --config, and wiring dumpJsonTo in generateJniBindings). Add a declarative stubClasses option in Dart Config to avoid 6,000+ line Context bloat, and restore a shared CLI override helper for tool/jnigen.dart.
  4. Add Native --set-exit-if-changed Freshness Mode & Eliminate Version-Header Diff Spam: Compare generated output in memory and print a unified diff on mismatch without mutating tracked files, replacing brittle git diff --exit-code checks. Unify ignore rules across CI and tests, drop the patch/minor version from // AUTO GENERATED BY JNIGEN $version to stop 103-file version-bump churn, and stop swallowing 'Gradle execution failed.' in regenerate_examples_test.dart.
  5. Unify ApiSummarizer.jar Cache with Auto-Rebuild & Eliminate CWD / Path / flutter Discovery Coupling: Give dart run jnigen:setup the same isPackageModifiedAfter staleness check as test_util.dart (plus --force) and store one canonical ApiSummarizer.jar resolved via Isolate.resolvePackageUri with file locking. Standardize Config paths on Uri, auto-detect ANDROID_HOME/ANDROID_SDK_ROOT, unify flutterExecutable discovery across jdk_util.dart and android_sdk_tools.dart, and standardize all examples on a single dart test-safe tool/jnigen.dart convention.
  6. Add dart run jnigen:doctor Environment Preflight Command: Validate JAVA_HOME, JDK 17/21 compatibility, javac/jar, kotlinc, Gradle/Maven, Android SDK, Windows jvm.dll, and ApiSummarizer.jar in one fast command with concise human and JSON output. Ensure it works cleanly even when jnigen is installed as a dev_dependency.
  7. Harden regenerate_all_bindings.dart & Local/CI Verification Ordering: Make regenerate_all_bindings.dart CWD-independent, include pkgs/jni and pkgs/jni_flutter via a shared target registry, add a fail-fast preflight compile check, and serialize Gradle-invoking targets to avoid caches-jvm corruption. Ensure verification workflows run jnigen:setup and binding regeneration before formatting, analysis, and APK builds (with streamed output and timeouts, without mutating pubspec.lock).
  8. Harden Test Harness & Add Pipeline Debug Introspection: Set a finite default timeout (3m or 5m) in pkgs/jnigen/dart_test.yaml to prevent indefinite hangs, compile test .java files into a wiped build/classes/ directory (javac -d), move temp dirs to Directory.systemTemp with cleanup, add keepTempOnFailure: true to generateAndAnalyzeBindings, and stop comparePaths from mutating checked-in files. Add a --dump-stage=<stage> debug flag, keep ApiSummarizer stdout clean JSON, add android_sdk_tools.dart unit tests, and document runtime_test_registrant.dart in pkgs/jnigen/test/README.md.
P2: Binding Ergonomics, Workspace Hygiene & Maintenance
  1. De-Clutter Generated Bindings, Stabilize Overload/Constructor Naming & Emit Optional R8 Keep Rules: Move _id_* and ProtectedJniExtensions.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 $N suffixes, fix Renamer's single-constructor new$1 bug (StringBox), and add optional proguardOutput for -keep and -keepattributes Exceptions rules.
  2. Make Nullability Annotations, abstract class Limits & DartException Wrapping Transparent: Warn on unrecognized *Nullable/*NonNull/*Nonnull annotations, fix @NotNull on type-variable fields, and document the supported annotation allowlist. Emit an explicit warning and generated doc note on Java abstract classes explaining the .implement() interface-only limit, and clearly document (or revisit for 2.0) PortProxyBuilder$DartException wrapping in UndeclaredThrowableException.
  3. Fix package:jni Type-Check & Lifecycle Ergonomics & Clean Stale Docs: Accept JType in JObject.isInstanceOf (or add isInstanceOfType(JType)), document the isA<ExtensionType>() false-positive trap, and ship an isJInstanceOf(Foo.type) test matcher. Document releaseOriginal: true vs releasedBy(arena) hazards, clean stale pre-0.16 comments in dart_generator.dart, and remove obsolete flutter build apk prerequisites from the 5 README/doc/changelog files.
  4. 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 12 pkgs/jni* projects in CI, bump pkgs/jni/example to >=3.3.0, add local analysis_options.yaml to standalone examples, fix stale invalid_null_aware_operator warnings, and exclude android_test_runner/** in pkgs/jnigen/analysis_options.yaml. Audit removing environment: flutter: from pkgs/jni/pubspec.yaml to unblock workspace integration, and add a tool/clean_android_builds.dart helper to curb significant local Android/Gradle build directory disk bloat.
  5. Fix Android GC Tests, Omitted On-Device Tests, Headless Emulator Helper & CI Doc Snippet Checks: Fix the JGlobalReference leak in java_gc.dart:47 and switch Android GC triggers from jcmd/System.gc() to Runtime.getRuntime().gc(), register the 3 omitted tests in on_device_jni_test.dart, and add a reliable headless emulator helper. Fix Jni.setDylibsDir and dynamic libararies in pkgs/jnigen/doc/threading.md:66-67, and wire pkgs/jnigen/doc/ into CI snippet checks.
Dominant language
Dart
Stars
280
Forks
166
Avg merge
3d 4h
Merged PRs (30d)
33

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from dart-lang/native

All issues in dart-lang/native

Similar issues

More Dart issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.