“Closes by itself during contemplation”: Anatomy of Our First Production Bug (FFI SIGSEGV, mmap, GPU Contention, and On-Device AI)

How a 6-word Google Play review — with zero Dart errors in Crashlytics — exposed a native use-after-free in tflite_flutter, three Flutter RenderObject traps, and a GPU tug-of-war between Impeller Vulkan and Gemma 4.

Editorial cover for pwE's production Post-Mortem: FFI SIGSEGV, mmap, Impeller Vulkan, and Gemma 4
Forensic production investigation at pwE (Pray With Me) — from a Play Store review to Linux kernel paging and GPU shadersv1.0.73 → v1.0.77 · ADR 0084 & 0085

Prologue: Six words are worth a thousand green tests

There is an inevitable rite of passage in the life of every software product: the day your test suite with thousands of automated checks is 100% green, static analysis reports 0 issues, and a real user hits a physical combination of hardware, concurrency, and operating system that takes down your app.

At pwE (Pray With Me), that baptism arrived almost poetically. Just days after shutting down our old closed-testing tracks on Google Play — which until then had held public comments back as private "Testing feedback" — we received our first public store review (3 ★).

It came from a deeply engaged user, exactly 5 minutes after completing and saving her 8th entry in the Spiritual Journal, running on a Xiaomi POCO X6 Pro 5G with the newly released Android 16 (SDK 36). The report was just six words long:

"Closes by itself during contemplation."

We immediately opened Firebase Crashlytics filtered by that device model and timestamp window. The result sent a chill down our spines: zero FATAL Dart events for that device.

That launched the richest forensic investigation in the history of the project — a descent from Flutter's Sliver tree down into C++ pointers across dart:ffi, Linux kernel mmap paging, and shader contention between Impeller Vulkan and Gemma 4 OpenCL.

0 Fatal DartDart Crashlytics blind to C++ SIGSEGV
22.8 MB → mmapEliminated native heap calloc leak
Android 16SDK 36 · POCO X6 Pro & Galaxy A34
$0 · Zero-PIIBreadcrumbs over AES-256-GCM vault

Act I: The Crashlytics Blind Spot and the C++ Killer (SIGSEGV)

The first hard lesson of mobile observability is simple: the standard firebase_crashlytics Flutter SDK catches unhandled exceptions inside the Dart VM (FlutterError.onError and PlatformDispatcher.instance.onError). However, without the native C++ module (firebase-crashlytics-ndk) wired to native debug symbols, any SIGSEGV or SIGABRT triggered inside a C/C++ library through JNI or dart:ffi kills the Android process on the spot. To the user, the app simply "closes by itself"; in the Dart Crashlytics dashboard, absolute silence reigns (the signal only surfaces in raw Android Vitals diagnostics).

Without a stack trace from that device, we had to follow the exact architectural clock.

In pwE, prayerful reading follows 4 sequential steps: Lectio, Meditatio, Oratio, and Contemplatio. Why did the app survive the first three steps flawlessly and die precisely on the fourth?

Because in daily readings, steps 1, 2, and 3 consume precomputed content served from a static CDN. Yet at the exact millisecond of the Oratio → Contemplatio transition, the app wakes up OnDeviceEmbeddingService for the very first time — a local service that loads a 22.8 MB MiniLM model via tflite_flutter (dart:ffi over libtensorflowlite_jni.so) to search semantic memories on-device. Seconds later, upon saving the journal entry, the same engine is invoked again to vectorize the new record and finally calls dispose().

