@app-swiss-knife/react-native-sdk 0.3.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,82 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@app-swiss-knife/react-native-sdk` are documented here.
4
+
5
+ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
6
+ this package follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+ While the major version is `0`, a minor bump may carry behavioral changes that a
8
+ `1.x` package would treat as breaking; each one is called out under **Changed**.
9
+
10
+ The native iOS and Android SDKs are not published separately — their sources are
11
+ vendored into this npm tarball at pack time, so a version here covers all three.
12
+
13
+ ## [0.4.0] - 2026-09-30
14
+
15
+ Crash reporting release. No API is removed or renamed, and upgrading from 0.3.2
16
+ requires no code changes — but several changes alter what lands in your error
17
+ dashboard, so read **Changed** before you compare week-over-week numbers.
18
+
19
+ ### Added
20
+
21
+ - **Custom issue grouping.** `SKCrashScope.setFingerprint(fingerprint: string[] | null)`
22
+ and a `fingerprint` field on `captureException`'s options let you override how
23
+ events collapse into issues. Sentry-compatible templates are supported —
24
+ `{{ default }}` expands to the computed grouping key and `{{ tags.<key> }}` to a
25
+ tag value, so `["{{ default }}", "{{ tags.tenant }}"]` splits one issue per
26
+ tenant. Omit it and grouping is unchanged.
27
+ - **`SKCrashScope` and `SKCaptureExceptionOptions` are now exported** from the
28
+ package root. `SKCrashScope` was previously an internal interface, so the object
29
+ handed to `configureScope()` could not be typed in user code; `captureException`'s
30
+ options parameter is now a named type instead of an inline literal.
31
+ - **Affected-user counts survive anonymous sessions.** When no user id is set, an
32
+ install id is sent so an issue still reports how many *installs* it hit instead
33
+ of collapsing to zero. The id comes from the Identity bridge's `anonymousId`,
34
+ falling back to a UUID persisted in AsyncStorage. With neither available nothing
35
+ is sent — a per-launch random id would inflate the count, so we prefer no number
36
+ to a wrong one.
37
+ - **Persisted session outbox** (`@swissknife:crash:sessions`, capped at 50).
38
+ Session `started`/`ended` beacons were fire-and-forget, so a 429 or a 5xx
39
+ silently corrupted the crash-free-rate denominator. They are now queued, ordered
40
+ so `started` precedes `ended`, retried honoring `Retry-After` (exponential
41
+ backoff otherwise), and survive an app relaunch.
42
+
43
+ ### Changed
44
+
45
+ Each of these reduces or redistributes event volume on purpose. Expect the
46
+ numbers to move once 0.4.0 rolls out; that is the fix working, not data loss.
47
+
48
+ - **iOS: one NSException crash reports once.** An uncaught NSException used to
49
+ surface as two events — the NSException report and the SIGABRT it raises. The
50
+ SIGABRT twin is now dropped, but only when the NSException report actually
51
+ decoded and its mtime is within 10s, so a genuine unrelated abort is still
52
+ reported.
53
+ - **iOS: ANR events no longer carry a fabricated stack.** The fallback path used
54
+ to attach the reporting thread's stack as if it were the hung main thread. An
55
+ ANR without a real watchdog capture now ships no `stacktrace` and sets
56
+ `extra.anr_stack = "unavailable"`.
57
+ - **iOS: in-app frame detection covers embedded binaries.** Frames from
58
+ `.debug.dylib` and embedded frameworks are now classified as in-app, so the
59
+ culprit line on a crash points at your code rather than at a system frame.
60
+ - **Android: one ANR reports once.** `AnrWatchdog` now latches — a single 30s hang
61
+ produced roughly six events and now produces one — and a system-reported
62
+ `REASON_ANR` is deduped against a watchdog hang that is still live.
63
+ - **Android: native frames group stably across installs.** The module path in a
64
+ native frame is reduced to its basename. Absolute paths embed an install- and
65
+ update-specific directory, which split one crash into a new issue on every app
66
+ update.
67
+ - **Android: ANR traces are parsed as ART dumps**, main thread (`tid=1`) only,
68
+ instead of being treated as a flat stack.
69
+ - **Ingest retries on 429.** The backend now enforces per-device rate limits and a
70
+ per-project quota; both iOS and Android honor the throttle and retry instead of
71
+ dropping the report.
72
+
73
+ ### Notes
74
+
75
+ - Server-side issue grouping moved to v3 (symbolicated-frame hashing and exception
76
+ chains). This is a backend change, already live — existing issues keep their
77
+ identity through ordered v1/v2 secondary keys. No SDK upgrade is required to get
78
+ it, and upgrading does not re-group anything.
79
+ - No new or changed dependencies; peer ranges (`react`, `react-native`,
80
+ `@react-native-async-storage/async-storage`) are untouched.
81
+
82
+ [0.4.0]: https://github.com/Remneys/swiss-knife/releases/tag/react-native-sdk-v0.4.0
@@ -42,7 +42,7 @@ internal object DeviceContextProvider {
42
42
  * eventually inject this via `BuildConfig`, but for now keep it in
43
43
  * source so we don't have to thread build settings through every test.
44
44
  */
45
- const val SDK_VERSION: String = "0.3.2"
45
+ const val SDK_VERSION: String = "0.4.0"
46
46
 
47
47
  private val cacheLock = Any()
48
48
 
@@ -25,6 +25,7 @@ import java.util.concurrent.CopyOnWriteArrayList
25
25
  import com.appswissknife.context.IDs
26
26
  import com.appswissknife.identity.Identity
27
27
  import java.util.concurrent.Executors
28
+ import java.util.concurrent.atomic.AtomicBoolean
28
29
 
29
30
  // MARK: - Supporting Types
30
31
 
@@ -183,37 +184,82 @@ internal class RingBuffer<T>(private val capacity: Int) {
183
184
 
184
185
  // MARK: - ANR Watchdog
185
186
 
187
+ /**
188
+ * Detects a blocked main thread by posting a ping and checking that it ran
189
+ * within [timeoutMs].
190
+ *
191
+ * **Latched:** one hang is reported exactly once. After a report the
192
+ * watchdog stops posting new pings and waits for the SAME ping to run; only
193
+ * once the main thread has responded does it re-arm. Before the latch, a
194
+ * 30-second hang produced six identical "Application Not Responding" events.
195
+ *
196
+ * [onRecover] fires when a reported hang ends (the main thread ran the
197
+ * ping), so the caller can drop state that only applies to a hang still in
198
+ * progress at process death.
199
+ *
200
+ * [postToMain] and [mainStack] are test seams; production uses the main
201
+ * Looper.
202
+ */
186
203
  internal class AnrWatchdog(
187
204
  private val timeoutMs: Long,
188
- private val onAnr: (String) -> Unit
205
+ postToMain: ((Runnable) -> Unit)? = null,
206
+ private val mainStack: () -> Array<StackTraceElement> = { Looper.getMainLooper().thread.stackTrace },
207
+ private val onRecover: () -> Unit = {},
208
+ private val onAnr: (Array<StackTraceElement>) -> Unit
189
209
  ) {
190
- private val executor = Executors.newSingleThreadExecutor()
191
- private val mainHandler = Handler(Looper.getMainLooper())
210
+ private val executor = Executors.newSingleThreadExecutor { r ->
211
+ Thread(r, "sk-anr-watchdog").apply { isDaemon = true }
212
+ }
213
+ private val post: (Runnable) -> Unit = postToMain ?: run {
214
+ val handler = Handler(Looper.getMainLooper())
215
+ val fn: (Runnable) -> Unit = { r -> handler.post(r) }
216
+ fn
217
+ }
192
218
  @Volatile private var active = false
193
219
 
194
220
  fun start() {
195
221
  active = true
196
222
  executor.execute {
197
- while (active) {
198
- var responded = false
199
- mainHandler.post { responded = true }
200
- Thread.sleep(timeoutMs)
201
- if (active && !responded) {
202
- // Main thread did not respond — capture its stack trace
203
- val mainThread = Looper.getMainLooper().thread
204
- val stackTrace = mainThread.stackTrace
205
- .joinToString("\n") { "\tat ${it.className}.${it.methodName}(${it.fileName}:${it.lineNumber})" }
206
- onAnr(stackTrace)
223
+ try {
224
+ while (active) {
225
+ val responded = AtomicBoolean(false)
226
+ post(Runnable { responded.set(true) })
227
+ Thread.sleep(timeoutMs)
228
+ if (!active) break
229
+ if (responded.get()) continue
230
+
231
+ // Main thread did not respond — report this hang once.
232
+ try {
233
+ onAnr(mainStack())
234
+ } catch (_: Throwable) { /* never kill the watchdog */ }
235
+
236
+ // Latch: wait for the same ping before re-arming.
237
+ val pollMs = minOf(timeoutMs, 500L).coerceAtLeast(1L)
238
+ while (active && !responded.get()) Thread.sleep(pollMs)
239
+ if (active) {
240
+ try {
241
+ onRecover()
242
+ } catch (_: Throwable) { /* never kill the watchdog */ }
243
+ }
207
244
  }
245
+ } catch (_: InterruptedException) {
246
+ // stop() — exit quietly
208
247
  }
209
248
  }
210
249
  }
211
250
 
212
251
  fun stop() {
213
252
  active = false
253
+ executor.shutdownNow()
214
254
  }
215
255
  }
216
256
 
257
+ /**
258
+ * A watchdog-reported ANR, persisted so the next launch can recognise the
259
+ * matching `ApplicationExitInfo.REASON_ANR` record as the same hang.
260
+ */
261
+ internal data class AnrMark(val pid: Int, val timestampMs: Long)
262
+
217
263
  // MARK: - Main SDK
218
264
 
219
265
  object SKCrashReporting {
@@ -375,15 +421,17 @@ object SKCrashReporting {
375
421
 
376
422
  // ANR watchdog
377
423
  anrWatchdog?.stop()
378
- anrWatchdog = AnrWatchdog(config.anrTimeoutMs) { stackTrace ->
379
- val event = buildEvent(SKErrorLevel.ERROR).apply {
380
- this.message = "Application Not Responding"
381
- this.mechanism = "anr_watchdog"
382
- // Parse the main thread's stack trace elements into structured frames
383
- val mainThread = Looper.getMainLooper().thread
384
- this.stacktrace = parseStackTraceElements(mainThread.stackTrace)
385
- }
386
- sendEvent(event)
424
+ val pid = android.os.Process.myPid()
425
+ anrWatchdog = AnrWatchdog(
426
+ config.anrTimeoutMs,
427
+ // The hang ended: the process was not killed for it, so a later
428
+ // system ANR in this process is a DIFFERENT hang (service start
429
+ // timeout, broadcast timeout, …) and must not be deduped.
430
+ // Same executor as the report, so clear always runs after record.
431
+ onRecover = { executor.execute { clearWatchdogAnrMarks(appCtx, pid) } },
432
+ ) { mainStack ->
433
+ val detectedAtMs = System.currentTimeMillis()
434
+ executor.execute { reportWatchdogAnr(appCtx, pid, detectedAtMs, mainStack) }
387
435
  }
388
436
  anrWatchdog?.start()
389
437
 
@@ -624,6 +672,35 @@ object SKCrashReporting {
624
672
  return chain
625
673
  }
626
674
 
675
+ /**
676
+ * Deliver a watchdog ANR durably, and only then persist the dedupe mark.
677
+ *
678
+ * The mark makes the next launch skip the system `REASON_ANR` record, so
679
+ * it must never outlive an event that was lost. The in-memory
680
+ * [pendingEvents] batch is not good enough: it flushes every 30 s and dies
681
+ * with the process, and the system kills an ANR'd process well within
682
+ * that. So the event goes through [sendEventPayload] (IngestClient's disk
683
+ * queue, or a direct POST) and the mark is written only on success. A
684
+ * kill between the two costs a duplicate report, never a lost one.
685
+ */
686
+ internal fun reportWatchdogAnr(
687
+ context: Context,
688
+ pid: Int,
689
+ detectedAtMs: Long,
690
+ mainStack: Array<StackTraceElement>,
691
+ ) {
692
+ val event = buildEvent(SKErrorLevel.ERROR).apply {
693
+ this.message = "Application Not Responding"
694
+ this.mechanism = "anr_watchdog"
695
+ // The stack captured at detection time, not re-read later
696
+ // (by then the main thread may have moved on).
697
+ this.stacktrace = parseStackTraceElements(mainStack)
698
+ }
699
+ if (sendEventPayload(event)) {
700
+ recordWatchdogAnr(context, pid, detectedAtMs)
701
+ }
702
+ }
703
+
627
704
  private fun sendEvent(event: SKErrorEvent) {
628
705
  executor.execute { enqueueEvent(event) }
629
706
  }
@@ -737,17 +814,21 @@ object SKCrashReporting {
737
814
  }
738
815
  }
739
816
 
740
- /** Legacy single-event send (used for crash flush, pending crash from prev session). */
741
- internal fun sendEventPayload(event: SKErrorEvent) {
742
- val cfg = config ?: return
817
+ /**
818
+ * Legacy single-event send (used for crash flush, pending crash from prev session).
819
+ *
820
+ * Returns true when the event is durable: persisted to IngestClient's
821
+ * on-disk queue, or accepted (2xx) by the server on the direct path.
822
+ */
823
+ internal fun sendEventPayload(event: SKErrorEvent): Boolean {
824
+ val cfg = config ?: return false
743
825
  // Round-C: prefer IngestClient when wired.
744
826
  val ingest = com.appswissknife.net.IngestClient.shared
745
827
  val ctx = appContext
746
828
  if (ingest != null && ctx != null) {
747
- ingest.enqueue(com.appswissknife.net.IngestItemType.Error, event.toJSON(), ctx)
748
- return
829
+ return ingest.enqueue(com.appswissknife.net.IngestItemType.Error, event.toJSON(), ctx)
749
830
  }
750
- try {
831
+ return try {
751
832
  val r = com.appswissknife.net.BackendHttpClient
752
833
  .create(cfg.apiKey, cfg.serverURL.ifEmpty { null })
753
834
  .simplePost(
@@ -757,8 +838,10 @@ object SKCrashReporting {
757
838
  if (r.code !in 200..299) {
758
839
  println("[SwissKnife CrashReporting] send failed: HTTP ${r.code}")
759
840
  }
841
+ r.code in 200..299
760
842
  } catch (e: Exception) {
761
843
  println("[SwissKnife CrashReporting] send error: ${e.message}")
844
+ false
762
845
  }
763
846
  }
764
847
 
@@ -768,11 +851,26 @@ object SKCrashReporting {
768
851
  val file = pendingCrashFile ?: return
769
852
  if (!file.exists()) return
770
853
 
854
+ val cfg = config ?: return
771
855
  val data = file.readBytes()
772
- // Delete before sending — best-effort delivery
773
- file.delete()
774
856
 
775
- val cfg = config ?: return
857
+ // Prefer the durable ingest queue: once enqueued, IngestClient owns
858
+ // delivery (and its 429 / 5xx backoff), so the file can go.
859
+ val ingest = com.appswissknife.net.IngestClient.shared
860
+ val ctx = appContext
861
+ if (ingest != null && ctx != null) {
862
+ val json = runCatching { JSONObject(String(data, Charsets.UTF_8)) }.getOrNull()
863
+ if (json == null) {
864
+ file.delete() // unreadable — retrying can never help
865
+ return
866
+ }
867
+ if (ingest.enqueue(com.appswissknife.net.IngestItemType.Error, json, ctx)) {
868
+ file.delete()
869
+ ingest.scheduleFlush(ctx)
870
+ }
871
+ return
872
+ }
873
+
776
874
  executor.execute {
777
875
  try {
778
876
  val r = com.appswissknife.net.BackendHttpClient
@@ -781,15 +879,26 @@ object SKCrashReporting {
781
879
  path = "/api/sdk/errors/event",
782
880
  body = String(data, Charsets.UTF_8),
783
881
  )
784
- if (r.code !in 200..299) {
785
- println("[SwissKnife CrashReporting] pending crash send failed: HTTP ${r.code}")
882
+ if (isRetryableStatus(r.code)) {
883
+ // Throttled (429) or server trouble: keep the file for
884
+ // the next launch instead of dropping the crash.
885
+ println("[SwissKnife CrashReporting] pending crash send deferred: HTTP ${r.code}")
886
+ } else {
887
+ if (r.code !in 200..299) {
888
+ println("[SwissKnife CrashReporting] pending crash rejected: HTTP ${r.code}")
889
+ }
890
+ file.delete()
786
891
  }
787
892
  } catch (e: Exception) {
893
+ // Network error — keep the file for the next launch.
788
894
  println("[SwissKnife CrashReporting] pending crash send error: ${e.message}")
789
895
  }
790
896
  }
791
897
  }
792
898
 
899
+ /** 429 and 5xx may succeed later; any other status is final. */
900
+ internal fun isRetryableStatus(code: Int): Boolean = code == 429 || code >= 500
901
+
793
902
  internal fun writeCrashToDisk(event: SKErrorEvent) {
794
903
  try {
795
904
  val file = pendingCrashFile ?: return
@@ -905,13 +1014,26 @@ object SKCrashReporting {
905
1014
  val exitInfos = am.getHistoricalProcessExitReasons(context.packageName, 0, 5)
906
1015
  val prefs = context.getSharedPreferences("sk_crash", Context.MODE_PRIVATE)
907
1016
  val lastReported = prefs.getLong("last_native_crash_ts", 0)
1017
+ val watchdogMarks = readWatchdogAnrMarks(context)
908
1018
 
909
- for (info in exitInfos) {
1019
+ // getHistoricalProcessExitReasons returns newest first. Walk
1020
+ // oldest → newest so the persisted high-water mark only ever
1021
+ // moves forward; newest-first left it at the OLDEST record,
1022
+ // and the newer ones were re-sent on the following launch.
1023
+ for (info in exitInfos.sortedBy { it.timestamp }) {
910
1024
  if (info.timestamp <= lastReported) continue
911
1025
  if (info.reason != ApplicationExitInfo.REASON_CRASH_NATIVE &&
912
1026
  info.reason != ApplicationExitInfo.REASON_ANR) continue
913
1027
 
914
1028
  val isNative = info.reason == ApplicationExitInfo.REASON_CRASH_NATIVE
1029
+
1030
+ // The in-process watchdog usually already reported this
1031
+ // hang (with a live main-thread stack). Don't send it twice.
1032
+ if (!isNative && isDuplicateOfWatchdogAnr(watchdogMarks, info.pid, info.timestamp)) {
1033
+ prefs.edit().putLong("last_native_crash_ts", info.timestamp).apply()
1034
+ continue
1035
+ }
1036
+
915
1037
  val traceText = try {
916
1038
  info.traceInputStream?.use { stream ->
917
1039
  stream.bufferedReader().readText()
@@ -922,7 +1044,9 @@ object SKCrashReporting {
922
1044
  exceptionType = if (isNative) "NativeCrash" else "ANR",
923
1045
  exceptionValue = info.description ?: if (isNative) "Native crash detected via ApplicationExitInfo" else "ANR detected via ApplicationExitInfo",
924
1046
  mechanism = if (isNative) "native_crash" else "anr_system",
925
- stacktrace = traceText?.let { parseNativeTrace(it) } ?: emptyList()
1047
+ stacktrace = traceText?.let {
1048
+ if (isNative) parseNativeTrace(it) else parseAnrThreadDump(it)
1049
+ } ?: emptyList()
926
1050
  )
927
1051
 
928
1052
  sendEventPayload(event)
@@ -935,21 +1059,117 @@ object SKCrashReporting {
935
1059
  }
936
1060
  }
937
1061
 
1062
+ // MARK: - Watchdog / system ANR dedupe
1063
+
1064
+ private const val ANR_MARKS_KEY = "anr_watchdog_marks"
1065
+ private const val MAX_ANR_MARKS = 8
1066
+
1067
+ /**
1068
+ * How far an `ApplicationExitInfo` ANR timestamp may sit from a watchdog
1069
+ * mark for the same pid and still count as the same hang. The exit record
1070
+ * is stamped when the process dies, which can be well after detection
1071
+ * (the user leaves the "App isn't responding" dialog up), so the window
1072
+ * is generous; the pid match is what makes it specific.
1073
+ */
1074
+ internal const val ANR_DEDUPE_BEFORE_MS = 60_000L
1075
+ internal const val ANR_DEDUPE_AFTER_MS = 30 * 60_000L
1076
+
1077
+ internal fun isDuplicateOfWatchdogAnr(marks: List<AnrMark>, pid: Int, exitTimestampMs: Long): Boolean =
1078
+ marks.any { m ->
1079
+ m.pid == pid &&
1080
+ exitTimestampMs >= m.timestampMs - ANR_DEDUPE_BEFORE_MS &&
1081
+ exitTimestampMs <= m.timestampMs + ANR_DEDUPE_AFTER_MS
1082
+ }
1083
+
1084
+ internal fun encodeAnrMarks(marks: List<AnrMark>): String =
1085
+ marks.joinToString(";") { "${it.pid}:${it.timestampMs}" }
1086
+
1087
+ internal fun decodeAnrMarks(raw: String?): List<AnrMark> =
1088
+ raw.orEmpty().split(';').mapNotNull { part ->
1089
+ val pid = part.substringBefore(':', "").toIntOrNull()
1090
+ val ts = part.substringAfter(':', "").toLongOrNull()
1091
+ if (pid != null && ts != null) AnrMark(pid, ts) else null
1092
+ }
1093
+
1094
+ /**
1095
+ * Watchdog-thread context. Uses `commit()` (synchronous) on purpose: the
1096
+ * system may kill the process moments after an ANR, and an `apply()`
1097
+ * that never reached disk would defeat the dedupe.
1098
+ */
1099
+ internal fun recordWatchdogAnr(context: Context, pid: Int, timestampMs: Long) {
1100
+ try {
1101
+ val prefs = context.getSharedPreferences("sk_crash", Context.MODE_PRIVATE)
1102
+ val marks = (decodeAnrMarks(prefs.getString(ANR_MARKS_KEY, null)) + AnrMark(pid, timestampMs))
1103
+ .takeLast(MAX_ANR_MARKS)
1104
+ prefs.edit().putString(ANR_MARKS_KEY, encodeAnrMarks(marks)).commit()
1105
+ } catch (_: Throwable) { /* best effort */ }
1106
+ }
1107
+
1108
+ /**
1109
+ * The main thread recovered from the hang the watchdog reported, so none
1110
+ * of this process's marks describe a hang in progress at death. Dropping
1111
+ * them keeps a later, unrelated system ANR in the same process (one the
1112
+ * main-thread ping cannot see) from being deduped away.
1113
+ */
1114
+ internal fun clearWatchdogAnrMarks(context: Context, pid: Int) {
1115
+ try {
1116
+ val prefs = context.getSharedPreferences("sk_crash", Context.MODE_PRIVATE)
1117
+ val marks = decodeAnrMarks(prefs.getString(ANR_MARKS_KEY, null))
1118
+ val kept = marks.filter { it.pid != pid }
1119
+ if (kept.size != marks.size) {
1120
+ prefs.edit().putString(ANR_MARKS_KEY, encodeAnrMarks(kept)).commit()
1121
+ }
1122
+ } catch (_: Throwable) { /* best effort */ }
1123
+ }
1124
+
1125
+ internal fun readWatchdogAnrMarks(context: Context): List<AnrMark> =
1126
+ try {
1127
+ decodeAnrMarks(
1128
+ context.getSharedPreferences("sk_crash", Context.MODE_PRIVATE).getString(ANR_MARKS_KEY, null)
1129
+ )
1130
+ } catch (_: Throwable) { emptyList() }
1131
+
1132
+ // MARK: - Trace parsing
1133
+
1134
+ private val NATIVE_FRAME = Regex("""^\s*(?:native:\s*)?#\d+\s+pc\s+([0-9a-fA-F]+)\s+(\S+)(.*)$""", RegexOption.MULTILINE)
1135
+ private val NATIVE_ANNOTATION = Regex("""\((?:offset 0x[0-9a-fA-F]+|BuildId: [0-9a-fA-F]+|deleted)\)""")
1136
+
1137
+ /**
1138
+ * Reduce a native module path to its stable basename.
1139
+ *
1140
+ * `/data/app/~~Xy==/com.app-Zq==/lib/arm64/libfoo.so` → `libfoo.so`, and
1141
+ * `…/base.apk!libhermes.so` → `libhermes.so`. The `/data/app/~~X==/`
1142
+ * directory is randomised per install and per update, so hashing the full
1143
+ * path split one native crash into a new issue for every install.
1144
+ * Bracketed pseudo-mappings (`[anon:…]`, `<anonymous:…>`) are kept as-is.
1145
+ */
1146
+ internal fun nativeModuleBasename(path: String): String {
1147
+ if (path.startsWith("[") || path.startsWith("<")) return path
1148
+ return path.substringAfterLast('/').substringAfterLast('!').ifEmpty { path }
1149
+ }
1150
+
938
1151
  /**
939
- * Parse Android tombstone / native trace format.
940
- * Each frame looks like: " #00 pc 0001a4e8 /system/lib/libc.so (abort+4)"
1152
+ * Parse Android tombstone / native trace format, one frame per line:
1153
+ * `#00 pc 0001a4e8 /system/lib/libc.so (abort+4) (BuildId: 1f2e…)`
1154
+ * `#05 pc 000a1b2c /data/app/~~X==/pkg-Y==/base.apk!libhermes.so (offset 0x1a000) (hermes::foo+44)`
1155
+ *
1156
+ * `module` is the basename (see [nativeModuleBasename]); `(offset …)`,
1157
+ * `(BuildId: …)` and `(deleted)` annotations are stripped so they can
1158
+ * never leak into `function`. In-app detection still uses the full path.
941
1159
  */
