Skip to content

Commit fd56790

Browse files
committed
perf(mobile): skip obsolete queued iOS diff row decodes
1 parent 53896ae commit fd56790

4 files changed

Lines changed: 283 additions & 2 deletions

File tree

‎apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,7 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
340340
private var pendingScrollAnimated = false
341341
private var isProgrammaticScrollActive = false
342342
private var rowsDecodeGeneration = 0
343+
private var rowsDecodeCancellation: ReviewDiffRowPreparation?
343344
private var tokensDecodeGeneration = 0
344345

345346
let onDebug = EventDispatcher()
@@ -387,6 +388,10 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
387388
scrollView.addSubview(contentView)
388389
}
389390

391+
deinit {
392+
rowsDecodeCancellation?.cancel()
393+
}
394+
390395
public override func layoutSubviews() {
391396
super.layoutSubviews()
392397
let anchor = contentView.viewportWidth != bounds.width ? contentView.viewportRowAnchor() : nil
@@ -426,10 +431,15 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
426431

427432
func setRowsJson(_ rowsJson: String) {
428433
contentView.cancelRowPreparation()
434+
rowsDecodeCancellation?.cancel()
435+
let cancellation = ReviewDiffRowPreparation()
436+
rowsDecodeCancellation = cancellation
429437
rowsDecodeGeneration += 1
430438
let generation = rowsDecodeGeneration
431439

432440
payloadDecodeQueue.async { [weak self] in
441+
// Check weak liveness without retaining the view or reading its UIKit state.
442+
guard !cancellation.isCancelled, self != nil else { return }
433443
guard let data = rowsJson.data(using: .utf8) else {
434444
return
435445
}
@@ -601,6 +611,8 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
601611
self.contentResetKey = contentResetKey
602612
lastVisibleRangeDebugKey = ""
603613
contentView.cancelRowPreparation()
614+
rowsDecodeCancellation?.cancel()
615+
rowsDecodeCancellation = nil
604616
rowsDecodeGeneration += 1
605617
tokensDecodeGeneration += 1
606618
contentView.tokensByRowId = [:]

‎apps/mobile/modules/t3-review-diff/tests/ios/geometry.swift‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ geometryView.prepareRows(geometryRows, on: geometryQueue, isCurrent: { true }, c
125125
DispatchQueue.main.async {
126126
check(geometryView.rows.isEmpty && geometryView.contentHeight == 0, "Reset must remain empty after obsolete work drains")
127127
print("Passed sparse geometry, reference heights/widths, font/wrap/collapse, hit testing, direct publication, and cancellation")
128-
exit(0)
128+
runRowDecodeTests()
129129
}
130130
}
131131
})
Lines changed: 262 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,262 @@
1+
// The harness instruments only decoder entry; scheduling and publication use the real view.
2+
private final class RowDecodeProbe {
3+
private let lock = NSLock()
4+
private var entries = 0
5+
private var onEntry: ((Int) -> Void)?
6+
7+
func reset(onEntry: ((Int) -> Void)? = nil) {
8+
lock.lock()
9+
entries = 0
10+
self.onEntry = onEntry
11+
lock.unlock()
12+
}
13+
14+
func enter() {
15+
lock.lock()
16+
entries += 1
17+
let entry = entries
18+
let callback = onEntry
19+
lock.unlock()
20+
callback?(entry)
21+
}
22+
23+
var count: Int {
24+
lock.lock()
25+
defer { lock.unlock() }
26+
return entries
27+
}
28+
}
29+
30+
private let rowDecodeProbe = RowDecodeProbe()
31+
32+
private func decodeRowsForTest(_ data: Data) throws -> [ReviewDiffNativeRow] {
33+
rowDecodeProbe.enter()
34+
return try JSONDecoder().decode([ReviewDiffNativeRow].self, from: data)
35+
}
36+
37+
private extension ReviewDiffContentView {
38+
func checkSameGeometry(as reference: ReviewDiffContentView) {
39+
check(rowOffsets == reference.rowOffsets && contentHeight == reference.contentHeight,
40+
"Queued decoding must preserve reference row offsets and height")
41+
check(contentWidthsByFileId == reference.contentWidthsByFileId,
42+
"Queued decoding must preserve reference widths")
43+
}
44+
}
45+
46+
private extension T3ReviewDiffView {
47+
// One worker/main round decodes, the next prepares and publishes geometry.
48+
func afterRowPipeline(_ completion: @escaping () -> Void) {
49+
Self.afterRowPipeline(on: payloadDecodeQueue, completion)
50+
}
51+
52+
static func afterRowPipeline(on queue: DispatchQueue, _ completion: @escaping () -> Void) {
53+
queue.async {
54+
DispatchQueue.main.async {
55+
queue.async {
56+
DispatchQueue.main.async(execute: completion)
57+
}
58+
}
59+
}
60+
}
61+
62+
func checkRowsMatch(_ json: String) {
63+
let expected = try! JSONDecoder().decode([ReviewDiffNativeRow].self, from: Data(json.utf8))
64+
check(rows.map { String(reflecting: $0) } == expected.map { String(reflecting: $0) },
65+
"Every decoded row field must match the unchanged decoder")
66+
check(contentView.rows.map { String(reflecting: $0) } == rows.map { String(reflecting: $0) })
67+
contentView.checkReferenceGeometry()
68+
let reference = ReviewDiffContentView(frame: contentView.frame)
69+
reference.style = contentView.style
70+
reference.viewportWidth = contentView.viewportWidth
71+
reference.collapsedFileIds = contentView.collapsedFileIds
72+
reference.collapsedCommentIds = contentView.collapsedCommentIds
73+
reference.rows = expected
74+
contentView.checkSameGeometry(as: reference)
75+
}
76+
77+
func checkEmptyRows() {
78+
check(rows.isEmpty && contentView.rows.isEmpty && contentView.contentHeight == 0,
79+
"Reset/error must remain empty after the queue drains")
80+
}
81+
}
82+
83+
private func rowDecodePayload(_ file: String) -> String {
84+
let objects: [[String: Any]] = [
85+
["kind": "file", "id": "\(file):header", "fileId": file, "filePath": "\(file).swift"],
86+
["kind": "hunk", "id": "\(file):hunk", "fileId": file, "text": "@@ context\t@@"],
87+
["kind": "line", "id": "\(file):ascii", "fileId": file, "content": String(repeating: "let value = 123; ", count: 60),
88+
"change": "add", "newLineNumber": 1, "wordDiffRanges": [["start": 0, "end": 3]]],
89+
["kind": "line", "id": "\(file):unicode", "fileId": file, "content": "漢字\t👨‍👩‍👧‍👦 e\u{301} مرحبا", "oldLineNumber": 2],
90+
["kind": "comment", "id": "\(file):comment", "fileId": file, "commentText": "Keep every field"],
91+
]
92+
return String(data: try! JSONSerialization.data(withJSONObject: objects), encoding: .utf8)!
93+
}
94+
95+
private extension T3ReviewDiffView {
96+
static func runQueuedRowDecodeCase(_ index: Int) {
97+
let names = ["A to B", "reset", "reset then B", "unchanged reset key", "current success", "current error", "obsolete error"]
98+
guard index < names.count else {
99+
runReleasedRowDecodeCase()
100+
return
101+
}
102+
rowDecodeProbe.reset()
103+
let view = T3ReviewDiffView()
104+
view.bounds = CGRect(x: 0, y: 0, width: 390, height: 844)
105+
view.layoutSubviews()
106+
view.setContentResetKey("section-a")
107+
view.setStyleJson("{\"wordWrap\":true}")
108+
view.pendingScrollFileId = "pending"
109+
var events: [[String: Any]] = []
110+
view.onDebug.onEvent = { payload in
111+
if (payload["message"] as? String)?.hasPrefix("rows-decode") == true { events.append(payload) }
112+
}
113+
let a = rowDecodePayload("a")
114+
let b = rowDecodePayload("b")
115+
view.payloadDecodeQueue.suspend()
116+
switch index {
117+
case 0:
118+
view.setRowsJson(a)
119+
view.setRowsJson(b)
120+
case 1, 2:
121+
view.setRowsJson(a)
122+
view.setContentResetKey("section-b")
123+
if index == 2 { view.setRowsJson(b) }
124+
case 3:
125+
view.setRowsJson(b)
126+
view.setContentResetKey("section-a")
127+
case 4:
128+
view.setRowsJson(b)
129+
case 5:
130+
view.rows = try! JSONDecoder().decode([ReviewDiffNativeRow].self, from: Data(a.utf8))
131+
view.contentView.rows = view.rows
132+
view.setRowsJson("invalid JSON")
133+
default:
134+
view.setRowsJson("invalid JSON")
135+
view.setRowsJson(b)
136+
}
137+
view.payloadDecodeQueue.resume()
138+
view.afterRowPipeline {
139+
let expected = index == 1 ? 0 : 1
140+
check(rowDecodeProbe.count == expected,
141+
"\(names[index]): expected \(expected) decoder entries, got \(rowDecodeProbe.count)")
142+
if index == 1 {
143+
view.checkEmptyRows()
144+
check(events.isEmpty, "Reset work must not publish success or error")
145+
} else if index == 5 {
146+
view.checkEmptyRows()
147+
check(view.pendingScrollFileId == nil, "Current error must clear pending scroll")
148+
check(events.count == 1 && events[0]["message"] as? String == "rows-decode-failed")
149+
do {
150+
_ = try JSONDecoder().decode([ReviewDiffNativeRow].self, from: Data("invalid JSON".utf8))
151+
check(false)
152+
} catch {
153+
check(events[0]["error"] as? String == error.localizedDescription, "Preserve the current error")
154+
}
155+
} else {
156+
view.checkRowsMatch(b)
157+
check(events.count == 1 && events[0]["message"] as? String == "rows-decoded",
158+
"Only the current payload may publish success")
159+
}
160+
print("Passed queued row decode: \(names[index]), decoder entries=\(rowDecodeProbe.count)")
161+
runQueuedRowDecodeCase(index + 1)
162+
}
163+
}
164+
165+
static func runReleasedRowDecodeCase() {
166+
rowDecodeProbe.reset()
167+
var view: T3ReviewDiffView? = T3ReviewDiffView()
168+
let isReleased = { [weak view] in view == nil }
169+
let queue = view!.payloadDecodeQueue
170+
queue.suspend()
171+
view!.setRowsJson(rowDecodePayload("released"))
172+
view = nil
173+
check(isReleased(), "Queued row work must not retain the view")
174+
queue.resume()
175+
T3ReviewDiffView.afterRowPipeline(on: queue) {
176+
check(rowDecodeProbe.count == 0, "Release before worker resume must skip decoding")
177+
print("Passed release before worker resume, decoder entries=0")
178+
runRunningRowDecodeCase(invalid: false)
179+
}
180+
}
181+
182+
static func runRunningRowDecodeCase(invalid: Bool) {
183+
let view = T3ReviewDiffView()
184+
let release = DispatchSemaphore(value: 0)
185+
let b = rowDecodePayload("current")
186+
var publications = 0
187+
view.onDebug.onEvent = { payload in
188+
if (payload["message"] as? String)?.hasPrefix("rows-decode") == true {
189+
check(payload["message"] as? String == "rows-decoded", "Running stale errors must not publish")
190+
publications += 1
191+
}
192+
}
193+
rowDecodeProbe.reset { entry in
194+
guard entry == 1 else { return }
195+
DispatchQueue.main.async {
196+
view.setContentResetKey("new-section")
197+
view.setRowsJson(b)
198+
release.signal()
199+
view.afterRowPipeline {
200+
check(rowDecodeProbe.count == 2, "An entered decoder must finish; the current payload must also decode")
201+
check(publications == 1, "Running obsolete success/error must not publish")
202+
view.checkRowsMatch(b)
203+
rowDecodeProbe.reset()
204+
print("Passed running \(invalid ? "error" : "success") replaced by current rows, decoder entries=2")
205+
if invalid { runReleasedRunningRowDecodeCase() } else { runRunningRowDecodeCase(invalid: true) }
206+
}
207+
}
208+
release.wait()
209+
}
210+
view.setRowsJson(invalid ? "invalid JSON" : rowDecodePayload("running"))
211+
}
212+
213+
static func runReleasedRunningRowDecodeCase() {
214+
var view: T3ReviewDiffView? = T3ReviewDiffView()
215+
let isReleased = { [weak view] in view == nil }
216+
let queue = view!.payloadDecodeQueue
217+
let release = DispatchSemaphore(value: 0)
218+
var publications = 0
219+
view!.onDebug.onEvent = { payload in
220+
if (payload["message"] as? String)?.hasPrefix("rows-decode") == true { publications += 1 }
221+
}
222+
rowDecodeProbe.reset { _ in
223+
DispatchQueue.main.async {
224+
view = nil
225+
check(isReleased(), "An entered decoder must not retain the view")
226+
release.signal()
227+
afterRowPipeline(on: queue) {
228+
check(rowDecodeProbe.count == 1 && publications == 0,
229+
"An entered decode may finish after release but must not publish")
230+
rowDecodeProbe.reset()
231+
print("Passed release after decoder entry without retaining the view, decoder entries=1")
232+
runAdditiveTokenPatchCase()
233+
}
234+
}
235+
release.wait()
236+
}
237+
view!.setRowsJson(rowDecodePayload("released-running"))
238+
}
239+
240+
static func runAdditiveTokenPatchCase() {
241+
let view = T3ReviewDiffView()
242+
view.setTokensResetKey("tokens")
243+
view.payloadDecodeQueue.suspend()
244+
var acknowledgements: [Bool] = []
245+
for id in ["one", "two"] {
246+
view.setTokensPatchJson("{\"resetKey\":\"tokens\",\"tokensByRowId\":{\"\(id)\":[{\"content\":\"\(id)\"}]}}") {
247+
acknowledgements.append($0)
248+
}
249+
}
250+
view.payloadDecodeQueue.resume()
251+
view.afterRowPipeline {
252+
check(acknowledgements == [true, true], "Every additive token patch must be acknowledged")
253+
check(Set(view.contentView.tokensByRowId.keys) == Set(["one", "two"]), "Token patches must never coalesce")
254+
print("Passed additive token patches and acknowledgements; all 12 row/payload lifecycle cases passed")
255+
exit(0)
256+
}
257+
}
258+
}
259+
260+
private func runRowDecodeTests() {
261+
T3ReviewDiffView.runQueuedRowDecodeCase(0)
262+
}

‎apps/mobile/modules/t3-review-diff/tests/run-ios.sh‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@ from pathlib import Path
1212
module = Path(sys.argv[1])
1313
source = (module / "ios/T3ReviewDiffView.swift").read_text()
1414
source = source.replace("import ExpoModulesCore\n", "")
15+
# Count entry into the real decoder without replacing the production queue or lifecycle.
16+
row_decode = "try JSONDecoder().decode([ReviewDiffNativeRow].self, from: data)"
17+
assert source.count(row_decode) == 1
18+
source = source.replace(row_decode, "try decodeRowsForTest(data)")
1519
stubs = """
1620
public final class AppContext {}
1721
open class ExpoView: UIView {
@@ -20,16 +24,19 @@ open class ExpoView: UIView {
2024
public required init?(coder: NSCoder) { fatalError("init(coder:) is unused") }
2125
}
2226
final class EventDispatcher {
23-
func callAsFunction(_ payload: [String: Any]) {}
27+
var onEvent: (([String: Any]) -> Void)?
28+
func callAsFunction(_ payload: [String: Any]) { onEvent?(payload) }
2429
}
2530
"""
2631
# Expo alone is stubbed; keep the real scroll container as well as the content view.
2732
Path(sys.argv[2]).write_text(source + "\n" + stubs + "\n"
2833
+ (module / "tests/ios/main.swift").read_text() + "\n"
2934
+ (module / "tests/ios/anchor.swift").read_text() + "\n"
35+
+ (module / "tests/ios/row-decode.swift").read_text() + "\n"
3036
+ (module / "tests/ios/geometry.swift").read_text())
3137
PYTHON
3238
"$compiler" -O -target "$(uname -m)-apple-ios16.1-macabi" -sdk "$sdk" \
39+
-module-cache-path "$output/module-cache" \
3340
-F "$sdk/System/iOSSupport/System/Library/Frameworks" \
3441
"$module_dir/ios/ReviewDiffCodeLayout.swift" "$output/main.swift" \
3542
-o "$output/layout-tests"

0 commit comments

Comments
 (0)