Skip to content

fix(android): synchronize JNI initialization and declare greeting safety - #865

Merged
ErikBjare merged 1 commit into
ActivityWatch:masterfrom
TimeToBuildBob:fix/android-init-once-3a66
Nov 18, 2026
Merged

ErikBjare merged 1 commit into
ActivityWatch:masterfrom
TimeToBuildBob:fix/android-init-once-3a66

Conversation

@TimeToBuildBob

Copy link
Copy Markdown
Contributor

Summary

  • Replace Android JNI's unsynchronized static mut INITIALIZED flag with std::sync::Once. Concurrent callers wait until logger/panic-hook setup completes; repeat callers keep the Already initialized log and the per-call JNI workaround.
  • Use call_once_force so an initialization panic caught by the existing JNI guard does not permanently poison initialization: a later caller can retry as before.
  • Declare the raw-pointer rust_greeting API unsafe extern "C" with a safety contract. Keep the live JNI string guard explicit at its caller. This does not change the C symbol or ABI, and aw-android still calls greeting through RustInterface.sayHello.
  • Add a host regression harness to the Android CI job. It extracts the production initialization body and greeting function, stubbing Android/JVM/logger dependencies only. No new dependencies.

Reproduction

At current master eed49e6, a host harness running the exact JNI initializer body with 16 simultaneous callers entered the initialization block 16 times and installed the panic hook 16 times. The final regression harness also fails against that original source. android_logger::init_once has its own guard, but the raw bool and log_panics::init around it are not synchronized.

The regression covers one-time setup under concurrency, waiting for panic-hook installation before returning, repeat-call logging/JNI workaround, retry after a caught setup panic, and greeting allocation/reclamation for valid, empty and non-UTF-8 C strings. It is a host test, not an Android device runtime test; the real Android dependencies are checked separately.

Verification

  • python3 scripts/test-android-init.py — passes (original source fails).
  • bash scripts/test-compile-android-cwd.sh — passes.
  • cargo check --locked -p aw-server --lib --target aarch64-linux-android — passes with NDK 27.2/API 24 compiler, archiver and ranlib.
  • cargo clippy --workspace --locked -- -D warnings — passes.
  • cargo test --locked -p aw-server --lib — 108 passed, 1 ignored.
  • cargo fmt --all -- --check and Python Ruff check/format — pass.

No device runtime verification claimed. The optional module-wide unsafe-operation lint is deliberately omitted to keep this scoped to the two unsafe API defects.

…ing safety

Git-Session-Id: c3c8da94-dbad-484a-96d4-d196650f3287
@TimeToBuildBob

Copy link
Copy Markdown
Contributor Author

Review guide (auto-posted)

Structured warm-up for reviewers — what changed, what to run, where to look.

Key files

  • scripts/test-android-init.py (+162/-0, Δ162)
  • aw-server/src/android/mod.rs (+20/-11, Δ31)
  • .github/workflows/build.yml (+2/-0, Δ2)

Suggested verification

  • make typecheck

Known risks / watch points

  • No automatic high-risk tags; use file list + diff for judgment.

Suggested review focus

  • Confirm behavior matches the PR description acceptance criteria.
  • Skim the largest diffs first (listed above).
  • If CI is green, spot-check the highest-risk paths called out here.

Generated by scripts/github/pr-warmup-review-guide.py for #865.

@greptile-apps

greptile-apps Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; no actionable issues were found.

Summary

This PR makes Android startup safe for simultaneous callers and states the safety requirements for the greeting function.

  • Android startup calls wait for logging setup to finish.
  • The greeting API now requires a live, valid C string.

No actionable issues found. The host checks could not run here because rustc is unavailable.

Reviews (1) · Last reviewed commit: "fix(android): synchronize JNI logger ini..." · Reviewed by Greptile

@TimeToBuildBob

Copy link
Copy Markdown
Contributor Author

Greptile reviewed current head be40bf84743e at 5/5 with no actionable findings; there are no inline review threads or unanswered maintainer comments. Android, Linux, macOS, clippy and format checks passed. Windows and coverage are still running, so no code change or merge made; the remaining CI results are the next gate.

@codecov

codecov Bot commented Nov 18, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 85.92%. Comparing base (656f3c9) to head (be40bf8).
⚠️ Report is 245 commits behind head on master.

