Skip to content

Conversation

bparrishMines
Copy link
Contributor

@bparrishMines bparrishMines commented Sep 19, 2025

ProxyApis for classes that override equals()/hashcode in Kotlin/Java were breaking the InstanceManager.

The Kotlin InstanceManager would:

  1. Return true for containsInstance.
  2. Then remove the strong reference to the original object in getIdentifierForStrongReference.
  3. Erroneously trigger the call to Dart to remove the strong reference of an instance.

This changes the the use of WeakReference to a new IdentityWeakReference that uses identity to check for equality. Java/Kotlin has an IdentityHashMap and a WeakHashMap, but not an IdentityWeakHashMap. So this is a quick workaround to create an equivalent.

Alternatively, getIdentifierForStrongReference could be updated to check containsInstance first, but this would leave small timeframes where objects would only have a weak reference. And it seems possible that Kotlin GC could cleanup at any moment.

Potential fix for flutter/flutter#174134 since the class they were creating a ProxyApi for was a data class: https://github.com/JavesonYehudi/proxy_bug_report/blob/main/android/src/main/kotlin/com/example/proxy_bug_report/auth/Credentials.kt

Pre-Review Checklist

If you need help, consider asking for advice on the #hackers-new channel on Discord.

Note: The Flutter team is currently trialing the use of Gemini Code Assist for GitHub. Comments from the gemini-code-assist bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed.

Footnotes

  1. Regular contributors who have demonstrated familiarity with the repository guidelines only need to comment if the PR is not auto-exempted by repo tooling. 2 3

@bparrishMines bparrishMines changed the title Pigeon override fix [pigeon] Fixes support for Kotlin/Java classes that override equals and hashCode for ProxyApis Sep 21, 2025
@bparrishMines
Copy link
Contributor Author

/gemini review

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request effectively addresses a bug in the Kotlin InstanceManager where classes overriding equals() and hashCode() could cause incorrect instance tracking. The introduction of the IdentityKey wrapper to enforce identity-based comparisons in the underlying WeakHashMap is a clever solution to the lack of a built-in IdentityWeakHashMap. The addition of new tests specifically for this scenario is also a great way to ensure the fix is robust. Furthermore, adding logging for failures during Dart proxy instance creation improves debuggability. I've found one critical issue in the implementation of the new IdentityKey class that should be addressed.

Comment on lines 58 to 60
override fun hashCode(): Int {
return instance.get().hashCode()
}

Choose a reason for hiding this comment

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

critical

The hashCode implementation for IdentityKey has a critical bug and a logical inconsistency.

  1. NPE Bug: If the WeakReference has been cleared by the garbage collector, instance.get() will return null. Calling .hashCode() on null will result in a NullPointerException. The equals method correctly handles this case, but hashCode does not.
  2. Logical Inconsistency: The purpose of IdentityKey is to enforce identity-based equality, similar to IdentityHashMap. Therefore, its hash code should also be based on identity. Using the instance's own hashCode() can lead to unnecessary hash collisions if different instances have the same value-based hash code, and it deviates from the principle of identity-based hashing.

The correct approach is to use System.identityHashCode(), which is safe for null inputs (it returns 0) and provides an identity-based hash code.

Suggested change
override fun hashCode(): Int {
return instance.get().hashCode()
}
override fun hashCode(): Int {
return System.identityHashCode(instance.get())
}

@bparrishMines bparrishMines marked this pull request as ready for review September 23, 2025 18:17
@bparrishMines bparrishMines marked this pull request as draft September 23, 2025 18:32
@bparrishMines
Copy link
Contributor Author

/gemini review

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request addresses a critical bug in the Kotlin/Java InstanceManager for ProxyApis where classes overriding equals() and hashCode() could cause incorrect instance tracking. The fix introduces an IdentityWeakReference wrapper to ensure instance management is based on object identity rather than equality, which is a robust solution to the problem. The changes are well-tested with new unit tests covering the identity comparison logic and edge cases related to garbage collection. Additionally, the PR improves diagnostics by adding logging for failed Dart proxy instance creations. The overall implementation is solid. I have one suggestion to reduce code duplication in the generated code for the new logging feature.

Comment on lines 1046 to 1052
registrar.get$hostProxyApiPrefix${api.name}().${classMemberNamePrefix}newInstance(value) {
if (it.isFailure) {
Log.w(
"${proxyApiCodecName(const InternalKotlinOptions(kotlinOut: ''))}",
"Failed to create new Dart proxy instance of ${api.name}: \$value. \${it.exceptionOrNull()}")
}
}

Choose a reason for hiding this comment

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

medium

While this logging is a great addition for debugging, the current implementation in the generator leads to duplicated code blocks in the generated writeValue method for each ProxyApi type. To improve the maintainability and readability of the generated code, consider refactoring this. You could generate a private helper method within the ProxyApiBaseCodec class to encapsulate the logging logic, and then call that helper from each if block.

For example, you could generate a method like this:

private fun logNewInstanceFailure(value: Any, apiName: String, result: Result<*>) {
  if (result.isFailure) {
    Log.w(
      "PigeonProxyApiBaseCodec",
      "Failed to create new Dart proxy instance of $apiName: $value. ${result.exceptionOrNull()}"
    )
  }
}

Then, the call site in the if block would be a single, clean line.

@bparrishMines bparrishMines marked this pull request as ready for review September 25, 2025 18:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant