Repository navigation
[copilot] Add JNI peer lifetime (GC.KeepAlive) guidelines - #13766
simonrozsival wants to merge 7 commits into
Conversation
Context: #13759 Context: #12315 Context: #12754 An audit of Java.Interop, Mono.Android, and device tests surfaced 37 missing GC.KeepAlive and peer-retention hazards (#13759). On CoreCLR and NativeAOT, JavaMarshalGCBridge deletes and replaces the global reference of any managed-unreachable peer even when the Java object survives, so copying .Handle or .PeerReference without retaining its managed owner can trigger CheckJNI 'use of deleted global reference' aborts. Document JNI peer-lifetime rules across the agent instructions and code-review references to prevent future regressions: * Authoring rules in .github/copilot-instructions.md and .github/instructions/java-interop.instructions.md: explain the JavaMarshalGCBridge gref-swap hazard, prefer owner-retaining APIs, require GC.KeepAlive after native calls on borrowed handles, read PeerReference once before IsValid, retain strong owner references in multi-call native wrappers (such as JniArrayElements), and list common traps (WithLocalJniHandle lambdas, fixed, ConditionalWeakTable proxies, unrooted WeakReference registration, and chained .Class.Handle in tests) alongside explicit exclusions. * Review rules in .github/skills/code-review/references/interop-rules.md and testing-rules.md: add a JNI peer-lifetime review checklist with false-positive exclusions, flag chained temporary .Class.Handle in device tests, and instruct reviewers not to request flaky GC-timing / early-collection tests for GC.KeepAlive fixes. Validation: Documentation-only update under .github/; verified formatting with git diff --check and confirmed all referenced APIs against src/Java.Interop/ and src/Mono.Android/. No SDK build or tests run because no executable code changed. Co-authored-by: Copilot App <[email protected]>
There was a problem hiding this comment.
🟡 Changes recommended
The guidance treats migration to FinishCreateInstance as fixing receiver retention, but the helper still lacks GC.KeepAlive(self), potentially leading reviewers to accept an unsafe lifetime gap.
1 open issue
What changed in this PR
Documents JNI peer-lifetime rules for .NET for Android authoring and review, building on the audit in #13759 and related fixes. This is documentation-only; runtime behavior is unchanged.
Changes:
- Explain borrowed-handle risks and how to retain managed owners through native calls.
- Add a lifetime-review checklist with common hazards and false-positive exclusions.
- Guide device tests toward safe peer handling and deterministic validation rather than GC-timing assertions.
| File | Description |
|---|---|
.github/skills/code-review/references/testing-rules.md |
Adds temporary-peer safety and GC-timing test guidance. |
.github/skills/code-review/references/interop-rules.md |
Adds a JNI lifetime checklist and review exclusions. |
.github/instructions/java-interop.instructions.md |
Documents borrowed-reference and multi-call owner retention. |
.github/copilot-instructions.md |
Adds repository-wide lifetime rules, placement guidance, and common traps. |
Review effort: Balanced
…uidelines Address review feedback on #13766: JniPeerMembers.InstanceMethods.FinishCreateInstance does not yet retain self on main (pending #13758), so require explicit GC.KeepAlive (this) for handwritten JNIEnv.FinishCreateInstance calls rather than suggesting migration to JniPeerMembers as sufficient today. Co-authored-by: Copilot App <[email protected]>
|
/review |
|
✅ Android PR Reviewer completed successfully!
|
There was a problem hiding this comment.
🤖 Review — ⚠️ Needs Changes (CI completion outstanding)
Findings: 0 ❌ errors · 0
Reviewed all four complete changed files and cross-checked the lifetime claims against JavaMarshalGCBridge, the instance-method/field helpers, JavaConvert.WithLocalJniHandle, JniType, and the array-elements wrapper. The guidance correctly distinguishes borrowed handles from owned local references and receiver retention from argument retention. The updated constructor caveat accurately reflects the current implementation and the still-open #13758; the previously resolved feedback is addressed.
CI is not yet green: the GitHub check response contains 38 checks: 28 successful, 9 in progress, and the aggregate dotnet-android check queued; none report failure. These checks point to Azure build 1698850. Direct Azure build-result verification was blocked because az devops invoke requires authentication in this environment, so the final pipeline result remains unverified. The verdict reflects outstanding CI, not a requested blocking code change.
No SDK build or device tests were run for this documentation-only PR.
Generated by Android PR Reviewer for #13766 · copilot · gpt61 · 28.5 AIC · ⌖ 7.66 AIC · ⊞ 20.3K
Comment /review to run again
Address review feedback on #13766: - List generator expected-output assertions (such as tests/generator-Tests/Integration-Tests/NormalMethods.cs) alongside deterministic JniEnvironment.LocalReferenceCount leak checks and targeted functional tests. - Clarify under 'Bug fixes need regression tests' not to ask for redundant or non-deterministic GC-timing tests unless a deterministic test reliably catches a real regression. Co-authored-by: Copilot App <[email protected]>
Fold learnings from the #13759 PR reviews (#13758, #13761-#13766) into the JNI peer-lifetime instructions and review rules, and cut added word count by 45% (1,366 -> 750 words) without losing technical precision: - Cover terminal Release clearing (including Release(Commit)) and avoiding throwing calls between native acquisition (Get*ArrayElements) and wrapper construction. - Cover all reconciliation branches (including unregistered Keep peers), WeakReference IsAlive/Target split races, GC.KeepAlive placement before error checks/conversions, and // SAFETY: contract preservation + 180-col line limit. - Emphasize warmed-up JniEnvironment.LocalReferenceCount leak checks and generator expected-output assertions over non-deterministic GC-timing tests. Co-authored-by: Copilot App <[email protected]>
Remove one-off method, PR, and test-file specifics (Get*ArrayElements, Release(Commit), Synchronize, #13758, NormalMethods.cs, unregistered Keep peers, 180-col restatement) so the JNI peer-lifetime guidelines express durable, general principles while staying 41% shorter than before compression. Co-authored-by: Copilot App <[email protected]>
…cise pointers Keep the full JNI peer-lifetime (GC.KeepAlive) checklist in a single location (.github/skills/code-review/references/interop-rules.md) and shrink .github/copilot-instructions.md and .github/instructions/java-interop.instructions.md to short pointers (44 and 38 words respectively). Co-authored-by: Copilot App <[email protected]>
|
/review |
|
✅ Android PR Reviewer completed successfully!
|
There was a problem hiding this comment.
Review complete — no blocking findings;
The centralized checklist and short cross-links keep the guidance consistent without duplicating it. The gref replacement explanation agrees with JavaMarshalGCBridge.TakeWeakGlobalReference/TakeGlobalReference; receiver-retaining Invoke* helpers and WithLocalJniHandle were checked against their implementations. Explicit generator expected-output coverage is a useful deterministic alternative to GC-timing assertions. Both checklist links resolve to the new heading.
Reviewed the GitHub diff and all four complete files at 2e33f07a1d82e9137caa16027f5daeded3bf084f, rather than the locally modified instruction files. No SDK compilation or device tests were needed for these documentation-only changes.
CI: Of 7 current check runs, 2 succeeded (CLA and Android Tools Tests Mac), 4 are in progress, and 1 is queued; none currently reports failure. Azure build 1699122 is not yet confirmed green. The Azure CLI build-detail query required authentication, so independent Azure result/timeline verification was unavailable.
Generated by Android PR Reviewer for #13766 · copilot · gpt61 · 38.5 AIC · ⌖ 7.41 AIC · ⊞ 20.3K
Comment /review to run again
PeppersMuse
left a comment
There was a problem hiding this comment.
One gap from a previously addressed review thread — see the inline comment.
… checklist Address review feedback on #13766: - Note that single-read PeerReference + GC.KeepAlive protects against early GC collection, not concurrent Dispose () (which still requires synchronization or a caller contract). - Reflect that JniPeerMembers.InstanceMethods.FinishCreateInstance now retains self on main (merged in #13758, commit 71f0c51). Co-authored-by: Copilot App <[email protected]>

Context: #13759
Context: #12315
Context: #12754
An audit of
Java.Interop,Mono.Android, and device tests surfaced 37 missingGC.KeepAliveand peer-retention hazards (#13759). On CoreCLR and NativeAOT,JavaMarshalGCBridgedeletes and replaces the global reference of any managed-unreachable peer even when the Java object survives, so copying.Handleor.PeerReferencewithout retaining its managed owner can trigger ART CheckJNIuse of deleted global referenceaborts.Document concise JNI peer-lifetime rules without duplicating them across instruction files:
.github/skills/code-review/references/interop-rules.md: explains theJavaMarshalGCBridgegref-swap hazard, prefers owner-retaining APIs (JniPeerMembers.InstanceMethods.Invoke*,JniInstanceFields.*,ToLocalJniHandle), requiresGC.KeepAliveafter native calls on borrowed handles (straight-line vsfinally), single-readPeerReference, retaining and clearing peer owners in multi-call native wrappers, common traps (WithLocalJniHandle,fixed,ConditionalWeakTableproxies,WeakReferenceregistration/check-then-read races),// SAFETY:accuracy, and explicit false-positive exclusions..github/copilot-instructions.mdand.github/instructions/java-interop.instructions.mdlinking to the checklist..github/skills/code-review/references/testing-rules.md: avoid chaining temporary.Class.Handlein JNI tests, and avoid non-deterministic GC-timing /GC.Collect ()tests in favor of deterministic checks (codegen expected-output assertions,JniEnvironment.LocalReferenceCountleak checks, targeted functional tests) where they catch real regressions.Validation
.github/; verified whitespace withgit diff --check(0 issues) and cross-checked all referenced types, links, and anchors againstsrc/Java.Interop/andsrc/Mono.Android/.