Additional details and impacted files
@@             Coverage Diff             @@
##           master     #865       +/-   ##
===========================================
+ Coverage   70.81%   85.92%   +15.11%     
===========================================
  Files          51       90       +39     
  Lines        2916    13105    +10189     
===========================================
+ Hits         2065    11261     +9196     
- Misses        851     1844      +993     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@TimeToBuildBob

Copy link
Copy Markdown
Contributor Author

CI-green and mergeable (Greptile 5/5) — waiting only on a maintainer click.

This PR is ready to merge, but the bot has pull-only access to this repo and can't self-merge — surfacing it here so it isn't lost. The monitoring loop will stop re-flagging it now that this note is posted.

@TimeToBuildBob

TimeToBuildBob commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 AI code review

Replaces the unsynchronized static mut INITIALIZED flag in the Android JNI initializer with a std::sync::Once (using call_once_force for retry after a caught panic), marks rust_greeting as unsafe extern "C" and keeps the JNI string guard alive at its call site, and adds a host-side regression harness (scripts/test-android-init.py) plus a CI step to exercise the extracted initialization body and greeting function without a JVM.

Safe to merge — no P0/P1 findings

Confidence 5/5

✅ No thread-worthy findings. Advisory notes follow; they are retained without opening review threads.

2 advisory findings (summary-only, not scored)

These P2 guard, heuristic, trade-off, or documentation claims are retained for judgment without opening review threads.

⚠️ P2 medium — aw-server/src/android/mod.rs

This is a fix(...) PR but no test files are included in the diff. Erik's feedback: 'where is the repro & fixes they are supposed to catch' (gptme#3441), 'that measurement should come with a regression test' (gptme#3446). Add a test that would have caught this bug. (Advisory: Erik merged all such PRs but consistently requested tests.)

Add a test file that reproduces the bug before the fix and passes after it.

How this was verified: static preflight: fix-commit + touched-files scan (rule 7)

⚠️ P2 medium — aw-server/src/android/mod.rs:21

The unsafe contract added to rust_greeting says to must point to a NUL-terminated C string, and its sole in-repo caller at line 97 now preserves the JNI pattern guard — good. But the function is still exported as a #[no_mangle] C symbol, and aw-android is the real consumer: nothing in this diff verifies the JNI GetStringUTFChars-backed buffer is actually NUL-terminated under Android's modified-UTF-8 encoding. A Java string containing an embedded NUL is encoded by JNI as 0xC0 0x80 (two bytes), so a literal 0xC0 0x80 sequence in the buffer is not a terminator under CStr::from_ptr, but a string that contains a lone 0xC0 byte followed by a non-continuation byte is invalid modified UTF-8; whether the returned buffer is still NUL-terminated in that case is an upstream JNI contract this code does not pin. Since the new safety comment makes this the documented precondition, and the greeting harness validates only non-UTF-8 byte 0xFF (not JNI's actual encoding), the documented contract is not enforced by any test.

pub unsafe extern "C" fn rust_greeting(to: *const c_char) -> *mut c_char {

How this was verified: Compared the safety comment (lines 15-19) against the only in-repo caller (lines 93-97) and the greeting harness inputs (script lines 142-149, which use raw bytes, not JNI modified UTF-8). No code path in the diff validates JNI's NUL-termination guarantee.

Consensus: 2/3 passes agreed — pass 1 looked and disagreed
Distinct keys: 1 (general)

Files changed (3) — the diff as I read it
  • .github/workflows/build.yml — Adds a 'Test concurrent JNI initialization' step running python3 ./scripts/test-android-init.py in the build-android job.
  • aw-server/src/android/mod.rs — Switches initialization from a static mut bool to a Once, uses call_once_force, and marks rust_greeting unsafe with an explicit safety contract.
  • scripts/test-android-init.py — Adds a host harness that extracts the real initialize and rust_greeting bodies, stubs JNI/logger dependencies, and checks concurrency, retry, and greeting allocation.

Reviewed be40bf84743e · openrouter/deepseek/deepseek-v4-flash-0731 · llm engine · 107s · about this reviewer

Maintainer commands

@TimeToBuildBob review (own line) — fresh review · @TimeToBuildBob fix — a worker acts on the findings. Once per comment; 👀 = received.

@ErikBjare
ErikBjare merged commit 6fd2902 into ActivityWatch:master Nov 18, 2026
8 checks passed
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.

2 participants