942
1160
  internal fun parseNativeTrace(tombstone: String): List<SKStackFrame> {
943
1161
  val frames = mutableListOf<SKStackFrame>()
944
- val regex = Regex("""#\d+\s+pc\s+([0-9a-f]+)\s+(\S+)(?:\s+\((.+)\))?""")
945
- for (match in regex.findAll(tombstone)) {
1162
+ for (match in NATIVE_FRAME.findAll(tombstone)) {
946
1163
  val address = match.groupValues[1]
947
1164
  val modulePath = match.groupValues[2]
948
- val funcName = match.groupValues[3].ifEmpty { null }
1165
+ val rest = NATIVE_ANNOTATION.replace(match.groupValues[3], "").trim()
1166
+ val funcName = if (rest.length > 2 && rest.startsWith("(") && rest.endsWith(")")) {
1167
+ rest.substring(1, rest.length - 1).trim().ifEmpty { null }
1168
+ } else null
949
1169
  frames.add(
950
1170
  SKStackFrame(
951
1171
  instructionAddress = "0x$address",
952
- module = modulePath,
1172
+ module = nativeModuleBasename(modulePath),
953
1173
  function = funcName,
954
1174
  inApp = !modulePath.startsWith("/system/") &&
955
1175
  !modulePath.startsWith("/apex/") &&
@@ -961,6 +1181,54 @@ object SKCrashReporting {
961
1181
  return frames
962
1182
  }
963
1183
 
1184
+ private val JAVA_DUMP_FRAME = Regex("""^\s*at\s+(\S+)\((.*)\)\s*$""")
1185
+
1186
+ /**
1187
+ * Extract the main thread's Java frames from an ANR trace
1188
+ * (`ApplicationExitInfo.REASON_ANR` gives a full ART thread dump, not a
1189
+ * tombstone). Running the tombstone parser over it mixed the native
1190
+ * frames of every thread in the process into one "stack".
1191
+ *
1192
+ * Finds the `"main" … tid=1` block, reads `at pkg.Class.method(File.kt:42)`
1193
+ * lines until the block ends, and maps them through the same
1194
+ * [parseStackTraceElements] used for JVM crashes so in-app rules match.
1195
+ * Falls back to the main block's `native: #NN pc …` frames when it has no
1196
+ * Java frames. Returns empty when there is no main-thread block.
1197
+ */
1198
+ internal fun parseAnrThreadDump(dump: String): List<SKStackFrame> {
1199
+ val lines = dump.lines()
1200
+ val start = lines.indexOfFirst { it.startsWith("\"main\"") && it.contains("tid=1") }
1201
+ .takeIf { it >= 0 }
1202
+ ?: lines.indexOfFirst { it.startsWith("\"main\"") }
1203
+ if (start < 0) return emptyList()
1204
+
1205
+ val block = mutableListOf<String>()
1206
+ for (i in start + 1 until lines.size) {
1207
+ val line = lines[i]
1208
+ if (line.isBlank() || line.startsWith("\"")) break
1209
+ block.add(line)
1210
+ }
1211
+
1212
+ val elements = block.mapNotNull { line ->
1213
+ val m = JAVA_DUMP_FRAME.matchEntire(line) ?: return@mapNotNull null
1214
+ val qualified = m.groupValues[1]
1215
+ val location = m.groupValues[2]
1216
+ val className = qualified.substringBeforeLast('.', "")
1217
+ val method = qualified.substringAfterLast('.')
1218
+ if (className.isEmpty()) return@mapNotNull null
1219
+ val (file, lineNo) = when {
1220
+ location == "Native method" -> null to -2
1221
+ location.contains(':') -> location.substringBeforeLast(':') to
1222
+ (location.substringAfterLast(':').toIntOrNull() ?: -1)
1223
+ location.isEmpty() || location == "Unknown Source" -> null to -1
1224
+ else -> location to -1
1225
+ }
1226
+ StackTraceElement(className, method, file, lineNo)
1227
+ }
1228
+ if (elements.isNotEmpty()) return parseStackTraceElements(elements.toTypedArray())
1229
+ return parseNativeTrace(block.joinToString("\n"))
1230
+ }
1231
+
964
1232
  // MARK: - Helpers
965
1233
 
966
1234
  /**
@@ -1029,6 +1297,12 @@ object SKCrashReporting {
1029
1297
  /** Test seam — events that have been enqueued but not yet flushed. */
1030
1298
  internal fun _pendingEventsForTesting(): List<SKErrorEvent> = pendingEvents.toList()
1031
1299
 
1300
+ /** Test seam — set config + context without the full [initialize] side effects. */
1301
+ internal fun _configureForTesting(cfg: Configuration, context: Context) {
1302
+ config = cfg
1303
+ appContext = context
1304
+ }
1305
+
1032
1306
  internal fun _resetForTesting() {
1033
1307
  config = null
1034
1308
  appContext = null
@@ -153,10 +153,15 @@ internal class BackendRejected(val code: Int, val serverMessage: String?) :
153
153
 
154
154
  /**
155
155
  * Thrown by [BackendHttpClient] after the retry budget is exhausted on
156
- * 5xx / network errors.
156
+ * 429 / 5xx / network errors. [retryAfterMillis] is the server's
157
+ * `Retry-After` on the last attempt, when it sent one.
157
158
  */
158
- internal class BackendUnavailable(val code: Int, val serverMessage: String?, cause: Throwable? = null) :
159
- IOException("backend unavailable ($code): ${serverMessage ?: ""}", cause)
159
+ internal class BackendUnavailable(
160
+ val code: Int,
161
+ val serverMessage: String?,
162
+ cause: Throwable? = null,
163
+ val retryAfterMillis: Long? = null,
164
+ ) : IOException("backend unavailable ($code): ${serverMessage ?: ""}", cause)
160
165
 
161
166
  /**
162
167
  * Thrown when the SDK hasn't been configured (apiKey empty).
@@ -425,7 +430,11 @@ internal class BackendHttpClient(
425
430
  attempt++
426
431
  continue
427
432
  }
428
- throw BackendUnavailable(code, extractMessage(r.body))
433
+ throw BackendUnavailable(
434
+ code,
435
+ extractMessage(r.body),
436
+ retryAfterMillis = r.retryAfterMillis,
437
+ )
429
438
  }
430
439
  // 4xx (other than 429) → terminal.
431
440
  throw BackendRejected(code, extractMessage(r.body))