Skip to content

[copilot] Add JNI peer lifetime (GC.KeepAlive) guidelines - #13766

Open
simonrozsival wants to merge 7 commits into
mainfrom
simonrozsival-gc-keepalive-guidelines
Open

simonrozsival wants to merge 7 commits into
mainfrom
simonrozsival-gc-keepalive-guidelines

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

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 ART CheckJNI use of deleted global reference aborts.

Document concise JNI peer-lifetime rules without duplicating them across instruction files:

  • Single detailed checklist in .github/skills/code-review/references/interop-rules.md: explains the JavaMarshalGCBridge gref-swap hazard, prefers owner-retaining APIs (JniPeerMembers.InstanceMethods.Invoke*, JniInstanceFields.*, ToLocalJniHandle), requires GC.KeepAlive after native calls on borrowed handles (straight-line vs finally), single-read PeerReference, retaining and clearing peer owners in multi-call native wrappers, common traps (WithLocalJniHandle, fixed, ConditionalWeakTable proxies, WeakReference registration/check-then-read races), // SAFETY: accuracy, and explicit false-positive exclusions.
  • Short pointers in .github/copilot-instructions.md and .github/instructions/java-interop.instructions.md linking to the checklist.
  • Test review rules in .github/skills/code-review/references/testing-rules.md: avoid chaining temporary .Class.Handle in JNI tests, and avoid non-deterministic GC-timing / GC.Collect () tests in favor of deterministic checks (codegen expected-output assertions, JniEnvironment.LocalReferenceCount leak checks, targeted functional tests) where they catch real regressions.

Validation

  • Documentation-only change under .github/; verified whitespace with git diff --check (0 issues) and cross-checked all referenced types, links, and anchors against src/Java.Interop/ and src/Mono.Android/.
  • No SDK build or unit/device tests were run because no executable code changed.

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]>
Copilot AI balanced review requested due to automatic review settings November 24, 2026 20:29

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 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]>
@simonrozsival

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Generated by Android PR Reviewer for #13766

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🤖 Review — ⚠️ Needs Changes (CI completion outstanding)

Findings: 0 ❌ errors · 0 ⚠️ warnings · 1 💡 non-blocking inline suggestion. No blocking documentation defects found.

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

simonrozsival and others added 4 commits November 25, 2026 13:05
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]>
@simonrozsival

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Generated by Android PR Reviewer for #13766

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review complete — no blocking findings; ⚠️ CI pending. Findings: 0 ❌ errors, 0 ⚠️ warnings, 1 💡 inline documentation suggestion.

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 PeppersMuse left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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]>
@simonrozsival simonrozsival changed the title [docs] Add JNI peer lifetime (GC.KeepAlive) guidelines [copilot] Add JNI peer lifetime (GC.KeepAlive) guidelines Nov 25, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants