Skip to content
TypeScript

perf(mobile): skip obsolete queued full token decodes (#25320)

Alex Southwell391b56af7d98
diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt
index 801f1c1ee64..af3ff74297d 100644
--- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt
+++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt
@@ -47,7 +47,8 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
private var contentResetKey = ""
@Volatile private var rowsDecodeGeneration = 0
- private var tokensDecodeGeneration = 0
+
+ @Volatile private var tokensDecodeGeneration = 0
private val payloadDecodeExecutor = Executors.newSingleThreadExecutor()
private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop
private val minimumFlingVelocity = ViewConfiguration.get(context).scaledMinimumFlingVelocity
@@ -203,6 +204,11 @@ class T3ReviewDiffView(context: Context, appContext: AppContext) : ExpoView(cont
tokensDecodeGeneration += 1
val generation = tokensDecodeGeneration
payloadDecodeExecutor.execute {
+ if (generation != tokensDecodeGeneration ||
+ Thread.currentThread().isInterrupted
+ ) {
+ return@execute
+ }
val decodedTokens = parseTokensObject(value)
post {
if (generation != tokensDecodeGeneration) return@post
diff --git a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift
index 6f9be4c5d7d..b799b7ad799 100644
--- a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift
+++ b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift
@@ -342,6 +342,7 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
private var rowsDecodeGeneration = 0
private var rowsDecodeCancellation: ReviewDiffRowPreparation?
private var tokensDecodeGeneration = 0
+ private var tokensDecodeCancellation: ReviewDiffRowPreparation?
let onDebug = EventDispatcher()
let onVisibleFileChange = EventDispatcher()
@@ -390,6 +391,7 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
deinit {
rowsDecodeCancellation?.cancel()
+ tokensDecodeCancellation?.cancel()
}
public override func layoutSubviews() {
@@ -485,10 +487,15 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
}
func setTokensJson(_ tokensJson: String) {
+ tokensDecodeCancellation?.cancel()
+ let cancellation = ReviewDiffRowPreparation()
+ tokensDecodeCancellation = cancellation
tokensDecodeGeneration += 1
let generation = tokensDecodeGeneration
payloadDecodeQueue.async { [weak self] in
+ // Entered decoding may finish; only skip full payloads already obsolete in the queue.
+ guard !cancellation.isCancelled, self != nil else { return }
guard let data = tokensJson.data(using: .utf8) else {
return
}
@@ -615,6 +622,7 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
rowsDecodeCancellation = nil
rowsDecodeGeneration += 1
tokensDecodeGeneration += 1
+ tokensDecodeCancellation?.cancel()
contentView.tokensByRowId = [:]
rows = []
contentView.rows = []
diff --git a/apps/mobile/modules/t3-review-diff/tests/android/build.gradle b/apps/mobile/modules/t3-review-diff/tests/android/build.gradle
index fa067950ed0..5a5565e8bf5 100644
--- a/apps/mobile/modules/t3-review-diff/tests/android/build.gradle
+++ b/apps/mobile/modules/t3-review-diff/tests/android/build.gradle
@@ -44,18 +44,39 @@ tasks.register('extractAndroidTestJars') {
}
def moduleRoot = file('../..')
+// Count decoder entry without replacing the production executor, parser, or lifecycle.
+def instrumentedView = layout.buildDirectory.file('token-fixture/T3ReviewDiffView.kt')
+tasks.register('instrumentTokenFixture') {
+ def original = file("${moduleRoot}/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt")
+ inputs.file original
+ outputs.file instrumentedView
+ doLast {
+ def source = original.text
+ def decode = ' val decodedTokens = parseTokensObject(value)'
+ def publish = ' canvasView.tokensByRowId = decodedTokens'
+ assert source.count(decode) == 1
+ assert source.count(publish) == 1
+ source = source.replace(decode, ' TokenDecodeProbe.enter()\n' + decode)
+ source = source.replace(publish, publish + '\n TokenDecodeProbe.publish()')
+ def destination = instrumentedView.get().asFile
+ destination.parentFile.mkdirs()
+ destination.text = source
+ }
+}
+
def sources = files(
+ instrumentedView,
fileTree('stubs') { include '**/*.kt' },
fileTree('src/test/kotlin') { include '**/*.kt' },
fileTree("${moduleRoot}/android/src/test/java") { include '**/*.kt' },
fileTree("${moduleRoot}/android/src/main/java/expo/modules/t3reviewdiff") {
include '**/*.kt'
- exclude '**/T3ReviewDiffModule.kt'
+ exclude '**/T3ReviewDiffModule.kt', '**/T3ReviewDiffView.kt'
},
)
tasks.register('compileRegression', JavaExec) {
- dependsOn 'extractAndroidTestJars'
+ dependsOn 'extractAndroidTestJars', 'instrumentTokenFixture'
classpath = configurations.compiler
mainClass = 'org.jetbrains.kotlin.cli.jvm.K2JVMCompiler'
inputs.files sources, configurations.testCompileClasspath
diff --git a/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffTokenDecodeTest.kt b/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffTokenDecodeTest.kt
new file mode 100644
index 00000000000..c058e9b8845
--- /dev/null
+++ b/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffTokenDecodeTest.kt
@@ -0,0 +1,293 @@
+package expo.modules.t3reviewdiff
+
+import android.app.Activity
+import android.graphics.Color
+import android.os.Looper
+import expo.modules.kotlin.AppContext
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.ExecutorService
+import java.util.concurrent.Semaphore
+import java.util.concurrent.atomic.AtomicInteger
+import java.util.concurrent.atomic.AtomicReference
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.Robolectric
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.Shadows.shadowOf
+import org.robolectric.annotation.Config
+import org.robolectric.annotation.LooperMode
+
+internal object TokenDecodeProbe {
+ val entries = AtomicInteger()
+ val publications = AtomicInteger()
+
+ @Volatile var onEntry: ((Int) -> Unit)? = null
+
+ fun reset() {
+ entries.set(0)
+ publications.set(0)
+ onEntry = null
+ }
+
+ fun enter() {
+ val entry = entries.incrementAndGet()
+ onEntry?.invoke(entry)
+ }
+ fun publish() {
+ publications.incrementAndGet()
+ }
+}
+
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [35], manifest = Config.NONE)
+@LooperMode(LooperMode.Mode.PAUSED)
+class ReviewDiffTokenDecodeTest {
+ @Test
+ fun queuedFullReplacementSkipsOnlyObsoleteWorkAndPreservesPatchOrdering() {
+ for (case in queuedCases()) {
+ fixture { view, executor ->
+ TokenDecodeProbe.reset()
+ view.setContentResetKey("content")
+ view.setTokensResetKey("tokens")
+ view.setTokensJson(payload("seed"))
+ drain(executor)
+ TokenDecodeProbe.reset()
+ val entered = CountDownLatch(1)
+ val release = Semaphore(0)
+ executor.execute {
+ entered.countDown()
+ release.acquire()
+ }
+ entered.await()
+ val acknowledgements = mutableListOf<Boolean>()
+ try {
+ case.enqueue(view) { id, chunk ->
+ view.setTokensPatchJson(patchPayload(id, chunk)) { acknowledgements.add(it) }
+ }
+ } finally {
+ release.release()
+ }
+ drain(executor)
+ assertEquals("${case.name} decoder entry", case.entries, TokenDecodeProbe.entries.get())
+ // Android's malformed full payload publishes its existing empty-map fallback.
+ assertEquals(
+ "${case.name} retained full publication",
+ case.entries,
+ TokenDecodeProbe.publications.get()
+ )
+ assertEquals("${case.name} token output", expected(case.ids), tokens(view))
+ assertEquals("${case.name} patch acknowledgements", case.acks, acknowledgements)
+ println(
+ "Passed tokens: ${case.name}, decoder entries=${case.entries}, " +
+ "retained full publications=${case.entries}"
+ )
+ }
+ }
+ }
+
+ private data class QueuedCase(
+ val name: String,
+ val ids: List<String> = listOf("b"),
+ val entries: Int = 1,
+ val acks: List<Boolean> = emptyList(),
+ val enqueue: (T3ReviewDiffView, (String, Int) -> Unit) -> Unit
+ )
+
+ private fun queuedCases() = listOf(
+ QueuedCase("A B C burst", ids = listOf("c")) { view, _ ->
+ listOf("a", "b", "c").forEach { view.setTokensJson(payload(it)) }
+ },
+ QueuedCase("content reset", ids = emptyList(), entries = 0) { view, _ ->
+ view.setTokensJson(payload("a"))
+ view.setContentResetKey("new")
+ },
+ QueuedCase("reset then B") { view, _ ->
+ view.setTokensJson(payload("a"))
+ view.setContentResetKey("new")
+ view.setTokensJson(payload("b"))
+ },
+ QueuedCase("same content key") { view, _ ->
+ view.setTokensJson(payload("b"))
+ view.setContentResetKey("content")
+ },
+ QueuedCase("token reset preserves full") { view, _ ->
+ view.setTokensJson(payload("b"))
+ view.setTokensResetKey("new")
+ },
+ QueuedCase("same token key") { view, _ ->
+ view.setTokensJson(payload("b"))
+ view.setTokensResetKey("tokens")
+ },
+ QueuedCase("current full") { view, _ -> view.setTokensJson(payload("b")) },
+ QueuedCase("current malformed", ids = emptyList()) { view, _ ->
+ view.setTokensJson("invalid JSON")
+ },
+ QueuedCase("obsolete malformed") { view, _ ->
+ view.setTokensJson("invalid JSON")
+ view.setTokensJson(payload("b"))
+ },
+ QueuedCase("full patch full", acks = listOf(true)) { view, patch ->
+ view.setTokensJson(payload("a"))
+ patch("patch", 0)
+ view.setTokensJson(payload("b"))
+ },
+ QueuedCase(
+ "full then patches",
+ ids = listOf("b", "one", "two"),
+ acks = listOf(true, true)
+ ) { view, patch ->
+ view.setTokensJson(payload("b"))
+ patch("one", 0)
+ patch("two", 1)
+ },
+ QueuedCase("patches then full", acks = listOf(true, true)) { view, patch ->
+ patch("one", 0)
+ patch("two", 1)
+ view.setTokensJson(payload("b"))
+ },
+ QueuedCase(
+ "additive patches",
+ ids = listOf("seed", "one", "two"),
+ entries = 0,
+ acks = listOf(true, true)
+ ) { _, patch ->
+ patch("one", 0)
+ patch("two", 1)
+ },
+ QueuedCase("reset rejects old patch", acks = listOf(false)) { view, patch ->
+ patch("old", 0)
+ view.setContentResetKey("new")
+ view.setTokensJson(payload("b"))
+ },
+ )
+
+ @Test
+ fun enteredFullSuccessAndErrorFinishButOnlyTheReplacementPublishes() {
+ for (invalid in listOf(false, true)) {
+ fixture { view, executor ->
+ TokenDecodeProbe.reset()
+ val entered = CountDownLatch(1)
+ val release = Semaphore(0)
+ TokenDecodeProbe.onEntry = { entry ->
+ if (entry == 1) {
+ entered.countDown()
+ release.acquire()
+ }
+ }
+ view.setTokensJson(if (invalid) "invalid JSON" else payload("a"))
+ entered.await()
+ try {
+ view.setContentResetKey("new")
+ view.setTokensJson(payload("b"))
+ } finally {
+ release.release()
+ }
+ drain(executor)
+ assertEquals(2, TokenDecodeProbe.entries.get())
+ assertEquals(1, TokenDecodeProbe.publications.get())
+ assertEquals(expected(listOf("b")), tokens(view))
+ println(
+ "Passed entered tokens invalid=$invalid, decoder entries=2, retained full publications=1"
+ )
+ }
+ }
+ }
+
+ @Test
+ fun cleanupDiscardsQueuedFullWorkOnTheProductionExecutor() {
+ fixture { view, executor ->
+ TokenDecodeProbe.reset()
+ val entered = CountDownLatch(1)
+ val worker = AtomicReference<Thread>()
+ val release = Semaphore(0)
+ executor.execute {
+ worker.set(Thread.currentThread())
+ entered.countDown()
+ try {
+ release.acquire()
+ } catch (
+ _: InterruptedException
+ ) {
+ Thread.currentThread().interrupt()
+ }
+ }
+ entered.await()
+ view.setTokensJson(payload("discarded"))
+ view.cleanup()
+ worker.get().join()
+ shadowOf(Looper.getMainLooper()).idle()
+ assertEquals(0, TokenDecodeProbe.entries.get())
+ assertEquals(0, TokenDecodeProbe.publications.get())
+ assertTrue(tokens(view).isEmpty())
+ println("Passed cleanup before entry, decoder entries=0, retained full publications=0")
+ }
+ }
+
+ @Test
+ fun cleanupAfterEntryKeepsTheExistingCurrentFullPublication() {
+ fixture { view, _ ->
+ TokenDecodeProbe.reset()
+ val entered = CountDownLatch(1)
+ val release = Semaphore(0)
+ val worker = AtomicReference<Thread>()
+ TokenDecodeProbe.onEntry = {
+ worker.set(Thread.currentThread())
+ entered.countDown()
+ // shutdownNow interrupts this worker; entered decoding must still finish.
+ release.acquireUninterruptibly()
+ }
+ view.setTokensJson(payload("entered"))
+ entered.await()
+ try {
+ view.cleanup()
+ } finally {
+ release.release()
+ }
+ worker.get().join()
+ shadowOf(Looper.getMainLooper()).idle()
+ assertEquals(1, TokenDecodeProbe.entries.get())
+ assertEquals(1, TokenDecodeProbe.publications.get())
+ assertEquals(expected(listOf("entered")), tokens(view))
+ println("Passed cleanup after entry, decoder entries=1, retained full publications=1")
+ }
+ }
+
+ private fun fixture(run: (T3ReviewDiffView, ExecutorService) -> Unit) {
+ val controller = Robolectric.buildActivity(Activity::class.java).setup()
+ val view = T3ReviewDiffView(controller.get(), AppContext())
+ controller.get().setContentView(view)
+ val executor = field(view, "payloadDecodeExecutor") as ExecutorService
+ try {
+ run(view, executor)
+ } finally {
+ view.cleanup()
+ TokenDecodeProbe.reset()
+ controller.pause().stop().destroy()
+ }
+ }
+
+ private fun drain(executor: ExecutorService) {
+ executor.submit {}.get()
+ shadowOf(Looper.getMainLooper()).idle()
+ }
+
+ private fun field(target: Any, name: String): Any = target.javaClass.getDeclaredField(name)
+ .apply { isAccessible = true }.get(target)
+
+ private fun tokens(view: T3ReviewDiffView) = field(
+ view.getChildAt(0),
+ "tokensByRowId"
+ ) as Map<*, *>
+
+ private fun expected(ids: List<String>) = ids.associateWith {
+ listOf(DiffToken("漢字 👨‍👩‍👧‍👦 é", Color.RED, 3), DiffToken("tail", null, 0))
+ }
+
+ private fun payload(id: String) =
+ """{"$id":[{"content":"漢字 👨‍👩‍👧‍👦 é","color":"#ff0000","fontStyle":3},{"content":"tail","fontStyle":0}]}"""
+
+ private fun patchPayload(id: String, chunk: Int) =
+ """{"resetKey":"tokens","chunkIndex":$chunk,"tokensByRowId":${payload(id)}}"""
+}
diff --git a/apps/mobile/modules/t3-review-diff/tests/ios/row-decode.swift b/apps/mobile/modules/t3-review-diff/tests/ios/row-decode.swift
index 30dc9924a2e..cad93d5b8b2 100644
--- a/apps/mobile/modules/t3-review-diff/tests/ios/row-decode.swift
+++ b/apps/mobile/modules/t3-review-diff/tests/ios/row-decode.swift
@@ -252,7 +252,7 @@ private extension T3ReviewDiffView {
check(acknowledgements == [true, true], "Every additive token patch must be acknowledged")
check(Set(view.contentView.tokensByRowId.keys) == Set(["one", "two"]), "Token patches must never coalesce")
print("Passed additive token patches and acknowledgements; all 12 row/payload lifecycle cases passed")
- exit(0)
+ T3ReviewDiffView.runQueuedTokenDecodeCase(0)
}
}
}
diff --git a/apps/mobile/modules/t3-review-diff/tests/ios/token-decode.swift b/apps/mobile/modules/t3-review-diff/tests/ios/token-decode.swift
new file mode 100644
index 00000000000..140e99326ab
--- /dev/null
+++ b/apps/mobile/modules/t3-review-diff/tests/ios/token-decode.swift
@@ -0,0 +1,222 @@
+// Instrument decoder entry and accepted publication in the real serial queue.
+private final class TokenDecodeProbe {
+ private let lock = NSLock()
+ private var entries = 0
+ private var publications = 0
+ private var onEntry: ((Int) -> Void)?
+
+ func reset(onEntry: ((Int) -> Void)? = nil) {
+ lock.lock()
+ entries = 0
+ publications = 0
+ self.onEntry = onEntry
+ lock.unlock()
+ }
+
+ func enter() {
+ lock.lock()
+ entries += 1
+ let entry = entries
+ let callback = onEntry
+ lock.unlock()
+ callback?(entry)
+ }
+
+ func publish() {
+ lock.lock()
+ publications += 1
+ lock.unlock()
+ }
+
+ func checkCounts(_ expectedEntries: Int, _ expectedPublications: Int, _ name: String) {
+ lock.lock()
+ defer { lock.unlock() }
+ check(entries == expectedEntries,
+ "\(name): expected \(expectedEntries) token decoder entries, got \(entries)")
+ check(publications == expectedPublications,
+ "\(name): expected \(expectedPublications) retained full publications, got \(publications)")
+ print("Passed tokens: \(name), decoder entries=\(entries), retained full publications=\(publications)")
+ }
+}
+
+private let tokenDecodeProbe = TokenDecodeProbe()
+
+private func decodeTokensForTest(
+ _ type: [String: [ReviewDiffNativeToken]].Type, from data: Data
+) throws -> [String: [ReviewDiffNativeToken]] {
+ tokenDecodeProbe.enter()
+ return try JSONDecoder().decode(type, from: data)
+}
+
+private func tokenPayload(_ id: String) -> String {
+ "{\"\(id)\":[{\"content\":\"漢字 👨‍👩‍👧‍👦 é\",\"color\":\"#ff0000\",\"fontStyle\":3},{\"content\":\"tail\",\"fontStyle\":0}]}"
+}
+
+private func tokenPatch(_ id: String, key: String = "tokens", chunk: Int = 0) -> String {
+ "{\"resetKey\":\"\(key)\",\"chunkIndex\":\(chunk),\"tokensByRowId\":\(tokenPayload(id))}"
+}
+
+private extension T3ReviewDiffView {
+ static func afterTokens(on queue: DispatchQueue, _ completion: @escaping () -> Void) {
+ queue.async { DispatchQueue.main.async(execute: completion) }
+ }
+
+ func checkTokens(_ payloads: [String]) {
+ var expected: [String: [ReviewDiffNativeToken]] = [:]
+ for payload in payloads {
+ let decoded = try! JSONDecoder().decode([String: [ReviewDiffNativeToken]].self, from: Data(payload.utf8))
+ expected.merge(decoded) { _, next in next }
+ }
+ let describe = { (value: [String: [ReviewDiffNativeToken]]) in
+ value.mapValues { $0.map { String(reflecting: $0) } }
+ }
+ check(describe(contentView.tokensByRowId) == describe(expected), "Token fields/output order changed")
+ }
+
+ static func runQueuedTokenDecodeCase(_ index: Int) {
+ let names = ["A B C burst", "content reset", "reset then B", "same content key",
+ "token reset preserves full", "same token key", "current full", "current malformed",
+ "obsolete malformed", "full patch full", "full then patches", "patches then full",
+ "additive patches", "reset rejects old patch"]
+ guard index < names.count else { runReleasedTokenDecodeCase(); return }
+ tokenDecodeProbe.reset()
+ let view = T3ReviewDiffView()
+ view.setContentResetKey("content")
+ view.setTokensResetKey("tokens")
+ var errors: [String] = []
+ view.onDebug.onEvent = { payload in
+ if payload["message"] as? String == "tokens-decode-failed" {
+ errors.append(payload["error"] as! String)
+ }
+ }
+ view.contentView.tokensByRowId = try! JSONDecoder().decode(
+ [String: [ReviewDiffNativeToken]].self, from: Data(tokenPayload("seed").utf8)
+ )
+ var acknowledgements: [Bool] = []
+ let patch = { (id: String, chunk: Int) in
+ view.setTokensPatchJson(tokenPatch(id, chunk: chunk)) { acknowledgements.append($0) }
+ }
+ view.payloadDecodeQueue.suspend()
+ switch index {
+ case 0:
+ for id in ["a", "b", "c"] { view.setTokensJson(tokenPayload(id)) }
+ case 1, 2:
+ view.setTokensJson(tokenPayload("a"))
+ view.setContentResetKey("new")
+ if index == 2 { view.setTokensJson(tokenPayload("b")) }
+ case 3:
+ view.setTokensJson(tokenPayload("b"))
+ view.setContentResetKey("content")
+ case 4, 5:
+ view.setTokensJson(tokenPayload("b"))
+ view.setTokensResetKey(index == 4 ? "new" : "tokens")
+ case 6: view.setTokensJson(tokenPayload("b"))
+ case 7: view.setTokensJson("invalid JSON")
+ case 8:
+ view.setTokensJson("invalid JSON")
+ view.setTokensJson(tokenPayload("b"))
+ case 9:
+ view.setTokensJson(tokenPayload("a"))
+ patch("patch", 0)
+ view.setTokensJson(tokenPayload("b"))
+ case 10:
+ view.setTokensJson(tokenPayload("b"))
+ patch("one", 0)
+ patch("two", 1)
+ case 11:
+ patch("one", 0)
+ patch("two", 1)
+ view.setTokensJson(tokenPayload("b"))
+ case 12:
+ patch("one", 0)
+ patch("two", 1)
+ default:
+ patch("old", 0)
+ view.setContentResetKey("new")
+ view.setTokensJson(tokenPayload("b"))
+ }
+ view.payloadDecodeQueue.resume()
+ afterTokens(on: view.payloadDecodeQueue) {
+ let entries = index == 1 || index == 12 ? 0 : 1
+ let publications = entries
+ tokenDecodeProbe.checkCounts(entries, publications, names[index])
+ if index == 1 || index == 7 {
+ view.checkTokens([])
+ } else if index == 0 {
+ view.checkTokens([tokenPayload("c")])
+ } else if index == 10 {
+ view.checkTokens([tokenPayload("b"), tokenPayload("one"), tokenPayload("two")])
+ } else if index == 12 {
+ view.checkTokens([tokenPayload("seed"), tokenPayload("one"), tokenPayload("two")])
+ } else {
+ view.checkTokens([tokenPayload("b")])
+ }
+ check(acknowledgements == (index == 9 ? [true] : index == 10 || index == 11 || index == 12 ? [true, true] : index == 13 ? [false] : []),
+ "All additive chunks must retain their acknowledgement semantics")
+ if index == 7 {
+ do {
+ _ = try JSONDecoder().decode([String: [ReviewDiffNativeToken]].self, from: Data("invalid JSON".utf8))
+ } catch { check(errors == [error.localizedDescription], "Current error/fallback changed") }
+ } else { check(errors.isEmpty, "Obsolete errors must not publish") }
+ runQueuedTokenDecodeCase(index + 1)
+ }
+ }
+
+ static func runReleasedTokenDecodeCase() {
+ tokenDecodeProbe.reset()
+ var view: T3ReviewDiffView? = T3ReviewDiffView()
+ let queue = view!.payloadDecodeQueue
+ let released = { [weak view] in view == nil }
+ queue.suspend()
+ view!.setTokensJson(tokenPayload("released"))
+ view = nil
+ check(released(), "Queued token closure must not retain the view")
+ queue.resume()
+ afterTokens(on: queue) {
+ tokenDecodeProbe.checkCounts(0, 0, "release before entry")
+ runEnteredTokenDecodeCase(invalid: false)
+ }
+ }
+
+ static func runEnteredTokenDecodeCase(invalid: Bool) {
+ let view = T3ReviewDiffView()
+ let release = DispatchSemaphore(value: 0)
+ tokenDecodeProbe.reset { entry in
+ guard entry == 1 else { return }
+ DispatchQueue.main.async {
+ view.setContentResetKey("new")
+ view.setTokensJson(tokenPayload("b"))
+ release.signal()
+ afterTokens(on: view.payloadDecodeQueue) {
+ tokenDecodeProbe.checkCounts(2, 1, "entered \(invalid ? "error" : "success") then replacement")
+ view.checkTokens([tokenPayload("b")])
+ tokenDecodeProbe.reset()
+ if invalid { runReleasedEnteredTokenDecodeCase() } else { runEnteredTokenDecodeCase(invalid: true) }
+ }
+ }
+ release.wait()
+ }
+ view.setTokensJson(invalid ? "invalid JSON" : tokenPayload("a"))
+ }
+
+ static func runReleasedEnteredTokenDecodeCase() {
+ var view: T3ReviewDiffView? = T3ReviewDiffView()
+ let released = { [weak view] in view == nil }
+ let queue = view!.payloadDecodeQueue
+ let release = DispatchSemaphore(value: 0)
+ tokenDecodeProbe.reset { _ in
+ DispatchQueue.main.async {
+ view = nil
+ check(released(), "Entered decoder must not keep the view alive")
+ release.signal()
+ afterTokens(on: queue) {
+ tokenDecodeProbe.checkCounts(1, 0, "release after entry")
+ tokenDecodeProbe.reset()
+ exit(0)
+ }
+ }
+ release.wait()
+ }
+ view!.setTokensJson(tokenPayload("a"))
+ }
+}
diff --git a/apps/mobile/modules/t3-review-diff/tests/run-ios.sh b/apps/mobile/modules/t3-review-diff/tests/run-ios.sh
index f7dff0997bd..65160539073 100644
--- a/apps/mobile/modules/t3-review-diff/tests/run-ios.sh
+++ b/apps/mobile/modules/t3-review-diff/tests/run-ios.sh
@@ -16,6 +16,21 @@ source = source.replace("import ExpoModulesCore\n", "")
row_decode = "try JSONDecoder().decode([ReviewDiffNativeRow].self, from: data)"
assert source.count(row_decode) == 1
source = source.replace(row_decode, "try decodeRowsForTest(data)")
+# Instrument the real full-token decoder and accepted publication only.
+start = source.index(" let decodedTokens = try JSONDecoder().decode(")
+end = source.index(" DispatchQueue.main.async", start)
+decode = source[start:end]
+source = source[:start] + decode.replace("try JSONDecoder().decode(", "try decodeTokensForTest(") + source[end:]
+publish = " self.contentView.tokensByRowId = decodedTokens"
+assert source.count(publish) == 1
+source = source.replace(publish, publish + "\n tokenDecodeProbe.publish()")
+# Include the accepted malformed-current fallback in publication counts.
+start = source.index(" func setTokensJson(")
+end = source.index(" func setTokensPatchJson(", start)
+method = source[start:end]
+fallback = " self.contentView.tokensByRowId = [:]"
+assert method.count(fallback) == 1
+source = source[:start] + method.replace(fallback, fallback + "\n tokenDecodeProbe.publish()") + source[end:]
stubs = """
public final class AppContext {}
open class ExpoView: UIView {
@@ -33,6 +48,7 @@ Path(sys.argv[2]).write_text(source + "\n" + stubs + "\n"
+ (module / "tests/ios/main.swift").read_text() + "\n"
+ (module / "tests/ios/anchor.swift").read_text() + "\n"
+ (module / "tests/ios/row-decode.swift").read_text() + "\n"
+ + (module / "tests/ios/token-decode.swift").read_text() + "\n"
+ (module / "tests/ios/geometry.swift").read_text())
PYTHON
"$compiler" -O -target "$(uname -m)-apple-ios16.1-macabi" -sdk "$sdk" \