We went straight into the internal source code of tflite_flutter and TensorFlow Lite's C header c_api.h. We uncovered two native time bombs:

  1. 22.8 MB C-heap leak + lifecycle contract violation: Interpreter.fromAsset() delegates internally to Model.fromBuffer(), which copies all 22.8 MB of the model via calloc<Uint8> onto the native heap without ever calling calloc.free (a leak completely invisible to Dart's Memory Profiler!). Worse yet, Interpreter.fromBuffer calls TfLiteModelDelete immediately after creating the interpreter, violating the c_api.h contract requiring the backing buffer to stay intact for the entire lifetime of TfLiteInterpreter.
  2. FFI race condition (Use-After-Free): In Dart, chaining .timeout(Duration(seconds: 2)) onto a Future does not abort a synchronous/native C++ call already in flight. If the entry-time inference lagged in the background and collided with the post-save dispose() (TfLiteInterpreterDelete), the native thread accessed freed memory — triggering an instant SIGSEGV.
Participating layers
  • Contemplatio Transition
  • Post-Save Flow
  • OnDeviceEmbeddingService
  • libtensorflowlite_jni.so (C++)
BEFORE

Race Condition + 22.8 MB calloc

  1. Contemplatio Transition to OnDeviceEmbeddingService

    generateEmbedding() [Fetch Echoes]

  2. OnDeviceEmbeddingService to libtensorflowlite_jni.so (C++)

    runForMultipleInputs() in flight...

  3. Post-Save Flow to OnDeviceEmbeddingService

    generateEmbedding() + dispose()

  4. OnDeviceEmbeddingService to libtensorflowlite_jni.so (C++)

    TfLiteInterpreterDelete() 💥

  5. libtensorflowlite_jni.so (C++) to Contemplatio Transition

    SIGSEGV (Use-After-Free -> Instant process death)

AFTER

mmap + Serial Queue + Deferred Disposal

  1. Contemplatio Transition to OnDeviceEmbeddingService

    _inFlightOperations++ -> _runExclusively()

  2. OnDeviceEmbeddingService to libtensorflowlite_jni.so (C++)

    Interpreter.fromFile (OS Kernel mmap)

  3. Post-Save Flow to OnDeviceEmbeddingService

    dispose() while _inFlightOperations > 0

  4. Note onOnDeviceEmbeddingService

    Sets _pendingDispose = true (Does NOT destroy pointer!)

  5. libtensorflowlite_jni.so (C++) to OnDeviceEmbeddingService

    Inference completes safely

  6. OnDeviceEmbeddingService to libtensorflowlite_jni.so (C++)

    _inFlightOperations == 0 -> safe close() ✅

Sequence diagram comparing the original FFI race condition (use-after-free / SIGSEGV) against the serialized queue and deferred disposal backed by mmap.

The Definitive Fix: mmap Paging + Mutual Exclusion Queue

We completely replaced Interpreter.fromAsset() with one-time atomic materialization of the model into the app's private directory (validated via a .size marker) and opened it through Interpreter.fromFile() — letting the Android/iOS kernel memory-map the file via mmap without allocating 22.8 MB in calloc. On top of that, we hardened the lifecycle with a serial queue (_runExclusively) and deferred disposal (_pendingDispose):

dart
Future<Interpreter> _loadDefaultFileBackedInterpreter() async {
  final modelFile = await _ensureMaterializedModelFile();
  final options = InterpreterOptions()..threads = 2;
  try {
    // Kernel-backed mmap: zero copy into calloc<Uint8>
    return Interpreter.fromFile(modelFile, options: options);
  } finally {
    options.delete();
  }
}

void dispose() {
  // If an FFI call is in flight, defer native close() to the finally block
  if (_inFlightOperations > 0) {
    _pendingDispose = true;
    return;
  }
  _pendingDispose = false;
  _closeInterpreterNow();
}

Future<Either<Failure, List<double>>> generateEmbedding(String text) async {
  _inFlightOperations++;
  try {
    return await _runExclusively(() async {
      if (_pendingDispose) {
        _pendingDispose = false;
        _closeInterpreterNow();
      }
      await _initializeLocked();
      return _runInference(text);
    });
  } finally {
    _inFlightOperations--;
    if (_inFlightOperations == 0 && _pendingDispose) {
      _pendingDispose = false;
      _closeInterpreterNow();
    }
  }
}

Act II: When you pull one thread, pull them all (3 UI & Android 16 Traps)

A golden rule of serious post-mortems is to never stop at the first plausible root cause. We swept every correlated event along the immersive journey across other devices in our fleet and defused three more subtle Flutter ecosystem traps:

1. flutter_quill inside CustomScrollView ('targetChild should not be null')

On entry-level devices, we spotted 7 FATAL events in RenderEditableContainerBox.childAtPosition. The culprit: QuillEditor.basic enables an internal SingleChildScrollView by default (scrollable: true) and keeps showCursor: true even when unfocused. Inside an outer CustomScrollView during keyboard metric changes (didChangeMetrics), QuillRawEditorState._showCaretOnScreen tried to scroll the caret into view on an empty or off-screen block.

The fix was delegating 100% of scrolling to the parent CustomScrollView and tying the cursor strictly to the FocusNode:

dart
ListenableBuilder(
  listenable: focusNode,
  builder: (context, _) {
    return QuillEditor.basic(
      controller: controller,
      focusNode: focusNode,
      config: QuillEditorConfig(
        scrollable: false, // Eliminates nested SingleChildScrollView
        showCursor: focusNode.hasFocus, // _showCaretOnScreen becomes a no-op when unfocused
        placeholder: placeholder,
      ),
    );
  },
)

2. SliverOffstage vs. Offstage (RenderBox was not laid out)

To pre-mount upcoming hidden stages inside CustomScrollView, we had used SliverOffstage. The internal Flutter gotcha: whereas traditional RenderOffstage performs full child layout (while painting at visual height 0.0), RenderSliverOffstage skips child.layout altogether when offstage: true. Whenever an asynchronous SelectionArea microtask inspected the hidden editors, it hit a RenderBox with neither _size nor _constraints. Switching to a SliverToBoxAdapter wrapping a standard Offstage eliminated 100% of geometry StateErrors.

3. Android 16 (SDK 36) and Resizable Windows

On Android 16 (especially under HyperOS, large screens, and multi-window modes), imperative calls to SystemChrome.setPreferredOrientations(...) can be rejected by the window manager with an asynchronous PlatformException. Without a dedicated .catchError(...) in the orientation policy, that rejection bubbles straight up as an unhandled fatal error.


Act III: How do you debug a Zero-Knowledge screen?

How do you preserve forensic traceability if any anomaly ever resurfaces in Contemplatio, given that the Spiritual Journal is a privacy sanctuary encrypted locally on the device with AES-256-GCM?

We built a 100% Zero-Knowledge, Zero-PII breadcrumb recorder (CrashlyticsBreadcrumbRecorder). It records strictly state-machine milestones into Crashlytics' local ring-buffer — never touching a single character typed by the user and never firing Google Analytics events (keeping FinOps cost at $0.00):

dart
@override
Future<void> recordContemplationBreadcrumb({
  required String step,
  required String action,
  String? detail,
}) async {
  final sanitized = detail != null && detail.trim().isNotEmpty
      ? ' detail=${detail.trim()}'
      : '';
  // E.g.: [ContemplatioFlow] step=contemplatio action=rag_vectorize_started
  await _crashlytics?.log(
    '[ContemplatioFlow] step=$step action=$action$sanitized',
  );
  await _crashlytics?.setCustomKey('lectio_current_step', step);
  await _crashlytics?.setCustomKey('lectio_last_action', action);
}

Epilogue: The Two Ghosts of Physical QA (Impeller Vulkan × Gemma 4)

We cut the release candidate (v1.0.76) and ran full end-to-end validation in airplane mode on a physical Samsung Galaxy A34 (Exynos 1380 / Mali-G68 GPU / Android 16) powered by our local Gemma 4 E2B (LiteRT-LM) LLM.

Zero crashes! Yet when entering Contemplatio offline, we watched two bizarre phenomena happen live on screen:

  1. The reflection card grew smoothly in height (~480px) as streaming tokens arrived, yet remained completely blank, revealing the entire text all at once only at the end!
  2. At 25s, GPU inference timed out and chopped the final sentence in half.

And why was Gemma 4 blowing past 25s on GPU just to produce a single paragraph? Digging into litertlm-android:0.10.0 logs, we discovered that calling conv.sendMessageAsync(prompt) without extra context left Gemma 4's hidden reasoning channel (channels["thought"]) enabled by default, where chunk.toString() returns an empty ""! The model was burning nearly 20 seconds of GPU time "thinking silently" before emitting its very first visible word.

The Double Fix (v1.0.77)

On the Flutter side, we banned selectable: true inside MarkdownBody (keeping lightweight Text.rich / RenderParagraph at all times) and wrapped the block in a single stable SelectionArea only after streaming completes:

dart
final markdownBody = MarkdownBody(
  data: data,
  styleSheet: styleSheet,
  softLineBreak: true, // Always lightweight Text.rich, zero UniqueKey() at 25 FPS!
);

if (selectable && !isStreaming) {
  return SelectionContainer.maybeOf(context) != null
      ? markdownBody
      : SelectionArea(child: markdownBody);
}
return markdownBody;

And inside our Kotlin plugin (GemmaInferencePlugin.kt), we explicitly disabled the thinking channel for on-device inference and gated soft stops strictly on terminal punctuation (., !, ?):

kotlin
private val NON_THINKING_EXTRA_CONTEXT: Map<String, Any> =
    mapOf("enable_thinking" to false)

conv.sendMessageAsync(prompt, NON_THINKING_EXTRA_CONTEXT)
    .takeWhile { !reachedLimit }
    .collect { chunk ->
        val chunkText = chunk.toString()
        if (chunkText.isEmpty()) return@collect // Ignore residual hidden chunks
        // Emit the 1st visible token immediately and batch subsequent ones every 40ms...
    }

Immediate result on the Galaxy A34: TTFT plummeted, progressive 60 FPS text rendering became visible from millisecond one, and mid-sentence cutoffs vanished completely.


5 Trench Lessons to Keep

  1. "Zero crashes in the Dart dashboard" ≠ "Zero crashes in the app": If you ship dart:ffi or C++/JNI plugins, remember that a SIGSEGV kills the process without ever reaching FlutterError.onError.
  2. Distrust fromAsset / fromBuffer for large ML models: Materialize the model to private disk once and open it via fromFile (mmap), serializing all FFI calls through a mutual-exclusion queue with deferred disposal.
  3. In complex CustomScrollView trees, master your RenderObjects: Disable flutter_quill's implicit SingleChildScrollView (scrollable: false) and remember that SliverOffstage skips layout on hidden children.
  4. LLM streaming + SelectableText with UniqueKey do not mix under a saturated GPU: Render plain Text.rich while tokens arrive and enable SelectionArea once generation finishes.
  5. Privacy and Observability are not enemies: State-machine breadcrumbs deliver surgical diagnostic clarity without ever collecting a single byte of sensitive user content.

In the end, that 6-word store review turned out to be one of the greatest engineering gifts we could have received.

PRODUCTION ENGINEERING · EDGE AI
Explore pwE & Our Architecture Showcase

Try pwE live on the Google Play Store (177 countries) powered by On-Device Gemma 4, mmap-backed vector RAG, and AES-256-GCM encryption, or audit our open architectural documentation:

About the Author · JHH Solutions

Elvis Freitas Lopes Herllain

Software engineering and solutions architecture professional with 10+ years in mission-critical enterprise systems (SRE / L3 RCA) and, in parallel, an independent developer of original products under the JHH Solutions brand.